context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Tasks;
using Microsoft.Build.Evaluation;
using System.Globalization;
using Xunit;
namespace Microsoft.Build.UnitTests
{
/*
* Class: AspNetCompilerTests
*
* Test the AspNetCompiler task in various ways.
*
*/
sealed public class AspNetCompilerTests
{
[Fact]
public void NoParameters()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
// It's invalid to have zero parameters, so we expect a "false" return value from ValidateParameters.
Assert.False(CommandLine.CallValidateParameters(t));
}
[Fact]
public void OnlyMetabasePath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.MetabasePath = @"/LM/W3SVC/1/Root/MyApp";
// This should be valid.
Assert.True(CommandLine.CallValidateParameters(t));
CommandLine.ValidateEquals(t, @"-m /LM/W3SVC/1/Root/MyApp", false);
}
[Fact]
public void OnlyVirtualPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.VirtualPath = @"/MyApp";
// This should be valid.
Assert.True(CommandLine.CallValidateParameters(t));
CommandLine.ValidateEquals(t, @"-v /MyApp", false);
}
[Fact]
public void OnlyPhysicalPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.PhysicalPath = @"c:\MyApp";
// This is not valid. Either MetabasePath or VirtualPath must be specified.
Assert.False(CommandLine.CallValidateParameters(t));
}
[Fact]
public void OnlyTargetPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.TargetPath = @"c:\MyTarget";
// This is not valid. Either MetabasePath or VirtualPath must be specified.
Assert.False(CommandLine.CallValidateParameters(t));
}
[Fact]
public void MetabasePathAndVirtualPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.MetabasePath = @"/LM/W3SVC/1/Root/MyApp";
t.VirtualPath = @"/MyApp";
// This is not valid. Can't specify both MetabasePath and (VirtualPath or PhysicalPath).
Assert.False(CommandLine.CallValidateParameters(t));
}
[Fact]
public void MetabasePathAndPhysicalPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.MetabasePath = @"/LM/W3SVC/1/Root/MyApp";
t.PhysicalPath = @"c:\MyApp";
// This is not valid. Can't specify both MetabasePath and (VirtualPath or PhysicalPath).
Assert.False(CommandLine.CallValidateParameters(t));
}
[Fact]
public void MetabasePathAndTargetPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.MetabasePath = @"/LM/W3SVC/1/Root/MyApp";
t.TargetPath = @"c:\MyTarget";
// This is valid.
Assert.True(CommandLine.CallValidateParameters(t));
CommandLine.ValidateEquals(t, @"-m /LM/W3SVC/1/Root/MyApp c:\MyTarget", false);
}
[Fact]
public void VirtualPathAndPhysicalPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.VirtualPath = @"/MyApp";
t.PhysicalPath = @"c:\MyApp";
// This is valid.
Assert.True(CommandLine.CallValidateParameters(t));
CommandLine.ValidateEquals(t, @"-v /MyApp -p c:\MyApp", false);
}
[Fact]
public void VirtualPathAndTargetPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.VirtualPath = @"/MyApp";
t.TargetPath = @"c:\MyTarget";
// This is valid.
Assert.True(CommandLine.CallValidateParameters(t));
CommandLine.ValidateEquals(t, @"-v /MyApp c:\MyTarget", false);
}
[Fact]
public void PhysicalPathAndTargetPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.PhysicalPath = @"c:\MyApp";
t.TargetPath = @"c:\MyTarget";
// This is not valid. Either MetabasePath or VirtualPath must be specified.
Assert.False(CommandLine.CallValidateParameters(t));
}
[Fact]
public void AllExceptMetabasePath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.VirtualPath = @"/MyApp";
t.PhysicalPath = @"c:\MyApp";
t.TargetPath = @"c:\MyTarget";
// This is valid.
Assert.True(CommandLine.CallValidateParameters(t));
CommandLine.ValidateEquals(t, @"-v /MyApp -p c:\MyApp c:\MyTarget", false);
}
[Fact]
public void AllExceptVirtualPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.MetabasePath = @"/LM/W3SVC/1/Root/MyApp";
t.PhysicalPath = @"c:\MyApp";
t.TargetPath = @"c:\MyTarget";
// This is not valid. Can't specify both MetabasePath and (VirtualPath or PhysicalPath).
Assert.False(CommandLine.CallValidateParameters(t));
}
[Fact]
public void AllExceptPhysicalPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.MetabasePath = @"/LM/W3SVC/1/Root/MyApp";
t.VirtualPath = @"/MyApp";
t.TargetPath = @"c:\MyTarget";
// This is not valid. Can't specify both MetabasePath and (VirtualPath or PhysicalPath).
Assert.False(CommandLine.CallValidateParameters(t));
}
[Fact]
public void AllExceptTargetPath()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.MetabasePath = @"/LM/W3SVC/1/Root/MyApp";
t.VirtualPath = @"/MyApp";
t.PhysicalPath = @"c:\MyApp";
// This is not valid. Can't specify both MetabasePath and (VirtualPath or PhysicalPath).
Assert.False(CommandLine.CallValidateParameters(t));
}
[Fact]
public void AllParameters()
{
AspNetCompiler t = new AspNetCompiler();
t.BuildEngine = new MockEngine();
t.MetabasePath = @"/LM/W3SVC/1/Root/MyApp";
t.VirtualPath = @"/MyApp";
t.PhysicalPath = @"c:\MyApp";
t.TargetPath = @"c:\MyTarget";
// This is not valid. Can't specify both MetabasePath and (VirtualPath or PhysicalPath).
Assert.False(CommandLine.CallValidateParameters(t));
}
/// <summary>
/// Make sure AspNetCompiler sends ExternalProjectStarted/Finished events properly. The tasks will fail since
/// the project files don't exist, but we only care about the events anyway.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestExternalProjectEvents()
{
string projectFileContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<UsingTask TaskName=`AspNetCompiler` AssemblyName=`{0}`/>
<Target Name=`Build`>
<AspNetCompiler VirtualPath=`/WebSite1` PhysicalPath=`..\..\solutions\WebSite1\`/>
<OnError ExecuteTargets=`Build2`/>
</Target>
<Target Name=`Build2`>
<AspNetCompiler VirtualPath=`/WebSite2` Clean=`true`/>
<OnError ExecuteTargets=`Build3`/>
</Target>
<Target Name=`Build3`>
<AspNetCompiler MetabasePath=`/LM/W3SVC/1/Root/MyApp`/>
</Target>
</Project>";
string fullProjectFile = string.Format(CultureInfo.InvariantCulture, projectFileContents, typeof(AspNetCompiler).Assembly.FullName);
MockLogger logger = new MockLogger();
Project proj = ObjectModelHelpers.CreateInMemoryProject(fullProjectFile, logger);
Assert.False(proj.Build(logger));
Assert.Equal(3, logger.ExternalProjectStartedEvents.Count);
Assert.Equal(3, logger.ExternalProjectFinishedEvents.Count);
Assert.Equal(@"..\..\solutions\WebSite1\", logger.ExternalProjectStartedEvents[0].ProjectFile);
Assert.Equal("/WebSite2", logger.ExternalProjectStartedEvents[1].ProjectFile);
Assert.Equal("/LM/W3SVC/1/Root/MyApp", logger.ExternalProjectStartedEvents[2].ProjectFile);
Assert.Equal(@"..\..\solutions\WebSite1\", logger.ExternalProjectFinishedEvents[0].ProjectFile);
Assert.Equal("/WebSite2", logger.ExternalProjectFinishedEvents[1].ProjectFile);
Assert.Equal("/LM/W3SVC/1/Root/MyApp", logger.ExternalProjectFinishedEvents[2].ProjectFile);
Assert.Null(logger.ExternalProjectStartedEvents[0].TargetNames);
Assert.Equal("Clean", logger.ExternalProjectStartedEvents[1].TargetNames);
Assert.Null(logger.ExternalProjectStartedEvents[2].TargetNames);
Assert.False(logger.ExternalProjectFinishedEvents[0].Succeeded);
Assert.False(logger.ExternalProjectFinishedEvents[1].Succeeded);
Assert.False(logger.ExternalProjectFinishedEvents[2].Succeeded);
}
}
}
| |
// 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.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.CryptoConfigTests
{
public static class CryptoConfigTests
{
[Fact]
public static void AllowOnlyFipsAlgorithms()
{
Assert.False(CryptoConfig.AllowOnlyFipsAlgorithms);
}
[Fact]
public static void AddOID_NotSupported()
{
Assert.Throws<PlatformNotSupportedException>(() => CryptoConfig.AddOID(string.Empty, string.Empty));
}
[Fact]
public static void AddAlgorithm_NotSupported()
{
Assert.Throws<PlatformNotSupportedException>(() => CryptoConfig.AddAlgorithm(typeof(CryptoConfigTests), string.Empty));
}
[Fact]
public static void StaticCreateMethods()
{
// Ensure static create methods exist and don't throw
// Some do not have public concrete types (in Algorithms assembly) so in those cases we only check for null\failure.
VerifyStaticCreateResult(Aes.Create(typeof(AesManaged).FullName), typeof(AesManaged));
Assert.Null(DES.Create(string.Empty));
Assert.Null(DSA.Create(string.Empty));
Assert.Null(ECDsa.Create(string.Empty));
Assert.Null(MD5.Create(string.Empty));
Assert.Null(RandomNumberGenerator.Create(string.Empty));
Assert.Null(RC2.Create(string.Empty));
VerifyStaticCreateResult(Rijndael.Create(typeof(RijndaelManaged).FullName), typeof(RijndaelManaged));
Assert.Null(RSA.Create(string.Empty));
Assert.Null(SHA1.Create(string.Empty));
VerifyStaticCreateResult(SHA256.Create(typeof(SHA256Managed).FullName), typeof(SHA256Managed));
VerifyStaticCreateResult(SHA384.Create(typeof(SHA384Managed).FullName), typeof(SHA384Managed));
VerifyStaticCreateResult(SHA512.Create(typeof(SHA512Managed).FullName), typeof(SHA512Managed));
}
private static void VerifyStaticCreateResult(object obj, Type expectedType)
{
Assert.NotNull(obj);
Assert.IsType(expectedType, obj);
}
[Fact]
public static void MapNameToOID()
{
Assert.Throws<ArgumentNullException>(() => CryptoConfig.MapNameToOID(null));
// Test some oids unique to CryptoConfig
Assert.Equal("1.3.14.3.2.26", CryptoConfig.MapNameToOID("SHA"));
Assert.Equal("1.3.14.3.2.26", CryptoConfig.MapNameToOID("sha"));
Assert.Equal("1.2.840.113549.3.7", CryptoConfig.MapNameToOID("TripleDES"));
// Test fallback to Oid class
Assert.Equal("1.3.36.3.3.2.8.1.1.8", CryptoConfig.MapNameToOID("brainpoolP256t1"));
// Invalid oid
Assert.Equal(null, CryptoConfig.MapNameToOID("NOT_A_VALID_OID"));
}
[Fact]
public static void CreateFromName_validation()
{
Assert.Throws<ArgumentNullException>(() => CryptoConfig.CreateFromName(null));
Assert.Throws<ArgumentNullException>(() => CryptoConfig.CreateFromName(null, null));
Assert.Throws<ArgumentNullException>(() => CryptoConfig.CreateFromName(null, string.Empty));
Assert.Null(CryptoConfig.CreateFromName(string.Empty, null));
Assert.Null(CryptoConfig.CreateFromName("SHA", 1, 2));
}
public static IEnumerable<object[]> AllValidNames
{
get
{
// Random number generator
yield return new object[] { "RandomNumberGenerator", "System.Security.Cryptography.RNGCryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.RandomNumberGenerator", "System.Security.Cryptography.RNGCryptoServiceProvider", false };
// Hash functions
yield return new object[] { "SHA", "System.Security.Cryptography.SHA1CryptoServiceProvider", false };
yield return new object[] { "SHA1", "System.Security.Cryptography.SHA1CryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.SHA1", "System.Security.Cryptography.SHA1CryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.HashAlgorithm", "System.Security.Cryptography.SHA1CryptoServiceProvider", false };
yield return new object[] { "MD5", "System.Security.Cryptography.MD5CryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.MD5", "System.Security.Cryptography.MD5CryptoServiceProvider", false };
yield return new object[] { "SHA256", typeof(SHA256Managed).FullName, true };
yield return new object[] { "SHA-256", typeof(SHA256Managed).FullName, true };
yield return new object[] { "System.Security.Cryptography.SHA256", typeof(SHA256Managed).FullName, true };
yield return new object[] { "SHA384", typeof(SHA384Managed).FullName, true };
yield return new object[] { "SHA-384", typeof(SHA384Managed).FullName, true };
yield return new object[] { "System.Security.Cryptography.SHA384", typeof(SHA384Managed).FullName, true };
yield return new object[] { "SHA512", typeof(SHA512Managed).FullName, true };
yield return new object[] { "SHA-512", typeof(SHA512Managed).FullName, true };
yield return new object[] { "System.Security.Cryptography.SHA512", typeof(SHA512Managed).FullName, true };
// Keyed Hash Algorithms
yield return new object[] { "System.Security.Cryptography.HMAC", "System.Security.Cryptography.HMACSHA1", true };
yield return new object[] { "System.Security.Cryptography.KeyedHashAlgorithm", "System.Security.Cryptography.HMACSHA1", true };
yield return new object[] { "HMACMD5", "System.Security.Cryptography.HMACMD5", true };
yield return new object[] { "System.Security.Cryptography.HMACMD5", null , true };
yield return new object[] { "HMACSHA1", "System.Security.Cryptography.HMACSHA1", true };
yield return new object[] { "System.Security.Cryptography.HMACSHA1", null , true };
yield return new object[] { "HMACSHA256", "System.Security.Cryptography.HMACSHA256", true };
yield return new object[] { "System.Security.Cryptography.HMACSHA256", null, true };
yield return new object[] { "HMACSHA384", "System.Security.Cryptography.HMACSHA384", true };
yield return new object[] { "System.Security.Cryptography.HMACSHA384", null , true };
yield return new object[] { "HMACSHA512", "System.Security.Cryptography.HMACSHA512", true };
yield return new object[] { "System.Security.Cryptography.HMACSHA512", null , true };
// Asymmetric algorithms
yield return new object[] { "RSA", "System.Security.Cryptography.RSACryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.RSA", "System.Security.Cryptography.RSACryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.AsymmetricAlgorithm", "System.Security.Cryptography.RSACryptoServiceProvider", false };
yield return new object[] { "DSA", "System.Security.Cryptography.DSACryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.DSA", "System.Security.Cryptography.DSACryptoServiceProvider", false };
yield return new object[] { "ECDsa", "System.Security.Cryptography.ECDsaCng", false };
yield return new object[] { "ECDsaCng", "System.Security.Cryptography.ECDsaCng", false };
yield return new object[] { "System.Security.Cryptography.ECDsaCng", null , false };
yield return new object[] { "DES", "System.Security.Cryptography.DESCryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.DES", "System.Security.Cryptography.DESCryptoServiceProvider", false };
yield return new object[] { "3DES", "System.Security.Cryptography.TripleDESCryptoServiceProvider", false };
yield return new object[] { "TripleDES", "System.Security.Cryptography.TripleDESCryptoServiceProvider", false };
yield return new object[] { "Triple DES", "System.Security.Cryptography.TripleDESCryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.TripleDES", "System.Security.Cryptography.TripleDESCryptoServiceProvider", false };
yield return new object[] { "RC2", "System.Security.Cryptography.RC2CryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.RC2", "System.Security.Cryptography.RC2CryptoServiceProvider", false };
yield return new object[] { "Rijndael", typeof(RijndaelManaged).FullName, true };
yield return new object[] { "System.Security.Cryptography.Rijndael", typeof(RijndaelManaged).FullName, true };
yield return new object[] { "System.Security.Cryptography.SymmetricAlgorithm", typeof(RijndaelManaged).FullName, true };
yield return new object[] { "AES", "System.Security.Cryptography.AesCryptoServiceProvider", false };
yield return new object[] { "AesCryptoServiceProvider", "System.Security.Cryptography.AesCryptoServiceProvider", false };
yield return new object[] { "System.Security.Cryptography.AesCryptoServiceProvider", "System.Security.Cryptography.AesCryptoServiceProvider", false };
yield return new object[] { "AesManaged", typeof(AesManaged).FullName, true };
yield return new object[] { "System.Security.Cryptography.AesManaged", typeof(AesManaged).FullName, true };
// Xml Dsig/ Enc Hash algorithms
yield return new object[] { "http://www.w3.org/2000/09/xmldsig#sha1", "System.Security.Cryptography.SHA1CryptoServiceProvider", false };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#sha256", typeof(SHA256Managed).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#sha512", typeof(SHA512Managed).FullName, true };
// Xml Encryption symmetric keys
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#des-cbc", "System.Security.Cryptography.DESCryptoServiceProvider", false };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#tripledes-cbc", "System.Security.Cryptography.TripleDESCryptoServiceProvider", false };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#kw-tripledes", "System.Security.Cryptography.TripleDESCryptoServiceProvider", false };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#aes128-cbc", typeof(RijndaelManaged).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#kw-aes128", typeof(RijndaelManaged).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#aes192-cbc", typeof(RijndaelManaged).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#kw-aes192", typeof(RijndaelManaged).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#aes256-cbc", typeof(RijndaelManaged).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmlenc#kw-aes256", typeof(RijndaelManaged).FullName, true };
// Xml Dsig HMAC URIs from http://www.w3.org/TR/xmldsig-core/
yield return new object[] { "http://www.w3.org/2000/09/xmldsig#hmac-sha1", typeof(HMACSHA1).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmldsig-more#sha384", typeof(SHA384Managed).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmldsig-more#hmac-md5", typeof(HMACMD5).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", typeof(HMACSHA256).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", typeof(HMACSHA384).FullName, true };
yield return new object[] { "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", typeof(HMACSHA512).FullName, true };
// X509
yield return new object[] { "2.5.29.10", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension", true };
yield return new object[] { "2.5.29.19", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension", true };
yield return new object[] { "2.5.29.14", "System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension", true };
yield return new object[] { "2.5.29.15", "System.Security.Cryptography.X509Certificates.X509KeyUsageExtension", true };
yield return new object[] { "2.5.29.37", "System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension", true };
yield return new object[] { "X509Chain", "System.Security.Cryptography.X509Certificates.X509Chain", true };
// PKCS9 attributes
yield return new object[] { "1.2.840.113549.1.9.3", "System.Security.Cryptography.Pkcs.Pkcs9ContentType", false };
yield return new object[] { "1.2.840.113549.1.9.4", "System.Security.Cryptography.Pkcs.Pkcs9MessageDigest", false };
yield return new object[] { "1.2.840.113549.1.9.5", "System.Security.Cryptography.Pkcs.Pkcs9SigningTime", false };
yield return new object[] { "1.3.6.1.4.1.311.88.2.1", "System.Security.Cryptography.Pkcs.Pkcs9DocumentName", false };
yield return new object[] { "1.3.6.1.4.1.311.88.2.2", "System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription", false };
}
}
[Theory, MemberData(nameof(AllValidNames))]
public static void CreateFromName_AllValidNames(string name, string typeName, bool supportsUnixMac)
{
if (supportsUnixMac || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
object obj = CryptoConfig.CreateFromName(name);
Assert.NotNull(obj);
if (typeName == null)
{
typeName = name;
}
Assert.Equal(typeName, obj.GetType().FullName);
if (obj is IDisposable)
{
((IDisposable)obj).Dispose();
}
}
else
{
// These will be the Csp types, which currently aren't supported on Mac\Unix
Assert.Throws<TargetInvocationException> (() => CryptoConfig.CreateFromName(name));
}
}
[Fact]
public static void CreateFromName_CtorArguments()
{
string className = typeof(ClassWithCtorArguments).FullName + ", System.Security.Cryptography.Algorithms.Tests";
// Pass int instead of string
Assert.Throws<MissingMethodException>(() => CryptoConfig.CreateFromName(className, 1));
// Valid case
object obj = CryptoConfig.CreateFromName(className, "Hello");
Assert.NotNull(obj);
Assert.IsType(typeof(ClassWithCtorArguments), obj);
ClassWithCtorArguments ctorObj = (ClassWithCtorArguments)obj;
Assert.Equal("Hello", ctorObj.MyString);
}
[Fact]
public static void EncodeOID_Validation()
{
Assert.Throws<ArgumentNullException>(() => CryptoConfig.EncodeOID(null));
Assert.Throws<FormatException>(() => CryptoConfig.EncodeOID(string.Empty));
Assert.Throws<FormatException>(() => CryptoConfig.EncodeOID("BAD.OID"));
Assert.Throws<FormatException>(() => CryptoConfig.EncodeOID("1.2.BAD.OID"));
Assert.Throws<OverflowException>(() => CryptoConfig.EncodeOID("1." + uint.MaxValue));
}
[Fact]
public static void EncodeOID_Compat()
{
string actual = CryptoConfig.EncodeOID("-1.2.-3").ByteArrayToHex();
Assert.Equal("0602DAFD", actual); // Negative values not checked
}
[Fact]
public static void EncodeOID_Length_Boundary()
{
string valueToRepeat = "1.1";
// Build a string like 1.11.11.11. ... .11.1, which has 0x80 separators.
// The BER/DER encoding of an OID has a minimum number of bytes as the number of separator characters,
// so this would produce an OID with a length segment of more than one byte, which EncodeOID can't handle.
string s = new StringBuilder(valueToRepeat.Length * 0x80).Insert(0, valueToRepeat, 0x80).ToString();
Assert.Throws<CryptographicUnexpectedOperationException>(() => CryptoConfig.EncodeOID(s));
// Try again with one less separator for the boundary case, but the particular output is really long
// and would just clutter up this test, so only verify it doesn't throw.
s = new StringBuilder(valueToRepeat.Length * 0x7f).Insert(0, valueToRepeat, 0x7f).ToString();
CryptoConfig.EncodeOID(s);
}
[Theory]
[InlineData(0x4000, "0603818028")]
[InlineData(0x200000, "060481808028")]
[InlineData(0x10000000, "06058180808028")]
[InlineData(0x10000001, "06058180808029")]
[InlineData(int.MaxValue, "060127")]
public static void EncodeOID_Value_Boundary_And_Compat(uint elementValue, string expectedEncoding)
{
// Boundary cases in EncodeOID; output may produce the wrong value mathematically due to encoding
// algorithm semantics but included here for compat reasons.
byte[] actual = CryptoConfig.EncodeOID("1." + elementValue.ToString());
byte[] expected = expectedEncoding.HexToByteArray();
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("SHA1", "1.3.14.3.2.26", "06052B0E03021A")]
[InlineData("DES", "1.3.14.3.2.7", "06052B0E030207")]
[InlineData("MD5", "1.2.840.113549.2.5", "06082A864886F70D0205")]
public static void MapAndEncodeOID(string alg, string expectedOid, string expectedEncoding)
{
string oid = CryptoConfig.MapNameToOID(alg);
Assert.Equal(expectedOid, oid);
byte[] actual = CryptoConfig.EncodeOID(oid);
byte[] expected = expectedEncoding.HexToByteArray();
Assert.Equal(expected, actual);
}
private static void VerifyCreateFromName<TExpected>(string name)
{
object obj = CryptoConfig.CreateFromName(name);
Assert.NotNull(obj);
Assert.IsType(typeof(TExpected), obj);
}
public class ClassWithCtorArguments
{
public ClassWithCtorArguments(string s)
{
MyString = s;
}
public string MyString;
}
}
}
| |
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace URSA.ReorderableList {
/// <summary>
/// Utility class for drawing reorderable lists.
/// </summary>
public static class ReorderableListGUI {
/// <summary>
/// Default list item height is 18 pixels.
/// </summary>
public const float DefaultItemHeight = 18;
/// <summary>
/// Gets or sets the zero-based index of the last item that was changed. A value of -1
/// indicates that no item was changed by list.
/// </summary>
/// <remarks>
/// <para>This property should not be set when items are added or removed.</para>
/// </remarks>
public static int IndexOfChangedItem { get; internal set; }
/// <summary>
/// Gets the control ID of the list that is currently being drawn.
/// </summary>
public static int CurrentListControlID {
get { return ReorderableListControl.CurrentListControlID; }
}
/// <summary>
/// Gets the position of the list control that is currently being drawn.
/// </summary>
/// <remarks>
/// <para>The value of this property should be ignored for <see cref="EventType.Layout"/>
/// type events when using reorderable list controls with automatic layout.</para>
/// </remarks>
/// <see cref="CurrentItemTotalPosition"/>
public static Rect CurrentListPosition {
get { return ReorderableListControl.CurrentListPosition; }
}
/// <summary>
/// Gets the zero-based index of the list item that is currently being drawn;
/// or a value of -1 if no item is currently being drawn.
/// </summary>
public static int CurrentItemIndex {
get { return ReorderableListControl.CurrentItemIndex; }
}
/// <summary>
/// Gets the total position of the list item that is currently being drawn.
/// </summary>
/// <remarks>
/// <para>The value of this property should be ignored for <see cref="EventType.Layout"/>
/// type events when using reorderable list controls with automatic layout.</para>
/// </remarks>
/// <see cref="CurrentItemIndex"/>
/// <see cref="CurrentListPosition"/>
public static Rect CurrentItemTotalPosition {
get { return ReorderableListControl.CurrentItemTotalPosition; }
}
#region Basic Item Drawers
/// <summary>
/// Default list item drawer implementation.
/// </summary>
/// <remarks>
/// <para>Always presents the label "Item drawer not implemented.".</para>
/// </remarks>
/// <param name="position">Position to draw list item control(s).</param>
/// <param name="item">Value of list item.</param>
/// <returns>
/// Unmodified value of list item.
/// </returns>
/// <typeparam name="T">Type of list item.</typeparam>
public static T DefaultItemDrawer<T>(Rect position, T item) {
GUI.Label(position, "Item drawer not implemented.");
return item;
}
/// <summary>
/// Draws text field allowing list items to be edited.
/// </summary>
/// <remarks>
/// <para>Null values are automatically changed to empty strings since null
/// values cannot be edited using a text field.</para>
/// <para>Value of <c>GUI.changed</c> is set to <c>true</c> if value of item
/// is modified.</para>
/// </remarks>
/// <param name="position">Position to draw list item control(s).</param>
/// <param name="item">Value of list item.</param>
/// <returns>
/// Modified value of list item.
/// </returns>
public static string TextFieldItemDrawer(Rect position, string item) {
if (item == null) {
item = "";
GUI.changed = true;
}
return EditorGUI.TextField(position, item);
}
#endregion
/// <summary>
/// Gets the default list control implementation.
/// </summary>
private static ReorderableListControl DefaultListControl { get; set; }
static ReorderableListGUI() {
DefaultListControl = new ReorderableListControl();
// Duplicate default styles to prevent user scripts from interferring with
// the default list control instance.
DefaultListControl.ContainerStyle = new GUIStyle(ReorderableListStyles.Container);
DefaultListControl.FooterButtonStyle = new GUIStyle(ReorderableListStyles.FooterButton);
DefaultListControl.ItemButtonStyle = new GUIStyle(ReorderableListStyles.ItemButton);
IndexOfChangedItem = -1;
}
private static GUIContent s_Temp = new GUIContent();
#region Title Control
/// <summary>
/// Draw title control for list field.
/// </summary>
/// <remarks>
/// <para>When needed, should be shown immediately before list field.</para>
/// </remarks>
/// <example>
/// <code language="csharp"><![CDATA[
/// ReorderableListGUI.Title(titleContent);
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// <code language="unityscript"><![CDATA[
/// ReorderableListGUI.Title(titleContent);
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// </example>
/// <param name="title">Content for title control.</param>
public static void Title(GUIContent title) {
Rect position = GUILayoutUtility.GetRect(title, ReorderableListStyles.Title);
position.height += 6;
Title(position, title);
}
/// <summary>
/// Draw title control for list field.
/// </summary>
/// <remarks>
/// <para>When needed, should be shown immediately before list field.</para>
/// </remarks>
/// <example>
/// <code language="csharp"><![CDATA[
/// ReorderableListGUI.Title("Your Title");
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// <code language="unityscript"><![CDATA[
/// ReorderableListGUI.Title('Your Title');
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// </example>
/// <param name="title">Text for title control.</param>
public static void Title(string title) {
s_Temp.text = title;
Title(s_Temp);
}
/// <summary>
/// Draw title control for list field with absolute positioning.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="title">Content for title control.</param>
public static void Title(Rect position, GUIContent title) {
if (Event.current.type == EventType.Repaint)
ReorderableListStyles.Title.Draw(position, title, false, false, false, false);
}
/// <summary>
/// Draw title control for list field with absolute positioning.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="text">Text for title control.</param>
public static void Title(Rect position, string text) {
s_Temp.text = text;
Title(position, s_Temp);
}
#endregion
#region List<T> Control
/// <summary>
/// Draw list field control.
/// </summary>
/// <param name="list">The list which can be reordered.</param>
/// <param name="drawItem">Callback to draw list item.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="itemHeight">Height of a single list item.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <typeparam name="T">Type of list item.</typeparam>
private static void DoListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) {
var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight);
ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags);
}
/// <summary>
/// Draw list field control with absolute positioning.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="list">The list which can be reordered.</param>
/// <param name="drawItem">Callback to draw list item.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="itemHeight">Height of a single list item.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <typeparam name="T">Type of list item.</typeparam>
private static void DoListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) {
var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight);
ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, drawEmpty, itemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight) {
DoListField<T>(list, drawItem, drawEmpty, itemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, 0);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, 0);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, null, itemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) {
DoListField<T>(list, drawItem, null, itemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) {
DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, 0);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, null, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) {
DoListField<T>(list, drawItem, null, DefaultItemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) {
DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, 0);
}
/// <summary>
/// Calculate height of list field for absolute positioning.
/// </summary>
/// <param name="itemCount">Count of items in list.</param>
/// <param name="itemHeight">Fixed height of list item.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <returns>
/// Required list height in pixels.
/// </returns>
public static float CalculateListFieldHeight(int itemCount, float itemHeight, ReorderableListFlags flags) {
// We need to push/pop flags so that nested controls are properly calculated.
var restoreFlags = DefaultListControl.Flags;
try {
DefaultListControl.Flags = flags;
return DefaultListControl.CalculateListHeight(itemCount, itemHeight);
}
finally {
DefaultListControl.Flags = restoreFlags;
}
}
/// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(int itemCount, ReorderableListFlags flags) {
return CalculateListFieldHeight(itemCount, DefaultItemHeight, flags);
}
/// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(int itemCount, float itemHeight) {
return CalculateListFieldHeight(itemCount, itemHeight, 0);
}
/// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(int itemCount) {
return CalculateListFieldHeight(itemCount, DefaultItemHeight, 0);
}
#endregion
#region SerializedProperty Control
/// <summary>
/// Draw list field control for serializable property array.
/// </summary>
/// <param name="arrayProperty">Serializable property.</param>
/// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight);
ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags);
}
/// <summary>
/// Draw list field control for serializable property array.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="arrayProperty">Serializable property.</param>
/// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight);
ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField(arrayProperty, 0, drawEmpty, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField(arrayProperty, 0, drawEmpty, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, 0);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, ReorderableListFlags flags) {
DoListField(arrayProperty, 0, null, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, 0, null, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty) {
DoListField(arrayProperty, 0, null, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty) {
DoListFieldAbsolute(position, arrayProperty, 0, null, 0);
}
/// <summary>
/// Calculate height of list field for absolute positioning.
/// </summary>
/// <param name="arrayProperty">Serializable property.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <returns>
/// Required list height in pixels.
/// </returns>
public static float CalculateListFieldHeight(SerializedProperty arrayProperty, ReorderableListFlags flags) {
// We need to push/pop flags so that nested controls are properly calculated.
var restoreFlags = DefaultListControl.Flags;
try {
DefaultListControl.Flags = flags;
return DefaultListControl.CalculateListHeight(new SerializedPropertyAdaptor(arrayProperty));
}
finally {
DefaultListControl.Flags = restoreFlags;
}
}
/// <inheritdoc cref="CalculateListFieldHeight(SerializedProperty, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(SerializedProperty arrayProperty) {
return CalculateListFieldHeight(arrayProperty, 0);
}
#endregion
#region SerializedProperty Control (Fixed Item Height)
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField(arrayProperty, fixedItemHeight, drawEmpty, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField(arrayProperty, fixedItemHeight, drawEmpty, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, 0);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) {
DoListField(arrayProperty, fixedItemHeight, null, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight) {
DoListField(arrayProperty, fixedItemHeight, null, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, 0);
}
#endregion
#region Adaptor Control
/// <summary>
/// Draw list field control for adapted collection.
/// </summary>
/// <param name="adaptor">Reorderable list adaptor.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags = 0) {
ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags);
}
/// <summary>
/// Draw list field control for adapted collection.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="adaptor">Reorderable list adaptor.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags = 0) {
ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField(adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField(adaptor, drawEmpty, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute(position, adaptor, drawEmpty, 0);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor, ReorderableListFlags flags) {
DoListField(adaptor, null, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListFlags flags) {
DoListFieldAbsolute(position, adaptor, null, flags);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor) {
DoListField(adaptor, null, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor) {
DoListFieldAbsolute(position, adaptor, null, 0);
}
/// <summary>
/// Calculate height of list field for adapted collection.
/// </summary>
/// <param name="adaptor">Reorderable list adaptor.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <returns>
/// Required list height in pixels.
/// </returns>
public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor, ReorderableListFlags flags) {
// We need to push/pop flags so that nested controls are properly calculated.
var restoreFlags = DefaultListControl.Flags;
try {
DefaultListControl.Flags = flags;
return DefaultListControl.CalculateListHeight(adaptor);
}
finally {
DefaultListControl.Flags = restoreFlags;
}
}
/// <inheritdoc cref="CalculateListFieldHeight(IReorderableListAdaptor, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor) {
return CalculateListFieldHeight(adaptor, 0);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddSaturateUInt16()
{
var test = new SimpleBinaryOpTest__AddSaturateUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddSaturateUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt16> _fld1;
public Vector128<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddSaturateUInt16 testClass)
{
var result = Sse2.AddSaturate(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSaturateUInt16 testClass)
{
fixed (Vector128<UInt16>* pFld1 = &_fld1)
fixed (Vector128<UInt16>* pFld2 = &_fld2)
{
var result = Sse2.AddSaturate(
Sse2.LoadVector128((UInt16*)(pFld1)),
Sse2.LoadVector128((UInt16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector128<UInt16> _clsVar1;
private static Vector128<UInt16> _clsVar2;
private Vector128<UInt16> _fld1;
private Vector128<UInt16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddSaturateUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
}
public SimpleBinaryOpTest__AddSaturateUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.AddSaturate(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.AddSaturate(
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.AddSaturate(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AddSaturate), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AddSaturate), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AddSaturate), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.AddSaturate(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt16>* pClsVar2 = &_clsVar2)
{
var result = Sse2.AddSaturate(
Sse2.LoadVector128((UInt16*)(pClsVar1)),
Sse2.LoadVector128((UInt16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var result = Sse2.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.AddSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddSaturateUInt16();
var result = Sse2.AddSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddSaturateUInt16();
fixed (Vector128<UInt16>* pFld1 = &test._fld1)
fixed (Vector128<UInt16>* pFld2 = &test._fld2)
{
var result = Sse2.AddSaturate(
Sse2.LoadVector128((UInt16*)(pFld1)),
Sse2.LoadVector128((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.AddSaturate(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt16>* pFld1 = &_fld1)
fixed (Vector128<UInt16>* pFld2 = &_fld2)
{
var result = Sse2.AddSaturate(
Sse2.LoadVector128((UInt16*)(pFld1)),
Sse2.LoadVector128((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.AddSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.AddSaturate(
Sse2.LoadVector128((UInt16*)(&test._fld1)),
Sse2.LoadVector128((UInt16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Sse2Verify.AddSaturate(left[0], right[0], result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Sse2Verify.AddSaturate(left[i], right[i], result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AddSaturate)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Entities;
using Abp.Domain.Uow;
using Abp.MultiTenancy;
using Abp.Reflection;
using Abp.Reflection.Extensions;
namespace Abp.Domain.Repositories
{
/// <summary>
/// Base class to implement <see cref="IRepository{TEntity,TPrimaryKey}"/>.
/// It implements some methods in most simple way.
/// </summary>
/// <typeparam name="TEntity">Type of the Entity for this repository</typeparam>
/// <typeparam name="TPrimaryKey">Primary key of the entity</typeparam>
public abstract class AbpRepositoryBase<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey>, IUnitOfWorkManagerAccessor
where TEntity : class, IEntity<TPrimaryKey>
{
/// <summary>
/// The multi tenancy side
/// </summary>
public static MultiTenancySides? MultiTenancySide { get; private set; }
public IUnitOfWorkManager UnitOfWorkManager { get; set; }
public IIocResolver IocResolver { get; set; }
static AbpRepositoryBase()
{
var attr = typeof(TEntity).GetSingleAttributeOfTypeOrBaseTypesOrNull<MultiTenancySideAttribute>();
if (attr != null)
{
MultiTenancySide = attr.Side;
}
}
public abstract IQueryable<TEntity> GetAll();
public virtual IQueryable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] propertySelectors)
{
return GetAll();
}
public virtual List<TEntity> GetAllList()
{
return GetAll().ToList();
}
public virtual Task<List<TEntity>> GetAllListAsync()
{
return Task.FromResult(GetAllList());
}
public virtual List<TEntity> GetAllList(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Where(predicate).ToList();
}
public virtual Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(GetAllList(predicate));
}
public virtual T Query<T>(Func<IQueryable<TEntity>, T> queryMethod)
{
return queryMethod(GetAll());
}
public virtual TEntity Get(TPrimaryKey id)
{
var entity = FirstOrDefault(id);
if (entity == null)
{
throw new EntityNotFoundException(typeof(TEntity), id);
}
return entity;
}
public virtual async Task<TEntity> GetAsync(TPrimaryKey id)
{
var entity = await FirstOrDefaultAsync(id);
if (entity == null)
{
throw new EntityNotFoundException(typeof(TEntity), id);
}
return entity;
}
public virtual TEntity Single(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Single(predicate);
}
public virtual Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(Single(predicate));
}
public virtual TEntity FirstOrDefault(TPrimaryKey id)
{
return GetAll().FirstOrDefault(CreateEqualityExpressionForId(id));
}
public virtual Task<TEntity> FirstOrDefaultAsync(TPrimaryKey id)
{
return Task.FromResult(FirstOrDefault(id));
}
public virtual TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().FirstOrDefault(predicate);
}
public virtual Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(FirstOrDefault(predicate));
}
public virtual TEntity Load(TPrimaryKey id)
{
return Get(id);
}
public abstract TEntity Insert(TEntity entity);
public virtual Task<TEntity> InsertAsync(TEntity entity)
{
return Task.FromResult(Insert(entity));
}
public virtual TPrimaryKey InsertAndGetId(TEntity entity)
{
return Insert(entity).Id;
}
public virtual async Task<TPrimaryKey> InsertAndGetIdAsync(TEntity entity)
{
var insertedEntity = await InsertAsync(entity);
return insertedEntity.Id;
}
public virtual TEntity InsertOrUpdate(TEntity entity)
{
return entity.IsTransient()
? Insert(entity)
: Update(entity);
}
public virtual async Task<TEntity> InsertOrUpdateAsync(TEntity entity)
{
return entity.IsTransient()
? await InsertAsync(entity)
: await UpdateAsync(entity);
}
public virtual TPrimaryKey InsertOrUpdateAndGetId(TEntity entity)
{
return InsertOrUpdate(entity).Id;
}
public virtual async Task<TPrimaryKey> InsertOrUpdateAndGetIdAsync(TEntity entity)
{
var insertedEntity = await InsertOrUpdateAsync(entity);
return insertedEntity.Id;
}
public abstract TEntity Update(TEntity entity);
public virtual Task<TEntity> UpdateAsync(TEntity entity)
{
return Task.FromResult(Update(entity));
}
public virtual TEntity Update(TPrimaryKey id, Action<TEntity> updateAction)
{
var entity = Get(id);
updateAction(entity);
return entity;
}
public virtual async Task<TEntity> UpdateAsync(TPrimaryKey id, Func<TEntity, Task> updateAction)
{
var entity = await GetAsync(id);
await updateAction(entity);
return entity;
}
public abstract void Delete(TEntity entity);
public virtual Task DeleteAsync(TEntity entity)
{
Delete(entity);
return Task.CompletedTask;
}
public abstract void Delete(TPrimaryKey id);
public virtual Task DeleteAsync(TPrimaryKey id)
{
Delete(id);
return Task.CompletedTask;
}
public virtual void Delete(Expression<Func<TEntity, bool>> predicate)
{
foreach (var entity in GetAllList(predicate))
{
Delete(entity);
}
}
public virtual async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate)
{
var entities = await GetAllListAsync(predicate);
foreach (var entity in entities)
{
await DeleteAsync(entity);
}
}
public virtual int Count()
{
return GetAll().Count();
}
public virtual Task<int> CountAsync()
{
return Task.FromResult(Count());
}
public virtual int Count(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Count(predicate);
}
public virtual Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(Count(predicate));
}
public virtual long LongCount()
{
return GetAll().LongCount();
}
public virtual Task<long> LongCountAsync()
{
return Task.FromResult(LongCount());
}
public virtual long LongCount(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().LongCount(predicate);
}
public virtual Task<long> LongCountAsync(Expression<Func<TEntity, bool>> predicate)
{
return Task.FromResult(LongCount(predicate));
}
protected virtual Expression<Func<TEntity, bool>> CreateEqualityExpressionForId(TPrimaryKey id)
{
var lambdaParam = Expression.Parameter(typeof(TEntity));
var leftExpression = Expression.PropertyOrField(lambdaParam, "Id");
var idValue = Convert.ChangeType(id, typeof(TPrimaryKey));
Expression<Func<object>> closure = () => idValue;
var rightExpression = Expression.Convert(closure.Body, leftExpression.Type);
var lambdaBody = Expression.Equal(leftExpression, rightExpression);
return Expression.Lambda<Func<TEntity, bool>>(lambdaBody, lambdaParam);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Searches for resources in Assembly manifest, used
** for assembly-based resource lookup.
**
**
===========================================================*/
namespace System.Resources {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
//
// Note: this type is integral to the construction of exception objects,
// and sometimes this has to be done in low memory situtations (OOM) or
// to create TypeInitializationExceptions due to failure of a static class
// constructor. This type needs to be extremely careful and assume that
// any type it references may have previously failed to construct, so statics
// belonging to that type may not be initialized. FrameworkEventSource.Log
// is one such example.
//
internal class ManifestBasedResourceGroveler : IResourceGroveler
{
private ResourceManager.ResourceManagerMediator _mediator;
public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator)
{
// here and below: convert asserts to preconditions where appropriate when we get
// contracts story in place.
Contract.Requires(mediator != null, "mediator shouldn't be null; check caller");
_mediator = mediator;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
Debug.Assert(culture != null, "culture shouldn't be null; check caller");
Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
ResourceSet rs = null;
Stream stream = null;
RuntimeAssembly satellite = null;
// 1. Fixups for ultimate fallbacks
CultureInfo lookForCulture = UltimateFallbackFixup(culture);
// 2. Look for satellite assembly or main assembly, as appropriate
if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
// don't bother looking in satellites in this case
satellite = _mediator.MainAssembly;
}
#if RESOURCE_SATELLITE_CONFIG
// If our config file says the satellite isn't here, don't ask for it.
else if (!lookForCulture.HasInvariantCultureName && !_mediator.TryLookingForSatellite(lookForCulture))
{
satellite = null;
}
#endif
else
{
satellite = GetSatelliteAssembly(lookForCulture, ref stackMark);
if (satellite == null)
{
bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite));
// didn't find satellite, give error if necessary
if (raiseException)
{
HandleSatelliteMissing();
}
}
}
// get resource file name we'll search for. Note, be careful if you're moving this statement
// around because lookForCulture may be modified from originally requested culture above.
String fileName = _mediator.GetResourceFileName(lookForCulture);
// 3. If we identified an assembly to search; look in manifest resource stream for resource file
if (satellite != null)
{
// Handle case in here where someone added a callback for assembly load events.
// While no other threads have called into GetResourceSet, our own thread can!
// At that point, we could already have an RS in our hash table, and we don't
// want to add it twice.
lock (localResourceSets)
{
localResourceSets.TryGetValue(culture.Name, out rs);
}
stream = GetManifestResourceStream(satellite, fileName, ref stackMark);
}
// 4a. Found a stream; create a ResourceSet if possible
if (createIfNotExists && stream != null && rs == null)
{
rs = CreateResourceSet(stream, satellite);
}
else if (stream == null && tryParents)
{
// 4b. Didn't find stream; give error if necessary
bool raiseException = culture.HasInvariantCultureName;
if (raiseException)
{
HandleResourceStreamMissing(fileName);
}
}
return rs;
}
private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture)
{
CultureInfo returnCulture = lookForCulture;
// If our neutral resources were written in this culture AND we know the main assembly
// does NOT contain neutral resources, don't probe for this satellite.
if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name &&
_mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
returnCulture = CultureInfo.InvariantCulture;
}
else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)
{
returnCulture = _mediator.NeutralResourcesCulture;
}
return returnCulture;
}
internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation)
{
Debug.Assert(a != null, "assembly != null");
string cultureName = null;
short fallback = 0;
if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(),
JitHelpers.GetStringHandleOnStack(ref cultureName),
out fallback)) {
if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite) {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", fallback));
}
fallbackLocation = (UltimateResourceFallbackLocation)fallback;
}
else {
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
try
{
CultureInfo c = CultureInfo.GetCultureInfo(cultureName);
return c;
}
catch (ArgumentException e)
{ // we should catch ArgumentException only.
// Note we could go into infinite loops if mscorlib's
// NeutralResourcesLanguageAttribute is mangled. If this assert
// fires, please fix the build process for the BCL directory.
if (a == typeof(Object).Assembly)
{
Debug.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
return CultureInfo.InvariantCulture;
}
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture", a.ToString(), cultureName), e);
}
}
// Constructs a new ResourceSet for a given file name. The logic in
// here avoids a ReflectionPermission check for our RuntimeResourceSet
// for perf and working set reasons.
// Use the assembly to resolve assembly manifest resource references.
// Note that is can be null, but probably shouldn't be.
// This method could use some refactoring. One thing at a time.
internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
{
Debug.Assert(store != null, "I need a Stream!");
// Check to see if this is a Stream the ResourceManager understands,
// and check for the correct resource reader type.
if (store.CanSeek && store.Length > 4)
{
long startPos = store.Position;
// not disposing because we want to leave stream open
BinaryReader br = new BinaryReader(store);
// Look for our magic number as a little endian Int32.
int bytes = br.ReadInt32();
if (bytes == ResourceManager.MagicNumber)
{
int resMgrHeaderVersion = br.ReadInt32();
String readerTypeName = null, resSetTypeName = null;
if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber)
{
br.ReadInt32(); // We don't want the number of bytes to skip.
readerTypeName = System.CoreLib.FixupCoreLibName(br.ReadString());
resSetTypeName = System.CoreLib.FixupCoreLibName(br.ReadString());
}
else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber)
{
// Assume that the future ResourceManager headers will
// have two strings for us - the reader type name and
// resource set type name. Read those, then use the num
// bytes to skip field to correct our position.
int numBytesToSkip = br.ReadInt32();
long endPosition = br.BaseStream.Position + numBytesToSkip;
readerTypeName = System.CoreLib.FixupCoreLibName(br.ReadString());
resSetTypeName = System.CoreLib.FixupCoreLibName(br.ReadString());
br.BaseStream.Seek(endPosition, SeekOrigin.Begin);
}
else
{
// resMgrHeaderVersion is older than this ResMgr version.
// We should add in backwards compatibility support here.
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ObsoleteResourcesFile", _mediator.MainAssembly.GetSimpleName()));
}
store.Position = startPos;
// Perf optimization - Don't use Reflection for our defaults.
// Note there are two different sets of strings here - the
// assembly qualified strings emitted by ResourceWriter, and
// the abbreviated ones emitted by InternalResGen.
if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName))
{
RuntimeResourceSet rs;
#if LOOSELY_LINKED_RESOURCE_REFERENCE
rs = new RuntimeResourceSet(store, assembly);
#else
rs = new RuntimeResourceSet(store);
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
return rs;
}
else
{
// we do not want to use partial binding here.
Type readerType = Type.GetType(readerTypeName, true);
Object[] args = new Object[1];
args[0] = store;
IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args);
Object[] resourceSetArgs =
#if LOOSELY_LINKED_RESOURCE_REFERENCE
new Object[2];
#else
new Object[1];
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
resourceSetArgs[0] = reader;
#if LOOSELY_LINKED_RESOURCE_REFERENCE
resourceSetArgs[1] = assembly;
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
Type resSetType;
if (_mediator.UserResourceSet == null)
{
Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
resSetType = Type.GetType(resSetTypeName, true, false);
}
else
resSetType = _mediator.UserResourceSet;
ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance,
null,
resourceSetArgs,
null,
null);
return rs;
}
}
else
{
store.Position = startPos;
}
}
if (_mediator.UserResourceSet == null)
{
// Explicitly avoid CreateInstance if possible, because it
// requires ReflectionPermission to call private & protected
// constructors.
#if LOOSELY_LINKED_RESOURCE_REFERENCE
return new RuntimeResourceSet(store, assembly);
#else
return new RuntimeResourceSet(store);
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
}
else
{
Object[] args = new Object[2];
args[0] = store;
args[1] = assembly;
try
{
ResourceSet rs = null;
// Add in a check for a constructor taking in an assembly first.
try
{
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
return rs;
}
catch (MissingMethodException) { }
args = new Object[1];
args[0] = store;
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
#if LOOSELY_LINKED_RESOURCE_REFERENCE
rs.Assembly = assembly;
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
return rs;
}
catch (MissingMethodException e)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", _mediator.UserResourceSet.AssemblyQualifiedName), e);
}
}
}
private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark)
{
Contract.Requires(satellite != null, "satellite shouldn't be null; check caller");
Contract.Requires(fileName != null, "fileName shouldn't be null; check caller");
// If we're looking in the main assembly AND if the main assembly was the person who
// created the ResourceManager, skip a security check for private manifest resources.
bool canSkipSecurityCheck = (_mediator.MainAssembly == satellite)
&& (_mediator.CallingAssembly == _mediator.MainAssembly);
Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName, canSkipSecurityCheck, ref stackMark);
if (stream == null)
{
stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName);
}
return stream;
}
// Looks up a .resources file in the assembly manifest using
// case-insensitive lookup rules. Yes, this is slow. The metadata
// dev lead refuses to make all assembly manifest resource lookups case-insensitive,
// even optionally case-insensitive.
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name)
{
Contract.Requires(satellite != null, "satellite shouldn't be null; check caller");
Contract.Requires(name != null, "name shouldn't be null; check caller");
StringBuilder sb = new StringBuilder();
if (_mediator.LocationInfo != null)
{
String nameSpace = _mediator.LocationInfo.Namespace;
if (nameSpace != null)
{
sb.Append(nameSpace);
if (name != null)
sb.Append(Type.Delimiter);
}
}
sb.Append(name);
String givenName = sb.ToString();
CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo;
String canonicalName = null;
foreach (String existingName in satellite.GetManifestResourceNames())
{
if (comparer.Compare(existingName, givenName, CompareOptions.IgnoreCase) == 0)
{
if (canonicalName == null)
{
canonicalName = existingName;
}
else
{
throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_MultipleBlobs", givenName, satellite.ToString()));
}
}
}
if (canonicalName == null)
{
return null;
}
// If we're looking in the main assembly AND if the main
// assembly was the person who created the ResourceManager,
// skip a security check for private manifest resources.
bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark)
{
if (!_mediator.LookedForSatelliteContractVersion)
{
_mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly);
_mediator.LookedForSatelliteContractVersion = true;
}
RuntimeAssembly satellite = null;
String satAssemblyName = GetSatelliteAssemblyName();
// Look up the satellite assembly, but don't let problems
// like a partially signed satellite assembly stop us from
// doing fallback and displaying something to the user.
// Yet also somehow log this error for a developer.
try
{
satellite = _mediator.MainAssembly.InternalGetSatelliteAssembly(satAssemblyName, lookForCulture, _mediator.SatelliteContractVersion, false, ref stackMark);
}
// Jun 08: for cases other than ACCESS_DENIED, we'll assert instead of throw to give release builds more opportunity to fallback.
catch (FileLoadException fle)
{
// Ignore cases where the loader gets an access
// denied back from the OS. This showed up for
// href-run exe's at one point.
int hr = fle._HResult;
if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED))
{
Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
}
}
// Don't throw for zero-length satellite assemblies, for compat with v1
catch (BadImageFormatException bife)
{
Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
}
return satellite;
}
// Perf optimization - Don't use Reflection for most cases with
// our .resources files. This makes our code run faster and we can
// creating a ResourceReader via Reflection. This would incur
// a security check (since the link-time check on the constructor that
// takes a String is turned into a full demand with a stack walk)
// and causes partially trusted localized apps to fail.
private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName)
{
Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
if (_mediator.UserResourceSet != null)
return false;
// Ignore the actual version of the ResourceReader and
// RuntimeResourceSet classes. Let those classes deal with
// versioning themselves.
AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName);
if (readerTypeName != null)
{
if (!ResourceManager.CompareNames(readerTypeName, ResourceManager.ResReaderTypeName, mscorlib))
return false;
}
if (resSetTypeName != null)
{
if (!ResourceManager.CompareNames(resSetTypeName, ResourceManager.ResSetTypeName, mscorlib))
return false;
}
return true;
}
private String GetSatelliteAssemblyName()
{
String satAssemblyName = _mediator.MainAssembly.GetSimpleName();
satAssemblyName += ".resources";
return satAssemblyName;
}
private void HandleSatelliteMissing()
{
String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll";
if (_mediator.SatelliteContractVersion != null)
{
satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString();
}
AssemblyName an = new AssemblyName();
an.SetPublicKey(_mediator.MainAssembly.GetPublicKey());
byte[] token = an.GetPublicKeyToken();
int iLen = token.Length;
StringBuilder publicKeyTok = new StringBuilder(iLen * 2);
for (int i = 0; i < iLen; i++)
{
publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture));
}
satAssemName += ", PublicKeyToken=" + publicKeyTok;
String missingCultureName = _mediator.NeutralResourcesCulture.Name;
if (missingCultureName.Length == 0)
{
missingCultureName = "<invariant>";
}
throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName);
}
private void HandleResourceStreamMissing(String fileName)
{
// Keep people from bothering me about resources problems
if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name))
{
// This would break CultureInfo & all our exceptions.
Debug.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
// We cannot continue further - simply FailFast.
string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!";
System.Environment.FailFast(mesgFailFast);
}
// We really don't think this should happen - we always
// expect the neutral locale's resources to be present.
String resName = String.Empty;
if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
resName = _mediator.LocationInfo.Namespace + Type.Delimiter;
resName += fileName;
throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralAsm", resName, _mediator.MainAssembly.GetSimpleName()));
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace CubeBrowser.Old.App.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using UIKit;
namespace MaterialComponents.MaterialTextFields
{
//public interface IMDCTextInput {}
// @protocol MDCTextInput <NSObject>
//[Protocol]//, Model]
[BaseType (typeof(NSObject))]
[Protocol, Model]
interface MDCTextInput
{
// @required @property (copy, nonatomic) NSAttributedString * _Nullable attributedPlaceholder;
[Abstract]
[NullAllowed, Export("attributedPlaceholder", ArgumentSemantic.Copy)]
NSAttributedString AttributedPlaceholder { get; set; }
// @required @property (copy, nonatomic) NSAttributedString * _Nullable attributedText;
[Abstract]
[NullAllowed, Export("attributedText", ArgumentSemantic.Copy)]
NSAttributedString AttributedText { get; set; }
// @required @property (copy, nonatomic) UIBezierPath * _Nullable borderPath __attribute__((annotate("ui_appearance_selector")));
[Abstract]
[NullAllowed, Export("borderPath", ArgumentSemantic.Copy)]
UIBezierPath BorderPath { get; set; }
// @required @property (nonatomic, strong) MDCTextInputBorderView * _Nullable borderView;
[Abstract]
[NullAllowed, Export("borderView", ArgumentSemantic.Strong)]
MDCTextInputBorderView BorderView { get; set; }
// @required @property (readonly, nonatomic, strong) UIButton * _Nonnull clearButton;
[Abstract]
[Export("clearButton", ArgumentSemantic.Strong)]
UIButton ClearButton { get; }
// @required @property (assign, nonatomic) UITextFieldViewMode clearButtonMode __attribute__((annotate("ui_appearance_selector")));
[Abstract]
[Export("clearButtonMode", ArgumentSemantic.Assign)]
UITextFieldViewMode ClearButtonMode { get; set; }
// @required @property (nonatomic, strong) UIColor * _Nullable cursorColor __attribute__((annotate("ui_appearance_selector")));
[Abstract]
[NullAllowed, Export("cursorColor", ArgumentSemantic.Strong)]
UIColor CursorColor { get; set; }
// @required @property (readonly, getter = isEditing, assign, nonatomic) BOOL editing;
[Abstract]
[Export("editing")]
bool Editing { [Bind("isEditing")] get; }
// @required @property (getter = isEnabled, assign, nonatomic) BOOL enabled;
[Abstract]
[Export("enabled")]
bool Enabled { [Bind("isEnabled")] get; set; }
// @required @property (nonatomic, strong) UIFont * _Nullable font;
[Abstract]
[NullAllowed, Export("font", ArgumentSemantic.Strong)]
UIFont Font { get; set; }
// @required @property (assign, nonatomic) BOOL hidesPlaceholderOnInput;
[Abstract]
[Export("hidesPlaceholderOnInput")]
bool HidesPlaceholderOnInput { get; set; }
// @required @property (readonly, nonatomic, strong) UILabel * _Nonnull leadingUnderlineLabel;
[Abstract]
[Export("leadingUnderlineLabel", ArgumentSemantic.Strong)]
UILabel LeadingUnderlineLabel { get; }
// @required @property (nonatomic, setter = mdc_setAdjustsFontForContentSizeCategory:) BOOL mdc_adjustsFontForContentSizeCategory __attribute__((annotate("ui_appearance_selector")));
[Abstract]
[Export("mdc_adjustsFontForContentSizeCategory")]
bool Mdc_adjustsFontForContentSizeCategory { get; [Bind("mdc_setAdjustsFontForContentSizeCategory:")] set; }
// @required @property (copy, nonatomic) NSString * _Nullable placeholder;
[Abstract]
[NullAllowed, Export("placeholder")]
string Placeholder { get; set; }
// @required @property (readonly, nonatomic, strong) UILabel * _Nonnull placeholderLabel;
[Abstract]
[Export("placeholderLabel", ArgumentSemantic.Strong)]
UILabel PlaceholderLabel { get; }
[Wrap("WeakPositioningDelegate")]//, Abstract]
[NullAllowed]
MDCTextInputPositioningDelegate PositioningDelegate { get; set; }
// @required @property (nonatomic, weak) id<MDCTextInputPositioningDelegate> _Nullable positioningDelegate;
//[Abstract]
[NullAllowed, Export("positioningDelegate", ArgumentSemantic.Weak)]
NSObject WeakPositioningDelegate { get; set; }
// @required @property (copy, nonatomic) NSString * _Nullable text;
[Abstract]
[NullAllowed, Export("text")]
string Text { get; set; }
// @required @property (nonatomic, strong) UIColor * _Nullable textColor;
[Abstract]
[NullAllowed, Export("textColor", ArgumentSemantic.Strong)]
UIColor TextColor { get; set; }
// @required @property (readonly, assign, nonatomic) UIEdgeInsets textInsets;
[Abstract]
[Export("textInsets", ArgumentSemantic.Assign)]
UIEdgeInsets TextInsets { get; }
// @required @property (assign, nonatomic) MDCTextInputTextInsetsMode textInsetsMode __attribute__((annotate("ui_appearance_selector")));
[Abstract]
[Export("textInsetsMode", ArgumentSemantic.Assign)]
MDCTextInputTextInsetsMode TextInsetsMode { get; set; }
// @required @property (readonly, nonatomic, strong) UILabel * _Nonnull trailingUnderlineLabel;
[Abstract]
[Export("trailingUnderlineLabel", ArgumentSemantic.Strong)]
UILabel TrailingUnderlineLabel { get; }
// @required @property (nonatomic, strong) UIView * _Nullable trailingView;
[Abstract]
[NullAllowed, Export("trailingView", ArgumentSemantic.Strong)]
UIView TrailingView { get; set; }
// @required @property (assign, nonatomic) UITextFieldViewMode trailingViewMode;
[Abstract]
[Export("trailingViewMode", ArgumentSemantic.Assign)]
UITextFieldViewMode TrailingViewMode { get; set; }
// @required @property (readonly, nonatomic, strong) MDCTextInputUnderlineView * _Nullable underline;
[Abstract]
[NullAllowed, Export("underline", ArgumentSemantic.Strong)]
MDCTextInputUnderlineView Underline { get; }
}
//public interface IMDCMultilineTextInput {}
// @protocol MDCMultilineTextInput <MDCTextInput>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface MDCMultilineTextInput : MDCTextInput
{
// @required @property (assign, nonatomic) BOOL expandsOnOverflow __attribute__((annotate("ui_appearance_selector")));
[Abstract]
[Export("expandsOnOverflow")]
bool ExpandsOnOverflow { get; set; }
// @required @property (assign, nonatomic) NSUInteger minimumLines __attribute__((annotate("ui_appearance_selector")));
[Abstract]
[Export("minimumLines")]
nuint MinimumLines { get; set; }
}
// @interface MDCTextInputUnderlineView : UIView <NSCopying, NSCoding>
[BaseType(typeof(UIView))]
interface MDCTextInputUnderlineView : INSCopying, INSCoding {
// @property (nonatomic, strong) UIColor * color;
[Export("color", ArgumentSemantic.Strong)]
UIColor Color { get; set; }
// @property (nonatomic, strong) UIColor * disabledColor;
[Export("disabledColor", ArgumentSemantic.Strong)]
UIColor DisabledColor { get; set; }
// @property (assign, nonatomic) BOOL enabled;
[Export("enabled")]
bool Enabled { get; set; }
// @property (assign, nonatomic) CGFloat lineHeight;
[Export("lineHeight")]
nfloat LineHeight { get; set; }
}
// @interface MDCTextField : UITextField <MDCTextInput>
[BaseType(typeof(UITextField))]
//[Model]
interface MDCTextField : MDCTextInput
{
[DesignatedInitializer]
[Export("initWithFrame:")]
IntPtr Constructor(CGRect frame);
// @property (nonatomic, strong) UIView * _Nullable leadingView;
[NullAllowed, Export("leadingView", ArgumentSemantic.Strong)]
UIView LeadingView { get; set; }
// @property (assign, nonatomic) UITextFieldViewMode leadingViewMode;
[Export("leadingViewMode", ArgumentSemantic.Assign)]
UITextFieldViewMode LeadingViewMode { get; set; }
}
//public interface IMDCTextInputPositioningDelegate { }
// @protocol MDCTextInputPositioningDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface MDCTextInputPositioningDelegate// : IMDCTextInputPositioningDelegate
{
// @optional -(UIEdgeInsets)textInsets:(UIEdgeInsets)defaultInsets;
[Export("textInsets:")]
UIEdgeInsets TextInsets(UIEdgeInsets defaultInsets);
// @optional -(CGRect)editingRectForBounds:(CGRect)bounds defaultRect:(CGRect)defaultRect;
[Export("editingRectForBounds:defaultRect:")]
CGRect EditingRectForBounds(CGRect bounds, CGRect defaultRect);
// VER 35.3.0
// @optional -(void)textInputDidLayoutSubviews;
[Export("textInputDidLayoutSubviews")]
void TextInputDidLayoutSubviews();
// VER 35.3.0
// @optional -(void)textInputDidUpdateConstraints;
[Export("textInputDidUpdateConstraints")]
void TextInputDidUpdateConstraints();
}
// @protocol MDCMultilineTextInputLayoutDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface MDCMultilineTextInputLayoutDelegate
{
// @optional -(void)multilineTextField:(id<MDCMultilineTextInput> _Nonnull)multilineTextField didChangeContentSize:(CGSize)size;
[Export("multilineTextField:didChangeContentSize:")]
void DidChangeContentSize(MDCMultilineTextInput multilineTextField, CGSize size);
}
[Static]
// XXX: [Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const _Nonnull MDCTextFieldTextDidSetTextNotification;
[Field ("MDCTextFieldTextDidSetTextNotification", "__Internal")]
NSString MDCTextFieldTextDidSetTextNotification { get; }
// extern const CGFloat MDCTextInputDefaultBorderRadius;
[Field("MDCTextInputDefaultBorderRadius", "__Internal")]
nfloat MDCTextInputDefaultBorderRadius { get; }
// extern const CGFloat MDCTextInputDefaultUnderlineActiveHeight;
[Field("MDCTextInputDefaultUnderlineActiveHeight", "__Internal")]
nfloat MDCTextInputDefaultUnderlineActiveHeight { get; }
}
//public interface IMDCTextInputCharacterCounter {}
// @protocol MDCTextInputCharacterCounter <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface MDCTextInputCharacterCounter//: IMDCTextInputCharacterCounter
{
// @required -(NSUInteger)characterCountForTextInput:(UIView<MDCTextInput> * _Nullable)textInput;
[Abstract]
[Export ("characterCountForTextInput:")]
nuint CharacterCountForTextInput ([NullAllowed] MDCTextInput textInput);
}
// @interface MDCTextInputAllCharactersCounter : NSObject <MDCTextInputCharacterCounter>
[BaseType (typeof(NSObject))]
interface MDCTextInputAllCharactersCounter : MDCTextInputCharacterCounter
{
}
//public interface IMDCTextInputController {}
// @protocol MDCTextInputController <NSObject, NSCoding, NSCopying, MDCTextInputPositioningDelegate>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface MDCTextInputController : INSCoding, INSCopying, MDCTextInputPositioningDelegate//, IMDCTextInputController
{
// @required @property (nonatomic, strong) UIColor * _Null_unspecified activeColor;
[Abstract]
[Export("activeColor", ArgumentSemantic.Strong)]
UIColor ActiveColor { get; set; }
// @required @property (nonatomic, strong, class) UIColor * _Null_unspecified activeColorDefault;
[Static, Abstract]
[Export("activeColorDefault", ArgumentSemantic.Strong)]
UIColor ActiveColorDefault { get; set; }
// @required @property (nonatomic, weak) id<MDCTextInputCharacterCounter> _Null_unspecified characterCounter;
[Abstract]
[Export ("characterCounter", ArgumentSemantic.Weak)]
MDCTextInputCharacterCounter CharacterCounter { get; set; }
// @required @property (assign, nonatomic) NSUInteger characterCountMax;
[Abstract]
[Export ("characterCountMax")]
nuint CharacterCountMax { get; set; }
// @required @property (assign, nonatomic) UITextFieldViewMode characterCountViewMode;
[Abstract]
[Export ("characterCountViewMode", ArgumentSemantic.Assign)]
UITextFieldViewMode CharacterCountViewMode { get; set; }
// @required @property (nonatomic, strong) UIColor * _Null_unspecified disabledColor;
[Abstract]
[Export("disabledColor", ArgumentSemantic.Strong)]
UIColor DisabledColor { get; set; }
// @required @property (nonatomic, strong, class) UIColor * _Null_unspecified disabledColorDefault;
[Static, Abstract]
[Export("disabledColorDefault", ArgumentSemantic.Strong)]
UIColor DisabledColorDefault { get; set; }
// @required @property (nonatomic, strong) UIColor * _Null_unspecified errorColor;
[Abstract]
[Export ("errorColor", ArgumentSemantic.Strong)]
UIColor ErrorColor { get; set; }
// @required @property (nonatomic, strong, class) UIColor * _Null_unspecified errorColorDefault;
[Static, Abstract]
[Export ("errorColorDefault", ArgumentSemantic.Strong)]
UIColor ErrorColorDefault { get; set; }
// @required @property (readonly, copy, nonatomic) NSString * _Nullable errorText;
[Abstract]
[NullAllowed, Export ("errorText")]
string ErrorText { get; }
// @required @property (copy, nonatomic) NSString * _Nullable helperText;
[Abstract]
[NullAllowed, Export ("helperText")]
string HelperText { get; set; }
// @required @property (nonatomic, strong) UIColor * _Null_unspecified inlinePlaceholderColor;
[Abstract]
[Export ("inlinePlaceholderColor", ArgumentSemantic.Strong)]
UIColor InlinePlaceholderColor { get; set; }
// @required @property (nonatomic, strong, class) UIColor * _Null_unspecified inlinePlaceholderColorDefault;
[Static, Abstract]
[Export ("inlinePlaceholderColorDefault", ArgumentSemantic.Strong)]
UIColor InlinePlaceholderColorDefault { get; set; }
// @required @property (nonatomic, strong) UIFont * _Null_unspecified inlinePlaceholderFont;
[Abstract]
[Export("inlinePlaceholderFont", ArgumentSemantic.Strong)]
UIFont InlinePlaceholderFont { get; set; }
// @required @property (nonatomic, strong, class) UIFont * _Null_unspecified inlinePlaceholderFontDefault;
[Static, Abstract]
[Export("inlinePlaceholderFontDefault", ArgumentSemantic.Strong)]
UIFont InlinePlaceholderFontDefault { get; set; }
// @required @property (nonatomic, strong) UIFont * _Null_unspecified leadingUnderlineLabelFont;
[Abstract]
[Export("leadingUnderlineLabelFont", ArgumentSemantic.Strong)]
UIFont LeadingUnderlineLabelFont { get; set; }
// @required @property (nonatomic, strong, class) UIFont * _Null_unspecified leadingUnderlineLabelFontDefault;
[Static, Abstract]
[Export("leadingUnderlineLabelFontDefault", ArgumentSemantic.Strong)]
UIFont LeadingUnderlineLabelFontDefault { get; set; }
// @required @property (nonatomic, strong) UIColor * _Null_unspecified leadingUnderlineLabelTextColor;
[Abstract]
[Export("leadingUnderlineLabelTextColor", ArgumentSemantic.Strong)]
UIColor LeadingUnderlineLabelTextColor { get; set; }
// @required @property (nonatomic, strong, class) UIColor * _Null_unspecified leadingUnderlineLabelTextColorDefault;
[Static, Abstract]
[Export("leadingUnderlineLabelTextColorDefault", ArgumentSemantic.Strong)]
UIColor LeadingUnderlineLabelTextColorDefault { get; set; }
// @required @property (assign, readwrite, nonatomic, setter = mdc_setAdjustsFontForContentSizeCategory:) BOOL mdc_adjustsFontForContentSizeCategory;
[Abstract]
[Export ("mdc_adjustsFontForContentSizeCategory")]
bool Mdc_adjustsFontForContentSizeCategory { get; [Bind ("mdc_setAdjustsFontForContentSizeCategory:")] set; }
// @required @property (assign, nonatomic, class) BOOL mdc_adjustsFontForContentSizeCategoryDefault;
[Static, Abstract]
[Export ("mdc_adjustsFontForContentSizeCategoryDefault")]
bool Mdc_adjustsFontForContentSizeCategoryDefault { get; set; }
// @required @property (nonatomic, strong) UIColor * _Null_unspecified normalColor;
[Abstract]
[Export("normalColor", ArgumentSemantic.Strong)]
UIColor NormalColor { get; set; }
// @required @property (nonatomic, strong, class) UIColor * _Null_unspecified normalColorDefault;
[Static, Abstract]
[Export("normalColorDefault", ArgumentSemantic.Strong)]
UIColor NormalColorDefault { get; set; }
// @required @property (copy, nonatomic) NSString * _Nullable placeholderText;
[Abstract]
[NullAllowed, Export("placeholderText")]
string PlaceholderText { get; set; }
// @required @property (assign, nonatomic) UIRectCorner roundedCorners;
[Abstract]
[Export("roundedCorners", ArgumentSemantic.Assign)]
UIRectCorner RoundedCorners { get; set; }
// @required @property (assign, nonatomic, class) UIRectCorner roundedCornersDefault;
[Static, Abstract]
[Export("roundedCornersDefault", ArgumentSemantic.Assign)]
UIRectCorner RoundedCornersDefault { get; set; }
// @required @property (nonatomic, strong) UIView<MDCTextInput> * _Nullable textInput;
[Abstract]
[NullAllowed, Export ("textInput", ArgumentSemantic.Strong)]
MDCTextInput TextInput { get; set; }
// @required @property (nonatomic, strong) UIFont * _Null_unspecified trailingUnderlineLabelFont;
[Abstract]
[Export("trailingUnderlineLabelFont", ArgumentSemantic.Strong)]
UIFont TrailingUnderlineLabelFont { get; set; }
// @required @property (nonatomic, strong, class) UIFont * _Null_unspecified trailingUnderlineLabelFontDefault;
[Static, Abstract]
[Export("trailingUnderlineLabelFontDefault", ArgumentSemantic.Strong)]
UIFont TrailingUnderlineLabelFontDefault { get; set; }
// @required @property (nonatomic, strong) UIColor * _Nullable trailingUnderlineLabelTextColor;
[Abstract]
[NullAllowed, Export("trailingUnderlineLabelTextColor", ArgumentSemantic.Strong)]
UIColor TrailingUnderlineLabelTextColor { get; set; }
// @required @property (nonatomic, strong, class) UIColor * _Nullable trailingUnderlineLabelTextColorDefault;
[Static, Abstract]
[NullAllowed, Export("trailingUnderlineLabelTextColorDefault", ArgumentSemantic.Strong)]
UIColor TrailingUnderlineLabelTextColorDefault { get; set; }
// @required @property (assign, nonatomic) UITextFieldViewMode underlineViewMode;
[Abstract]
[Export ("underlineViewMode", ArgumentSemantic.Assign)]
UITextFieldViewMode UnderlineViewMode { get; set; }
// @required @property (assign, nonatomic, class) UITextFieldViewMode underlineViewModeDefault;
[Static, Abstract]
[Export ("underlineViewModeDefault", ArgumentSemantic.Assign)]
UITextFieldViewMode UnderlineViewModeDefault { get; set; }
// @required -(instancetype _Nonnull)initWithTextInput:(UIView<MDCTextInput> * _Nullable)input;
//[Abstract]
[Export ("initWithTextInput:")]
IntPtr Constructor ([NullAllowed] MDCTextInput input);
// @required -(void)setErrorText:(NSString * _Nullable)errorText errorAccessibilityValue:(NSString * _Nullable)errorAccessibilityValue;
[Abstract]
[Export ("setErrorText:errorAccessibilityValue:")]
void SetErrorText ([NullAllowed] string errorText, [NullAllowed] string errorAccessibilityValue);
}
// @interface MDCTextInputControllerDefault : NSObject <MDCTextInputController>
[BaseType (typeof(NSObject))]
interface MDCTextInputControllerDefault : MDCTextInputController
{
//MARK: V34.0.1
// @property (nonatomic, strong) UIColor * _Nullable borderFillColor;
[NullAllowed, Export("borderFillColor", ArgumentSemantic.Strong)]
UIColor BorderFillColor { get; set; }
// @property (nonatomic, strong, class) UIColor * _Null_unspecified borderFillColorDefault;
[Static]
[Export("borderFillColorDefault", ArgumentSemantic.Strong)]
UIColor BorderFillColorDefault { get; set; }
// @property (assign, nonatomic) BOOL expandsOnOverflow;
[Export("expandsOnOverflow")]
bool ExpandsOnOverflow { get; set; }
// @property (nonatomic, strong) UIColor * _Null_unspecified floatingPlaceholderNormalColor;
// MARK V35.3.0[Static]
[Export ("floatingPlaceholderNormalColor", ArgumentSemantic.Strong)]
UIColor FloatingPlaceholderNormalColor { get; set; }
// @property (nonatomic, strong, class) UIColor * _Null_unspecified floatingPlaceholderNormalColorDefault;
[Static]
[Export ("floatingPlaceholderNormalColorDefault", ArgumentSemantic.Strong)]
UIColor FloatingPlaceholderNormalColorDefault { get; set; }
// @property (readonly, nonatomic) UIOffset floatingPlaceholderOffset;
[Export("floatingPlaceholderOffset")]
UIOffset FloatingPlaceholderOffset { get; }
// @property (nonatomic, strong) NSNumber * _Null_unspecified floatingPlaceholderScale;
[Export ("floatingPlaceholderScale", ArgumentSemantic.Strong)]
NSNumber FloatingPlaceholderScale { get; set; }
// @property (assign, nonatomic, class) CGFloat floatingPlaceholderScaleDefault;
[Static]
[Export ("floatingPlaceholderScaleDefault")]
nfloat FloatingPlaceholderScaleDefault { get; set; }
// @property (getter = isFloatingEnabled, assign, nonatomic) BOOL floatingEnabled;
[Export ("floatingEnabled")]
bool FloatingEnabled { [Bind ("isFloatingEnabled")] get; set; }
// @property (getter = isFloatingEnabledDefault, assign, nonatomic, class) BOOL floatingEnabledDefault;
[Static]
[Export ("floatingEnabledDefault")]
bool FloatingEnabledDefault { [Bind ("isFloatingEnabledDefault")] get; set; }
// @property (assign, nonatomic) NSUInteger minimumLines;
[Export("minimumLines")]
nuint MinimumLines { get; set; }
}
// @interface MDCTextInputControllerFullWidth : NSObject <MDCTextInputController>
[BaseType (typeof(NSObject))]
interface MDCTextInputControllerFullWidth : MDCTextInputController
{
}
// @interface MDCMultilineTextField : UIView <MDCTextInput, MDCMultilineTextInput>
[BaseType (typeof(UIView))]
interface MDCMultilineTextField : MDCTextInput, MDCMultilineTextInput
{
// @property (assign, nonatomic) BOOL adjustsFontForContentSizeCategory;
[Export ("adjustsFontForContentSizeCategory")]
bool AdjustsFontForContentSizeCategory { get; set; }
[Wrap ("WeakLayoutDelegate")]
[NullAllowed]
MDCMultilineTextInputLayoutDelegate LayoutDelegate { get; set; }
// @property (nonatomic, weak) id<MDCMultilineTextInputLayoutDelegate> _Nullable layoutDelegate __attribute__((iboutlet));
[NullAllowed, Export ("layoutDelegate", ArgumentSemantic.Weak)]
NSObject WeakLayoutDelegate { get; set; }
[Wrap("WeakMultilineDelegate")]
[NullAllowed]
MDCMultilineTextInputDelegate MultilineDelegate { get; set; }
// @property (nonatomic, weak) id<MDCMultilineTextInputDelegate> _Nullable multilineDelegate __attribute__((iboutlet));
[NullAllowed, Export("multilineDelegate", ArgumentSemantic.Weak)]
NSObject WeakMultilineDelegate { get; set; }
// @property (readonly, assign, nonatomic) UIEdgeInsets textInsets;
//FIXME: CS0108 added new keywError, test whether it works or not.
[Export ("textInsets", ArgumentSemantic.Assign)]
new UIEdgeInsets TextInsets { get; }
// @property (nonatomic, weak) UITextView * _Nullable textView __attribute__((iboutlet));
[NullAllowed, Export ("textView", ArgumentSemantic.Weak)]
UITextView TextView { get; set; }
}
// @interface MDCTextInputControllerLegacyDefault : NSObject <MDCTextInputController>
[BaseType(typeof(NSObject))]
interface MDCTextInputControllerLegacyDefault : MDCTextInputController {
// @property (nonatomic, strong) UIColor * _Null_unspecified floatingPlaceholderNormalColor;
[Static]
[Export("floatingPlaceholderNormalColor", ArgumentSemantic.Strong)]
UIColor FloatingPlaceholderNormalColor { get; set; }
// @property (nonatomic, strong, class) UIColor * _Null_unspecified floatingPlaceholderNormalColorDefault;
[Static]
[Export("floatingPlaceholderNormalColorDefault", ArgumentSemantic.Strong)]
UIColor FloatingPlaceholderNormalColorDefault { get; set; }
// @property (nonatomic, strong) NSNumber * _Null_unspecified floatingPlaceholderScale;
[Export("floatingPlaceholderScale", ArgumentSemantic.Strong)]
NSNumber FloatingPlaceholderScale { get; set; }
// @property (assign, nonatomic, class) CGFloat floatingPlaceholderScaleDefault;
[Static]
[Export("floatingPlaceholderScaleDefault")]
nfloat FloatingPlaceholderScaleDefault { get; set; }
// @property (getter = isFloatingEnabled, assign, nonatomic) BOOL floatingEnabled;
[Export("floatingEnabled")]
bool FloatingEnabled { [Bind("isFloatingEnabled")] get; set; }
// @property (getter = isFloatingEnabledDefault, assign, nonatomic, class) BOOL floatingEnabledDefault;
[Static]
[Export("floatingEnabledDefault")]
bool FloatingEnabledDefault { [Bind("isFloatingEnabledDefault")] get; set; }
}
// @interface MDCTextInputControllerLegacyFullWidth : NSObject <MDCTextInputController>
[BaseType(typeof(NSObject))]
interface MDCTextInputControllerLegacyFullWidth : MDCTextInputController {
}
// @interface MDCTextInputControllerOutlined : MDCTextInputControllerDefault
[BaseType(typeof(MDCTextInputControllerDefault))]
interface MDCTextInputControllerOutlined
{
}
// @interface MDCTextInputControllerOutlinedTextArea : MDCTextInputControllerDefault
[BaseType(typeof(MDCTextInputControllerDefault))]
interface MDCTextInputControllerOutlinedTextArea
{
}
// @interface MDCTextInputControllerFilled : MDCTextInputControllerDefault
[BaseType(typeof(MDCTextInputControllerDefault))]
interface MDCTextInputControllerFilled
{
}
// @interface MDCTextInputBorderView : UIView <NSCopying>
[BaseType(typeof(UIView))]
interface MDCTextInputBorderView : INSCopying
{
// @property (nonatomic, strong) UIColor * _Nullable borderFillColor __attribute__((annotate("ui_appearance_selector")));
[NullAllowed, Export("borderFillColor", ArgumentSemantic.Strong)]
UIColor BorderFillColor { get; set; }
// @property (nonatomic, strong) UIBezierPath * _Nullable borderPath __attribute__((annotate("ui_appearance_selector")));
[NullAllowed, Export("borderPath", ArgumentSemantic.Strong)]
UIBezierPath BorderPath { get; set; }
// @property (nonatomic, strong) UIColor * _Nullable borderStrokeColor __attribute__((annotate("ui_appearance_selector")));
[NullAllowed, Export("borderStrokeColor", ArgumentSemantic.Strong)]
UIColor BorderStrokeColor { get; set; }
}
// @protocol MDCMultilineTextInputDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface MDCMultilineTextInputDelegate
{
// @optional -(BOOL)multilineTextFieldShouldClear:(UIView *)textField;
[Export("multilineTextFieldShouldClear:")]
bool MultilineTextFieldShouldClear(UIView textField);
}
}
| |
namespace FakeItEasy.Specs
{
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Xbehave;
public static class UnconfiguredFakeSpecs
{
public interface IFoo
{
bool IsADummy { get; }
}
[Scenario]
public static void VirtualMethodCalledDuringConstruction(
MakesVirtualCallInConstructor fake)
{
"Given a type with a default constructor"
.x(() => { }); // see MakesVirtualCallInConstructor
"And the constructor calls a virtual method"
.x(() => { }); // see MakesVirtualCallInConstructor.ctor()
"And the method returns a non-default value"
.x(() => { }); // see MakesVirtualCallInConstructor.VirtualMethod()
"When I create a fake of the type"
.x(() => fake = A.Fake<MakesVirtualCallInConstructor>());
"Then the method will return a default value"
.x(() => fake.VirtualMethodValueDuringConstructorCall.Should().Be(string.Empty));
"And the method call will be recorded"
.x(() => A.CallTo(() => fake.VirtualMethod("call in constructor")).MustHaveHappened());
}
[Scenario]
public static void VirtualMethodCalledAfterConstruction(
MakesVirtualCallInConstructor fake,
string result)
{
"Given a type with a virtual method"
.x(() => { }); // see MakesVirtualCallInConstructor
"And the method returns a non-default value"
.x(() => { }); // see MakesVirtualCallInConstructor.VirtualMethod
"And a fake of that type"
.x(() => fake = A.Fake<MakesVirtualCallInConstructor>());
"When I call the method"
.x(() => result = fake.VirtualMethod("call after constructor"));
"Then it will return a default value"
.x(() => result.Should().Be(string.Empty));
"And the method call will be recorded"
.x(() => A.CallTo(() => fake.VirtualMethod("call after constructor")).MustHaveHappened());
}
[Scenario]
public static void VirtualPropertiesCalledDuringConstruction(
FakedClass fake)
{
"Given a type with a default constructor"
.x(() => { }); // see FakedClass
"And the constructor calls some virtual properties"
.x(() => { }); // see FakedClass.ctor()
"And the properties return non-default values"
.x(() => { }); // see FakedClass.StringProperty, FakedClass.ValueTypeProperty
"When I create a fake of the type"
.x(() => fake = A.Fake<FakedClass>());
"Then the reference-type property will return a default value"
.x(() => fake.StringPropertyValueDuringConstructorCall.Should().Be(string.Empty));
"And the value-type property will return a default value"
.x(() => fake.ValueTypePropertyValueDuringConstructorCall.Should().Be(0));
}
[Scenario]
public static void VirtualReferenceTypeProperty(
FakedClass fake,
string result)
{
"Given a type with a default constructor"
.x(() => { }); // see FakedClass
"And the constructor assigns a value to a virtual reference-type property"
.x(() => { }); // see FakedClass.ctor()
"And a fake of that type"
.x(() => fake = A.Fake<FakedClass>());
"When I fetch the property value"
.x(() => result = fake.StringProperty);
"Then it will be the value assigned during construction"
.x(() => result.Should().Be("value set in constructor"));
}
[Scenario]
public static void VirtualValueTypeProperty(
FakedClass fake,
int result)
{
"Given a type with a default constructor"
.x(() => { }); // see FakedClass
"And the constructor assigns a value to a virtual value-type property"
.x(() => { }); // see FakedClass.ctor()
"And a fake of that type"
.x(() => fake = A.Fake<FakedClass>());
"When I fetch the property value"
.x(() => result = fake.ValueTypeProperty);
"Then it will be the value assigned during construction"
.x(() => result.Should().Be(123456));
}
[Scenario]
public static void FakeableProperty(
FakedClass fake,
IFoo? result)
{
"Given a type with a virtual fakeable-type property"
.x(() => { }); // see FakedClasss
"And a fake of that type"
.x(() => fake = A.Fake<FakedClass>());
"When I get the property value"
.x(() => result = fake.FakeableProperty);
"Then the property will not be null"
.x(() => result.Should().NotBeNull());
"And it will be a Dummy"
.x(() => result!.IsADummy.Should().BeTrue("because the property value should be a Dummy"));
}
[Scenario]
public static void ToStringDescribesFake(FakedClass fake, string? toStringValue)
{
"Given a faked class instance"
.x(() => fake = A.Fake<FakedClass>());
"When I call ToString on it"
.x(() => toStringValue = fake.ToString());
"Then it indicates that it's a fake"
.x(() => toStringValue.Should().Be("Faked FakeItEasy.Specs.UnconfiguredFakeSpecs+FakedClass"));
}
[Scenario]
public static void EqualsSameFake(FakedClass fake, bool equalsResult)
{
"Given a faked class instance"
.x(() => fake = A.Fake<FakedClass>());
"When I compare it to itself using Equals"
.x(() => equalsResult = fake.Equals(fake));
"Then it compares as equal"
.x(() => equalsResult.Should().BeTrue());
}
[Scenario]
public static void EqualsDifferentInstanceOfSameFakedType(FakedClass fake1, FakedClass fake2, bool equalsResult)
{
"Given a faked class instance"
.x(() => fake1 = A.Fake<FakedClass>());
"And a second faked class instance of the same type"
.x(() => fake2 = A.Fake<FakedClass>());
"When I compare the instances using Equals"
.x(() => equalsResult = fake1.Equals(fake2));
"Then they compare as unequal"
.x(() => equalsResult.Should().BeFalse());
}
public class FakedClass
{
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This anti-pattern is part of the the tested scenario.")]
public FakedClass()
{
this.StringPropertyValueDuringConstructorCall = this.StringProperty;
this.ValueTypePropertyValueDuringConstructorCall = this.ValueTypeProperty;
this.StringProperty = "value set in constructor";
this.ValueTypeProperty = 123456;
}
public virtual string StringProperty { get; set; }
public string StringPropertyValueDuringConstructorCall { get; }
public virtual int ValueTypeProperty { get; set; }
public int ValueTypePropertyValueDuringConstructorCall { get; }
public virtual IFoo? FakeableProperty { get; set; }
}
public class Foo : IFoo
{
public bool IsADummy { get; set; }
}
public class FooFactory : DummyFactory<IFoo>
{
protected override IFoo Create()
{
return new Foo { IsADummy = true };
}
}
}
}
| |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
//
// Windows.Kinect.BodyFrameReader
//
public sealed partial class BodyFrameReader : RootSystem.IDisposable, Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal BodyFrameReader(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Windows_Kinect_BodyFrameReader_AddRefObject(ref _pNative);
}
~BodyFrameReader()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_BodyFrameReader_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_BodyFrameReader_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
__EventCleanup();
Helper.NativeObjectCache.RemoveObject<BodyFrameReader>(_pNative);
if (disposing)
{
Windows_Kinect_BodyFrameReader_Dispose(_pNative);
}
Windows_Kinect_BodyFrameReader_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Windows_Kinect_BodyFrameReader_get_BodyFrameSource(RootSystem.IntPtr pNative);
public Windows.Kinect.BodyFrameSource BodyFrameSource
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("BodyFrameReader");
}
RootSystem.IntPtr objectPointer = Windows_Kinect_BodyFrameReader_get_BodyFrameSource(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.BodyFrameSource>(objectPointer, n => new Windows.Kinect.BodyFrameSource(n));
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern bool Windows_Kinect_BodyFrameReader_get_IsPaused(RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_BodyFrameReader_put_IsPaused(RootSystem.IntPtr pNative, bool isPaused);
public bool IsPaused
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("BodyFrameReader");
}
return Windows_Kinect_BodyFrameReader_get_IsPaused(_pNative);
}
set
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("BodyFrameReader");
}
Windows_Kinect_BodyFrameReader_put_IsPaused(_pNative, value);
Helper.ExceptionHelper.CheckLastError();
}
}
// Events
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Kinect_BodyFrameArrivedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.BodyFrameArrivedEventArgs>>> Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.BodyFrameArrivedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Kinect_BodyFrameArrivedEventArgs_Delegate))]
private static void Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Kinect.BodyFrameArrivedEventArgs>> callbackList = null;
Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<BodyFrameReader>(pNative);
var args = new Windows.Kinect.BodyFrameArrivedEventArgs(result);
foreach(var func in callbackList)
{
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_BodyFrameReader_add_FrameArrived(RootSystem.IntPtr pNative, _Windows_Kinect_BodyFrameArrivedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Kinect.BodyFrameArrivedEventArgs> FrameArrived
{
add
{
Helper.EventPump.EnsureInitialized();
Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Kinect_BodyFrameArrivedEventArgs_Delegate(Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_Handler);
_Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Windows_Kinect_BodyFrameReader_add_FrameArrived(_pNative, del, false);
}
}
}
remove
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Windows_Kinect_BodyFrameReader_add_FrameArrived(_pNative, Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_Handler, true);
_Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_Handle.Free();
}
}
}
}
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))]
private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null;
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<BodyFrameReader>(pNative);
var args = new Windows.Data.PropertyChangedEventArgs(result);
foreach(var func in callbackList)
{
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_BodyFrameReader_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged
{
add
{
Helper.EventPump.EnsureInitialized();
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Windows_Kinect_BodyFrameReader_add_PropertyChanged(_pNative, del, false);
}
}
}
remove
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Windows_Kinect_BodyFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
// Public Methods
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Windows_Kinect_BodyFrameReader_AcquireLatestFrame(RootSystem.IntPtr pNative);
public Windows.Kinect.BodyFrame AcquireLatestFrame()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("BodyFrameReader");
}
RootSystem.IntPtr objectPointer = Windows_Kinect_BodyFrameReader_AcquireLatestFrame(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.BodyFrame>(objectPointer, n => new Windows.Kinect.BodyFrame(n));
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_BodyFrameReader_Dispose(RootSystem.IntPtr pNative);
public void Dispose()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Dispose(true);
RootSystem.GC.SuppressFinalize(this);
}
private void __EventCleanup()
{
{
Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
if (callbackList.Count > 0)
{
callbackList.Clear();
if (_pNative != RootSystem.IntPtr.Zero)
{
Windows_Kinect_BodyFrameReader_add_FrameArrived(_pNative, Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_Handler, true);
}
_Windows_Kinect_BodyFrameArrivedEventArgs_Delegate_Handle.Free();
}
}
}
{
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
if (callbackList.Count > 0)
{
callbackList.Clear();
if (_pNative != RootSystem.IntPtr.Zero)
{
Windows_Kinect_BodyFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
}
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Catapult.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;
#endregion
namespace CatapultMiniGame
{
/// <summary>
/// States for the Catapult
/// </summary>
public enum CatapultState
{
Rolling,
Firing,
Crash,
ProjectileFlying,
ProjectileHit,
Reset
}
/// <summary>
/// Class to manage the catapult and the projectile
/// </summary>
public class Catapult : DrawableGameComponent
{
#region Fields
// Hold what game I belong to
CatapultGame curGame = null;
// Current state of the Catapult
CatapultState currentState;
public CatapultState CurrentState
{
get { return currentState; }
set { currentState = value; }
}
// Texture used for base of Catapult
Texture2D baseTexture;
Texture2D baseTextureBack;
// Texture for the arm
Texture2D armTexture;
// Textures for pumpkins
Texture2D pumpkinTexture;
Texture2D pumpkinSmashTexture;
// Position and speed of catapult base
Vector2 basePosition = Vector2.Zero;
float baseSpeed;
// Position and rotation of catapult arm
Vector2 armCenter = new Vector2(200, 27);
Vector2 armOffset = new Vector2(280, 100);
float armRotation;
// Position, speed, and rotation of pumpkin
Vector2 pumpkinPosition = Vector2.Zero;
public Vector2 PumpkinPosition
{
get { return pumpkinPosition; }
set { pumpkinPosition = value; }
}
Vector2 pumpkinVelocity = Vector2.Zero;
Vector2 pumpkinAcceleration = new Vector2(0, 0.001f);
Vector2 pumpkinRotationPosition = Vector2.Zero;
float pumpkinLaunchPosition;
public float PumpkinLaunchPosition
{
get { return pumpkinLaunchPosition; }
set { pumpkinLaunchPosition = value; }
}
float pumpkinRotation;
// Level of boost power
int boostPower;
public int BoostPower
{
get { return boostPower; }
set { boostPower = value; }
}
// Are we playing the crash sound
Cue playingCue;
Cue crashCue;
#endregion
#region Initialization
public Catapult(Game game) : base(game)
{
curGame = (CatapultGame)game;
ResetCatapult();
}
public override void Initialize()
{
baseTexture =
curGame.Content.Load<Texture2D>("Textures/body_front");
baseTextureBack =
curGame.Content.Load<Texture2D>("Textures/body_back");
pumpkinTexture =
curGame.Content.Load<Texture2D>("Textures/pumpkin");
pumpkinSmashTexture =
curGame.Content.Load<Texture2D>("Textures/pumpkinsmash");
armTexture = curGame.Content.Load<Texture2D>("Textures/arm");
base.Initialize();
}
#endregion
#region Update and Draw
public override void Update(GameTime gameTime)
{
if (gameTime == null)
throw new ArgumentNullException("gameTime");
// Do we need to reset
if (currentState == CatapultState.Reset)
ResetCatapult();
// Are we currently rolling?
if (currentState == CatapultState.Rolling)
{
// Add to current speed
float speedAmt = curGame.CurrentGamePadState.Triggers.Left;
if (curGame.CurrentKeyboardState.IsKeyDown(Keys.Right))
speedAmt = 1.0f;
baseSpeed += speedAmt *
gameTime.ElapsedGameTime.Milliseconds * 0.001f;
// Move catapult based on speed
basePosition.X += baseSpeed * gameTime.ElapsedGameTime.Milliseconds;
// Move pumpkin to match catapult
pumpkinPosition.X = pumpkinLaunchPosition = basePosition.X + 120;
pumpkinPosition.Y = basePosition.Y + 80;
// Play moving sound
if (playingCue == null && baseSpeed > 0)
{
playingCue = curGame.SoundBank.GetCue("Move");
playingCue.Play();
}
// Check to see if we fire the pumpkin
if ((curGame.CurrentGamePadState.Buttons.A == ButtonState.Pressed &&
curGame.LastGamePadState.Buttons.A != ButtonState.Pressed) ||
(curGame.CurrentKeyboardState.IsKeyDown(Keys.Space) &&
curGame.LastKeyboardState.IsKeyUp(Keys.Space)))
{
Fire();
if (playingCue != null && playingCue.IsPlaying)
{
playingCue.Stop(AudioStopOptions.Immediate);
playingCue.Dispose();
playingCue = curGame.SoundBank.GetCue("Flying");
playingCue.Play();
}
}
}
// Are we in the firing state
else if (currentState == CatapultState.Firing)
{
// Rotate the arm
if (armRotation < MathHelper.ToRadians(81))
{
armRotation +=
MathHelper.ToRadians(gameTime.ElapsedGameTime.Milliseconds);
Matrix matTranslate, matTranslateBack, matRotate, matFinal;
matTranslate = Matrix.CreateTranslation((-pumpkinRotationPosition.X)
- 170, -pumpkinRotationPosition.Y, 0);
matTranslateBack =
Matrix.CreateTranslation(pumpkinRotationPosition.X + 170,
pumpkinRotationPosition.Y, 0);
matRotate = Matrix.CreateRotationZ(armRotation);
matFinal = matTranslate * matRotate * matTranslateBack;
Vector2.Transform(ref pumpkinRotationPosition, ref matFinal,
out pumpkinPosition);
pumpkinLaunchPosition = pumpkinPosition.X;
pumpkinRotation += MathHelper.ToRadians(
gameTime.ElapsedGameTime.Milliseconds / 10.0f);
}
// We are done rotating so send the pumpkin flying
else
{
currentState = CatapultState.ProjectileFlying;
pumpkinVelocity.X = baseSpeed * 2.0f + 1;
pumpkinVelocity.Y = -baseSpeed * 0.75f;
// Add extra velocity for Right trigger
float rightTriggerAmt = curGame.CurrentGamePadState.Triggers.Right;
if (rightTriggerAmt > 0.5f)
rightTriggerAmt = 1.0f - rightTriggerAmt;
if (curGame.CurrentKeyboardState.IsKeyDown(Keys.B))
rightTriggerAmt = 0.5f;
rightTriggerAmt *= 2;
pumpkinVelocity *= 1.0f + rightTriggerAmt;
// Check for extra boost power
if (basePosition.X > 620)
{
boostPower = 3;
pumpkinVelocity *= 2.0f;
curGame.SoundBank.PlayCue("Boost");
}
else if (basePosition.X > 600)
{
boostPower = 2;
pumpkinVelocity *= 1.6f;
curGame.SoundBank.PlayCue("Boost");
}
else if (basePosition.X > 580)
{
boostPower = 1;
pumpkinVelocity *= 1.3f;
curGame.SoundBank.PlayCue("Boost");
}
}
}
// Pumpkin is in the flying state
else if (currentState == CatapultState.ProjectileFlying)
{
// Update the position of the pumpkin
pumpkinPosition += pumpkinVelocity *
gameTime.ElapsedGameTime.Milliseconds;
pumpkinVelocity += pumpkinAcceleration *
gameTime.ElapsedGameTime.Milliseconds;
// Move the catapult away from the pumpkin
basePosition.X -= pumpkinVelocity.X *
gameTime.ElapsedGameTime.Milliseconds;
// Rotate the pumpkin as it flys
pumpkinRotation += MathHelper.ToRadians(pumpkinVelocity.X * 3.5f);
// Is the pumpkin hitting the ground
if (pumpkinPosition.Y > 630)
{
// Stop playing any sounds
if (playingCue != null && playingCue.IsPlaying)
{
playingCue.Stop(AudioStopOptions.Immediate);
playingCue.Dispose();
playingCue = null;
}
// Play the bounce sound
curGame.SoundBank.PlayCue("Bounce");
// Move the pumpkin out of the ground and Change the pumkin velocity
pumpkinPosition.Y = 630;
pumpkinVelocity.Y *= -0.8f;
pumpkinVelocity.X *= 0.7f;
// Stop the pumpkin if the speed is too low
if (pumpkinVelocity.X < 0.1f)
{
currentState = CatapultState.ProjectileHit;
curGame.SoundBank.PlayCue("Hit");
if (curGame.HighScore == (int)curGame.PumpkinDistance &&
curGame.HighScore > 1000)
curGame.SoundBank.PlayCue("HighScore");
}
}
}
// Did we crash into the log
if (basePosition.X > 650)
{
currentState = CatapultState.Crash;
if (playingCue != null && playingCue.IsPlaying)
{
playingCue.Stop(AudioStopOptions.Immediate);
playingCue.Dispose();
playingCue = null;
if (crashCue != null)
{
crashCue.Stop(AudioStopOptions.Immediate);
crashCue.Dispose();
crashCue = null;
}
crashCue = curGame.SoundBank.GetCue("Crash");
crashCue.Play();
}
}
// If the projectile hit or we crashed reset the catapult
if ((currentState == CatapultState.Crash ||
currentState == CatapultState.ProjectileHit) &&
(curGame.CurrentGamePadState.Buttons.A == ButtonState.Pressed ||
curGame.CurrentKeyboardState.IsKeyDown(Keys.Space)) &&
curGame.CurrentGamePadState.Triggers.Left == 0 &&
curGame.CurrentKeyboardState.IsKeyUp(Keys.Right))
{
currentState = CatapultState.Reset;
}
base.Update(gameTime);
}
// Draw the catapult and pumpkin
public override void Draw(GameTime gameTime)
{
if (gameTime == null)
throw new ArgumentNullException("gameTime");
if (currentState == CatapultState.Crash)
{
curGame.SpriteBatch.Draw(baseTextureBack, basePosition, null,
Color.White, MathHelper.ToRadians(-5),
Vector2.Zero, 1.0f, SpriteEffects.None, 0);
curGame.SpriteBatch.Draw(armTexture, basePosition + armOffset, null,
Color.White, armRotation, armCenter, 1.0f, SpriteEffects.None, 0.0f);
curGame.SpriteBatch.Draw(baseTexture, basePosition, null, Color.White,
MathHelper.ToRadians(5), Vector2.Zero, 1.0f, SpriteEffects.None, 0);
}
else
{
curGame.SpriteBatch.Draw(baseTextureBack, basePosition, Color.White);
curGame.SpriteBatch.Draw(armTexture, basePosition + armOffset, null,
Color.White, armRotation, armCenter, 1.0f, SpriteEffects.None, 0.0f);
curGame.SpriteBatch.Draw(baseTexture, basePosition, Color.White);
}
if (currentState != CatapultState.ProjectileHit &&
currentState != CatapultState.Crash)
curGame.SpriteBatch.Draw(pumpkinTexture,
new Vector2(pumpkinLaunchPosition, pumpkinPosition.Y),
null, Color.White, pumpkinRotation,
new Vector2(32, 32), 1.0f, SpriteEffects.None, 0.0f);
else
curGame.SpriteBatch.Draw(pumpkinSmashTexture,
new Vector2(pumpkinLaunchPosition, pumpkinPosition.Y),
null, Color.White, 0,
new Vector2(50, 32), 1.0f, SpriteEffects.None, 0.0f);
base.Draw(gameTime);
}
#endregion
#region Actions
// Reset the catapult and pumpkin to default positions
private void ResetCatapult()
{
basePosition.X = -100;
basePosition.Y = 430;
baseSpeed = 0;
pumpkinPosition = Vector2.Zero;
armRotation = MathHelper.ToRadians(0);
currentState = CatapultState.Rolling;
pumpkinPosition = Vector2.Zero;
pumpkinVelocity = Vector2.Zero;
pumpkinPosition.X = pumpkinLaunchPosition = basePosition.X + 120;
pumpkinPosition.Y = basePosition.Y + 80;
pumpkinRotation = 0;
boostPower = 0;
}
// Change state to firing and play fire sound
private void Fire()
{
currentState = CatapultState.Firing;
pumpkinRotationPosition = pumpkinPosition;
curGame.SoundBank.PlayCue("ThrowSound");
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void PackUnsignedSaturateUInt16()
{
var test = new HorizontalBinaryOpTest__PackUnsignedSaturateUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class HorizontalBinaryOpTest__PackUnsignedSaturateUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(HorizontalBinaryOpTest__PackUnsignedSaturateUInt16 testClass)
{
var result = Sse41.PackUnsignedSaturate(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(HorizontalBinaryOpTest__PackUnsignedSaturateUInt16 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse41.PackUnsignedSaturate(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static HorizontalBinaryOpTest__PackUnsignedSaturateUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public HorizontalBinaryOpTest__PackUnsignedSaturateUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.PackUnsignedSaturate(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.PackUnsignedSaturate(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.PackUnsignedSaturate(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.PackUnsignedSaturate), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.PackUnsignedSaturate), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.PackUnsignedSaturate), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.PackUnsignedSaturate(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Sse41.PackUnsignedSaturate(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse41.PackUnsignedSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.PackUnsignedSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.PackUnsignedSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new HorizontalBinaryOpTest__PackUnsignedSaturateUInt16();
var result = Sse41.PackUnsignedSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new HorizontalBinaryOpTest__PackUnsignedSaturateUInt16();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Sse41.PackUnsignedSaturate(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.PackUnsignedSaturate(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse41.PackUnsignedSaturate(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.PackUnsignedSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.PackUnsignedSaturate(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var outer = 0; outer < (LargestVectorSize / 16); outer++)
{
for (var inner = 0; inner < (8 / sizeof(UInt16)); inner++)
{
var i1 = (outer * (16 / sizeof(UInt16))) + inner;
var i2 = i1 + (8 / sizeof(UInt16));
var i3 = (outer * (16 / sizeof(UInt16))) + (inner * 2);
if (result[i1] != ((left[i3 - inner] > 0xFFFF) ? 0xFFFF : ((left[i3 - inner] < 0) ? 0 : BitConverter.ToUInt16(BitConverter.GetBytes(left[i3 - inner]), 0))))
{
succeeded = false;
break;
}
if (result[i2] != ((right[i3 - inner] > 0xFFFF) ? 0xFFFF : ((right[i3 - inner] < 0) ? 0 : BitConverter.ToUInt16(BitConverter.GetBytes(right[i3 - inner]), 0))))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.PackUnsignedSaturate)}<UInt16>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCollectionInitializer
{
public partial class UseCollectionInitializerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseCollectionInitializerDiagnosticAnalyzer(),
new CSharpUseCollectionInitializerCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestOnVariableDeclarator()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(1);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexAccess1()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
[1] = 2
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexAccess1_NotInCSharp5()
{
await TestMissingAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestComplexIndexAccess1()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
a.b.c = [||]new List<int>();
a.b.c[1] = 2;
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
a.b.c = new List<int>
{
[1] = 2
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexAccess2()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
c[2] = """";
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
[1] = 2,
[2] = """"
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexAccess3()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
c[2] = """";
c[3, 4] = 5;
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
[1] = 2,
[2] = """",
[3, 4] = 5
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestIndexFollowedByInvocation()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c[1] = 2;
c.Add(0);
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
[1] = 2
};
c.Add(0);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestInvocationFollowedByIndex()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(0);
c[1] = 2;
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
0
};
c[1] = 2;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestWithInterimStatement()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(1);
c.Add(2);
throw new Exception();
c.Add(3);
c.Add(4);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
1,
2
};
throw new Exception();
c.Add(3);
c.Add(4);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestMissingBeforeCSharp3()
{
await TestMissingAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(1);
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp2)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingOnNonIEnumerable()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new C();
c.Add(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingOnNonIEnumerableEvenWithAdd()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new C();
c.Add(1);
}
public void Add(int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestWithCreationArguments()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>(1);
c.Add(1);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>(1)
{
1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestOnAssignmentExpression()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
List<int> c = null;
c = [||]new List<int>();
c.Add(1);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
List<int> c = null;
c = new List<int>
{
1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingOnRefAdd()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(ref i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestComplexInitializer()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
List<int>[] array;
array[0] = [||]new List<int>();
array[0].Add(1);
array[0].Add(2);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
List<int>[] array;
array[0] = new List<int>
{
1,
2
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestNotOnNamedArg()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(arg: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestMissingWithExistingInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>() { 1 };
c.Add(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestFixAllInDocument1()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
List<int>[] array;
array[0] = {|FixAllInDocument:new|} List<int>();
array[0].Add(1);
array[0].Add(2);
array[1] = new List<int>();
array[1].Add(3);
array[1].Add(4);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
List<int>[] array;
array[0] = new List<int>
{
1,
2
};
array[1] = new List<int>
{
3,
4
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestFixAllInDocument2()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var list1 = {|FixAllInDocument:new|} List<int>(() => {
var list2 = new List<int>();
list2.Add(2);
});
list1.Add(1);
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var list1 = new List<int>(() => {
var list2 = new List<int>
{
2
};
})
{
1
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestFixAllInDocument3()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var list1 = {|FixAllInDocument:new|} List<int>();
list1.Add(() => {
var list2 = new List<int>();
list2.Add(2);
});
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var list1 = new List<int>
{
() => {
var list2 = new List<int>
{
2
};
}
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestTrivia1()
{
await TestInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = [||]new List<int>();
c.Add(1); // Foo
c.Add(2); // Bar
}
}",
@"
using System.Collections.Generic;
class C
{
void M()
{
var c = new List<int>
{
1, // Foo
2 // Bar
};
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
public async Task TestComplexInitializer2()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new [||]Dictionary<int, string>();
c.Add(1, ""x"");
c.Add(2, ""y"");
}
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var c = new Dictionary<int, string>
{
{
1,
""x""
},
{
2,
""y""
}
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(16158, "https://github.com/dotnet/roslyn/issues/16158")]
public async Task TestIncorrectAddName()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
public class Foo
{
public static void Bar()
{
string item = null;
var items = new List<string>();
var values = new [||]List<string>(); // Collection initialization can be simplified
values.Add(item);
values.AddRange(items);
}
}",
@"using System.Collections.Generic;
public class Foo
{
public static void Bar()
{
string item = null;
var items = new List<string>();
var values = new List<string>
{
item
}; // Collection initialization can be simplified
values.AddRange(items);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(16241, "https://github.com/dotnet/roslyn/issues/16241")]
public async Task TestNestedCollectionInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var myStringArray = new string[] { ""Test"", ""123"", ""ABC"" };
var myStringList = myStringArray?.ToList() ?? new [||]List<string>();
myStringList.Add(""Done"");
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")]
public async Task TestMissingWhenReferencedInInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Collections.Generic;
class C
{
static void M()
{
var items = new [||]List<object>();
items[0] = items[0];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
[WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")]
public async Task TestWhenReferencedInInitializer()
{
await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;
class C
{
static void M()
{
var items = new [||]List<object>();
items[0] = 1;
items[1] = items[0];
}
}",
@"
using System.Collections.Generic;
class C
{
static void M()
{
var items = new [||]List<object>
{
[0] = 1
};
items[1] = items[0];
}
}");
}
[WorkItem(17853, "https://github.com/dotnet/roslyn/issues/17853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
public async Task TestMissingForDynamic()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Dynamic;
class C
{
void Foo()
{
dynamic body = [||]new ExpandoObject();
body[0] = new ExpandoObject();
}
}");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public unsafe struct BlobReader
{
/// <summary>An array containing the '\0' character.</summary>
private static readonly char[] s_nullCharArray = new char[1] { '\0' };
internal const int InvalidCompressedInteger = Int32.MaxValue;
private readonly MemoryBlock _block;
// Points right behind the last byte of the block.
private readonly byte* _endPointer;
private byte* _currentPointer;
public unsafe BlobReader(byte* buffer, int length)
: this(MemoryBlock.CreateChecked(buffer, length))
{
}
internal BlobReader(MemoryBlock block)
{
Debug.Assert(BitConverter.IsLittleEndian && block.Length >= 0 && (block.Pointer != null || block.Length == 0));
_block = block;
_currentPointer = block.Pointer;
_endPointer = block.Pointer + block.Length;
}
internal string GetDebuggerDisplay()
{
if (_block.Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = _block.GetDebuggerDisplay(out displayedBytes);
if (this.Offset < displayedBytes)
{
display = display.Insert(this.Offset * 3, "*");
}
else if (displayedBytes == _block.Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
#region Offset, Skipping, Marking, Alignment, Bounds Checking
public int Length
{
get
{
return _block.Length;
}
}
public int Offset
{
get
{
return (int)(_currentPointer - _block.Pointer);
}
}
public int RemainingBytes
{
get
{
return (int)(_endPointer - _currentPointer);
}
}
public void Reset()
{
_currentPointer = _block.Pointer;
}
internal bool SeekOffset(int offset)
{
if (unchecked((uint)offset) >= (uint)_block.Length)
{
return false;
}
_currentPointer = _block.Pointer + offset;
return true;
}
internal void SkipBytes(int count)
{
GetCurrentPointerAndAdvance(count);
}
internal void Align(byte alignment)
{
if (!TryAlign(alignment))
{
Throw.OutOfBounds();
}
}
internal bool TryAlign(byte alignment)
{
int remainder = this.Offset & (alignment - 1);
Debug.Assert((alignment & (alignment - 1)) == 0, "Alignment must be a power of two.");
Debug.Assert(remainder >= 0 && remainder < alignment);
if (remainder != 0)
{
int bytesToSkip = alignment - remainder;
if (bytesToSkip > RemainingBytes)
{
return false;
}
_currentPointer += bytesToSkip;
}
return true;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(_currentPointer + offset, length);
}
#endregion
#region Bounds Checking
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)(_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int byteCount)
{
if (unchecked((uint)byteCount) > (_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance(int length)
{
byte* p = _currentPointer;
if (unchecked((uint)length) > (uint)(_endPointer - p))
{
Throw.OutOfBounds();
}
_currentPointer = p + length;
return p;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance1()
{
byte* p = _currentPointer;
if (p == _endPointer)
{
Throw.OutOfBounds();
}
_currentPointer = p + 1;
return p;
}
#endregion
#region Read Methods
public bool ReadBoolean()
{
// It's not clear from the ECMA spec what exactly is the encoding of Boolean.
// Some metadata writers encode "true" as 0xff, others as 1. So we treat all non-zero values as "true".
//
// We propose to clarify and relax the current wording in the spec as follows:
//
// Chapter II.16.2 "Field init metadata"
// ... bool '(' true | false ')' Boolean value stored in a single byte, 0 represents false, any non-zero value represents true ...
//
// Chapter 23.3 "Custom attributes"
// ... A bool is a single byte with value 0 reprseenting false and any non-zero value representing true ...
return ReadByte() != 0;
}
public sbyte ReadSByte()
{
return *(sbyte*)GetCurrentPointerAndAdvance1();
}
public byte ReadByte()
{
return *(byte*)GetCurrentPointerAndAdvance1();
}
public char ReadChar()
{
return *(char*)GetCurrentPointerAndAdvance(sizeof(char));
}
public short ReadInt16()
{
return *(short*)GetCurrentPointerAndAdvance(sizeof(short));
}
public ushort ReadUInt16()
{
return *(ushort*)GetCurrentPointerAndAdvance(sizeof(ushort));
}
public int ReadInt32()
{
return *(int*)GetCurrentPointerAndAdvance(sizeof(int));
}
public uint ReadUInt32()
{
return *(uint*)GetCurrentPointerAndAdvance(sizeof(uint));
}
public long ReadInt64()
{
return *(long*)GetCurrentPointerAndAdvance(sizeof(long));
}
public ulong ReadUInt64()
{
return *(ulong*)GetCurrentPointerAndAdvance(sizeof(ulong));
}
public float ReadSingle()
{
return *(float*)GetCurrentPointerAndAdvance(sizeof(float));
}
public double ReadDouble()
{
return *(double*)GetCurrentPointerAndAdvance(sizeof(double));
}
public Guid ReadGuid()
{
const int size = 16;
return *(Guid*)GetCurrentPointerAndAdvance(size);
}
/// <summary>
/// Reads <see cref="decimal"/> number.
/// </summary>
/// <remarks>
/// Decimal number is encoded in 13 bytes as follows:
/// - byte 0: highest bit indicates sign (1 for negative, 0 for non-negative); the remaining 7 bits encode scale
/// - bytes 1..12: 96-bit unsigned integer in little endian encoding.
/// </remarks>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid <see cref="decimal"/> number.</exception>
public decimal ReadDecimal()
{
byte* ptr = GetCurrentPointerAndAdvance(13);
byte scale = (byte)(*ptr & 0x7f);
if (scale > 28)
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
return new decimal(
*(int*)(ptr + 1),
*(int*)(ptr + 5),
*(int*)(ptr + 9),
isNegative: (*ptr & 0x80) != 0,
scale: scale);
}
public DateTime ReadDateTime()
{
return new DateTime(ReadInt64());
}
public SignatureHeader ReadSignatureHeader()
{
return new SignatureHeader(ReadByte());
}
/// <summary>
/// Reads UTF8 encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF8(int byteCount)
{
string s = _block.PeekUtf8(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads UTF16 (little-endian) encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF16(int byteCount)
{
string s = _block.PeekUtf16(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads bytes starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The byte array.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public byte[] ReadBytes(int byteCount)
{
byte[] bytes = _block.PeekBytes(this.Offset, byteCount);
_currentPointer += byteCount;
return bytes;
}
internal string ReadUtf8NullTerminated()
{
int bytesRead;
string value = _block.PeekUtf8NullTerminated(this.Offset, null, MetadataStringDecoder.DefaultUTF8, out bytesRead, '\0');
_currentPointer += bytesRead;
return value;
}
private int ReadCompressedIntegerOrInvalid()
{
int bytesRead;
int value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
_currentPointer += bytesRead;
return value;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedInteger(out int value)
{
value = ReadCompressedIntegerOrInvalid();
return value != InvalidCompressedInteger;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedInteger()
{
int value;
if (!TryReadCompressedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedSignedInteger(out int value)
{
int bytesRead;
value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
if (value == InvalidCompressedInteger)
{
return false;
}
bool signExtend = (value & 0x1) != 0;
value >>= 1;
if (signExtend)
{
switch (bytesRead)
{
case 1:
value |= unchecked((int)0xffffffc0);
break;
case 2:
value |= unchecked((int)0xffffe000);
break;
default:
Debug.Assert(bytesRead == 4);
value |= unchecked((int)0xf0000000);
break;
}
}
_currentPointer += bytesRead;
return true;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedSignedInteger()
{
int value;
if (!TryReadCompressedSignedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads type code encoded in a serialized custom attribute value.
/// </summary>
/// <returns><see cref="SerializationTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SerializationTypeCode ReadSerializationTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
if (value > byte.MaxValue)
{
return SerializationTypeCode.Invalid;
}
return unchecked((SerializationTypeCode)value);
}
/// <summary>
/// Reads type code encoded in a signature.
/// </summary>
/// <returns><see cref="SignatureTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SignatureTypeCode ReadSignatureTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
switch (value)
{
case (int)CorElementType.ELEMENT_TYPE_CLASS:
case (int)CorElementType.ELEMENT_TYPE_VALUETYPE:
return SignatureTypeCode.TypeHandle;
default:
if (value > byte.MaxValue)
{
return SignatureTypeCode.Invalid;
}
return unchecked((SignatureTypeCode)value);
}
}
/// <summary>
/// Reads a string encoded as a compressed integer containing its length followed by
/// its contents in UTF8. Null strings are encoded as a single 0xFF byte.
/// </summary>
/// <remarks>Defined as a 'SerString' in the Ecma CLI specification.</remarks>
/// <returns>String value or null.</returns>
/// <exception cref="BadImageFormatException">If the encoding is invalid.</exception>
public string ReadSerializedString()
{
int length;
if (TryReadCompressedInteger(out length))
{
// Removal of trailing '\0' is a departure from the spec, but required
// for compatibility with legacy compilers.
return ReadUTF8(length).TrimEnd(s_nullCharArray);
}
if (ReadByte() != 0xFF)
{
Throw.InvalidSerializedString();
}
return null;
}
/// <summary>
/// Reads a type handle encoded in a signature as TypeDefOrRefOrSpecEncoded (see ECMA-335 II.23.2.8).
/// </summary>
/// <returns>The handle or nil if the encoding is invalid.</returns>
public EntityHandle ReadTypeHandle()
{
uint value = (uint)ReadCompressedIntegerOrInvalid();
uint tokenType = s_corEncodeTokenArray[value & 0x3];
if (value == InvalidCompressedInteger || tokenType == 0)
{
return default(EntityHandle);
}
return new EntityHandle(tokenType | (value >> 2));
}
private static readonly uint[] s_corEncodeTokenArray = new uint[] { TokenTypeIds.TypeDef, TokenTypeIds.TypeRef, TokenTypeIds.TypeSpec, 0 };
/// <summary>
/// Reads a #Blob heap handle encoded as a compressed integer.
/// </summary>
/// <remarks>
/// Blobs that contain references to other blobs are used in Portable PDB format, for example <see cref="Document.Name"/>.
/// </remarks>
public BlobHandle ReadBlobHandle()
{
return BlobHandle.FromOffset(ReadCompressedInteger());
}
/// <summary>
/// Reads a constant value (see ECMA-335 Partition II section 22.9) from the current position.
/// </summary>
/// <exception cref="BadImageFormatException">Error while reading from the blob.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="typeCode"/> is not a valid <see cref="ConstantTypeCode"/>.</exception>
/// <returns>
/// Boxed constant value. To avoid allocating the object use Read* methods directly.
/// Constants of type <see cref="ConstantTypeCode.String"/> are encoded as UTF16 strings, use <see cref="ReadUTF16(int)"/> to read them.
/// </returns>
public object ReadConstant(ConstantTypeCode typeCode)
{
// Partition II section 22.9:
//
// Type shall be exactly one of: ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1,
// ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, ELEMENT_TYPE_U4,
// ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, or ELEMENT_TYPE_STRING;
// or ELEMENT_TYPE_CLASS with a Value of zero (23.1.16)
switch (typeCode)
{
case ConstantTypeCode.Boolean:
return ReadBoolean();
case ConstantTypeCode.Char:
return ReadChar();
case ConstantTypeCode.SByte:
return ReadSByte();
case ConstantTypeCode.Int16:
return ReadInt16();
case ConstantTypeCode.Int32:
return ReadInt32();
case ConstantTypeCode.Int64:
return ReadInt64();
case ConstantTypeCode.Byte:
return ReadByte();
case ConstantTypeCode.UInt16:
return ReadUInt16();
case ConstantTypeCode.UInt32:
return ReadUInt32();
case ConstantTypeCode.UInt64:
return ReadUInt64();
case ConstantTypeCode.Single:
return ReadSingle();
case ConstantTypeCode.Double:
return ReadDouble();
case ConstantTypeCode.String:
return ReadUTF16(RemainingBytes);
case ConstantTypeCode.NullReference:
// Partition II section 22.9:
// The encoding of Type for the nullref value is ELEMENT_TYPE_CLASS with a Value of a 4-byte zero.
// Unlike uses of ELEMENT_TYPE_CLASS in signatures, this one is not followed by a type token.
if (ReadUInt32() != 0)
{
throw new BadImageFormatException(SR.InvalidConstantValue);
}
return null;
default:
throw new ArgumentOutOfRangeException("typeCode");
}
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Python.Runtime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Util;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace QuantConnect.Python
{
/// <summary>
/// Organizes a list of data to create pandas.DataFrames
/// </summary>
public class PandasData
{
private static dynamic _pandas;
private readonly static HashSet<string> _baseDataProperties = typeof(BaseData).GetProperties().ToHashSet(x => x.Name.ToLowerInvariant());
private readonly static ConcurrentDictionary<Type, List<MemberInfo>> _membersByType = new ConcurrentDictionary<Type, List<MemberInfo>>();
private readonly Symbol _symbol;
private readonly Dictionary<string, Tuple<List<DateTime>, List<object>>> _series;
private readonly List<MemberInfo> _members;
/// <summary>
/// Gets true if this is a custom data request, false for normal QC data
/// </summary>
public bool IsCustomData { get; }
/// <summary>
/// Implied levels of a multi index pandas.Series (depends on the security type)
/// </summary>
public int Levels { get; } = 2;
/// <summary>
/// Initializes an instance of <see cref="PandasData"/>
/// </summary>
public PandasData(object data)
{
if (_pandas == null)
{
using (Py.GIL())
{
// Use our PandasMapper class that modifies pandas indexing to support tickers, symbols and SIDs
_pandas = PythonEngine.ImportModule("PandasMapper");
}
}
// in the case we get a list/collection of data we take the first data point to determine the type
// but it's also possible to get a data which supports enumerating we don't care about those cases
if (data is not IBaseData && data is IEnumerable enumerable)
{
foreach (var item in enumerable)
{
data = item;
break;
}
}
var type = data.GetType();
IsCustomData = type.Namespace != typeof(Bar).Namespace;
_members = new List<MemberInfo>();
_symbol = ((IBaseData)data).Symbol;
if (_symbol.SecurityType == SecurityType.Future) Levels = 3;
if (_symbol.SecurityType.IsOption()) Levels = 5;
var columns = new HashSet<string>
{
"open", "high", "low", "close", "lastprice", "volume",
"askopen", "askhigh", "asklow", "askclose", "askprice", "asksize", "quantity", "suspicious",
"bidopen", "bidhigh", "bidlow", "bidclose", "bidprice", "bidsize", "exchange", "openinterest"
};
if (IsCustomData)
{
var keys = (data as DynamicData)?.GetStorageDictionary().ToHashSet(x => x.Key);
// C# types that are not DynamicData type
if (keys == null)
{
if (_membersByType.TryGetValue(type, out _members))
{
keys = _members.ToHashSet(x => x.Name.ToLowerInvariant());
}
else
{
var members = type.GetMembers().Where(x => x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property).ToList();
var duplicateKeys = members.GroupBy(x => x.Name.ToLowerInvariant()).Where(x => x.Count() > 1).Select(x => x.Key);
foreach (var duplicateKey in duplicateKeys)
{
throw new ArgumentException($"PandasData.ctor(): More than one \'{duplicateKey}\' member was found in \'{type.FullName}\' class.");
}
// If the custom data derives from a Market Data (e.g. Tick, TradeBar, QuoteBar), exclude its keys
keys = members.ToHashSet(x => x.Name.ToLowerInvariant());
keys.ExceptWith(_baseDataProperties);
keys.ExceptWith(GetPropertiesNames(typeof(QuoteBar), type));
keys.ExceptWith(GetPropertiesNames(typeof(TradeBar), type));
keys.ExceptWith(GetPropertiesNames(typeof(Tick), type));
keys.Add("value");
_members = members.Where(x => keys.Contains(x.Name.ToLowerInvariant())).ToList();
_membersByType.TryAdd(type, _members);
}
}
columns.Add("value");
columns.UnionWith(keys);
}
_series = columns.ToDictionary(k => k, v => Tuple.Create(new List<DateTime>(), new List<object>()));
}
/// <summary>
/// Adds security data object to the end of the lists
/// </summary>
/// <param name="baseData"><see cref="IBaseData"/> object that contains security data</param>
public void Add(object baseData)
{
foreach (var member in _members)
{
var key = member.Name.ToLowerInvariant();
var endTime = ((IBaseData) baseData).EndTime;
var propertyMember = member as PropertyInfo;
if (propertyMember != null)
{
AddToSeries(key, endTime, propertyMember.GetValue(baseData));
continue;
}
var fieldMember = member as FieldInfo;
if (fieldMember != null)
{
AddToSeries(key, endTime, fieldMember.GetValue(baseData));
}
}
var storage = (baseData as DynamicData)?.GetStorageDictionary();
if (storage != null)
{
var endTime = ((IBaseData) baseData).EndTime;
var value = ((IBaseData) baseData).Value;
AddToSeries("value", endTime, value);
foreach (var kvp in storage.Where(x => x.Key != "value"))
{
AddToSeries(kvp.Key, endTime, kvp.Value);
}
}
else
{
var ticks = new List<Tick> { baseData as Tick };
var tradeBar = baseData as TradeBar;
var quoteBar = baseData as QuoteBar;
Add(ticks, tradeBar, quoteBar);
}
}
/// <summary>
/// Adds Lean data objects to the end of the lists
/// </summary>
/// <param name="ticks">List of <see cref="Tick"/> object that contains tick information of the security</param>
/// <param name="tradeBar"><see cref="TradeBar"/> object that contains trade bar information of the security</param>
/// <param name="quoteBar"><see cref="QuoteBar"/> object that contains quote bar information of the security</param>
public void Add(IEnumerable<Tick> ticks, TradeBar tradeBar, QuoteBar quoteBar)
{
if (tradeBar != null)
{
var time = tradeBar.EndTime;
AddToSeries("open", time, tradeBar.Open);
AddToSeries("high", time, tradeBar.High);
AddToSeries("low", time, tradeBar.Low);
AddToSeries("close", time, tradeBar.Close);
AddToSeries("volume", time, tradeBar.Volume);
}
if (quoteBar != null)
{
var time = quoteBar.EndTime;
if (tradeBar == null)
{
AddToSeries("open", time, quoteBar.Open);
AddToSeries("high", time, quoteBar.High);
AddToSeries("low", time, quoteBar.Low);
AddToSeries("close", time, quoteBar.Close);
}
if (quoteBar.Ask != null)
{
AddToSeries("askopen", time, quoteBar.Ask.Open);
AddToSeries("askhigh", time, quoteBar.Ask.High);
AddToSeries("asklow", time, quoteBar.Ask.Low);
AddToSeries("askclose", time, quoteBar.Ask.Close);
AddToSeries("asksize", time, quoteBar.LastAskSize);
}
if (quoteBar.Bid != null)
{
AddToSeries("bidopen", time, quoteBar.Bid.Open);
AddToSeries("bidhigh", time, quoteBar.Bid.High);
AddToSeries("bidlow", time, quoteBar.Bid.Low);
AddToSeries("bidclose", time, quoteBar.Bid.Close);
AddToSeries("bidsize", time, quoteBar.LastBidSize);
}
}
if (ticks != null)
{
foreach (var tick in ticks)
{
if (tick == null) continue;
var time = tick.EndTime;
var column = tick.TickType == TickType.OpenInterest
? "openinterest"
: "lastprice";
if (tick.TickType == TickType.Quote)
{
AddToSeries("askprice", time, tick.AskPrice);
AddToSeries("asksize", time, tick.AskSize);
AddToSeries("bidprice", time, tick.BidPrice);
AddToSeries("bidsize", time, tick.BidSize);
}
AddToSeries("exchange", time, tick.Exchange);
AddToSeries("suspicious", time, tick.Suspicious);
AddToSeries("quantity", time, tick.Quantity);
AddToSeries(column, time, tick.LastPrice);
}
}
}
/// <summary>
/// Get the pandas.DataFrame of the current <see cref="PandasData"/> state
/// </summary>
/// <param name="levels">Number of levels of the multi index</param>
/// <returns>pandas.DataFrame object</returns>
public PyObject ToPandasDataFrame(int levels = 2)
{
var empty = new PyString(string.Empty);
var list = Enumerable.Repeat<PyObject>(empty, 5).ToList();
list[3] = _symbol.ID.ToString().ToPython();
if (_symbol.SecurityType == SecurityType.Future)
{
list[0] = _symbol.ID.Date.ToPython();
list[3] = _symbol.ID.ToString().ToPython();
}
if (_symbol.SecurityType.IsOption())
{
list[0] = _symbol.ID.Date.ToPython();
list[1] = _symbol.ID.StrikePrice.ToPython();
list[2] = _symbol.ID.OptionRight.ToString().ToPython();
list[3] = _symbol.ID.ToString().ToPython();
}
// Create the index labels
var names = "expiry,strike,type,symbol,time";
if (levels == 2)
{
names = "symbol,time";
list.RemoveRange(0, 3);
}
if (levels == 3)
{
names = "expiry,symbol,time";
list.RemoveRange(1, 2);
}
Func<object, bool> filter = x =>
{
var isNaNOrZero = x is double && ((double)x).IsNaNOrZero();
var isNullOrWhiteSpace = x is string && string.IsNullOrWhiteSpace((string)x);
var isFalse = x is bool && !(bool)x;
return x == null || isNaNOrZero || isNullOrWhiteSpace || isFalse;
};
Func<DateTime, PyTuple> selector = x =>
{
list[list.Count - 1] = x.ToPython();
return new PyTuple(list.ToArray());
};
// creating the pandas MultiIndex is expensive so we keep a cash
var indexCache = new Dictionary<List<DateTime>, dynamic>(new ListComparer<DateTime>());
using (Py.GIL())
{
// Returns a dictionary keyed by column name where values are pandas.Series objects
var pyDict = new PyDict();
var splitNames = names.Split(',');
foreach (var kvp in _series)
{
var values = kvp.Value.Item2;
if (values.All(filter)) continue;
dynamic index;
if (!indexCache.TryGetValue(kvp.Value.Item1, out index))
{
var tuples = kvp.Value.Item1.Select(selector).ToArray();
index = _pandas.MultiIndex.from_tuples(tuples, names: splitNames);
indexCache[kvp.Value.Item1] = index;
}
// Adds pandas.Series value keyed by the column name
pyDict.SetItem(kvp.Key, _pandas.Series(values, index));
}
_series.Clear();
// Create the DataFrame
return _pandas.DataFrame(pyDict);
}
}
/// <summary>
/// Adds data to dictionary
/// </summary>
/// <param name="key">The key of the value to get</param>
/// <param name="time"><see cref="DateTime"/> object to add to the value associated with the specific key</param>
/// <param name="input"><see cref="Object"/> to add to the value associated with the specific key. Can be null.</param>
private void AddToSeries(string key, DateTime time, object input)
{
Tuple<List<DateTime>, List<object>> value;
if (_series.TryGetValue(key, out value))
{
value.Item1.Add(time);
value.Item2.Add(input is decimal ? input.ConvertInvariant<double>() : input);
}
else
{
throw new ArgumentException($"PandasData.AddToSeries(): {key} key does not exist in series dictionary.");
}
}
/// <summary>
/// Get the lower-invariant name of properties of the type that a another type is assignable from
/// </summary>
/// <param name="baseType">The type that is assignable from</param>
/// <param name="type">The type that is assignable by</param>
/// <returns>List of string. Empty list if not assignable from</returns>
private static IEnumerable<string> GetPropertiesNames(Type baseType, Type type)
{
return baseType.IsAssignableFrom(type)
? baseType.GetProperties().Select(x => x.Name.ToLowerInvariant())
: Enumerable.Empty<string>();
}
}
}
| |
using System;
using System.Collections;
using System.Web;
using System.Xml;
using StackExchange.Profiling;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Profiling;
using Umbraco.Core.Strings;
namespace umbraco
{
/// <summary>
///
/// </summary>
public class item
{
private String _fieldContent = "";
private readonly String _fieldName;
public String FieldContent
{
get { return _fieldContent; }
}
public item(string itemValue, IDictionary attributes)
{
_fieldContent = itemValue;
ParseItem(attributes);
}
/// <summary>
/// Creates a new Legacy item
/// </summary>
/// <param name="elements"></param>
/// <param name="attributes"></param>
public item(IDictionary elements, IDictionary attributes)
: this(null, elements, attributes)
{
}
/// <summary>
/// Creates an Item with a publishedContent item in order to properly recurse and return the value.
/// </summary>
/// <param name="publishedContent"></param>
/// <param name="elements"></param>
/// <param name="attributes"></param>
/// <remarks>
/// THIS ENTIRE CLASS WILL BECOME LEGACY, THE FIELD RENDERING NEEDS TO BE REPLACES SO THAT IS WHY THIS
/// CTOR IS INTERNAL.
/// </remarks>
internal item(IPublishedContent publishedContent, IDictionary elements, IDictionary attributes)
{
_fieldName = helper.FindAttribute(attributes, "field");
if (_fieldName.StartsWith("#"))
{
_fieldContent = library.GetDictionaryItem(_fieldName.Substring(1, _fieldName.Length - 1));
}
else
{
// Loop through XML children we need to find the fields recursive
if (helper.FindAttribute(attributes, "recursive") == "true")
{
if (publishedContent == null)
{
var recursiveVal = GetRecursiveValueLegacy(elements);
_fieldContent = recursiveVal.IsNullOrWhiteSpace() ? _fieldContent : recursiveVal;
}
else
{
var recursiveVal = publishedContent.GetRecursiveValue(_fieldName);
_fieldContent = recursiveVal.IsNullOrWhiteSpace() ? _fieldContent : recursiveVal;
}
}
else
{
if (elements[_fieldName] != null && !string.IsNullOrEmpty(elements[_fieldName].ToString()))
{
_fieldContent = elements[_fieldName].ToString().Trim();
}
else if (!string.IsNullOrEmpty(helper.FindAttribute(attributes, "useIfEmpty")))
{
if (elements[helper.FindAttribute(attributes, "useIfEmpty")] != null && !string.IsNullOrEmpty(elements[helper.FindAttribute(attributes, "useIfEmpty")].ToString()))
{
_fieldContent = elements[helper.FindAttribute(attributes, "useIfEmpty")].ToString().Trim();
}
}
}
}
ParseItem(attributes);
}
/// <summary>
/// Returns the recursive value using a legacy strategy of looking at the xml cache and the splitPath in the elements collection
/// </summary>
/// <param name="elements"></param>
/// <returns></returns>
private string GetRecursiveValueLegacy(IDictionary elements)
{
using (DisposableTimer.DebugDuration<item>("Checking recusively"))
{
var content = "";
var umbracoXml = presentation.UmbracoContext.Current.GetXml();
var splitpath = (String[])elements["splitpath"];
for (int i = 0; i < splitpath.Length - 1; i++)
{
XmlNode element = umbracoXml.GetElementById(splitpath[splitpath.Length - i - 1]);
if (element == null)
continue;
var xpath = UmbracoSettings.UseLegacyXmlSchema ? "./data [@alias = '{0}']" : "./{0}";
var currentNode = element.SelectSingleNode(string.Format(xpath, _fieldName));
//continue if all is null
if (currentNode == null || currentNode.FirstChild == null || string.IsNullOrEmpty(currentNode.FirstChild.Value) || string.IsNullOrEmpty(currentNode.FirstChild.Value.Trim()))
continue;
HttpContext.Current.Trace.Write("item.recursive", "Item loaded from " + splitpath[splitpath.Length - i - 1]);
content = currentNode.FirstChild.Value;
break;
}
return content;
}
}
private void ParseItem(IDictionary attributes)
{
using (DisposableTimer.DebugDuration<item>("Start parsing " + _fieldName))
{
HttpContext.Current.Trace.Write("item", "Start parsing '" + _fieldName + "'");
if (helper.FindAttribute(attributes, "textIfEmpty") != "" && _fieldContent == "")
_fieldContent = helper.FindAttribute(attributes, "textIfEmpty");
_fieldContent = _fieldContent.Trim();
// DATE FORMATTING FUNCTIONS
if (helper.FindAttribute(attributes, "formatAsDateWithTime") == "true")
{
if (_fieldContent == "")
_fieldContent = DateTime.Now.ToString();
_fieldContent = Convert.ToDateTime(_fieldContent).ToLongDateString() +
helper.FindAttribute(attributes, "formatAsDateWithTimeSeparator") +
Convert.ToDateTime(_fieldContent).ToShortTimeString();
}
else if (helper.FindAttribute(attributes, "formatAsDate") == "true")
{
if (_fieldContent == "")
_fieldContent = DateTime.Now.ToString();
_fieldContent = Convert.ToDateTime(_fieldContent).ToLongDateString();
}
// TODO: Needs revision to check if parameter-tags has attributes
if (helper.FindAttribute(attributes, "stripParagraph") == "true" && _fieldContent.Length > 5)
{
_fieldContent = _fieldContent.Trim();
string fieldContentLower = _fieldContent.ToLower();
// the field starts with an opening p tag
if (fieldContentLower.Substring(0, 3) == "<p>"
// it ends with a closing p tag
&& fieldContentLower.Substring(_fieldContent.Length - 4, 4) == "</p>"
// it doesn't contain multiple p-tags
&& fieldContentLower.IndexOf("<p>", 1) < 0)
{
_fieldContent = _fieldContent.Substring(3, _fieldContent.Length - 7);
}
}
// CASING
if (helper.FindAttribute(attributes, "case") == "lower")
_fieldContent = _fieldContent.ToLower();
else if (helper.FindAttribute(attributes, "case") == "upper")
_fieldContent = _fieldContent.ToUpper();
else if (helper.FindAttribute(attributes, "case") == "title")
_fieldContent = _fieldContent.ToCleanString(CleanStringType.Ascii | CleanStringType.Alias | CleanStringType.PascalCase);
// OTHER FORMATTING FUNCTIONS
// If we use masterpages, this is moved to the ItemRenderer to add support for before/after in inline XSLT
if (!UmbracoSettings.UseAspNetMasterPages)
{
if (_fieldContent != "" && helper.FindAttribute(attributes, "insertTextBefore") != "")
_fieldContent = HttpContext.Current.Server.HtmlDecode(helper.FindAttribute(attributes, "insertTextBefore")) +
_fieldContent;
if (_fieldContent != "" && helper.FindAttribute(attributes, "insertTextAfter") != "")
_fieldContent += HttpContext.Current.Server.HtmlDecode(helper.FindAttribute(attributes, "insertTextAfter"));
}
if (helper.FindAttribute(attributes, "urlEncode") == "true")
_fieldContent = HttpUtility.UrlEncode(_fieldContent);
if (helper.FindAttribute(attributes, "htmlEncode") == "true")
_fieldContent = HttpUtility.HtmlEncode(_fieldContent);
if (helper.FindAttribute(attributes, "convertLineBreaks") == "true")
_fieldContent = _fieldContent.Replace("\n", "<br/>\n");
HttpContext.Current.Trace.Write("item", "Done parsing '" + _fieldName + "'");
}
}
}
}
| |
// 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.Diagnostics.Contracts;
namespace System.Globalization
{
public partial class CompareInfo
{
private unsafe void InitSort(CultureInfo culture)
{
const uint LCMAP_SORTHANDLE = 0x20000000;
_sortName = culture.SortName;
IntPtr handle;
int ret = Interop.mincore.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero);
_sortHandle = ret > 0 ? handle : IntPtr.Zero;
}
private static unsafe int FindStringOrdinal(
uint dwFindStringOrdinalFlags,
string stringSource,
int offset,
int cchSource,
string value,
int cchValue,
bool bIgnoreCase)
{
fixed (char* pSource = stringSource)
fixed (char* pValue = value)
{
int ret = Interop.mincore.FindStringOrdinal(
dwFindStringOrdinalFlags,
pSource + offset,
cchSource,
pValue,
cchValue,
bIgnoreCase ? 1 : 0);
return ret < 0 ? ret : ret + offset;
}
}
internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
}
internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
}
private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Debug.Assert(source != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int tmpHash = 0;
fixed (char* pSource = source)
{
if (Interop.mincore.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
LCMAP_HASH | (uint)GetNativeCompareFlags(options),
pSource, source.Length,
&tmpHash, sizeof(int),
null, null, _sortHandle) == 0)
{
Environment.FailFast("LCMapStringEx failed!");
}
}
return tmpHash;
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
// Use the OS to compare and then convert the result to expected value by subtracting 2
return Interop.mincore.CompareStringOrdinal(string1, count1, string2, count2, true) - 2;
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Debug.Assert(string1 != null);
Debug.Assert(string2 != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pString1 = string1)
fixed (char* pString2 = string2)
{
int result = Interop.mincore.CompareStringEx(
pLocaleName,
(uint)GetNativeCompareFlags(options),
pString1 + offset1,
length1,
pString2 + offset2,
length2,
null,
null,
_sortHandle);
if (result == 0)
{
Environment.FailFast("CompareStringEx failed");
}
// Map CompareStringEx return value to -1, 0, 1.
return result - 2;
}
}
private unsafe int FindString(
uint dwFindNLSStringFlags,
string lpStringSource,
int startSource,
int cchSource,
string lpStringValue,
int startValue,
int cchValue,
int* matchLengthPtr)
{
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pSource = lpStringSource)
fixed (char* pValue = lpStringValue)
{
char* pS = pSource + startSource;
char* pV = pValue + startValue;
return Interop.mincore.FindNLSStringEx(
pLocaleName,
dwFindNLSStringFlags,
pS,
cchSource,
pV,
cchValue,
null,
null,
null,
_sortHandle,
matchLengthPtr);
}
}
internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
int index;
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
if (target.Length == 0)
{
if(matchLengthPtr != null)
*matchLengthPtr = 0;
return startIndex; // keep Whidbey compatibility
}
if ((options & CompareOptions.Ordinal) != 0)
{
index = FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false);
if(index != -1 && matchLengthPtr != null)
*matchLengthPtr = target.Length;
return index;
}
else
{
int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options),
source,
startIndex,
count,
target,
0,
target.Length,
matchLengthPtr);
if (retValue >= 0)
{
return retValue + startIndex;
}
}
return -1;
}
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
if (target.Length == 0)
return startIndex; // keep Whidbey compatibility
if ((options & CompareOptions.Ordinal) != 0)
{
return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true);
}
else
{
int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options),
source,
startIndex - count + 1,
count,
target,
0,
target.Length,
null);
if (retValue >= 0)
{
return retValue + startIndex - (count - 1);
}
}
return -1;
}
private unsafe bool StartsWith(string source, string prefix, CompareOptions options)
{
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(prefix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options),
source,
0,
source.Length,
prefix,
0,
prefix.Length,
null) >= 0;
}
private unsafe bool EndsWith(string source, string suffix, CompareOptions options)
{
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(suffix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options),
source,
0,
source.Length,
suffix,
0,
suffix.Length,
null) >= 0;
}
// PAL ends here
[NonSerialized]
private IntPtr _sortHandle;
private const uint LCMAP_HASH = 0x00040000;
private const int FIND_STARTSWITH = 0x00100000;
private const int FIND_ENDSWITH = 0x00200000;
private const int FIND_FROMSTART = 0x00400000;
private const int FIND_FROMEND = 0x00800000;
// TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false?
private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex)
{
int retValue = -1;
int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex;
fixed (char* pSource = source, spTarget = target)
{
char* spSubSource = pSource + sourceStartIndex;
if (findLastIndex)
{
int startPattern = (sourceCount - 1) - targetCount + 1;
if (startPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex - sourceCount + 1;
}
}
else
{
int endPattern = (sourceCount - 1) - targetCount + 1;
if (endPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex;
}
}
}
return retValue;
}
private unsafe SortKey CreateSortKey(String source, CompareOptions options)
{
if (source == null) { throw new ArgumentNullException(nameof(source)); }
Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
throw new NotImplementedException();
}
private static unsafe bool IsSortable(char* text, int length)
{
// CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
// return (InternalIsSortable(c.m_dataHandle, c.m_handleOrigin, c.m_sortName, text, text.Length));
throw new NotImplementedException();
}
private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal
private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead)
private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal.
private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead)
private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols.
private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character.
private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing
private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols.
private static int GetNativeCompareFlags(CompareOptions options)
{
// Use "linguistic casing" by default (load the culture's casing exception tables)
int nativeCompareFlags = NORM_LINGUISTIC_CASING;
if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; }
if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; }
if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; }
if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; }
if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; }
if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; }
// TODO: Can we try for GetNativeCompareFlags to never
// take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special
// in some places.
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
CompareOptions.IgnoreWidth |
CompareOptions.StringSort)) == 0) ||
(options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
return nativeCompareFlags;
}
private SortVersion GetSortVersion()
{
throw new NotImplementedException();
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* support class for constructing intergrated encryption ciphers
* for doing basic message exchanges on top of key agreement ciphers
*/
public class IesEngine
{
private readonly IBasicAgreement agree;
private readonly IDerivationFunction kdf;
private readonly IMac mac;
private readonly BufferedBlockCipher cipher;
private readonly byte[] macBuf;
private bool forEncryption;
private ICipherParameters privParam, pubParam;
private IesParameters param;
/**
* set up for use with stream mode, where the key derivation function
* is used to provide a stream of bytes to xor with the message.
*
* @param agree the key agreement used as the basis for the encryption
* @param kdf the key derivation function used for byte generation
* @param mac the message authentication code generator for the message
*/
public IesEngine(
IBasicAgreement agree,
IDerivationFunction kdf,
IMac mac)
{
this.agree = agree;
this.kdf = kdf;
this.mac = mac;
this.macBuf = new byte[mac.GetMacSize()];
// this.cipher = null;
}
/**
* set up for use in conjunction with a block cipher to handle the
* message.
*
* @param agree the key agreement used as the basis for the encryption
* @param kdf the key derivation function used for byte generation
* @param mac the message authentication code generator for the message
* @param cipher the cipher to used for encrypting the message
*/
public IesEngine(
IBasicAgreement agree,
IDerivationFunction kdf,
IMac mac,
BufferedBlockCipher cipher)
{
this.agree = agree;
this.kdf = kdf;
this.mac = mac;
this.macBuf = new byte[mac.GetMacSize()];
this.cipher = cipher;
}
/**
* Initialise the encryptor.
*
* @param forEncryption whether or not this is encryption/decryption.
* @param privParam our private key parameters
* @param pubParam the recipient's/sender's public key parameters
* @param param encoding and derivation parameters.
*/
public void Init(
bool forEncryption,
ICipherParameters privParameters,
ICipherParameters pubParameters,
ICipherParameters iesParameters)
{
this.forEncryption = forEncryption;
this.privParam = privParameters;
this.pubParam = pubParameters;
this.param = (IesParameters)iesParameters;
}
private byte[] DecryptBlock(
byte[] in_enc,
int inOff,
int inLen,
byte[] z)
{
byte[] M = null;
KeyParameter macKey = null;
KdfParameters kParam = new KdfParameters(z, param.GetDerivationV());
int macKeySize = param.MacKeySize;
kdf.Init(kParam);
inLen -= mac.GetMacSize();
if (cipher == null) // stream mode
{
byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));
M = new byte[inLen];
for (int i = 0; i != inLen; i++)
{
M[i] = (byte)(in_enc[inOff + i] ^ Buffer[i]);
}
macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8));
}
else
{
int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));
cipher.Init(false, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));
M = cipher.DoFinal(in_enc, inOff, inLen);
macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8));
}
byte[] macIV = param.GetEncodingV();
mac.Init(macKey);
mac.BlockUpdate(in_enc, inOff, inLen);
mac.BlockUpdate(macIV, 0, macIV.Length);
mac.DoFinal(macBuf, 0);
inOff += inLen;
for (int t = 0; t < macBuf.Length; t++)
{
if (macBuf[t] != in_enc[inOff + t])
{
throw (new InvalidCipherTextException("IMac codes failed to equal."));
}
}
return M;
}
private byte[] EncryptBlock(
byte[] input,
int inOff,
int inLen,
byte[] z)
{
byte[] C = null;
KeyParameter macKey = null;
KdfParameters kParam = new KdfParameters(z, param.GetDerivationV());
int c_text_length = 0;
int macKeySize = param.MacKeySize;
if (cipher == null) // stream mode
{
byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));
C = new byte[inLen + mac.GetMacSize()];
c_text_length = inLen;
for (int i = 0; i != inLen; i++)
{
C[i] = (byte)(input[inOff + i] ^ Buffer[i]);
}
macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8));
}
else
{
int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));
cipher.Init(true, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));
c_text_length = cipher.GetOutputSize(inLen);
byte[] tmp = new byte[c_text_length];
int len = cipher.ProcessBytes(input, inOff, inLen, tmp, 0);
len += cipher.DoFinal(tmp, len);
C = new byte[len + mac.GetMacSize()];
c_text_length = len;
Array.Copy(tmp, 0, C, 0, len);
macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8));
}
byte[] macIV = param.GetEncodingV();
mac.Init(macKey);
mac.BlockUpdate(C, 0, c_text_length);
mac.BlockUpdate(macIV, 0, macIV.Length);
//
// return the message and it's MAC
//
mac.DoFinal(C, c_text_length);
return C;
}
private byte[] GenerateKdfBytes(
KdfParameters kParam,
int length)
{
byte[] buf = new byte[length];
kdf.Init(kParam);
kdf.GenerateBytes(buf, 0, buf.Length);
return buf;
}
public byte[] ProcessBlock(
byte[] input,
int inOff,
int inLen)
{
agree.Init(privParam);
BigInteger z = agree.CalculateAgreement(pubParam);
// TODO Is a fixed length result expected?
byte[] zBytes = z.ToByteArrayUnsigned();
return forEncryption
? EncryptBlock(input, inOff, inLen, zBytes)
: DecryptBlock(input, inOff, inLen, zBytes);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class libproc
{
// Constants from sys\param.h
private const int MAXCOMLEN = 16;
private const int MAXPATHLEN = 1024;
// Constants from proc_info.h
private const int MAXTHREADNAMESIZE = 64;
private const int PROC_PIDTASKALLINFO = 2;
private const int PROC_PIDTHREADINFO = 5;
private const int PROC_PIDLISTTHREADS = 6;
private const int PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN;
private static int PROC_PIDLISTTHREADS_SIZE = (Marshal.SizeOf<uint>() * 2);
// Constants from sys\resource.h
private const int RUSAGE_SELF = 0;
// Defines from proc_info.h
internal enum ThreadRunState
{
TH_STATE_RUNNING = 1,
TH_STATE_STOPPED = 2,
TH_STATE_WAITING = 3,
TH_STATE_UNINTERRUPTIBLE = 4,
TH_STATE_HALTED = 5
}
// Defines in proc_info.h
[Flags]
internal enum ThreadFlags
{
TH_FLAGS_SWAPPED = 0x1,
TH_FLAGS_IDLE = 0x2
}
// From proc_info.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct proc_bsdinfo
{
internal uint pbi_flags;
internal uint pbi_status;
internal uint pbi_xstatus;
internal uint pbi_pid;
internal uint pbi_ppid;
internal uint pbi_uid;
internal uint pbi_gid;
internal uint pbi_ruid;
internal uint pbi_rgid;
internal uint pbi_svuid;
internal uint pbi_svgid;
internal uint reserved;
internal fixed byte pbi_comm[MAXCOMLEN];
internal fixed byte pbi_name[MAXCOMLEN * 2];
internal uint pbi_nfiles;
internal uint pbi_pgid;
internal uint pbi_pjobc;
internal uint e_tdev;
internal uint e_tpgid;
internal int pbi_nice;
internal ulong pbi_start_tvsec;
internal ulong pbi_start_tvusec;
}
// From proc_info.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct proc_taskinfo
{
internal ulong pti_virtual_size;
internal ulong pti_resident_size;
internal ulong pti_total_user;
internal ulong pti_total_system;
internal ulong pti_threads_user;
internal ulong pti_threads_system;
internal int pti_policy;
internal int pti_faults;
internal int pti_pageins;
internal int pti_cow_faults;
internal int pti_messages_sent;
internal int pti_messages_received;
internal int pti_syscalls_mach;
internal int pti_syscalls_unix;
internal int pti_csw;
internal int pti_threadnum;
internal int pti_numrunning;
internal int pti_priority;
};
// from sys\resource.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct rusage_info_v3
{
internal fixed byte ri_uuid[16];
internal ulong ri_user_time;
internal ulong ri_system_time;
internal ulong ri_pkg_idle_wkups;
internal ulong ri_interrupt_wkups;
internal ulong ri_pageins;
internal ulong ri_wired_size;
internal ulong ri_resident_size;
internal ulong ri_phys_footprint;
internal ulong ri_proc_start_abstime;
internal ulong ri_proc_exit_abstime;
internal ulong ri_child_user_time;
internal ulong ri_child_system_time;
internal ulong ri_child_pkg_idle_wkups;
internal ulong ri_child_interrupt_wkups;
internal ulong ri_child_pageins;
internal ulong ri_child_elapsed_abstime;
internal ulong ri_diskio_bytesread;
internal ulong ri_diskio_byteswritten;
internal ulong ri_cpu_time_qos_default;
internal ulong ri_cpu_time_qos_maintenance;
internal ulong ri_cpu_time_qos_background;
internal ulong ri_cpu_time_qos_utility;
internal ulong ri_cpu_time_qos_legacy;
internal ulong ri_cpu_time_qos_user_initiated;
internal ulong ri_cpu_time_qos_user_interactive;
internal ulong ri_billed_system_time;
internal ulong ri_serviced_system_time;
}
// From proc_info.h
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal unsafe struct proc_taskallinfo
{
internal proc_bsdinfo pbsd;
internal proc_taskinfo ptinfo;
}
// From proc_info.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct proc_threadinfo
{
internal ulong pth_user_time;
internal ulong pth_system_time;
internal int pth_cpu_usage;
internal int pth_policy;
internal int pth_run_state;
internal int pth_flags;
internal int pth_sleep_time;
internal int pth_curpri;
internal int pth_priority;
internal int pth_maxpriority;
internal fixed byte pth_name[MAXTHREADNAMESIZE];
}
[StructLayout(LayoutKind.Sequential)]
internal struct proc_fdinfo
{
internal int proc_fd;
internal uint proc_fdtype;
}
/// <summary>
/// Queries the OS for the PIDs for all running processes
/// </summary>
/// <param name="buffer">A pointer to the memory block where the PID array will start</param>
/// <param name="buffersize">The length of the block of memory allocated for the PID array</param>
/// <returns>Returns the number of elements (PIDs) in the buffer</returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_listallpids(
int* pBuffer,
int buffersize);
/// <summary>
/// Queries the OS for the list of all running processes and returns the PID for each
/// </summary>
/// <returns>Returns a list of PIDs corresponding to all running processes</returns>
internal static unsafe int[] proc_listallpids()
{
// Get the number of processes currently running to know how much data to allocate
int numProcesses = proc_listallpids(null, 0);
if (numProcesses <= 0)
{
throw new Win32Exception(SR.CantGetAllPids);
}
int[] processes;
do
{
// Create a new array for the processes (plus a 10% buffer in case new processes have spawned)
// Since we don't know how many threads there could be, if result == size, that could mean two things
// 1) We guessed exactly how many processes there are
// 2) There are more processes that we didn't get since our buffer is too small
// To make sure it isn't #2, when the result == size, increase the buffer and try again
processes = new int[(int)(numProcesses * 1.10)];
fixed (int* pBuffer = processes)
{
numProcesses = proc_listallpids(pBuffer, processes.Length * Marshal.SizeOf<int>());
if (numProcesses <= 0)
{
throw new Win32Exception(SR.CantGetAllPids);
}
}
}
while (numProcesses == processes.Length);
// Remove extra elements
Array.Resize<int>(ref processes, numProcesses);
return processes;
}
/// <summary>
/// Gets information about a process given it's PID
/// </summary>
/// <param name="pid">The PID of the process</param>
/// <param name="flavor">Should be PROC_PIDTASKALLINFO</param>
/// <param name="arg">Flavor dependent value</param>
/// <param name="buffer">A pointer to a block of memory (of size proc_taskallinfo) allocated that will contain the data</param>
/// <param name="bufferSize">The size of the allocated block above</param>
/// <returns>
/// The amount of data actually returned. If this size matches the bufferSize parameter then
/// the data is valid. If the sizes do not match then the data is invalid, most likely due
/// to not having enough permissions to query for the data of that specific process
/// </returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidinfo(
int pid,
int flavor,
ulong arg,
proc_taskallinfo* buffer,
int bufferSize);
/// <summary>
/// Gets information about a process given it's PID
/// </summary>
/// <param name="pid">The PID of the process</param>
/// <param name="flavor">Should be PROC_PIDTHREADINFO</param>
/// <param name="arg">Flavor dependent value</param>
/// <param name="buffer">A pointer to a block of memory (of size proc_threadinfo) allocated that will contain the data</param>
/// <param name="bufferSize">The size of the allocated block above</param>
/// <returns>
/// The amount of data actually returned. If this size matches the bufferSize parameter then
/// the data is valid. If the sizes do not match then the data is invalid, most likely due
/// to not having enough permissions to query for the data of that specific process
/// </returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidinfo(
int pid,
int flavor,
ulong arg,
proc_threadinfo* buffer,
int bufferSize);
/// <summary>
/// Gets information about a process given it's PID
/// </summary>
/// <param name="pid">The PID of the process</param>
/// <param name="flavor">Should be PROC_PIDLISTFDS</param>
/// <param name="arg">Flavor dependent value</param>
/// <param name="buffer">A pointer to a block of memory (of size proc_fdinfo) allocated that will contain the data</param>
/// <param name="bufferSize">The size of the allocated block above</param>
/// <returns>
/// The amount of data actually returned. If this size matches the bufferSize parameter then
/// the data is valid. If the sizes do not match then the data is invalid, most likely due
/// to not having enough permissions to query for the data of that specific process
/// </returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidinfo(
int pid,
int flavor,
ulong arg,
proc_fdinfo* buffer,
int bufferSize);
/// <summary>
/// Gets information about a process given it's PID
/// </summary>
/// <param name="pid">The PID of the process</param>
/// <param name="flavor">Should be PROC_PIDTASKALLINFO</param>
/// <param name="arg">Flavor dependent value</param>
/// <param name="buffer">A pointer to a block of memory (of size ulong[]) allocated that will contain the data</param>
/// <param name="bufferSize">The size of the allocated block above</param>
/// <returns>
/// The amount of data actually returned. If this size matches the bufferSize parameter then
/// the data is valid. If the sizes do not match then the data is invalid, most likely due
/// to not having enough permissions to query for the data of that specific process
/// </returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidinfo(
int pid,
int flavor,
ulong arg,
ulong* buffer,
int bufferSize);
/// <summary>
/// Gets the process information for a given process
/// </summary>
/// <param name="pid">The PID (process ID) of the process</param>
/// <returns>
/// Returns a valid proc_taskallinfo struct for valid processes that the caller
/// has permission to access; otherwise, returns null
/// </returns>
internal static unsafe proc_taskallinfo? GetProcessInfoById(int pid)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException(nameof(pid));
}
// Get the process information for the specified pid
int size = Marshal.SizeOf<proc_taskallinfo>();
proc_taskallinfo info = default(proc_taskallinfo);
int result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &info, size);
return (result == size ? new proc_taskallinfo?(info) : null);
}
/// <summary>
/// Gets the thread information for the given thread
/// </summary>
/// <param name="thread">The ID of the thread to query for information</param>
/// <returns>
/// Returns a valid proc_threadinfo struct for valid threads that the caller
/// has permissions to access; otherwise, returns null
/// </returns>
internal static unsafe proc_threadinfo? GetThreadInfoById(int pid, ulong thread)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException(nameof(pid));
}
// Negative TIDs are invalid
if (thread < 0)
{
throw new ArgumentOutOfRangeException(nameof(thread));
}
// Get the thread information for the specified thread in the specified process
int size = Marshal.SizeOf<proc_threadinfo>();
proc_threadinfo info = default(proc_threadinfo);
int result = proc_pidinfo(pid, PROC_PIDTHREADINFO, (ulong)thread, &info, size);
return (result == size ? new proc_threadinfo?(info) : null);
}
internal static unsafe List<KeyValuePair<ulong, proc_threadinfo?>> GetAllThreadsInProcess(int pid)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException(nameof(pid));
}
int result = 0;
int size = 20; // start assuming 20 threads is enough
ulong[] threadIds = null;
var threads = new List<KeyValuePair<ulong, proc_threadinfo?>>();
// We have no way of knowning how many threads the process has (and therefore how big our buffer should be)
// so while the return value of the function is the same as our buffer size (meaning it completely filled
// our buffer), double our buffer size and try again. This ensures that we don't miss any threads
do
{
threadIds = new ulong[size];
fixed (ulong* pBuffer = threadIds)
{
result = proc_pidinfo(pid, PROC_PIDLISTTHREADS, 0, pBuffer, Marshal.SizeOf<ulong>() * threadIds.Length);
}
if (result <= 0)
{
// If we were unable to access the information, just return the empty list.
// This is likely to happen for privileged processes, if the process went away
// by the time we tried to query it, etc.
return threads;
}
else
{
checked
{
size *= 2;
}
}
}
while (result == Marshal.SizeOf<ulong>() * threadIds.Length);
Debug.Assert((result % Marshal.SizeOf<ulong>()) == 0);
// Loop over each thread and get the thread info
int count = (int)(result / Marshal.SizeOf<ulong>());
threads.Capacity = count;
for (int i = 0; i < count; i++)
{
threads.Add(new KeyValuePair<ulong, proc_threadinfo?>(threadIds[i], GetThreadInfoById(pid, threadIds[i])));
}
return threads;
}
/// <summary>
/// Gets the full path to the executable file identified by the specified PID
/// </summary>
/// <param name="pid">The PID of the running process</param>
/// <param name="buffer">A pointer to an allocated block of memory that will be filled with the process path</param>
/// <param name="bufferSize">The size of the buffer, should be PROC_PIDPATHINFO_MAXSIZE</param>
/// <returns>Returns the length of the path returned on success</returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidpath(
int pid,
byte* buffer,
uint bufferSize);
/// <summary>
/// Gets the full path to the executable file identified by the specified PID
/// </summary>
/// <param name="pid">The PID of the running process</param>
/// <returns>Returns the full path to the process executable</returns>
internal static unsafe string proc_pidpath(int pid)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException(nameof(pid), SR.NegativePidNotSupported);
}
// The path is a fixed buffer size, so use that and trim it after
int result = 0;
byte* pBuffer = stackalloc byte[PROC_PIDPATHINFO_MAXSIZE];
result = proc_pidpath(pid, pBuffer, (uint)(PROC_PIDPATHINFO_MAXSIZE * Marshal.SizeOf<byte>()));
if (result <= 0)
{
throw new Win32Exception();
}
// OS X uses UTF-8. The conversion may not strip off all trailing \0s so remove them here
return System.Text.Encoding.UTF8.GetString(pBuffer, result);
}
/// <summary>
/// Gets the rusage information for the process identified by the PID
/// </summary>
/// <param name="pid">The process to retrieve the rusage for</param>
/// <param name="flavor">Should be RUSAGE_SELF to specify getting the info for the specified process</param>
/// <param name="rusage_info_t">A buffer to be filled with rusage_info data</param>
/// <returns>Returns 0 on success; on fail, -1 and errno is set with the error code</returns>
/// <remarks>
/// We need to use IntPtr here for the buffer since the function signature uses
/// void* and not a strong type even though it returns a rusage_info struct
/// </remarks>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pid_rusage(
int pid,
int flavor,
rusage_info_v3* rusage_info_t);
/// <summary>
/// Gets the rusage information for the process identified by the PID
/// </summary>
/// <param name="pid">The process to retrieve the rusage for</param>
/// <returns>On success, returns a struct containing info about the process; on
/// failure or when the caller doesn't have permissions to the process, throws a Win32Exception
/// </returns>
internal static unsafe rusage_info_v3 proc_pid_rusage(int pid)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException(nameof(pid), SR.NegativePidNotSupported);
}
rusage_info_v3 info = new rusage_info_v3();
// Get the PIDs rusage info
int result = proc_pid_rusage(pid, RUSAGE_SELF, &info);
if (result < 0)
{
throw new InvalidOperationException(SR.RUsageFailure);
}
return info;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading;
using Xunit;
namespace System.Tests
{
public static class LazyTests
{
[Fact]
public static void TestConstructor()
{
// Make sure the default constructor does not throw
new Lazy<object>();
Assert.Throws<ArgumentNullException>(() => new Lazy<object>(null));
}
[Fact]
public static void TestToString()
{
Lazy<object> lazy = new Lazy<object>(() => (object)1);
Assert.NotEqual(1.ToString(), lazy.ToString());
Assert.False(lazy.IsValueCreated, "ToString shouldn't force allocation");
object tmp = lazy.Value;
Assert.Equal(1.ToString(), lazy.ToString());
}
[Fact]
public static void TestIsValueCreated()
{
Lazy<string> lazy = new Lazy<string>(() => "Test");
Assert.False(lazy.IsValueCreated, "Expected lazy to be uninitialized.");
string temp = lazy.Value;
Assert.True(lazy.IsValueCreated, "Expected lazy to be initialized.");
}
[Fact]
public static void TestValue()
{
string value = "Test";
Lazy<string> lazy = new Lazy<string>(() => value);
string lazilyAllocatedValue = lazy.Value;
Assert.Equal(value, lazilyAllocatedValue);
int valueInt = 99;
Lazy<int> LazyInt = new Lazy<int>(() => valueInt);
int lazilyAllocatedValueInt = LazyInt.Value;
Assert.Equal(valueInt, lazilyAllocatedValueInt);
lazy = new Lazy<string>(() => value, true);
lazilyAllocatedValue = lazy.Value;
Assert.Equal(value, lazilyAllocatedValue);
lazy = new Lazy<string>(() => null, false);
lazilyAllocatedValue = lazy.Value;
Assert.Null(lazilyAllocatedValue);
}
[Fact]
public static void TestValueExceptions()
{
string value = "Test";
Lazy<string> lazy = new Lazy<string>(() => value);
string lazilyAllocatedValue;
Assert.Throws<InvalidOperationException>(() =>
{
int x = 0;
lazy = new Lazy<string>(delegate
{
if (x++ < 5)
return lazy.Value;
else
return "Test";
}, true);
lazilyAllocatedValue = lazy.Value;
});
Assert.Throws<MissingMemberException>(() =>
{
lazy = new Lazy<string>();
lazilyAllocatedValue = lazy.Value;
});
}
[Fact]
public static void TestValueFactoryExceptions()
{
Lazy<string> l = new Lazy<string>(() =>
{
int zero = 0;
int x = 1 / zero;
return "";
}, true);
string s;
Assert.Throws<DivideByZeroException>(() => s = l.Value);
Assert.Throws<DivideByZeroException>(() => s = l.Value);
Assert.False(l.IsValueCreated, "Expected l to be uninitialized");
}
[Fact]
public static void TestLazyInitializerSimpleRefTypes()
{
HasDefaultCtor hdcTemplate = new HasDefaultCtor();
string strTemplate = "foo";
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
Assert.NotNull(LazyInitializer.EnsureInitialized<HasDefaultCtor>(ref a));
Assert.NotNull(a);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized<HasDefaultCtor>(ref b));
Assert.Equal(hdcTemplate, b);
// Func based initialization (uninitialized).
string c = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized<string>(ref c, () => strTemplate));
Assert.Equal(strTemplate, c);
// Func based initialization (already initialized).
string d = strTemplate;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized<string>(ref d, () => strTemplate + "bar"));
Assert.Equal(strTemplate, d);
// Func based initialization (nulls not permitted).
string e = null;
Assert.Throws<InvalidOperationException>(() => LazyInitializer.EnsureInitialized<string>(ref e, () => null));
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized<NoDefaultCtor>(ref ndc));
}
[Fact]
public static void TestLazyInitializerComplexRefTypes()
{
string strTemplate = "foo";
HasDefaultCtor hdcTemplate = new HasDefaultCtor();
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
bool aInit = false;
object aLock = null;
Assert.NotNull(LazyInitializer.EnsureInitialized<HasDefaultCtor>(ref a, ref aInit, ref aLock));
Assert.NotNull(a);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
bool bInit = true;
object bLock = null;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized<HasDefaultCtor>(ref b, ref bInit, ref bLock));
Assert.Equal(hdcTemplate, b);
// Func based initialization (uninitialized).
string c = null;
bool cInit = false;
object cLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized<string>(ref c, ref cInit, ref cLock, () => strTemplate));
Assert.Equal(strTemplate, c);
// Func based initialization (already initialized).
string d = strTemplate;
bool dInit = true;
object dLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized<string>(ref d, ref dInit, ref dLock, () => strTemplate + "bar"));
Assert.Equal(strTemplate, d);
// Func based initialization (nulls *ARE* permitted).
string e = null;
bool einit = false;
object elock = null;
int initCount = 0;
Assert.Null(LazyInitializer.EnsureInitialized<string>(ref e, ref einit, ref elock, () => { initCount++; return null; }));
Assert.Null(e);
Assert.Equal(1, initCount);
Assert.Null(LazyInitializer.EnsureInitialized<string>(ref e, ref einit, ref elock, () => { initCount++; return null; }));
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
bool ndcInit = false;
object ndcLock = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized<NoDefaultCtor>(ref ndc, ref ndcInit, ref ndcLock));
}
[Fact]
public static void TestLazyInitializerComplexValueTypes()
{
LIX empty = new LIX();
LIX template = new LIX(33);
// Activator.CreateInstance (uninitialized).
LIX a = default(LIX);
bool aInit = false;
object aLock = null;
LIX ensuredValA = LazyInitializer.EnsureInitialized<LIX>(ref a, ref aInit, ref aLock);
Assert.Equal(empty, ensuredValA);
Assert.Equal(empty, a);
// Activator.CreateInstance (already initialized).
LIX b = template;
bool bInit = true;
object bLock = null;
LIX ensuredValB = LazyInitializer.EnsureInitialized<LIX>(ref b, ref bInit, ref bLock);
Assert.Equal(template, ensuredValB);
Assert.Equal(template, b);
// Func based initialization (uninitialized).
LIX c = default(LIX);
bool cInit = false;
object cLock = null;
LIX ensuredValC = LazyInitializer.EnsureInitialized<LIX>(ref c, ref cInit, ref cLock, () => template);
Assert.Equal(template, c);
Assert.Equal(template, ensuredValC);
// Func based initialization (already initialized).
LIX d = template;
bool dInit = true;
object dLock = null;
LIX template2 = new LIX(template.f * 2);
LIX ensuredValD = LazyInitializer.EnsureInitialized<LIX>(ref d, ref dInit, ref dLock, () => template2);
Assert.Equal(template, ensuredValD);
Assert.Equal(template, d);
}
#region Helper Classes and Methods
private class HasDefaultCtor { }
private class NoDefaultCtor
{
public NoDefaultCtor(int x) { }
}
private struct LIX
{
internal int f;
public LIX(int f) { this.f = f; }
public override bool Equals(object other) { return other is LIX && ((LIX)other).f == f; }
public override int GetHashCode() { return f.GetHashCode(); }
public override string ToString() { return "LIX<" + f + ">"; }
}
#endregion
}
}
| |
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;
namespace MySqlConnector;
/// <summary>
/// <para><see cref="MySqlBulkLoader"/> lets you efficiently load a MySQL Server Table with data from a CSV or TSV file or <see cref="Stream"/>.</para>
/// <para>Example code:</para>
/// <code>
/// using var connection = new MySqlConnection("...;AllowLoadLocalInfile=True");
/// await connection.OpenAsync();
/// var bulkLoader = new MySqlBulkLoader(connection)
/// {
/// FileName = @"C:\Path\To\file.csv",
/// TableName = "destination",
/// CharacterSet = "UTF8",
/// NumberOfLinesToSkip = 1,
/// FieldTerminator = ",",
/// FieldQuotationCharacter = '"',
/// FieldQuotationOptional = true,
/// Local = true,
/// }
/// var rowCount = await bulkLoader.LoadAsync();
/// </code>
/// </summary>
/// <remarks>Due to <a href="https://mysqlconnector.net/troubleshooting/load-data-local-infile/">security features</a>
/// in MySQL Server, the connection string <strong>must</strong> have <c>AllowLoadLocalInfile=true</c> in order to use a local source.
/// </remarks>
public sealed class MySqlBulkLoader
{
/// <summary>
/// (Optional) The character set of the source data. By default, the database's character set is used.
/// </summary>
public string? CharacterSet { get; set; }
/// <summary>
/// (Optional) A list of the column names in the destination table that should be filled with data from the input file.
/// </summary>
public List<string> Columns { get; }
/// <summary>
/// A <see cref="MySqlBulkLoaderConflictOption"/> value that specifies how conflicts are resolved (default <see cref="MySqlBulkLoaderConflictOption.None"/>).
/// </summary>
public MySqlBulkLoaderConflictOption ConflictOption { get; set; }
/// <summary>
/// The <see cref="MySqlConnection"/> to use.
/// </summary>
public MySqlConnection Connection { get; set; }
/// <summary>
/// (Optional) The character used to escape instances of <see cref="FieldQuotationCharacter"/> within field values.
/// </summary>
public char EscapeCharacter { get; set; }
/// <summary>
/// (Optional) A list of expressions used to set field values from the columns in the source data.
/// </summary>
public List<string> Expressions { get; }
/// <summary>
/// (Optional) The character used to enclose fields in the source data.
/// </summary>
public char FieldQuotationCharacter { get; set; }
/// <summary>
/// Whether quoting fields is optional (default <c>false</c>).
/// </summary>
public bool FieldQuotationOptional { get; set; }
/// <summary>
/// (Optional) The string fields are terminated with.
/// </summary>
public string? FieldTerminator { get; set; }
/// <summary>
/// The name of the local (if <see cref="Local"/> is <c>true</c>) or remote (otherwise) file to load.
/// Either this or <see cref="SourceStream"/> must be set.
/// </summary>
public string? FileName { get; set; }
/// <summary>
/// (Optional) A prefix in each line that should be skipped when loading.
/// </summary>
public string? LinePrefix { get; set; }
/// <summary>
/// (Optional) The string lines are terminated with.
/// </summary>
public string? LineTerminator { get; set; }
/// <summary>
/// Whether a local file is being used (default <c>true</c>).
/// </summary>
public bool Local { get; set; }
/// <summary>
/// The number of lines to skip at the beginning of the file (default <c>0</c>).
/// </summary>
public int NumberOfLinesToSkip { get; set; }
/// <summary>
/// A <see cref="MySqlBulkLoaderPriority"/> giving the priority to load with (default <see cref="MySqlBulkLoaderPriority.None"/>).
/// </summary>
public MySqlBulkLoaderPriority Priority { get; set; }
/// <summary>
/// A <see cref="Stream"/> containing the data to load. Either this or <see cref="FileName"/> must be set.
/// The <see cref="Local"/> property must be <c>true</c> if this is set.
/// </summary>
public Stream? SourceStream
{
get => Source as Stream;
set => Source = value;
}
/// <summary>
/// The name of the table to load into. If this is a reserved word or contains spaces, it must be quoted.
/// </summary>
public string? TableName { get; set; }
/// <summary>
/// The timeout (in milliseconds) to use.
/// </summary>
public int Timeout { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MySqlBulkLoader"/> class with the specified <see cref="MySqlConnection"/>.
/// </summary>
/// <param name="connection">The <see cref="MySqlConnection"/> to use.</param>
public MySqlBulkLoader(MySqlConnection connection)
{
Connection = connection;
Local = true;
Columns = new();
Expressions = new();
}
/// <summary>
/// Loads all data in the source file or stream into the destination table.
/// </summary>
/// <returns>The number of rows inserted.</returns>
#pragma warning disable CA2012 // Safe because method completes synchronously
public int Load() => LoadAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult();
#pragma warning restore CA2012
/// <summary>
/// Asynchronously loads all data in the source file or stream into the destination table.
/// </summary>
/// <returns>A <see cref="Task{Int32}"/> that will be completed with the number of rows inserted.</returns>
public Task<int> LoadAsync() => LoadAsync(IOBehavior.Asynchronous, CancellationToken.None).AsTask();
/// <summary>
/// Asynchronously loads all data in the source file or stream into the destination table.
/// </summary>
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>A <see cref="Task{Int32}"/> that will be completed with the number of rows inserted.</returns>
public Task<int> LoadAsync(CancellationToken cancellationToken) => LoadAsync(IOBehavior.Asynchronous, cancellationToken).AsTask();
internal async ValueTask<int> LoadAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
if (Connection is null)
throw new InvalidOperationException("Connection not set");
if (string.IsNullOrWhiteSpace(TableName))
throw new InvalidOperationException("TableName is required.");
if (!string.IsNullOrWhiteSpace(FileName) && Source is not null)
throw new InvalidOperationException("Exactly one of FileName or SourceStream must be set.");
if (!string.IsNullOrWhiteSpace(FileName))
{
if (Local)
{
// replace the file name with a sentinel so that we know (when processing the result set) that it's not spoofed by the server
var newFileName = GenerateSourceFileName();
lock (s_lock)
s_sources.Add(newFileName, CreateFileStream(FileName!));
FileName = newFileName;
}
}
else
{
if (!Local)
throw new InvalidOperationException("Local must be true to use SourceStream, SourceDataTable, or SourceDataReader.");
FileName = GenerateSourceFileName();
lock (s_lock)
s_sources.Add(FileName, Source!);
}
var closeConnection = false;
if (Connection.State != ConnectionState.Open)
{
closeConnection = true;
Connection.Open();
}
bool closeStream = SourceStream is not null;
try
{
if (Local && !Connection.AllowLoadLocalInfile)
throw new NotSupportedException("To use MySqlBulkLoader.Local=true, set AllowLoadLocalInfile=true in the connection string. See https://fl.vu/mysql-load-data");
using var cmd = new MySqlCommand(CreateSql(), Connection, Connection.CurrentTransaction)
{
AllowUserVariables = true,
CommandTimeout = Timeout,
};
var result = await cmd.ExecuteNonQueryAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
closeStream = false;
return result;
}
finally
{
if (closeStream && TryGetAndRemoveSource(FileName!, out var source))
((IDisposable) source).Dispose();
if (closeConnection)
Connection.Close();
}
}
internal const string SourcePrefix = ":SOURCE:";
internal object? Source { get; set; }
private string CreateSql()
{
var sb = new StringBuilder("LOAD DATA ");
sb.Append(Priority switch
{
MySqlBulkLoaderPriority.Low => "LOW_PRIORITY ",
MySqlBulkLoaderPriority.Concurrent => "CONCURRENT ",
_ => "",
});
if (Local)
sb.Append("LOCAL ");
sb.AppendFormat(CultureInfo.InvariantCulture, "INFILE '{0}' ", MySqlHelper.EscapeString(FileName!));
sb.Append(ConflictOption switch
{
MySqlBulkLoaderConflictOption.Replace => "REPLACE ",
MySqlBulkLoaderConflictOption.Ignore => "IGNORE ",
_ => "",
});
sb.AppendFormat(CultureInfo.InvariantCulture, "INTO TABLE {0} ", TableName);
if (CharacterSet is not null)
sb.AppendFormat(CultureInfo.InvariantCulture, "CHARACTER SET {0} ", CharacterSet);
var fieldsTerminatedBy = FieldTerminator is null ? "" : "TERMINATED BY '{0}' ".FormatInvariant(MySqlHelper.EscapeString(FieldTerminator));
var fieldsEnclosedBy = FieldQuotationCharacter == default ? "" : "{0}ENCLOSED BY '{1}' ".FormatInvariant(FieldQuotationOptional ? "OPTIONALLY " : "", MySqlHelper.EscapeString(FieldQuotationCharacter.ToString()));
var fieldsEscapedBy = EscapeCharacter == default ? "" : "ESCAPED BY '{0}' ".FormatInvariant(MySqlHelper.EscapeString(EscapeCharacter.ToString()));
if (fieldsTerminatedBy.Length + fieldsEnclosedBy.Length + fieldsEscapedBy.Length > 0)
sb.AppendFormat(CultureInfo.InvariantCulture, "FIELDS {0}{1}{2}", fieldsTerminatedBy, fieldsEnclosedBy, fieldsEscapedBy);
var linesTerminatedBy = LineTerminator is null ? "" : "TERMINATED BY '{0}' ".FormatInvariant(MySqlHelper.EscapeString(LineTerminator));
var linesStartingBy = LinePrefix is null ? "" : "STARTING BY '{0}' ".FormatInvariant(MySqlHelper.EscapeString(LinePrefix));
if (linesTerminatedBy.Length + linesStartingBy.Length > 0)
sb.AppendFormat(CultureInfo.InvariantCulture, "LINES {0}{1}", linesTerminatedBy, linesStartingBy);
sb.AppendFormat(CultureInfo.InvariantCulture, "IGNORE {0} LINES ", NumberOfLinesToSkip);
if (Columns.Count > 0)
sb.AppendFormat(CultureInfo.InvariantCulture, "({0}) ", string.Join(",", Columns));
if (Expressions.Count > 0)
sb.AppendFormat(CultureInfo.InvariantCulture, "SET {0}", string.Join(",", Expressions));
sb.Append(';');
return sb.ToString();
}
private static Stream CreateFileStream(string fileName)
{
try
{
return File.OpenRead(fileName);
}
catch (Exception ex)
{
throw new MySqlException($"Could not access file \"{fileName}\"", ex);
}
}
internal static object GetAndRemoveSource(string sourceKey)
{
lock (s_lock)
{
var source = s_sources[sourceKey];
s_sources.Remove(sourceKey);
return source;
}
}
internal static bool TryGetAndRemoveSource(string sourceKey, [NotNullWhen(true)] out object? source)
{
lock (s_lock)
{
if (s_sources.TryGetValue(sourceKey, out source))
{
s_sources.Remove(sourceKey);
return true;
}
}
return false;
}
private static string GenerateSourceFileName() => SourcePrefix + Guid.NewGuid().ToString("N");
private static readonly object s_lock = new();
private static readonly Dictionary<string, object> s_sources = new();
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using SquishIt.Framework.Files;
using SquishIt.Framework.Renderers;
using SquishIt.Framework.Utilities;
namespace SquishIt.Framework.Base
{
public abstract partial class BundleBase<T> where T : BundleBase<T>
{
IEnumerable<string> GetFiles(IEnumerable<Asset> assets)
{
var inputFiles = assets.Select(a => Input.FromAsset(a, pathTranslator, IsDebuggingEnabled));
var resolvedFilePaths = new List<string>();
foreach (Input input in inputFiles)
{
resolvedFilePaths.AddRange(input.Resolve(allowedExtensions, disallowedExtensions, debugExtension));
}
return resolvedFilePaths;
}
protected IEnumerable<string> GetFilesForSingleAsset(Asset asset)
{
var inputFile = Input.FromAsset(asset, pathTranslator, IsDebuggingEnabled);
return inputFile.Resolve(allowedExtensions, disallowedExtensions, debugExtension);
}
protected IPreprocessor[] FindPreprocessors(string file)
{
//using rails convention of applying preprocessing based on file extension components in reverse order
return file.Split('.')
.Skip(1)
.Reverse()
.Select(FindPreprocessor)
.TakeWhile(p => p != null)
.Where(p => !(p is NullPreprocessor))
.ToArray();
}
protected string PreprocessFile(string file, IPreprocessor[] preprocessors)
{
return directoryWrapper.ExecuteInDirectory(Path.GetDirectoryName(file),
() => PreprocessContent(file, preprocessors, ReadFile(file)));
}
protected string PreprocessArbitrary(Asset asset)
{
if (!asset.IsArbitrary) throw new InvalidOperationException("PreprocessArbitrary can only be called on Arbitrary assets.");
var filename = "dummy." + (asset.Extension ?? defaultExtension);
var preprocessors = FindPreprocessors(filename);
return asset.ArbitraryWorkingDirectory != null ?
directoryWrapper.ExecuteInDirectory(asset.ArbitraryWorkingDirectory, () => MinifyIfNeeded(PreprocessContent(filename, preprocessors, asset.Content), asset.Minify)) :
MinifyIfNeeded(PreprocessContent(filename, preprocessors, asset.Content), asset.Minify);
}
protected string PreprocessContent(string file, IPreprocessor[] preprocessors, string content)
{
return preprocessors.NullSafeAny()
? preprocessors.Aggregate(content, (cntnt, pp) =>
{
var result = pp.Process(file, cntnt);
bundleState.DependentFiles.AddRange(result.Dependencies);
return result.Result;
})
: content;
}
IPreprocessor FindPreprocessor(string extension)
{
var instanceTypes = bundleState.Preprocessors.Select(ipp => ipp.GetType()).ToArray();
var preprocessor =
bundleState.Preprocessors.Union(Configuration.Instance.Preprocessors.Where(pp => !instanceTypes.Contains(pp.GetType())))
.FirstOrDefault(p => p.ValidFor(extension));
return preprocessor;
}
protected string ReadFile(string file)
{
using (var sr = fileReaderFactory.GetFileReader(file))
{
return sr.ReadToEnd();
}
}
bool FileExists(string file)
{
return fileReaderFactory.FileExists(file);
}
string GetAdditionalAttributes(BundleState state)
{
var result = new StringBuilder();
foreach (var attribute in state.Attributes)
{
result.Append(attribute.Key);
result.Append("=\"");
result.Append(attribute.Value);
result.Append("\" ");
}
return result.ToString();
}
string GetFilesForRemote(IEnumerable<string> remoteAssetPaths, BundleState state)
{
var sb = new StringBuilder();
foreach (var uri in remoteAssetPaths)
{
sb.Append(FillTemplate(state, uri));
}
return sb.ToString();
}
string Render(string renderTo, string key, IRenderer renderer)
{
var cacheUniquenessHash = key.Contains("#") ? hasher.GetHash(bundleState.Assets
.Select(a => a.IsRemote ? a.RemotePath :
a.IsArbitrary ? a.Content : a.LocalPath)
.OrderBy(s => s)
.Aggregate(string.Empty, (acc, val) => acc + val)) : string.Empty;
key = CachePrefix + key + cacheUniquenessHash;
if (!String.IsNullOrEmpty(BaseOutputHref))
{
key = BaseOutputHref + key;
}
if (IsDebuggingEnabled())
{
var content = RenderDebug(renderTo, key, renderer);
return content;
}
return RenderRelease(key, renderTo, renderer);
}
string RenderDebug(string renderTo, string name, IRenderer renderer)
{
bundleState.DependentFiles.Clear();
var renderedFiles = new HashSet<string>();
var sb = new StringBuilder();
bundleState.DependentFiles.AddRange(GetFiles(bundleState.Assets.Where(a => !a.IsArbitrary).ToList()));
foreach (var asset in bundleState.Assets)
{
if (asset.IsArbitrary)
{
var filename = "dummy" + asset.Extension;
var preprocessors = FindPreprocessors(filename);
var processedContent = asset.ArbitraryWorkingDirectory != null ?
directoryWrapper.ExecuteInDirectory(asset.ArbitraryWorkingDirectory, () => PreprocessContent(filename, preprocessors, asset.Content)) :
PreprocessContent(filename, preprocessors, asset.Content);
sb.AppendLine(string.Format(tagFormat, processedContent));
}
else
{
var inputFile = Input.FromAsset(asset, pathTranslator, IsDebuggingEnabled);
var files = inputFile.Resolve(allowedExtensions, disallowedExtensions, debugExtension);
if (asset.IsEmbeddedResource)
{
var tsb = new StringBuilder();
foreach (var fn in files)
{
tsb.Append(GetEmbeddedContentForDebugging(fn) + "\n\n\n");
}
var processedFile = pathTranslator.ExpandAppRelativePath(asset.LocalPath);
//embedded resources need to be rendered regardless to be usable
renderer.Render(tsb.ToString(), pathTranslator.ResolveAppRelativePathToFileSystem(processedFile));
sb.AppendLine(FillTemplate(bundleState, processedFile));
}
else if (asset.RemotePath != null)
{
sb.AppendLine(FillTemplate(bundleState, pathTranslator.ExpandAppRelativePath(asset.LocalPath)));
}
else
{
foreach (var file in files)
{
if (!renderedFiles.Contains(file))
{
var fileBase = pathTranslator.ResolveAppRelativePathToFileSystem(asset.LocalPath);
var newPath = PreprocessForDebugging(file).Replace(fileBase, "");
var path = pathTranslator.ExpandAppRelativePath(asset.LocalPath + newPath.Replace("\\", "/"));
sb.AppendLine(FillTemplate(bundleState, path));
renderedFiles.Add(file);
}
}
}
}
}
var content = sb.ToString();
if (bundleCache.ContainsKey(name))
{
bundleCache.Remove(name);
}
if (debugStatusReader.IsDebuggingEnabled()) //default for predicate is null - only want to add to cache if not forced via predicate
{
bundleCache.Add(name, content, bundleState.DependentFiles, IsDebuggingEnabled());
}
//need to render the bundle to caches, otherwise leave it
if (renderer is CacheRenderer)
renderer.Render(content, renderTo);
return content;
}
bool TryGetCachedBundle(string key, out string content)
{
if (bundleState.DebugPredicate.SafeExecute())
{
content = "";
return false;
}
return bundleCache.TryGetValue(key, out content);
}
string RenderRelease(string key, string renderTo, IRenderer renderer)
{
string content;
if (!TryGetCachedBundle(key, out content))
{
using (new CriticalRenderingSection(renderTo))
{
if (!TryGetCachedBundle(key, out content))
{
var uniqueFiles = new List<string>();
string hash = null;
bundleState.DependentFiles.Clear();
if (renderTo == null)
{
renderTo = renderPathCache[CachePrefix + "." + key];
}
else
{
renderPathCache[CachePrefix + "." + key] = renderTo;
}
var outputFile = pathTranslator.ResolveAppRelativePathToFileSystem(renderTo);
var renderToPath = pathTranslator.ExpandAppRelativePath(renderTo);
if (!String.IsNullOrEmpty(BaseOutputHref))
{
renderToPath = String.Concat(BaseOutputHref.TrimEnd('/'), "/", renderToPath.TrimStart('/'));
}
var remoteAssetPaths = new List<string>();
remoteAssetPaths.AddRange(bundleState.Assets.Where(a => a.IsRemote).Select(a => a.RemotePath));
uniqueFiles.AddRange(GetFiles(bundleState.Assets.Where(asset =>
asset.IsEmbeddedResource ||
asset.IsLocal ||
asset.IsRemoteDownload).ToList()).Distinct());
var renderedTag = string.Empty;
if (uniqueFiles.Count > 0 || bundleState.Assets.Count(a => a.IsArbitrary) > 0)
{
bundleState.DependentFiles.AddRange(uniqueFiles);
var minifiedContent = GetMinifiedContent(bundleState.Assets, outputFile);
if (!string.IsNullOrEmpty(bundleState.HashKeyName))
{
hash = hasher.GetHash(minifiedContent);
}
renderToPath = bundleState.CacheInvalidationStrategy.GetOutputWebPath(renderToPath, bundleState.HashKeyName, hash);
outputFile = bundleState.CacheInvalidationStrategy.GetOutputFileLocation(outputFile, hash);
if (!(bundleState.ShouldRenderOnlyIfOutputFileIsMissing && FileExists(outputFile)))
{
renderer.Render(minifiedContent, outputFile);
}
renderedTag = FillTemplate(bundleState, renderToPath);
}
content += String.Concat(GetFilesForRemote(remoteAssetPaths, bundleState), renderedTag);
}
}
//don't cache bundles where debugging was forced via predicate
if (!bundleState.DebugPredicate.SafeExecute())
{
bundleCache.Add(key, content, bundleState.DependentFiles, IsDebuggingEnabled());
}
}
return content;
}
protected string GetMinifiedContent(List<Asset> assets, string outputFile)
{
var filteredAssets = assets.Where(asset =>
asset.IsEmbeddedResource ||
asset.IsLocal ||
asset.IsRemoteDownload ||
asset.IsArbitrary)
.ToList();
var sb = new StringBuilder();
AggregateContent(filteredAssets, sb, outputFile);
return sb.ToString();
}
protected string MinifyIfNeeded(string content, bool minify)
{
if (minify && !string.IsNullOrEmpty(content) && !IsDebuggingEnabled())
{
var minified = Minifier.Minify(content);
return AppendFileClosure(minified);
}
return AppendFileClosure(content);
}
protected virtual string AppendFileClosure(string content)
{
return content;
}
string GetEmbeddedContentForDebugging(string filename)
{
var preprocessors = FindPreprocessors(filename);
return preprocessors.NullSafeAny()
? PreprocessFile(filename, preprocessors)
: ReadFile(filename);
}
string PreprocessForDebugging(string filename)
{
var preprocessors = FindPreprocessors(filename);
if (preprocessors.NullSafeAny())
{
var content = PreprocessFile(filename, preprocessors);
filename += debugExtension;
using (var fileWriter = fileWriterFactory.GetFileWriter(filename))
{
fileWriter.Write(content);
}
}
return filename;
}
}
}
| |
using System.Runtime.InteropServices;
using System;
namespace BizHawk.Emulation.Cores.Components.Z80
{
public partial class Z80A
{
[StructLayout(LayoutKind.Explicit)]
[Serializable()]
public struct RegisterPair
{
[FieldOffset(0)]
public ushort Word;
[FieldOffset(0)]
public byte Low;
[FieldOffset(1)]
public byte High;
public RegisterPair(ushort value)
{
Word = value;
Low = (byte)(Word);
High = (byte)(Word >> 8);
}
public static implicit operator ushort(RegisterPair rp)
{
return rp.Word;
}
public static implicit operator RegisterPair(ushort value)
{
return new RegisterPair(value);
}
}
private bool RegFlagC
{
get { return (RegAF.Low & 0x01) != 0; }
set { RegAF.Low = (byte)((RegAF.Low & ~0x01) | (value ? 0x01 : 0x00)); }
}
private bool RegFlagN
{
get { return (RegAF.Low & 0x02) != 0; }
set { RegAF.Low = (byte)((RegAF.Low & ~0x02) | (value ? 0x02 : 0x00)); }
}
private bool RegFlagP
{
get { return (RegAF.Low & 0x04) != 0; }
set { RegAF.Low = (byte)((RegAF.Low & ~0x04) | (value ? 0x04 : 0x00)); }
}
private bool RegFlag3
{
get { return (RegAF.Low & 0x08) != 0; }
set { RegAF.Low = (byte)((RegAF.Low & ~0x08) | (value ? 0x08 : 0x00)); }
}
private bool RegFlagH
{
get { return (RegAF.Low & 0x10) != 0; }
set { RegAF.Low = (byte)((RegAF.Low & ~0x10) | (value ? 0x10 : 0x00)); }
}
private bool RegFlag5
{
get { return (RegAF.Low & 0x20) != 0; }
set { RegAF.Low = (byte)((RegAF.Low & ~0x20) | (value ? 0x20 : 0x00)); }
}
private bool RegFlagZ
{
get { return (RegAF.Low & 0x40) != 0; }
set { RegAF.Low = (byte)((RegAF.Low & ~0x40) | (value ? 0x40 : 0x00)); }
}
private bool RegFlagS
{
get { return (RegAF.Low & 0x80) != 0; }
set { RegAF.Low = (byte)((RegAF.Low & ~0x80) | (value ? 0x80 : 0x00)); }
}
private RegisterPair RegAF;
private RegisterPair RegBC;
private RegisterPair RegDE;
private RegisterPair RegHL;
private RegisterPair RegAltAF; // Shadow for A and F
private RegisterPair RegAltBC; // Shadow for B and C
private RegisterPair RegAltDE; // Shadow for D and E
private RegisterPair RegAltHL; // Shadow for H and L
private byte RegI; // I (interrupt vector)
private byte RegR; // R (memory refresh)
private RegisterPair RegIX; // IX (index register x)
private RegisterPair RegIY; // IY (index register y)
private RegisterPair RegSP; // SP (stack pointer)
private RegisterPair RegPC; // PC (program counter)
private void ResetRegisters()
{
// Clear main registers
RegAF = 0; RegBC = 0; RegDE = 0; RegHL = 0;
// Clear alternate registers
RegAltAF = 0; RegAltBC = 0; RegAltDE = 0; RegAltHL = 0;
// Clear special purpose registers
RegI = 0; RegR = 0;
RegIX.Word = 0; RegIY.Word = 0;
RegSP.Word = 0; RegPC.Word = 0;
}
public byte RegisterA
{
get { return RegAF.High; }
set { RegAF.High = value; }
}
public byte RegisterF
{
get { return RegAF.Low; }
set { RegAF.Low = value; }
}
public ushort RegisterAF
{
get { return RegAF.Word; }
set { RegAF.Word = value; }
}
public byte RegisterB
{
get { return RegBC.High; }
set { RegBC.High = value; }
}
public byte RegisterC
{
get { return RegBC.Low; }
set { RegBC.Low = value; }
}
public ushort RegisterBC
{
get { return RegBC.Word; }
set { RegBC.Word = value; }
}
public byte RegisterD
{
get { return RegDE.High; }
set { RegDE.High = value; }
}
public byte RegisterE
{
get { return RegDE.Low; }
set { RegDE.Low = value; }
}
public ushort RegisterDE
{
get { return RegDE.Word; }
set { RegDE.Word = value; }
}
public byte RegisterH
{
get { return RegHL.High; }
set { RegHL.High = value; }
}
public byte RegisterL
{
get { return RegHL.Low; }
set { RegHL.Low = value; }
}
public ushort RegisterHL
{
get { return RegHL.Word; }
set { RegHL.Word = value; }
}
public ushort RegisterPC
{
get { return RegPC.Word; }
set { RegPC.Word = value; }
}
public ushort RegisterSP
{
get { return RegSP.Word; }
set { RegSP.Word = value; }
}
public ushort RegisterIX
{
get { return RegIX.Word; }
set { RegIX.Word = value; }
}
public ushort RegisterIY
{
get { return RegIY.Word; }
set { RegIY.Word = value; }
}
public byte RegisterI
{
get { return RegI; }
set { RegI = value; }
}
public byte RegisterR
{
get { return RegR; }
set { RegR = value; }
}
public ushort RegisterShadowAF
{
get { return RegAltAF.Word; }
set { RegAltAF.Word = value; }
}
public ushort RegisterShadowBC
{
get { return RegAltBC.Word; }
set { RegAltBC.Word = value; }
}
public ushort RegisterShadowDE
{
get { return RegAltDE.Word; }
set { RegAltDE.Word = value; }
}
public ushort RegisterShadowHL
{
get { return RegAltHL.Word; }
set { RegAltHL.Word = value; }
}
}
}
| |
// 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.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Threading;
using MemberListType = System.RuntimeType.MemberListType;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
using System.Runtime.CompilerServices;
[Serializable]
public abstract class MethodInfo : MethodBase
{
#region Constructor
protected MethodInfo() { }
#endregion
public static bool operator ==(MethodInfo left, MethodInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeMethodInfo || right is RuntimeMethodInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(MethodInfo left, MethodInfo right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } }
#endregion
#region Public Abstract\Virtual Members
public virtual Type ReturnType { get { throw new NotImplementedException(); } }
public virtual ParameterInfo ReturnParameter { get { throw new NotImplementedException(); } }
public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; }
public abstract MethodInfo GetBaseDefinition();
public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
#endregion
}
[Serializable]
internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo
{
#region Private Data Members
private IntPtr m_handle;
private RuntimeTypeCache m_reflectedTypeCache;
private string m_name;
private string m_toString;
private ParameterInfo[] m_parameters;
private ParameterInfo m_returnParameter;
private BindingFlags m_bindingFlags;
private MethodAttributes m_methodAttributes;
private Signature m_signature;
private RuntimeType m_declaringType;
private object m_keepalive;
private INVOCATION_FLAGS m_invocationFlags;
#if FEATURE_APPX
private bool IsNonW8PFrameworkAPI()
{
if (m_declaringType.IsArray && IsPublic && !IsStatic)
return false;
RuntimeAssembly rtAssembly = GetRuntimeAssembly();
if (rtAssembly.IsFrameworkAssembly())
{
int ctorToken = rtAssembly.InvocableAttributeCtorToken;
if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
!CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
return true;
}
if (GetRuntimeType().IsNonW8PFrameworkAPI())
return true;
if (IsGenericMethod && !IsGenericMethodDefinition)
{
foreach (Type t in GetGenericArguments())
{
if (((RuntimeType)t).IsNonW8PFrameworkAPI())
return true;
}
}
return false;
}
#endif
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN;
Type declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
if (ContainsGenericParameters ||
ReturnType.IsByRef ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||
((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))
{
// We don't need other flags if this method cannot be invoked
invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
else
{
// this should be an invocable method, determine the other flags that participate in invocation
invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this);
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0)
{
if ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
(declaringType != null && declaringType.NeedsReflectionSecurityCheck))
{
// If method is non-public, or declaring type is not visible
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
}
else if (IsGenericMethod)
{
Type[] genericArguments = GetGenericArguments();
for (int i = 0; i < genericArguments.Length; i++)
{
if (genericArguments[i].NeedsReflectionSecurityCheck)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
break;
}
}
}
}
}
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
#endif // FEATURE_APPX
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
#region Constructor
internal RuntimeMethodInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType,
RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive)
{
Contract.Ensures(!m_handle.IsNull());
Debug.Assert(!handle.IsNullHandle());
Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
m_keepalive = keepalive;
m_handle = handle.Value;
m_reflectedTypeCache = reflectedTypeCache;
m_methodAttributes = methodAttributes;
}
#endregion
#region Private Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
get
{
return new RuntimeMethodHandleInternal(m_handle);
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
private ParameterInfo[] FetchNonReturnParameters()
{
if (m_parameters == null)
m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);
return m_parameters;
}
private ParameterInfo FetchReturnParameter()
{
if (m_returnParameter == null)
m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature);
return m_returnParameter;
}
#endregion
#region Internal Members
internal override string FormatNameAndSig(bool serialization)
{
// Serialization uses ToString to resolve MethodInfo overloads.
StringBuilder sbName = new StringBuilder(Name);
// serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads.
// serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString().
TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic;
if (IsGenericMethod)
sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format));
sbName.Append("(");
sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization));
sbName.Append(")");
return sbName.ToString();
}
internal override bool CacheEquals(object o)
{
RuntimeMethodInfo m = o as RuntimeMethodInfo;
if ((object)m == null)
return false;
return m.m_handle == m_handle;
}
internal Signature Signature
{
get
{
if (m_signature == null)
m_signature = new Signature(this, m_declaringType);
return m_signature;
}
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
internal RuntimeMethodInfo GetParentDefinition()
{
if (!IsVirtual || m_declaringType.IsInterface)
return null;
RuntimeType parent = (RuntimeType)m_declaringType.BaseType;
if (parent == null)
return null;
int slot = RuntimeMethodHandle.GetSlot(this);
if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot)
return null;
return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot));
}
// Unlike DeclaringType, this will return a valid type even for global methods
internal RuntimeType GetDeclaringTypeInternal()
{
return m_declaringType;
}
#endregion
#region Object Overrides
public override String ToString()
{
if (m_toString == null)
m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig();
return m_toString;
}
public override int GetHashCode()
{
// See RuntimeMethodInfo.Equals() below.
if (IsGenericMethod)
return ValueType.GetHashCodeOfPtr(m_handle);
else
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (!IsGenericMethod)
return obj == (object)this;
// We cannot do simple object identity comparisons for generic methods.
// Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo()
// retrieve items from and insert items into s_methodInstantiations which is a CerHashtable.
RuntimeMethodInfo mi = obj as RuntimeMethodInfo;
if (mi == null || !mi.IsGenericMethod)
return false;
// now we know that both operands are generic methods
IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this);
IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi);
if (handle1.Value.Value != handle2.Value.Value)
return false;
Type[] lhs = GetGenericArguments();
Type[] rhs = mi.GetGenericArguments();
if (lhs.Length != rhs.Length)
return false;
for (int i = 0; i < lhs.Length; i++)
{
if (lhs[i] != rhs[i])
return false;
}
if (DeclaringType != mi.DeclaringType)
return false;
if (ReflectedType != mi.ReflectedType)
return false;
return true;
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
if (m_name == null)
m_name = RuntimeMethodHandle.GetName(this);
return m_name;
}
}
public override Type DeclaringType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_declaringType;
}
}
public override Type ReflectedType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override MemberTypes MemberType { get { return MemberTypes.Method; } }
public override int MetadataToken
{
get { return RuntimeMethodHandle.GetMethodDef(this); }
}
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
public override bool IsSecurityCritical
{
get { return true; }
}
public override bool IsSecuritySafeCritical
{
get { return false; }
}
public override bool IsSecurityTransparent
{
get { return false; }
}
#endregion
#region MethodBase Overrides
internal override ParameterInfo[] GetParametersNoCopy()
{
FetchNonReturnParameters();
return m_parameters;
}
[System.Diagnostics.Contracts.Pure]
public override ParameterInfo[] GetParameters()
{
FetchNonReturnParameters();
if (m_parameters.Length == 0)
return m_parameters;
ParameterInfo[] ret = new ParameterInfo[m_parameters.Length];
Array.Copy(m_parameters, ret, m_parameters.Length);
return ret;
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return RuntimeMethodHandle.GetImplAttributes(this);
}
public override RuntimeMethodHandle MethodHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
return new RuntimeMethodHandle(this);
}
}
public override MethodAttributes Attributes { get { return m_methodAttributes; } }
public override CallingConventions CallingConvention
{
get
{
return Signature.CallingConvention;
}
}
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb.m_methodBase = this;
return mb;
}
#endregion
#region Invocation Logic(On MemberBase)
private void CheckConsistency(Object target)
{
// only test instance methods
if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
else
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
}
}
}
private void ThrowNoInvokeException()
{
// method is ReflectionOnly
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
{
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke"));
}
// method is on a class that contains stack pointers
else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0)
{
throw new NotSupportedException();
}
// method is vararg
else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
{
throw new NotSupportedException();
}
// method is generic or on a generic class
else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters)
{
throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam"));
}
// method is abstract class
else if (IsAbstract)
{
throw new MemberAccessException();
}
// ByRef return are not allowed in reflection
else if (ReturnType.IsByRef)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn"));
}
throw new TargetException();
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
#region Security Check
INVOCATION_FLAGS invocationFlags = InvocationFlags;
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
#endregion
return UnsafeInvokeInternal(obj, parameters, arguments);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
return UnsafeInvokeInternal(obj, parameters, arguments);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
{
if (arguments == null || arguments.Length == 0)
return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false);
else
{
Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
Signature sig = Signature;
// get the signature
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
INVOCATION_FLAGS invocationFlags = InvocationFlags;
// INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type)
// contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot
// be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects.
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0)
ThrowNoInvokeException();
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
if (formalCount != actualCount)
throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
if (actualCount != 0)
return CheckArguments(parameters, binder, invokeAttr, culture, sig);
else
return null;
}
#endregion
#region MethodInfo Overrides
public override Type ReturnType
{
get { return Signature.ReturnType; }
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
get { return ReturnParameter; }
}
public override ParameterInfo ReturnParameter
{
get
{
Contract.Ensures(m_returnParameter != null);
FetchReturnParameter();
return m_returnParameter as ParameterInfo;
}
}
public override MethodInfo GetBaseDefinition()
{
if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
return this;
int slot = RuntimeMethodHandle.GetSlot(this);
RuntimeType declaringType = (RuntimeType)DeclaringType;
RuntimeType baseDeclaringType = declaringType;
RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal();
do
{
int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType);
if (cVtblSlots <= slot)
break;
baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot);
baseDeclaringType = declaringType;
declaringType = (RuntimeType)declaringType.BaseType;
} while (declaringType != null);
return (MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
}
public override Delegate CreateDelegate(Type delegateType)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
// open delegates only for backwards compatibility. But we'll allow
// relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
return CreateDelegateInternal(
delegateType,
null,
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature,
ref stackMark);
}
public override Delegate CreateDelegate(Type delegateType, Object target)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
// instance methods with relaxed signature checking). The delegate
// can also be closed over null. There's no ambiguity with all these
// options since the caller is providing us a specific MethodInfo.
return CreateDelegateInternal(
delegateType,
target,
DelegateBindingFlags.RelaxedSignature,
ref stackMark);
}
private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark)
{
// Validate the parameters.
if (delegateType == null)
throw new ArgumentNullException(nameof(delegateType));
Contract.EndContractBlock();
RuntimeType rtType = delegateType as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(delegateType));
if (!rtType.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(delegateType));
Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark);
if (d == null)
{
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
}
return d;
}
#endregion
#region Generics
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
{
if (methodInstantiation == null)
throw new ArgumentNullException(nameof(methodInstantiation));
Contract.EndContractBlock();
RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(
Environment.GetResourceString("Arg_NotGenericMethodDefinition", this));
for (int i = 0; i < methodInstantiation.Length; i++)
{
Type methodInstantiationElem = methodInstantiation[i];
if (methodInstantiationElem == null)
throw new ArgumentNullException();
RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType;
if (rtMethodInstantiationElem == null)
{
Type[] methodInstantiationCopy = new Type[methodInstantiation.Length];
for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++)
methodInstantiationCopy[iCopy] = methodInstantiation[iCopy];
methodInstantiation = methodInstantiationCopy;
return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation);
}
methodInstantionRuntimeType[i] = rtMethodInstantiationElem;
}
RuntimeType[] genericParameters = GetGenericArgumentsInternal();
RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters);
MethodInfo ret = null;
try
{
ret = RuntimeType.GetMethodBase(ReflectedTypeInternal,
RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo;
}
catch (VerificationException e)
{
RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e);
throw;
}
return ret;
}
internal RuntimeType[] GetGenericArgumentsInternal()
{
return RuntimeMethodHandle.GetMethodInstantiationInternal(this);
}
public override Type[] GetGenericArguments()
{
Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this);
if (types == null)
{
types = EmptyArray<Type>.Value;
}
return types;
}
public override MethodInfo GetGenericMethodDefinition()
{
if (!IsGenericMethod)
throw new InvalidOperationException();
Contract.EndContractBlock();
return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo;
}
public override bool IsGenericMethod
{
get { return RuntimeMethodHandle.HasMethodInstantiation(this); }
}
public override bool IsGenericMethodDefinition
{
get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); }
}
public override bool ContainsGenericParameters
{
get
{
if (DeclaringType != null && DeclaringType.ContainsGenericParameters)
return true;
if (!IsGenericMethod)
return false;
Type[] pis = GetGenericArguments();
for (int i = 0; i < pis.Length; i++)
{
if (pis[i].ContainsGenericParameters)
return true;
}
return false;
}
}
#endregion
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_reflectedTypeCache.IsGlobal)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
SerializationToString(),
MemberTypes.Method,
IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null);
}
internal string SerializationToString()
{
return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true);
}
#endregion
#region Legacy Internal
internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark)
{
IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);
if (method == null)
return null;
return RuntimeType.GetMethodBase(method);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Interop.VixCOM;
using Microsoft.Win32;
namespace Vestris.VMWareLib
{
/// <summary>
/// A VMWare virtual host.
/// </summary>
public class VMWareVirtualHost : VMWareVixHandle<IHost>
{
/// <summary>
/// VMWare service provider type.
/// </summary>
public enum ServiceProviderType
{
/// <summary>
/// No service provider type, not connected.
/// </summary>
None = 0,
/// <summary>
/// VMWare Server.
/// </summary>
Server = Constants.VIX_SERVICEPROVIDER_VMWARE_SERVER,
/// <summary>
/// VMWare Workstation.
/// </summary>
Workstation = Constants.VIX_SERVICEPROVIDER_VMWARE_WORKSTATION,
/// <summary>
/// Virtual Infrastructure Server, eg. ESX.
/// </summary>
VirtualInfrastructureServer = Constants.VIX_SERVICEPROVIDER_VMWARE_VI_SERVER,
/// <summary>
/// VMWare Player.
/// </summary>
Player = Constants.VIX_SERVICEPROVIDER_VMWARE_PLAYER
}
private ServiceProviderType _serviceProviderType = ServiceProviderType.None;
/// <summary>
/// An IHost2 handle, where supported.
/// </summary>
protected IHost2 _host2
{
get
{
return _handle as IHost2;
}
}
/// <summary>
/// A VMWare virtual host.
/// </summary>
public VMWareVirtualHost()
{
}
/// <summary>
/// Connected host type.
/// </summary>
public ServiceProviderType ConnectionType
{
get
{
return _serviceProviderType;
}
}
/// <summary>
/// Connect to a WMWare Player.
/// </summary>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWarePlayer();
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("C:\Virtual Machines\xp\xp.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
public void ConnectToVMWarePlayer()
{
ConnectToVMWarePlayer(VMWareInterop.Timeouts.ConnectTimeout);
}
/// <summary>
/// Connect to a WMWare Player.
/// </summary>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void ConnectToVMWarePlayer(int timeoutInSeconds)
{
Connect(ServiceProviderType.Player, null, 0, null, null, timeoutInSeconds);
}
/// <summary>
/// Connect to a WMWare Workstation.
/// </summary>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareWorkstation();
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("C:\Virtual Machines\xp\xp.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
public void ConnectToVMWareWorkstation()
{
ConnectToVMWareWorkstation(VMWareInterop.Timeouts.ConnectTimeout);
}
/// <summary>
/// Connect to a WMWare Workstation.
/// </summary>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void ConnectToVMWareWorkstation(int timeoutInSeconds)
{
Connect(ServiceProviderType.Workstation, null, 0, null, null, timeoutInSeconds);
}
/// <summary>
/// Connect to a WMWare Virtual Infrastructure Server (eg. ESX or VMWare Server 2.x).
/// </summary>
/// <param name="hostName">VMWare host name and optional port.</param>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareVIServer("esx.mycompany.com", "vmuser", "password");
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("[storage] testvm/testvm.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareVIServer("localhost:8333", "vmuser", "password");
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("[standard] testvm/testvm.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
public void ConnectToVMWareVIServer(string hostName, string username, string password)
{
ConnectToVMWareVIServer(hostName, username, password, VMWareInterop.Timeouts.ConnectTimeout);
}
/// <summary>
/// Connect to a WMWare Virtual Infrastructure Server (eg. ESX or VMWare Server 2.x).
/// </summary>
/// <param name="hostName">VMWare host name and optional port.</param>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareVIServer("esx.mycompany.com", "vmuser", "password");
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("[storage] testvm/testvm.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareVIServer("localhost:8333", "vmuser", "password");
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("[standard] testvm/testvm.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
public void ConnectToVMWareVIServer(string hostName, string username, string password, int timeoutInSeconds)
{
if (string.IsNullOrEmpty(hostName))
{
throw new ArgumentException("The host is required.");
}
ConnectToVMWareVIServer(new Uri(string.Format("https://{0}/sdk", hostName)),
username, password, timeoutInSeconds);
}
/// <summary>
/// Connect to a WMWare Virtual Infrastructure Server (eg. ESX).
/// </summary>
/// <param name="hostUri">Host SDK uri, eg. http://server/sdk.</param>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void ConnectToVMWareVIServer(Uri hostUri, string username, string password, int timeoutInSeconds)
{
if (string.IsNullOrEmpty(username))
{
throw new ArgumentException("The username is required.");
}
Connect(ServiceProviderType.VirtualInfrastructureServer,
hostUri.ToString(), 0, username, password, timeoutInSeconds);
}
/// <summary>
/// Connect to a WMWare Server.
/// </summary>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <param name="hostName">DNS name or IP address of a VMWare host, leave blank for localhost.</param>
public void ConnectToVMWareServer(string hostName, string username, string password)
{
ConnectToVMWareServer(hostName, username, password, VMWareInterop.Timeouts.ConnectTimeout);
}
/// <summary>
/// Connect to a WMWare Server.
/// </summary>
/// <param name="hostName">DNS name or IP address of a VMWare host, leave blank for localhost.</param>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void ConnectToVMWareServer(string hostName, string username, string password, int timeoutInSeconds)
{
Connect(ServiceProviderType.Server,
hostName, 0, username, password, timeoutInSeconds);
}
/// <summary>
/// Connects to a VMWare VI Server, VMWare Server or Workstation.
/// </summary>
private void Connect(ServiceProviderType serviceProviderType,
string hostName, int hostPort, string username, string password, int timeout)
{
try
{
// check if VmWare COM object could be loaded
// if we try to load a COM object which does not exist, an RCW exception will occure on exit of Visual Studio 2013
using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry32)) {
using (var xReg = baseKey.OpenSubKey(@"CLSID\{6874E949-7186-4308-A1B9-D55A91F60728}", false)) {
if (xReg == null) {
throw new ApplicationException("No Vmware Library installed!");
}
}
}
int serviceProvider = (int)serviceProviderType;
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(new VixLib().Connect(
Constants.VIX_API_VERSION, serviceProvider, hostName, hostPort,
username, password, 0, null, callback), callback))
{
_handle = job.Wait<IHost>(Constants.VIX_PROPERTY_JOB_RESULT_HANDLE, timeout);
}
_serviceProviderType = serviceProviderType;
}
catch (ApplicationException)
{
throw;
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to connect: serviceProviderType=\"{0}\" hostName=\"{1}\" hostPort={2} username=\"{3}\" timeout={4}",
Enum.GetName(serviceProviderType.GetType(), serviceProviderType), hostName, hostPort, username, timeout), ex);
}
}
/// <summary>
/// Open a virtual machine.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
/// <returns>An instance of a virtual machine.</returns>
public VMWareVirtualMachine Open(string fileName)
{
return Open(fileName, VMWareInterop.Timeouts.OpenVMTimeout);
}
/// <summary>
/// Open a virtual machine.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
/// <returns>An instance of a virtual machine.</returns>
public VMWareVirtualMachine Open(string fileName, int timeoutInSeconds)
{
try
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.OpenVM(fileName, callback), callback))
{
return new VMWareVirtualMachine(job.Wait<IVM2>(
Constants.VIX_PROPERTY_JOB_RESULT_HANDLE,
timeoutInSeconds));
}
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to open virtual machine: fileName=\"{0}\" timeoutInSeconds={1}",
fileName, timeoutInSeconds), ex);
}
}
/// <summary>
/// Add a virtual machine to the host's inventory.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
public void Register(string fileName)
{
Register(fileName, VMWareInterop.Timeouts.RegisterVMTimeout);
}
/// <summary>
/// Add a virtual machine to the host's inventory.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void Register(string fileName, int timeoutInSeconds)
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
switch (ConnectionType)
{
case ServiceProviderType.VirtualInfrastructureServer:
case ServiceProviderType.Server:
break;
default:
throw new NotSupportedException(string.Format("Register is not supported on {0}",
ConnectionType));
}
try
{
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.RegisterVM(fileName, callback), callback))
{
job.Wait(timeoutInSeconds);
}
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to register virtual machine: fileName=\"{0}\" timeoutInSeconds={1}",
fileName, timeoutInSeconds), ex);
}
}
/// <summary>
/// Remove a virtual machine from the host's inventory.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
public void Unregister(string fileName)
{
Unregister(fileName, VMWareInterop.Timeouts.RegisterVMTimeout);
}
/// <summary>
/// Remove a virtual machine from the host's inventory.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void Unregister(string fileName, int timeoutInSeconds)
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
switch (ConnectionType)
{
case ServiceProviderType.VirtualInfrastructureServer:
case ServiceProviderType.Server:
break;
default:
throw new NotSupportedException(string.Format("Unregister is not supported on {0}",
ConnectionType));
}
try
{
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.UnregisterVM(fileName, callback), callback))
{
job.Wait(timeoutInSeconds);
}
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to unregister virtual machine: fileName=\"{0}\" timeoutInSeconds={1}",
fileName, timeoutInSeconds), ex);
}
}
/// <summary>
/// Dispose the object, hard-disconnect from the remote host.
/// </summary>
public override void Dispose()
{
if (_handle != null)
{
Disconnect();
}
GC.SuppressFinalize(this);
}
/// <summary>
/// Disconnect from a remote host.
/// </summary>
public void Disconnect()
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
_handle.Disconnect();
_handle = null;
_serviceProviderType = ServiceProviderType.None;
}
/// <summary>
/// Returns true when connected to a virtual host, false otherwise.
/// </summary>
public bool IsConnected
{
get
{
return _handle != null;
}
}
/// <summary>
/// Destructor.
/// </summary>
~VMWareVirtualHost()
{
if (_handle != null)
{
Disconnect();
}
}
/// <summary>
/// Returns all running virtual machines.
/// </summary>
public IEnumerable<VMWareVirtualMachine> RunningVirtualMachines
{
get
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
try
{
List<VMWareVirtualMachine> runningVirtualMachines = new List<VMWareVirtualMachine>();
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.FindItems(
Constants.VIX_FIND_RUNNING_VMS, null, -1, callback),
callback))
{
object[] properties = { Constants.VIX_PROPERTY_FOUND_ITEM_LOCATION };
foreach (object[] runningVirtualMachine in job.YieldWait(
properties, VMWareInterop.Timeouts.FindItemsTimeout))
{
runningVirtualMachines.Add(this.Open((string)runningVirtualMachine[0]));
}
}
return runningVirtualMachines;
}
catch (Exception ex)
{
throw new Exception("Failed to get all running virtual machines", ex);
}
}
}
/// <summary>
/// All registered virtual machines.
/// </summary>
/// <remarks>This function is only supported on Virtual Infrastructure servers.</remarks>
public IEnumerable<VMWareVirtualMachine> RegisteredVirtualMachines
{
get
{
switch (ConnectionType)
{
case ServiceProviderType.VirtualInfrastructureServer:
case ServiceProviderType.Server:
break;
default:
throw new NotSupportedException(string.Format("RegisteredVirtualMachines is not supported on {0}",
ConnectionType));
}
try
{
List<VMWareVirtualMachine> registeredVirtualMachines = new List<VMWareVirtualMachine>();
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.FindItems(
Constants.VIX_FIND_REGISTERED_VMS, null, -1, callback),
callback))
{
object[] properties = { Constants.VIX_PROPERTY_FOUND_ITEM_LOCATION };
foreach (object[] runningVirtualMachine in job.YieldWait(properties, VMWareInterop.Timeouts.FindItemsTimeout))
{
registeredVirtualMachines.Add(this.Open((string)runningVirtualMachine[0]));
}
}
return registeredVirtualMachines;
}
catch (Exception ex)
{
throw new Exception("Failed to get all registered virtual machines", ex);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Bogus;
using Examine;
using Lucene.Net.Util;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Infrastructure.Examine;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.Integration.Umbraco.Examine.Lucene.UmbracoExamine
{
/// <summary>
/// Tests the standard indexing capabilities
/// </summary>
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.None)]
public class IndexTest : ExamineBaseTest
{
[Test]
public void GivenValidationParentNode_WhenContentIndexedUnderDifferentParent_DocumentIsNotIndexed()
{
using (GetSynchronousContentIndex(false, out UmbracoContentIndex index, out _, out _, 999))
{
var searcher = index.Searcher;
var contentService = new ExamineDemoDataContentService();
//get a node from the data repo
var node = contentService.GetPublishedContentByXPath("//*[string-length(@id)>0 and number(@id)>0]")
.Root
.Elements()
.First();
ValueSet valueSet = node.ConvertToValueSet(IndexTypes.Content);
// Ignored since the path isn't under 999
index.IndexItems(new[] { valueSet });
Assert.AreEqual(0, searcher.CreateQuery().Id(valueSet.Id).Execute().TotalItemCount);
// Change so that it's under 999 and verify
valueSet.Values["path"] = new List<object> { "-1,999," + valueSet.Id };
index.IndexItems(new[] { valueSet });
Assert.AreEqual(1, searcher.CreateQuery().Id(valueSet.Id).Execute().TotalItemCount);
}
}
[Test]
public void GivenIndexingDocument_WhenRichTextPropertyData_CanStoreImmenseFields()
{
using (GetSynchronousContentIndex(false, out UmbracoContentIndex index, out _, out ContentValueSetBuilder contentValueSetBuilder, null))
{
index.CreateIndex();
ContentType contentType = ContentTypeBuilder.CreateBasicContentType();
contentType.AddPropertyType(new PropertyType(TestHelper.ShortStringHelper, "test", ValueStorageType.Ntext)
{
Alias = "rte",
Name = "RichText",
PropertyEditorAlias = Cms.Core.Constants.PropertyEditors.Aliases.TinyMce
});
Content content = ContentBuilder.CreateBasicContent(contentType);
content.Id = 555;
content.Path = "-1,555";
var luceneStringFieldMaxLength = ByteBlockPool.BYTE_BLOCK_SIZE - 2;
var faker = new Faker();
var immenseText = faker.Random.String(length: luceneStringFieldMaxLength + 10);
content.Properties["rte"].SetValue(immenseText);
IEnumerable<ValueSet> valueSet = contentValueSetBuilder.GetValueSets(content);
index.IndexItems(valueSet);
ISearchResults results = index.Searcher.CreateQuery().Id(555).Execute();
ISearchResult result = results.First();
var key = $"{UmbracoExamineFieldNames.RawFieldPrefix}rte";
Assert.IsTrue(result.Values.ContainsKey(key));
Assert.Greater(result.Values[key].Length, luceneStringFieldMaxLength);
}
}
[Test]
public void GivenIndexingDocument_WhenGridPropertyData_ThenDataIndexedInSegregatedFields()
{
using (GetSynchronousContentIndex(false, out UmbracoContentIndex index, out _, out ContentValueSetBuilder contentValueSetBuilder, null))
{
index.CreateIndex();
ContentType contentType = ContentTypeBuilder.CreateBasicContentType();
contentType.AddPropertyType(new PropertyType(TestHelper.ShortStringHelper, "test", ValueStorageType.Ntext)
{
Alias = "grid",
Name = "Grid",
PropertyEditorAlias = Cms.Core.Constants.PropertyEditors.Aliases.Grid
});
Content content = ContentBuilder.CreateBasicContent(contentType);
content.Id = 555;
content.Path = "-1,555";
var gridVal = new GridValue
{
Name = "n1",
Sections = new List<GridValue.GridSection>
{
new GridValue.GridSection
{
Grid = "g1",
Rows = new List<GridValue.GridRow>
{
new GridValue.GridRow
{
Id = Guid.NewGuid(),
Name = "row1",
Areas = new List<GridValue.GridArea>
{
new GridValue.GridArea
{
Grid = "g2",
Controls = new List<GridValue.GridControl>
{
new GridValue.GridControl
{
Editor = new GridValue.GridEditor
{
Alias = "editor1",
View = "view1"
},
Value = "value1"
},
new GridValue.GridControl
{
Editor = new GridValue.GridEditor
{
Alias = "editor1",
View = "view1"
},
Value = "value2"
}
}
}
}
}
}
}
}
};
var json = JsonConvert.SerializeObject(gridVal);
content.Properties["grid"].SetValue(json);
IEnumerable<ValueSet> valueSet = contentValueSetBuilder.GetValueSets(content);
index.IndexItems(valueSet);
ISearchResults results = index.Searcher.CreateQuery().Id(555).Execute();
Assert.AreEqual(1, results.TotalItemCount);
ISearchResult result = results.First();
Assert.IsTrue(result.Values.ContainsKey("grid.row1"));
Assert.AreEqual("value1", result.AllValues["grid.row1"][0]);
Assert.AreEqual("value2", result.AllValues["grid.row1"][1]);
Assert.IsTrue(result.Values.ContainsKey("grid"));
Assert.AreEqual("value1 value2 ", result["grid"]);
Assert.IsTrue(result.Values.ContainsKey($"{UmbracoExamineFieldNames.RawFieldPrefix}grid"));
Assert.AreEqual(json, result[$"{UmbracoExamineFieldNames.RawFieldPrefix}grid"]);
}
}
[Test]
public void GivenEmptyIndex_WhenUsingWithContentAndMediaPopulators_ThenIndexPopulated()
{
var mediaRebuilder = IndexInitializer.GetMediaIndexRebuilder(IndexInitializer.GetMockMediaService());
using (GetSynchronousContentIndex(false, out UmbracoContentIndex index, out ContentIndexPopulator contentRebuilder, out _, null))
{
//create the whole thing
contentRebuilder.Populate(index);
mediaRebuilder.Populate(index);
var result = index.Searcher.CreateQuery().All().Execute();
Assert.AreEqual(29, result.TotalItemCount);
}
}
/// <summary>
/// Check that the node signalled as protected in the content service is not present in the index.
/// </summary>
[Test]
public void GivenPublishedContentIndex_WhenProtectedContentIndexed_ThenItIsIgnored()
{
using (GetSynchronousContentIndex(true, out UmbracoContentIndex index, out ContentIndexPopulator contentRebuilder, out _, null))
{
//create the whole thing
contentRebuilder.Populate(index);
Assert.Greater(
index.Searcher.CreateQuery().All().Execute().TotalItemCount,
0);
Assert.AreEqual(
0,
index.Searcher.CreateQuery().Id(ExamineDemoDataContentService.ProtectedNode.ToString()).Execute().TotalItemCount);
}
}
[Test]
public void GivenMediaUnderNonIndexableParent_WhenMediaMovedUnderIndexableParent_ThenItIsIncludedInTheIndex()
{
// create a validator with
// publishedValuesOnly false
// parentId 1116 (only content under that parent will be indexed)
using (GetSynchronousContentIndex(false, out UmbracoContentIndex index, out ContentIndexPopulator contentRebuilder, out _, 1116))
{
//get a node from the data repo (this one exists underneath 2222)
var node = _mediaService.GetLatestMediaByXpath("//*[string-length(@id)>0 and number(@id)>0]")
.Root.Elements()
.First(x => (int)x.Attribute("id") == 2112);
var currPath = (string)node.Attribute("path"); //should be : -1,1111,2222,2112
Assert.AreEqual("-1,1111,2222,2112", currPath);
//ensure it's indexed
index.IndexItem(node.ConvertToValueSet(IndexTypes.Media));
//it will not exist because it exists under 2222
var results = index.Searcher.CreateQuery().Id(2112).Execute();
Assert.AreEqual(0, results.Count());
//now mimic moving 2112 to 1116
//node.SetAttributeValue("path", currPath.Replace("2222", "1116"));
node.SetAttributeValue("path", "-1,1116,2112");
node.SetAttributeValue("parentID", "1116");
//now reindex the node, this should first delete it and then WILL add it because of the parent id constraint
index.IndexItems(new[] { node.ConvertToValueSet(IndexTypes.Media) });
//now ensure it exists
results = index.Searcher.CreateQuery().Id(2112).Execute();
Assert.AreEqual(1, results.Count());
}
}
[Test]
public void GivenMediaUnderIndexableParent_WhenMediaMovedUnderNonIndexableParent_ThenItIsRemovedFromTheIndex()
{
// create a validator with
// publishedValuesOnly false
// parentId 2222 (only content under that parent will be indexed)
using (GetSynchronousContentIndex(false, out UmbracoContentIndex index, out ContentIndexPopulator contentRebuilder, out _, 2222))
{
var searcher = index.Searcher;
//get a node from the data repo (this one exists underneath 2222)
var node = _mediaService.GetLatestMediaByXpath("//*[string-length(@id)>0 and number(@id)>0]")
.Root.Elements()
.First(x => (int)x.Attribute("id") == 2112);
var currPath = (string)node.Attribute("path"); //should be : -1,1111,2222,2112
Assert.AreEqual("-1,1111,2222,2112", currPath);
//ensure it's indexed
index.IndexItem(node.ConvertToValueSet(IndexTypes.Media));
//it will exist because it exists under 2222
var results = searcher.CreateQuery().Id(2112).Execute();
Assert.AreEqual(1, results.Count());
//now mimic moving the node underneath 1116 instead of 2222
node.SetAttributeValue("path", currPath.Replace("2222", "1116"));
node.SetAttributeValue("parentID", "1116");
//now reindex the node, this should first delete it and then NOT add it because of the parent id constraint
index.IndexItems(new[] { node.ConvertToValueSet(IndexTypes.Media) });
//now ensure it's deleted
results = searcher.CreateQuery().Id(2112).Execute();
Assert.AreEqual(0, results.Count());
}
}
/// <summary>
/// This will ensure that all 'Content' (not media) is cleared from the index using the Lucene API directly.
/// We then call the Examine method to re-index Content and do some comparisons to ensure that it worked correctly.
/// </summary>
[Test]
public void GivenEmptyIndex_WhenIndexedWithContentPopulator_ThenTheIndexIsPopulated()
{
using (GetSynchronousContentIndex(false, out UmbracoContentIndex index, out ContentIndexPopulator contentRebuilder, out _, null))
{
//create the whole thing
contentRebuilder.Populate(index);
var result = index.Searcher
.CreateQuery()
.Field(ExamineFieldNames.CategoryFieldName, IndexTypes.Content)
.Execute();
Assert.AreEqual(21, result.TotalItemCount);
//delete all content
index.DeleteFromIndex(result.Select(x => x.Id));
//ensure it's all gone
result = index.Searcher.CreateQuery().Field(ExamineFieldNames.CategoryFieldName, IndexTypes.Content).Execute();
Assert.AreEqual(0, result.TotalItemCount);
//call our indexing methods
contentRebuilder.Populate(index);
result = index.Searcher
.CreateQuery()
.Field(ExamineFieldNames.CategoryFieldName, IndexTypes.Content)
.Execute();
Assert.AreEqual(21, result.TotalItemCount);
}
}
/// <summary>
/// This will delete an item from the index and ensure that all children of the node are deleted too!
/// </summary>
[Test]
public void GivenPopulatedIndex_WhenDocumentDeleted_ThenItsHierarchyIsAlsoDeleted()
{
using (GetSynchronousContentIndex(false, out UmbracoContentIndex index, out ContentIndexPopulator contentRebuilder, out _, null))
{
var searcher = index.Searcher;
//create the whole thing
contentRebuilder.Populate(index);
var results = searcher.CreateQuery().Id(1141).Execute();
Assert.AreEqual(1, results.Count());
//now delete a node that has children
index.DeleteFromIndex(1140.ToString());
//this node had children: 1141 & 1142, let's ensure they are also removed
results = searcher.CreateQuery().Id(1141).Execute();
Assert.AreEqual(0, results.Count());
results = searcher.CreateQuery().Id(1142).Execute();
Assert.AreEqual(0, results.Count());
}
}
private readonly ExamineDemoDataMediaService _mediaService = new ExamineDemoDataMediaService();
}
}
| |
//---------------------------------------------------------------------
// <copyright file="DmlSqlGenerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.SqlClient.SqlGen
{
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Common.CommandTrees;
using System.Data.Common.Utils;
using System.Data.Mapping;
using System.Data.Metadata.Edm;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
/// <summary>
/// Class generating SQL for a DML command tree.
/// </summary>
internal static class DmlSqlGenerator
{
private const int s_commandTextBuilderInitialCapacity = 256;
private const string s_generatedValuesVariableName = "@generated_keys";
internal static string GenerateUpdateSql(DbUpdateCommandTree tree, SqlVersion sqlVersion, out List<SqlParameter> parameters)
{
const string dummySetParameter = "@p";
StringBuilder commandText = new StringBuilder(s_commandTextBuilderInitialCapacity);
ExpressionTranslator translator = new ExpressionTranslator(commandText, tree, null != tree.Returning, sqlVersion);
if (tree.SetClauses.Count == 0)
{
commandText.AppendLine("declare " + dummySetParameter + " int");
}
// update [schemaName].[tableName]
commandText.Append("update ");
tree.Target.Expression.Accept(translator);
commandText.AppendLine();
// set c1 = ..., c2 = ..., ...
bool first = true;
commandText.Append("set ");
foreach (DbSetClause setClause in tree.SetClauses)
{
if (first) { first = false; }
else { commandText.Append(", "); }
setClause.Property.Accept(translator);
commandText.Append(" = ");
setClause.Value.Accept(translator);
}
if (first)
{
// If first is still true, it indicates there were no set
// clauses. Introduce a fake set clause so that:
// - we acquire the appropriate locks
// - server-gen columns (e.g. timestamp) get recomputed
//
// We use the following pattern:
//
// update Foo
// set @p = 0
// where ...
commandText.Append(dummySetParameter + " = 0");
}
commandText.AppendLine();
// where c1 = ..., c2 = ...
commandText.Append("where ");
tree.Predicate.Accept(translator);
commandText.AppendLine();
// generate returning sql
GenerateReturningSql(commandText, tree, null, translator, tree.Returning, false);
parameters = translator.Parameters;
return commandText.ToString();
}
internal static string GenerateDeleteSql(DbDeleteCommandTree tree, SqlVersion sqlVersion, out List<SqlParameter> parameters)
{
StringBuilder commandText = new StringBuilder(s_commandTextBuilderInitialCapacity);
ExpressionTranslator translator = new ExpressionTranslator(commandText, tree, false, sqlVersion);
// delete [schemaName].[tableName]
commandText.Append("delete ");
tree.Target.Expression.Accept(translator);
commandText.AppendLine();
// where c1 = ... AND c2 = ...
commandText.Append("where ");
tree.Predicate.Accept(translator);
parameters = translator.Parameters;
return commandText.ToString();
}
internal static string GenerateInsertSql(DbInsertCommandTree tree, SqlVersion sqlVersion, out List<SqlParameter> parameters)
{
StringBuilder commandText = new StringBuilder(s_commandTextBuilderInitialCapacity);
ExpressionTranslator translator = new ExpressionTranslator(commandText, tree,
null != tree.Returning, sqlVersion);
bool useGeneratedValuesVariable = UseGeneratedValuesVariable(tree, sqlVersion, translator);
EntityType tableType = (EntityType)((DbScanExpression)tree.Target.Expression).Target.ElementType;
if (useGeneratedValuesVariable)
{
// manufacture the variable, e.g. "declare @generated_values table(id uniqueidentifier)"
commandText
.Append("declare ")
.Append(s_generatedValuesVariableName)
.Append(" table(");
bool first = true;
foreach (EdmMember column in tableType.KeyMembers)
{
if (first)
{
first = false;
}
else
{
commandText.Append(", ");
}
string columnType = SqlGenerator.GenerateSqlForStoreType(sqlVersion, column.TypeUsage);
if (columnType == "rowversion" || columnType == "timestamp")
{
// rowversion and timestamp are intrinsically read-only. use binary to gather server generated
// values for these types.
columnType = "binary(8)";
}
commandText
.Append(GenerateMemberTSql(column))
.Append(" ")
.Append(columnType);
Facet collationFacet;
if (column.TypeUsage.Facets.TryGetValue(DbProviderManifest.CollationFacetName, false, out collationFacet))
{
string collation = collationFacet.Value as string;
if (!string.IsNullOrEmpty(collation))
{
commandText.Append(" collate ").Append(collation);
}
}
}
Debug.Assert(!first, "if useGeneratedValuesVariable is true, it implies some columns do not have values");
commandText.AppendLine(")");
}
// insert [schemaName].[tableName]
commandText.Append("insert ");
tree.Target.Expression.Accept(translator);
if (0 < tree.SetClauses.Count)
{
// (c1, c2, c3, ...)
commandText.Append("(");
bool first = true;
foreach (DbSetClause setClause in tree.SetClauses)
{
if (first) { first = false; }
else { commandText.Append(", "); }
setClause.Property.Accept(translator);
}
commandText.AppendLine(")");
}
else
{
commandText.AppendLine();
}
if (useGeneratedValuesVariable)
{
// output inserted.id into @generated_values
commandText.Append("output ");
bool first = true;
foreach (EdmMember column in tableType.KeyMembers)
{
if (first)
{
first = false;
}
else
{
commandText.Append(", ");
}
commandText.Append("inserted.");
commandText.Append(GenerateMemberTSql(column));
}
commandText
.Append(" into ")
.AppendLine(s_generatedValuesVariableName);
}
if (0 < tree.SetClauses.Count)
{
// values c1, c2, ...
bool first = true;
commandText.Append("values (");
foreach (DbSetClause setClause in tree.SetClauses)
{
if (first) { first = false; }
else { commandText.Append(", "); }
setClause.Value.Accept(translator);
translator.RegisterMemberValue(setClause.Property, setClause.Value);
}
commandText.AppendLine(")");
}
else
{
// default values
commandText.AppendLine("default values");
}
// generate returning sql
GenerateReturningSql(commandText, tree, tableType, translator, tree.Returning, useGeneratedValuesVariable);
parameters = translator.Parameters;
return commandText.ToString();
}
/// <summary>
/// Determine whether we should use a generated values variable to return server generated values.
/// This is true when we're attempting to insert a row where the primary key is server generated
/// but is not an integer type (and therefore can't be used with scope_identity()). It is also true
/// where there is a compound server generated key.
/// </summary>
private static bool UseGeneratedValuesVariable(DbInsertCommandTree tree, SqlVersion sqlVersion, ExpressionTranslator translator)
{
bool useGeneratedValuesVariable = false;
if (sqlVersion > SqlVersion.Sql8 && tree.Returning != null)
{
// Figure out which columns have values
HashSet<EdmMember> columnsWithValues = new HashSet<EdmMember>(tree.SetClauses.Cast<DbSetClause>().Select(s => ((DbPropertyExpression)s.Property).Property));
// Only SQL Server 2005+ support an output clause for inserts
bool firstKeyFound = false;
foreach (EdmMember keyMember in ((DbScanExpression)tree.Target.Expression).Target.ElementType.KeyMembers)
{
if (!columnsWithValues.Contains(keyMember))
{
if (firstKeyFound)
{
// compound server gen key
useGeneratedValuesVariable = true;
break;
}
else
{
firstKeyFound = true;
if (!IsValidScopeIdentityColumnType(keyMember.TypeUsage))
{
// unsupported type
useGeneratedValuesVariable = true;
break;
}
}
}
}
}
return useGeneratedValuesVariable;
}
// Generates T-SQL describing a member
// Requires: member must belong to an entity type (a safe requirement for DML
// SQL gen, where we only access table columns)
private static string GenerateMemberTSql(EdmMember member)
{
EntityType entityType = (EntityType)member.DeclaringType;
string sql;
if (!entityType.TryGetMemberSql(member, out sql))
{
sql = SqlGenerator.QuoteIdentifier(member.Name);
entityType.SetMemberSql(member, sql);
}
return sql;
}
/// <summary>
/// Generates SQL fragment returning server-generated values.
/// Requires: translator knows about member values so that we can figure out
/// how to construct the key predicate.
/// <code>
/// Sample SQL:
///
/// select IdentityValue
/// from dbo.MyTable
/// where @@ROWCOUNT > 0 and IdentityValue = scope_identity()
///
/// or
///
/// select TimestampValue
/// from dbo.MyTable
/// where @@ROWCOUNT > 0 and Id = 1
///
/// Note that we filter on rowcount to ensure no rows are returned if no rows were modified.
///
/// On SQL Server 2005 and up, we have an additional syntax used for non integer return types:
///
/// declare @generatedValues table(ID uniqueidentifier)
/// insert dbo.MyTable
/// output ID into @generated_values
/// values (...);
/// select ID
/// from @generatedValues as g join dbo.MyTable as t on g.ID = t.ID
/// where @@ROWCOUNT > 0;
/// </code>
/// </summary>
/// <param name="commandText">Builder containing command text</param>
/// <param name="tree">Modification command tree</param>
/// <param name="tableType">Type of table.</param>
/// <param name="translator">Translator used to produce DML SQL statement
/// for the tree</param>
/// <param name="returning">Returning expression. If null, the method returns
/// immediately without producing a SELECT statement.</param>
private static void GenerateReturningSql(StringBuilder commandText, DbModificationCommandTree tree, EntityType tableType,
ExpressionTranslator translator, DbExpression returning, bool useGeneratedValuesVariable)
{
// Nothing to do if there is no Returning expression
if (null == returning) { return; }
// select
commandText.Append("select ");
if (useGeneratedValuesVariable)
{
translator.PropertyAlias = "t";
}
returning.Accept(translator);
if (useGeneratedValuesVariable)
{
translator.PropertyAlias = null;
}
commandText.AppendLine();
if (useGeneratedValuesVariable)
{
// from @generated_values
commandText.Append("from ");
commandText.Append(s_generatedValuesVariableName);
commandText.Append(" as g join ");
tree.Target.Expression.Accept(translator);
commandText.Append(" as t on ");
string separator = string.Empty;
foreach (EdmMember keyMember in tableType.KeyMembers)
{
commandText.Append(separator);
separator = " and ";
commandText.Append("g.");
string memberTSql = GenerateMemberTSql(keyMember);
commandText.Append(memberTSql);
commandText.Append(" = t.");
commandText.Append(memberTSql);
}
commandText.AppendLine();
commandText.Append("where @@ROWCOUNT > 0");
}
else
{
// from
commandText.Append("from ");
tree.Target.Expression.Accept(translator);
commandText.AppendLine();
// where
commandText.Append("where @@ROWCOUNT > 0");
EntitySetBase table = ((DbScanExpression)tree.Target.Expression).Target;
bool identity = false;
foreach (EdmMember keyMember in table.ElementType.KeyMembers)
{
commandText.Append(" and ");
commandText.Append(GenerateMemberTSql(keyMember));
commandText.Append(" = ");
// retrieve member value sql. the translator remembers member values
// as it constructs the DML statement (which precedes the "returning"
// SQL)
SqlParameter value;
if (translator.MemberValues.TryGetValue(keyMember, out value))
{
commandText.Append(value.ParameterName);
}
else
{
// if no value is registered for the key member, it means it is an identity
// which can be retrieved using the scope_identity() function
if (identity)
{
// there can be only one server generated key
throw EntityUtil.NotSupported(System.Data.Entity.Strings.Update_NotSupportedServerGenKey(table.Name));
}
if (!IsValidScopeIdentityColumnType(keyMember.TypeUsage))
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.Update_NotSupportedIdentityType(
keyMember.Name, keyMember.TypeUsage.ToString()));
}
commandText.Append("scope_identity()");
identity = true;
}
}
}
}
private static bool IsValidScopeIdentityColumnType(TypeUsage typeUsage)
{
// SQL Server supports the following types for identity columns:
// tinyint, smallint, int, bigint, decimal(p,0), or numeric(p,0)
// make sure it's a primitive type
if (typeUsage.EdmType.BuiltInTypeKind != BuiltInTypeKind.PrimitiveType)
{
return false;
}
// check if this is a supported primitive type (compare by name)
string typeName = typeUsage.EdmType.Name;
// integer types
if (typeName == "tinyint" || typeName == "smallint" ||
typeName == "int" || typeName == "bigint")
{
return true;
}
// variable scale types (require scale = 0)
if (typeName == "decimal" || typeName == "numeric")
{
Facet scaleFacet;
return (typeUsage.Facets.TryGetValue(DbProviderManifest.ScaleFacetName,
false, out scaleFacet) && Convert.ToInt32(scaleFacet.Value, CultureInfo.InvariantCulture) == 0);
}
// type not in supported list
return false;
}
/// <summary>
/// Lightweight expression translator for DML expression trees, which have constrained
/// scope and support.
/// </summary>
private class ExpressionTranslator : BasicExpressionVisitor
{
/// <summary>
/// Initialize a new expression translator populating the given string builder
/// with command text. Command text builder and command tree must not be null.
/// </summary>
/// <param name="commandText">Command text with which to populate commands</param>
/// <param name="commandTree">Command tree generating SQL</param>
/// <param name="preserveMemberValues">Indicates whether the translator should preserve
/// member values while compiling t-SQL (only needed for server generation)</param>
internal ExpressionTranslator(StringBuilder commandText, DbModificationCommandTree commandTree,
bool preserveMemberValues, SqlVersion version)
{
Debug.Assert(null != commandText);
Debug.Assert(null != commandTree);
_commandText = commandText;
_commandTree = commandTree;
_version = version;
_parameters = new List<SqlParameter>();
_memberValues = preserveMemberValues ? new Dictionary<EdmMember, SqlParameter>() :
null;
}
private readonly StringBuilder _commandText;
private readonly DbModificationCommandTree _commandTree;
private readonly List<SqlParameter> _parameters;
private readonly Dictionary<EdmMember, SqlParameter> _memberValues;
private readonly static AliasGenerator s_parameterNames = new AliasGenerator("@", 1000);
private readonly SqlVersion _version;
internal List<SqlParameter> Parameters { get { return _parameters; } }
internal Dictionary<EdmMember, SqlParameter> MemberValues { get { return _memberValues; } }
internal string PropertyAlias { get; set; }
// generate parameter (name based on parameter ordinal)
internal SqlParameter CreateParameter(object value, TypeUsage type)
{
// Suppress the MaxLength facet in the type usage because
// SqlClient will silently truncate data when SqlParameter.Size < |SqlParameter.Value|.
const bool preventTruncation = true;
SqlParameter parameter = SqlProviderServices.CreateSqlParameter(s_parameterNames.GetName(_parameters.Count), type, ParameterMode.In, value, preventTruncation, _version);
_parameters.Add(parameter);
return parameter;
}
public override void Visit(DbAndExpression expression)
{
VisitBinary(expression, " and ");
}
public override void Visit(DbOrExpression expression)
{
VisitBinary(expression, " or ");
}
public override void Visit(DbComparisonExpression expression)
{
Debug.Assert(expression.ExpressionKind == DbExpressionKind.Equals,
"only equals comparison expressions are produced in DML command trees in V1");
VisitBinary(expression, " = ");
RegisterMemberValue(expression.Left, expression.Right);
}
/// <summary>
/// Call this method to register a property value pair so the translator "remembers"
/// the values for members of the row being modified. These values can then be used
/// to form a predicate for server-generation (based on the key of the row)
/// </summary>
/// <param name="propertyExpression">DbExpression containing the column reference (property expression).</param>
/// <param name="value">DbExpression containing the value of the column.</param>
internal void RegisterMemberValue(DbExpression propertyExpression, DbExpression value)
{
if (null != _memberValues)
{
// register the value for this property
Debug.Assert(propertyExpression.ExpressionKind == DbExpressionKind.Property,
"DML predicates and setters must be of the form property = value");
// get name of left property
EdmMember property = ((DbPropertyExpression)propertyExpression).Property;
// don't track null values
if (value.ExpressionKind != DbExpressionKind.Null)
{
Debug.Assert(value.ExpressionKind == DbExpressionKind.Constant,
"value must either constant or null");
// retrieve the last parameter added (which describes the parameter)
_memberValues[property] = _parameters[_parameters.Count - 1];
}
}
}
public override void Visit(DbIsNullExpression expression)
{
expression.Argument.Accept(this);
_commandText.Append(" is null");
}
public override void Visit(DbNotExpression expression)
{
_commandText.Append("not (");
expression.Accept(this);
_commandText.Append(")");
}
public override void Visit(DbConstantExpression expression)
{
SqlParameter parameter = CreateParameter(expression.Value, expression.ResultType);
_commandText.Append(parameter.ParameterName);
}
public override void Visit(DbScanExpression expression)
{
// we know we won't hit this code unless there is no function defined for this
// ModificationOperation, so if this EntitySet is using a DefiningQuery, instead
// of a table, that is an error
if (expression.Target.DefiningQuery != null)
{
string missingCudElement;
if (_commandTree.CommandTreeKind == DbCommandTreeKind.Delete)
{
missingCudElement = StorageMslConstructs.DeleteFunctionElement;
}
else if (_commandTree.CommandTreeKind == DbCommandTreeKind.Insert)
{
missingCudElement = StorageMslConstructs.InsertFunctionElement;
}
else
{
Debug.Assert(_commandTree.CommandTreeKind == DbCommandTreeKind.Update, "did you add a new option?");
missingCudElement = StorageMslConstructs.UpdateFunctionElement;
}
throw EntityUtil.Update(System.Data.Entity.Strings.Update_SqlEntitySetWithoutDmlFunctions(expression.Target.Name, missingCudElement, StorageMslConstructs.ModificationFunctionMappingElement), null);
}
_commandText.Append(SqlGenerator.GetTargetTSql(expression.Target));
}
public override void Visit(DbPropertyExpression expression)
{
if (!string.IsNullOrEmpty(this.PropertyAlias))
{
_commandText.Append(this.PropertyAlias);
_commandText.Append(".");
}
_commandText.Append(GenerateMemberTSql(expression.Property));
}
public override void Visit(DbNullExpression expression)
{
_commandText.Append("null");
}
public override void Visit(DbNewInstanceExpression expression)
{
// assumes all arguments are self-describing (no need to use aliases
// because no renames are ever used in the projection)
bool first = true;
foreach (DbExpression argument in expression.Arguments)
{
if (first) { first = false; }
else { _commandText.Append(", "); }
argument.Accept(this);
}
}
private void VisitBinary(DbBinaryExpression expression, string separator)
{
_commandText.Append("(");
expression.Left.Accept(this);
_commandText.Append(separator);
expression.Right.Accept(this);
_commandText.Append(")");
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Network.Fluent
{
using ApplicationGatewayBackend.Definition;
using ApplicationGatewayBackend.UpdateDefinition;
using Models;
using ResourceManager.Fluent.Core;
using System.Collections.Generic;
using ResourceManager.Fluent.Core.ChildResourceActions;
/// <summary>
/// Implementation for ApplicationGatewayBackend.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm5ldHdvcmsuaW1wbGVtZW50YXRpb24uQXBwbGljYXRpb25HYXRld2F5QmFja2VuZEltcGw=
internal partial class ApplicationGatewayBackendImpl :
ChildResource<ApplicationGatewayBackendAddressPoolInner, ApplicationGatewayImpl, IApplicationGateway>,
IApplicationGatewayBackend,
IDefinition<ApplicationGateway.Definition.IWithCreate>,
IUpdateDefinition<ApplicationGateway.Update.IUpdate>,
ApplicationGatewayBackend.Update.IUpdate
{
///GENMHASH:57E12F644F2C3EB367E99CBE582AD951:C0847EA0CDA78F6D91EFD239C70F0FA7
internal ApplicationGatewayBackendImpl(ApplicationGatewayBackendAddressPoolInner inner, ApplicationGatewayImpl parent) : base(inner, parent)
{
}
#region Accessors
///GENMHASH:3E38805ED0E7BA3CAEE31311D032A21C:61C1065B307679F3800C701AE0D87070
public override string Name()
{
return Inner.Name;
}
///GENMHASH:660646CB1AAA13CCBA50483108FFFCBF:B74483DFB822D3E7D17AE4E2E8CAE6E0
public IReadOnlyDictionary<string, string> BackendNicIPConfigurationNames()
{
// This assumes a NIC can only have one IP config associated with the backend of an app gateway,
// which is correct at the time of this implementation and seems unlikely to ever change
Dictionary<string, string> ipConfigNames = new Dictionary<string, string>();
if (Inner.BackendIPConfigurations != null)
{
foreach (var inner in Inner.BackendIPConfigurations)
{
string nicId = ResourceUtils.ParentResourcePathFromResourceId(inner.Id);
string ipConfigName = ResourceUtils.NameFromResourceId(inner.Id);
ipConfigNames.Add(nicId, ipConfigName);
}
}
return ipConfigNames;
}
///GENMHASH:BD4433E096C5BD5A3392F44B28BA9083:B81C8A45BECCD7571A580B4729B2CD0C
public bool ContainsFqdn(string fqdn)
{
if (fqdn != null)
{
foreach (var address in Inner.BackendAddresses)
{
if (fqdn.ToLower().Equals(address.Fqdn.ToLower()))
{
return true;
}
}
}
return false;
}
///GENMHASH:9193794DEF17F74A12490023F8AF6168:436637A06A9B4E6B2B3F2BA7F6A702C2
public bool ContainsIPAddress(string ipAddress)
{
if (ipAddress != null)
{
foreach (var address in Inner.BackendAddresses)
{
if (ipAddress.ToLower().Equals(address.IpAddress))
{
return true;
}
}
}
return false;
}
ApplicationGateway.Update.IUpdate ISettable<ApplicationGateway.Update.IUpdate>.Parent()
{
return Parent;
}
///GENMHASH:B9D8E0EB1A218491349631635CDA92D3:FACDE5B36FEA8EBE27DA67C1C581284E
public IReadOnlyList<ApplicationGatewayBackendAddress> Addresses()
{
var addresses = new List<ApplicationGatewayBackendAddress>();
if (Inner.BackendAddresses != null)
{
foreach (var address in Inner.BackendAddresses)
{
addresses.Add(address);
}
}
return addresses;
}
#endregion
#region Helpers
///GENMHASH:CA426728D89DF7B679F3082001CE7DB8:631561FDE1B5174113A31FA550BA7525
private IList<ApplicationGatewayBackendAddress> EnsureAddresses()
{
var addresses = Inner.BackendAddresses;
if (addresses == null)
{
addresses = new List<ApplicationGatewayBackendAddress>();
Inner.BackendAddresses = addresses;
}
return addresses;
}
#endregion
#region Withers
///GENMHASH:DFE562EDA69B9B5779C74F1A7206D23B:524E74936C9A9591669EB81BA006DE87
public ApplicationGatewayBackendImpl WithoutAddress(ApplicationGatewayBackendAddress address)
{
EnsureAddresses().Remove(address);
return this;
}
///GENMHASH:944BF1730016EB109BA8A7D6EE074FD9:5D921AD08070E5CDAC4685DF69DE7C5A
public ApplicationGatewayBackendImpl WithIPAddress(string ipAddress)
{
if (ipAddress == null)
{
return this;
}
ApplicationGatewayBackendAddress address = new ApplicationGatewayBackendAddress()
{
IpAddress = ipAddress
};
var addresses = EnsureAddresses();
foreach (var a in addresses)
{
if (a.IpAddress == null)
{
continue;
}
else if (ipAddress.ToLower().Equals(a.IpAddress.ToLower()))
{
return this;
}
}
addresses.Add(address);
return this;
}
///GENMHASH:BE71ABDD6202EC63298CCC3687E0D342:BFAC6742569FBE1AAA654B5BC52885A4
public ApplicationGatewayBackendImpl WithFqdn(string fqdn)
{
if (fqdn == null)
{
return this;
}
ApplicationGatewayBackendAddress address = new ApplicationGatewayBackendAddress()
{
Fqdn = fqdn
};
EnsureAddresses().Add(address);
return this;
}
///GENMHASH:6B55F5B12011B69BF6093386394EBE36:361E56BFBC466A31D98F6A02214458EB
public ApplicationGatewayBackendImpl WithoutIPAddress(string ipAddress)
{
if (ipAddress == null)
{
return this;
}
if (Inner.BackendAddresses == null)
{
return this;
}
var addresses = EnsureAddresses();
for (int i = 0; i < addresses.Count; i++)
{
string curIPAddress = addresses[i].IpAddress;
if (curIPAddress != null && curIPAddress.ToLower().Equals(ipAddress.ToLower()))
{
addresses.RemoveAt(i);
break;
}
}
return this;
}
///GENMHASH:237A061FC122426B3FAE4D0084C2C114:6E6DCF6440064F537DE973B900C3AB46
public ApplicationGatewayBackendImpl WithoutFqdn(string fqdn)
{
if (fqdn == null)
{
return this;
}
var addresses = EnsureAddresses();
for (int i = 0; i < addresses.Count; i++)
{
string curFqdn = addresses[i].Fqdn;
if (curFqdn != null && curFqdn.ToLower().Equals(fqdn.ToLower()))
{
addresses.RemoveAt(i);
break;
}
}
return this;
}
#endregion
#region Actions
///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:321924EA2E0782F0638FD1917D19DF54
public ApplicationGatewayImpl Attach()
{
return Parent.WithBackend(this);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TemplatingOptionsDialog.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.Design.MobileControls
{
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
// using System.Web.UI.Design.Util;
using System.Web.UI.Design.MobileControls.Util;
using System.Web.UI.MobileControls;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using Panel = System.Windows.Forms.Panel;
using Button = System.Windows.Forms.Button;
using Label = System.Windows.Forms.Label;
using ComboBox = System.Windows.Forms.ComboBox;
using Form = System.Windows.Forms.Form;
using UnsettableComboBox = System.Web.UI.Design.MobileControls.Util.UnsettableComboBox;
[
System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand,
Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)
]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
internal class TemplatingOptionsDialog : DesignerForm, IRefreshableDeviceSpecificEditor, IDeviceSpecificDesigner
{
private System.Windows.Forms.Control _header;
private MobileTemplatedControlDesigner _designer;
private IDeviceSpecificDesigner _dsd;
private DeviceSpecific _ds;
private ISite _site;
private ComboBox _cmbChoices;
private UnsettableComboBox _cmbSchemas;
private Button _btnEditChoices;
private Button _btnClose;
private int _mergingContext;
private StringCollection _strCollSchemas;
private Label _lblChoices = new Label();
private Label _lblSchemas = new Label();
private Panel _pnlMain = new Panel();
private String[] _schemasFriendly;
private String[] _schemasUrl;
private const int _standardSchemaNumber = 2;
internal TemplatingOptionsDialog(MobileTemplatedControlDesigner designer,
ISite site,
int mergingContext) : base(site)
{
_strCollSchemas = new StringCollection();
_mergingContext = mergingContext;
_designer = designer;
_site = site;
_dsd = (IDeviceSpecificDesigner) designer;
_dsd.SetDeviceSpecificEditor(this);
InitializeComponent();
this.Text = SR.GetString(SR.TemplatingOptionsDialog_Title);
_btnClose.Text = SR.GetString(SR.GenericDialog_CloseBtnCaption);
_lblSchemas.Text = SR.GetString(SR.TemplatingOptionsDialog_SchemaCaption);
_btnEditChoices.Text = SR.GetString(SR.TemplatingOptionsDialog_EditBtnCaption);
_lblChoices.Text = SR.GetString(SR.TemplatingOptionsDialog_FilterCaption);
_schemasFriendly = new String[] { SR.GetString(SR.TemplatingOptionsDialog_HTMLSchemaFriendly),
SR.GetString(SR.TemplatingOptionsDialog_CHTMLSchemaFriendly) };
_schemasUrl = new String[] { SR.GetString(SR.MarkupSchema_HTML32),
SR.GetString(SR.MarkupSchema_cHTML10) };
int tabOffset = GenericUI.InitDialog(
this,
_dsd,
_mergingContext
);
SetTabIndexes(tabOffset);
_dsd.RefreshHeader(_mergingContext);
String currentDeviceSpecificID = _dsd.CurrentDeviceSpecificID;
if (null != currentDeviceSpecificID && currentDeviceSpecificID.Length > 0)
{
DeviceSpecific ds;
_dsd.GetDeviceSpecific(currentDeviceSpecificID, out ds);
((IRefreshableDeviceSpecificEditor) this).Refresh(currentDeviceSpecificID, ds);
}
UpdateControlEnabling();
}
protected override string HelpTopic {
get {
return "net.Mobile.TemplatingOptionsDialog";
}
}
private void SetTabIndexes(int tabIndexOffset)
{
_pnlMain.TabIndex = ++tabIndexOffset;
_lblChoices.TabIndex = ++tabIndexOffset;
_cmbChoices.TabIndex = ++tabIndexOffset;
_btnEditChoices.TabIndex = ++tabIndexOffset;
_lblSchemas.TabIndex = ++tabIndexOffset;
_cmbSchemas.TabIndex = ++tabIndexOffset;
_btnClose.TabIndex = ++tabIndexOffset;
}
private void InitializeComponent()
{
_cmbChoices = new ComboBox();
_cmbSchemas = new UnsettableComboBox();
_btnEditChoices = new Button();
_btnClose = new Button();
_lblChoices.Location = new System.Drawing.Point(0, 0);
_lblChoices.Size = new System.Drawing.Size(276, 16);
_lblChoices.TabStop = false;
_cmbChoices.Location = new System.Drawing.Point(0, 16);
_cmbChoices.Size = new System.Drawing.Size(195, 21);
_cmbChoices.TabStop = true;
_cmbChoices.Enabled = false;
_cmbChoices.Sorted = true;
_cmbChoices.DropDownStyle = ComboBoxStyle.DropDownList;
_cmbChoices.SelectedIndexChanged += new EventHandler(this.OnSelectedIndexChangedChoicesComboBox);
_btnEditChoices.Location = new System.Drawing.Point(201, 15);
_btnEditChoices.Size = new System.Drawing.Size(75, 23);
_btnEditChoices.TabStop = true;
_btnEditChoices.Click += new EventHandler(this.OnClickEditChoicesButton);
_lblSchemas.Location = new System.Drawing.Point(0, 48);
_lblSchemas.Size = new System.Drawing.Size(276, 16);
_lblSchemas.TabStop = false;
_cmbSchemas.Location = new System.Drawing.Point(0, 64);
_cmbSchemas.Size = new System.Drawing.Size(276, 21);
_cmbSchemas.TabStop = true;
_cmbSchemas.Sorted = true;
_cmbSchemas.DropDownStyle = ComboBoxStyle.DropDown;
_cmbSchemas.LostFocus += new EventHandler(this.OnLostFocusSchemasComboBox);
_btnClose.Location = new System.Drawing.Point(201, 104);
_btnClose.Size = new System.Drawing.Size(75, 23);
_btnClose.TabStop = true;
_btnClose.Click += new EventHandler(this.OnClickCloseButton);
this._pnlMain.Controls.AddRange(new System.Windows.Forms.Control[] {
this._btnClose,
this._cmbSchemas,
this._lblSchemas,
this._btnEditChoices,
this._lblChoices,
this._cmbChoices
});
this._pnlMain.Location = new System.Drawing.Point(6, 5);
this._pnlMain.Size = new System.Drawing.Size(276, 128);
this._pnlMain.TabIndex = 0;
this._pnlMain.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
this.ClientSize = new Size(285, 139);
this.AcceptButton = _btnClose;
this.CancelButton = _btnClose;
this.Controls.Add(_pnlMain);
}
private void FillChoicesComboBox()
{
Debug.Assert(_dsd != null);
_cmbChoices.Items.Clear();
if (null != _ds || null != _dsd.UnderlyingObject)
{
_cmbChoices.Items.Add(SR.GetString(SR.DeviceFilter_NoChoice));
}
if (null == _ds)
{
if (_cmbChoices.Items.Count > 0)
{
_cmbChoices.SelectedIndex = 0;
}
}
else
{
bool addedDefault = false;
foreach (DeviceSpecificChoice choice in _ds.Choices)
{
if (choice.Filter.Length == 0)
{
if (!addedDefault)
{
_cmbChoices.Items.Add(SR.GetString(SR.DeviceFilter_DefaultChoice));
addedDefault = true;
}
}
else
{
if (!choice.Filter.Equals(SR.GetString(SR.DeviceFilter_NoChoice)))
{
_cmbChoices.Items.Add(DesignerUtility.ChoiceToUniqueIdentifier(choice));
}
}
}
if (null != _designer.CurrentChoice && _designer.CurrentDeviceSpecific == _ds)
{
if (_designer.CurrentChoice.Filter.Length == 0)
{
_cmbChoices.SelectedItem = SR.GetString(SR.DeviceFilter_DefaultChoice);
}
else
{
_cmbChoices.SelectedItem = DesignerUtility.ChoiceToUniqueIdentifier(_designer.CurrentChoice);
}
}
else
{
Debug.Assert(_cmbChoices.Items.Count > 0);
_cmbChoices.SelectedItem = SR.GetString(SR.DeviceFilter_NoChoice);
}
}
}
private void FillSchemasComboBox()
{
String friendlySchema;
_cmbSchemas.Items.Clear();
_cmbSchemas.Text = String.Empty;
if (null != _ds)
{
// Add the standard HTML 3.2 and cHTML1.0 schemas
for (int i = 0; i < _standardSchemaNumber; i++)
{
_cmbSchemas.AddItem(_schemasFriendly[i]);
}
// Add the Xmlns entries existing in the applied device filters of the page
IContainer container = _site.Container;
Debug.Assert(null != container, "container is null");
ComponentCollection allComponents = container.Components;
_strCollSchemas.Clear();
foreach (IComponent component in allComponents)
{
ExtractDeviceFilterSchemas(component as System.Web.UI.Control);
}
foreach (String strSchema in _strCollSchemas)
{
friendlySchema = UrlToFriendlySchema(strSchema);
if (!CaseSensitiveComboSearch(_cmbSchemas, friendlySchema))
{
_cmbSchemas.AddItem(friendlySchema);
}
}
// Add the Xmlns entries existing in the currently selected device filter
foreach (DeviceSpecificChoice choice in _ds.Choices)
{
friendlySchema = UrlToFriendlySchema(choice.Xmlns);
if (friendlySchema != null && friendlySchema.Length > 0 &&
!CaseSensitiveComboSearch(_cmbSchemas, friendlySchema))
{
_cmbSchemas.AddItem(friendlySchema);
}
}
}
}
private String FriendlyToUrlSchema(String friendlySchema)
{
for (int i = 0; i < _standardSchemaNumber; i++)
{
if (0 == String.Compare(_schemasFriendly[i], friendlySchema, StringComparison.OrdinalIgnoreCase))
{
return _schemasUrl[i];
}
}
return friendlySchema;
}
private String UrlToFriendlySchema(String urlSchema)
{
for (int i = 0; i < _standardSchemaNumber; i++)
{
if (0 == String.Compare(_schemasUrl[i], urlSchema, StringComparison.Ordinal))
{
return _schemasFriendly[i];
}
}
return urlSchema;
}
private void SetSchemaValue()
{
if (_ds != null &&
_cmbChoices.SelectedIndex >= 0)
{
String currentChoiceIdentifier = _cmbChoices.SelectedItem as String;
if (currentChoiceIdentifier != null && !currentChoiceIdentifier.Equals(SR.GetString(SR.DeviceFilter_NoChoice)))
{
DeviceSpecificChoice dsc = GetChoiceFromIdentifier((String) currentChoiceIdentifier, _ds);
_cmbSchemas.Text = UrlToFriendlySchema(dsc.Xmlns);
}
}
}
private void ExtractDeviceFilterSchemas(System.Web.UI.Control control)
{
if (null == control)
{
return;
}
MobileControl mobileControl = control as MobileControl;
if (null != mobileControl)
{
DeviceSpecific deviceSpecific;
DeviceSpecificChoiceCollection choices;
if (mobileControl is StyleSheet)
{
StyleSheet styleSheet = (StyleSheet) mobileControl;
ICollection styleKeys = styleSheet.Styles;
foreach (String key in styleKeys)
{
Style style = styleSheet[key];
deviceSpecific = style.DeviceSpecific;
if (null != deviceSpecific && _ds != deviceSpecific)
{
choices = deviceSpecific.Choices;
foreach (DeviceSpecificChoice choice in choices)
{
if (choice.Xmlns != null && choice.Xmlns.Length > 0 &&
!_strCollSchemas.Contains(choice.Xmlns))
{
_strCollSchemas.Add(choice.Xmlns);
}
}
}
}
}
else
{
deviceSpecific = mobileControl.DeviceSpecific;
if (null != deviceSpecific && _ds != deviceSpecific)
{
choices = deviceSpecific.Choices;
foreach (DeviceSpecificChoice choice in choices)
{
if (choice.Xmlns != null && choice.Xmlns.Length > 0 &&
!_strCollSchemas.Contains(choice.Xmlns))
{
_strCollSchemas.Add(choice.Xmlns);
}
}
}
}
}
if (control.HasControls())
{
foreach (System.Web.UI.Control child in control.Controls)
{
ExtractDeviceFilterSchemas(child);
}
}
}
private bool CaseSensitiveComboSearch(ComboBox cmb, String str)
{
foreach (Object obj in cmb.Items)
{
if (String.Compare(str, (String) obj, StringComparison.Ordinal) == 0)
{
return true;
}
}
return false;
}
private void UpdateControlEnabling()
{
_btnEditChoices.Enabled = (_dsd.UnderlyingObject != null);
_cmbChoices.Enabled = (_cmbChoices.Items.Count > 0);
_cmbSchemas.Enabled = (_cmbChoices.Items.Count > 1) &&
(!((String)_cmbChoices.SelectedItem).Equals(SR.GetString(SR.DeviceFilter_NoChoice)));
}
private DeviceSpecificChoice GetChoiceFromIdentifier(String choiceIdentifier, DeviceSpecific ds)
{
if (null == ds)
{
return null;
}
Debug.Assert(ds.Choices != null);
foreach (DeviceSpecificChoice choice in ds.Choices)
{
if (DesignerUtility.ChoiceToUniqueIdentifier(choice).Equals(choiceIdentifier) ||
(choice.Filter.Length == 0 &&
choiceIdentifier.Equals(SR.GetString(SR.DeviceFilter_DefaultChoice))))
{
return choice;
}
}
return null;
}
bool IRefreshableDeviceSpecificEditor.RequestRefresh()
{
return true;
}
void IRefreshableDeviceSpecificEditor.Refresh(String deviceSpecificID, DeviceSpecific ds)
{
_ds = ds;
FillChoicesComboBox();
FillSchemasComboBox();
SetSchemaValue();
UpdateControlEnabling();
}
void IRefreshableDeviceSpecificEditor.UnderlyingObjectsChanged()
{
}
void IRefreshableDeviceSpecificEditor.BeginExternalDeviceSpecificEdit() {}
void IRefreshableDeviceSpecificEditor.EndExternalDeviceSpecificEdit(
bool commitChanges) {}
void IRefreshableDeviceSpecificEditor.DeviceSpecificRenamed(
String oldDeviceSpecificID, String newDeviceSpecificID) {}
void IRefreshableDeviceSpecificEditor.DeviceSpecificDeleted(
String deviceSpecificID) {}
private void OnClickCloseButton(Object sender, EventArgs e)
{
_dsd.UseCurrentDeviceSpecificID();
if (0 <= _cmbChoices.SelectedIndex &&
!_cmbChoices.Text.Equals(SR.GetString(SR.DeviceFilter_NoChoice)))
{
_designer.CurrentChoice = GetChoiceFromIdentifier((String) _cmbChoices.SelectedItem, _ds);
}
else
{
_designer.CurrentChoice = null;
}
Close();
DialogResult = DialogResult.OK;
}
private void OnSelectedIndexChangedChoicesComboBox(Object sender, EventArgs e)
{
if (_cmbChoices.Text.Equals(SR.GetString(SR.DeviceFilter_NoChoice)))
{
_cmbSchemas.Enabled = false;
_cmbSchemas.Text = String.Empty;
}
else
{
_cmbSchemas.Enabled = true;
SetSchemaValue();
}
_designer.SetTemplateVerbsDirty();
}
private void OnLostFocusSchemasComboBox(Object sender, EventArgs e)
{
Debug.Assert(_ds != null);
Debug.Assert(_cmbChoices.SelectedIndex >= 0);
DeviceSpecificChoice choice = GetChoiceFromIdentifier((String) _cmbChoices.SelectedItem, _ds);
String urlSchema = FriendlyToUrlSchema(_cmbSchemas.Text);
if (0 != String.Compare(choice.Xmlns, urlSchema, StringComparison.Ordinal))
{
String previousUrlSchema = choice.Xmlns;
if (!_strCollSchemas.Contains(previousUrlSchema))
{
int previousSchemaOccurrences = 0;
foreach (DeviceSpecificChoice choiceTmp in _ds.Choices)
{
if (0 == String.Compare(choiceTmp.Xmlns, previousUrlSchema, StringComparison.Ordinal))
{
previousSchemaOccurrences++;
}
}
Debug.Assert(previousSchemaOccurrences > 0);
if (previousSchemaOccurrences == 1)
{
bool standardSchema = false;
for (int i = 0; i < _standardSchemaNumber; i++)
{
if (0 == String.Compare(_schemasUrl[i], previousUrlSchema, StringComparison.Ordinal))
{
standardSchema = true;
break;
}
}
if (!standardSchema)
{
_cmbSchemas.Items.Remove(UrlToFriendlySchema(previousUrlSchema));
}
}
}
choice.Xmlns = urlSchema;
String friendlySchema = UrlToFriendlySchema(urlSchema);
if (friendlySchema == null || friendlySchema.Length > 0 &&
!CaseSensitiveComboSearch(_cmbSchemas, friendlySchema))
{
_cmbSchemas.AddItem(friendlySchema);
}
}
}
private void OnClickEditChoicesButton(Object source, EventArgs e)
{
AppliedDeviceFiltersDialog dialog = new AppliedDeviceFiltersDialog(this, _mergingContext);
if (dialog.ShowDialog() == DialogResult.OK)
{
_designer.UpdateRendering();
FillChoicesComboBox();
FillSchemasComboBox();
SetSchemaValue();
UpdateControlEnabling();
}
}
////////////////////////////////////////////////////////////////////////
// Begin IDeviceSpecificDesigner Implementation
////////////////////////////////////////////////////////////////////////
void IDeviceSpecificDesigner.SetDeviceSpecificEditor
(IRefreshableDeviceSpecificEditor editor)
{
}
String IDeviceSpecificDesigner.CurrentDeviceSpecificID
{
get
{
return _dsd.CurrentDeviceSpecificID;
}
}
System.Windows.Forms.Control IDeviceSpecificDesigner.Header
{
get
{
return _header;
}
}
System.Web.UI.Control IDeviceSpecificDesigner.UnderlyingControl
{
get
{
return _dsd.UnderlyingControl;
}
}
Object IDeviceSpecificDesigner.UnderlyingObject
{
get
{
return _dsd.UnderlyingObject;
}
}
bool IDeviceSpecificDesigner.GetDeviceSpecific(String deviceSpecificParentID, out DeviceSpecific ds)
{
return _dsd.GetDeviceSpecific(deviceSpecificParentID, out ds);
}
void IDeviceSpecificDesigner.SetDeviceSpecific(String deviceSpecificParentID, DeviceSpecific ds)
{
_ds = ds;
_dsd.SetDeviceSpecific(deviceSpecificParentID, ds);
}
void IDeviceSpecificDesigner.InitHeader(int mergingContext)
{
HeaderPanel panel = new HeaderPanel();
HeaderLabel lblDescription = new HeaderLabel();
lblDescription.TabIndex = 0;
lblDescription.Text = SR.GetString(SR.MobileControl_SettingGenericChoiceDescription);
panel.Height = lblDescription.Height;
panel.Width = lblDescription.Width;
panel.Controls.Add(lblDescription);
_header = panel;
}
void IDeviceSpecificDesigner.RefreshHeader(int mergingContext)
{
}
void IDeviceSpecificDesigner.UseCurrentDeviceSpecificID()
{
}
/////////////////////////////////////////////////////////////////////////
// End IDeviceSpecificDesigner Implementation
/////////////////////////////////////////////////////////////////////////
}
}
| |
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Spark.Parser.Code;
namespace Spark.Compiler
{
public class SourceWriter
{
private readonly StringWriter _writer;
private string _escrow;
static SourceWriter()
{
AdjustDebugSymbolsDefault = true;
}
public SourceWriter(StringWriter writer)
{
_writer = writer;
Mappings = new List<SourceMapping>();
AdjustDebugSymbols = AdjustDebugSymbolsDefault;
}
public int Indentation { get; set; }
public bool StartOfLine { get; set; }
public IList<SourceMapping> Mappings { get; set; }
public static bool AdjustDebugSymbolsDefault { get; set; }
public bool AdjustDebugSymbols { get; set; }
public int Length
{
get { return _writer.GetStringBuilder().Length; }
}
public SourceWriter AddIndent()
{
Indentation += 4;
return this;
}
public SourceWriter RemoveIndent()
{
Indentation -= 4;
return this;
}
public SourceWriter Indent()
{
return Indent(Indentation);
}
public SourceWriter Indent(int size)
{
if (StartOfLine)
{
_writer.Write(new string(' ', size));
StartOfLine = false;
}
return this;
}
public override string ToString()
{
return _writer.ToString();
}
private void Flush()
{
if (_escrow != null)
{
_writer.Write(_escrow);
_escrow = null;
}
Indent();
}
public SourceWriter Write(string value)
{
Flush();
_writer.Write(value);
return this;
}
public SourceWriter WriteFormat(string format, params object[] args)
{
return Write(string.Format(format, args));
}
public SourceWriter Write(IEnumerable<Snippet> value)
{
return WriteCode(value);
}
public SourceWriter WriteCode(IEnumerable<Snippet> snippets)
{
// compact snippets so vs language service doesn't have to
var compacted = new Snippets(snippets.Count());
Snippet prior = null;
foreach (var snippet in snippets)
{
if (prior != null && SnippetAreConnected(prior, snippet))
{
prior = new Snippet
{
Value = prior.Value + snippet.Value,
Begin = prior.Begin,
End = snippet.End
};
continue;
}
if (prior != null)
compacted.Add(prior);
prior = snippet;
}
if (prior != null)
compacted.Add(prior);
// write them out and keep mapping-to-spark source information
foreach (var snippet in compacted)
{
if (snippet.Begin != null)
{
Mappings.Add(new SourceMapping
{
Source = snippet,
OutputBegin = Length,
OutputEnd = Length + snippet.Value.Length
});
}
Write(snippet.Value);
}
return this;
}
private static bool SnippetAreConnected(Snippet first, Snippet second)
{
if (first.End == null || second.Begin == null)
return false;
if (first.End.SourceContext != second.Begin.SourceContext)
return false;
if (first.End.Offset != second.Begin.Offset)
return false;
return true;
}
public SourceWriter WriteLine()
{
Flush();
_writer.WriteLine();
StartOfLine = true;
return this;
}
public SourceWriter WriteLine(string value)
{
return Write(value).WriteLine();
}
public SourceWriter WriteLine(string format, params object[] args)
{
return WriteLine(string.Format(format, args));
}
public SourceWriter WriteDirective(string line)
{
if (!StartOfLine)
WriteLine();
StartOfLine = false;
return WriteLine(line);
}
public SourceWriter WriteDirective(string format, params object[] args)
{
return WriteDirective(string.Format(format, args));
}
public SourceWriter EscrowLine(string value)
{
if (_escrow != null)
_writer.Write(_escrow);
_escrow = new string(' ', Indentation) + value + _writer.NewLine;
return this;
}
public SourceWriter ClearEscrowLine()
{
_escrow = null;
return this;
}
public StringBuilder GetStringBuilder()
{
// for backwards compatability with extensions
return _writer.GetStringBuilder();
}
}
}
| |
/// 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.Text.RegularExpressions;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Soomla.Levelup {
/// <summary>
/// This class provides functions for event handling.
/// </summary>
public class LevelUpEvents : MonoBehaviour {
private const string TAG = "SOOMLA LevelUpEvents";
#if UNITY_IOS && !UNITY_EDITOR
[DllImport ("__Internal")]
private static extern void soomlaLevelup_Init();
#endif
/// <summary>
/// The instance of <c>LevelUpEvents</c> for this game.
/// </summary>
private static LevelUpEvents instance = null;
/// <summary>
/// Initializes game state before the game starts.
/// </summary>
void Awake(){
if(instance == null){ // making sure we only initialize one instance.
instance = this;
GameObject.DontDestroyOnLoad(this.gameObject);
Initialize();
} else { // Destroying unused instances.
GameObject.Destroy(this.gameObject);
}
}
/// <summary>
/// Initializes this instance.
/// </summary>
public static void Initialize() {
SoomlaUtils.LogDebug (TAG, "Initialize");
#if UNITY_ANDROID && !UNITY_EDITOR
AndroidJNI.PushLocalFrame(100);
using(AndroidJavaClass jniEventHandler = new AndroidJavaClass("com.soomla.unity.LevelUpEventHandler")) {
jniEventHandler.CallStatic("initialize");
}
AndroidJNI.PopLocalFrame(IntPtr.Zero);
#elif UNITY_IOS && !UNITY_EDITOR
soomlaLevelup_Init();
#endif
}
/** Functions that handle various events that are fired throughout the code. **/
public void onGateOpened(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGateOpened with message: " + message);
Gate gate = SoomlaLevelUp.GetGate(message);
LevelUpEvents.OnGateOpened(gate);
}
public void onGateClosed(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGateClosed with message: " + message);
Gate gate = SoomlaLevelUp.GetGate(message);
LevelUpEvents.OnGateClosed(gate);
}
public void onLevelEnded(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLevelEnded with message: " + message);
Level level = (Level) SoomlaLevelUp.GetWorld(message);
LevelUpEvents.OnLevelEnded(level);
}
public void onLevelStarted(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLevelStarted with message: " + message);
Level level = (Level) SoomlaLevelUp.GetWorld(message);
LevelUpEvents.OnLevelStarted(level);
}
public void onLevelUpInitialized(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLevelStarted");
LevelUpEvents.OnLevelUpInitialized();
}
public void onMissionCompleted(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onMissionCompleted with message: " + message);
Mission mission = SoomlaLevelUp.GetMission(message);
LevelUpEvents.OnMissionCompleted(mission);
}
public void onMissionCompletionRevoked(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onMissionCompletionRevoked with message: " + message);
Mission mission = SoomlaLevelUp.GetMission(message);
LevelUpEvents.OnMissionCompletionRevoked(mission);
}
public void onLatestScoreChanged(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLatestScoreChanged with message: " + message);
Score score = SoomlaLevelUp.GetScore(message);
LevelUpEvents.OnLatestScoreChanged(score);
}
public void onScoreRecordChanged(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onScoreRecordChanged with message: " + message);
Score score = SoomlaLevelUp.GetScore(message);
LevelUpEvents.OnScoreRecordChanged(score);
}
public void onWorldCompleted(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onWorldCompleted with message: " + message);
World world = SoomlaLevelUp.GetWorld(message);
LevelUpEvents.OnWorldCompleted(world);
}
public void onWorldAssignedReward(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onWorldAssignedReward with message: " + message);
World world = SoomlaLevelUp.GetWorld(message);
LevelUpEvents.OnWorldAssignedReward(world);
}
public void onLastCompletedInnerWorldChanged(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLastCompletedInnerWorldChanged with message: " + message);
JSONObject eventJSON = new JSONObject(message);
string worldId = eventJSON["worldId"].str;
string innerWorldId = eventJSON["innerWorldId"].str;
World world = SoomlaLevelUp.GetWorld(worldId);
LevelUpEvents.OnLastCompletedInnerWorldChanged(world, innerWorldId);
}
/** To handle various events, just add your specific behavior to the following delegates. **/
public delegate void Action();
public static Action<Gate> OnGateOpened = delegate {};
public static Action<Gate> OnGateClosed = delegate {};
public static Action<Level> OnLevelEnded = delegate {};
public static Action<Level> OnLevelStarted = delegate {};
public static Action OnLevelUpInitialized = delegate {};
public static Action<Mission> OnMissionCompleted = delegate {};
public static Action<Mission> OnMissionCompletionRevoked = delegate {};
public static Action<Score> OnScoreRecordChanged = delegate {};
public static Action<Score> OnLatestScoreChanged = delegate {};
public static Action<World> OnWorldCompleted = delegate {};
public static Action<World> OnWorldAssignedReward = delegate {};
public static Action<World, string> OnLastCompletedInnerWorldChanged = delegate {};
public static Action<Score> OnScoreRecordReached = delegate {};
}
}
| |
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Internal.Tests
{
public class DefaultDeserializationContextTest
{
FakeBufferReaderManager fakeBufferReaderManager;
[SetUp]
public void Init()
{
fakeBufferReaderManager = new FakeBufferReaderManager();
}
[TearDown]
public void Cleanup()
{
fakeBufferReaderManager.Dispose();
}
[TestCase]
public void PayloadAsReadOnlySequence_ZeroSegmentPayload()
{
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateMultiSegmentBufferReader(new List<byte[]> {}));
Assert.AreEqual(0, context.PayloadLength);
var sequence = context.PayloadAsReadOnlySequence();
Assert.AreEqual(ReadOnlySequence<byte>.Empty, sequence);
Assert.IsTrue(sequence.IsEmpty);
Assert.IsTrue(sequence.IsSingleSegment);
}
[TestCase(0)]
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
[TestCase(1000)]
public void PayloadAsReadOnlySequence_SingleSegmentPayload(int segmentLength)
{
var origBuffer = GetTestBuffer(segmentLength);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer));
Assert.AreEqual(origBuffer.Length, context.PayloadLength);
var sequence = context.PayloadAsReadOnlySequence();
Assert.AreEqual(origBuffer.Length, sequence.Length);
Assert.AreEqual(origBuffer.Length, sequence.First.Length);
Assert.IsTrue(sequence.IsSingleSegment);
CollectionAssert.AreEqual(origBuffer, sequence.First.ToArray());
}
[TestCase(0, 5, 10)]
[TestCase(1, 1, 1)]
[TestCase(10, 100, 1000)]
[TestCase(100, 100, 10)]
[TestCase(1000, 1000, 1000)]
public void PayloadAsReadOnlySequence_MultiSegmentPayload(int segmentLen1, int segmentLen2, int segmentLen3)
{
var origBuffer1 = GetTestBuffer(segmentLen1);
var origBuffer2 = GetTestBuffer(segmentLen2);
var origBuffer3 = GetTestBuffer(segmentLen3);
int totalLen = origBuffer1.Length + origBuffer2.Length + origBuffer3.Length;
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateMultiSegmentBufferReader(new List<byte[]> { origBuffer1, origBuffer2, origBuffer3 }));
Assert.AreEqual(totalLen, context.PayloadLength);
var sequence = context.PayloadAsReadOnlySequence();
Assert.AreEqual(totalLen, sequence.Length);
var segmentEnumerator = sequence.GetEnumerator();
Assert.IsTrue(segmentEnumerator.MoveNext());
CollectionAssert.AreEqual(origBuffer1, segmentEnumerator.Current.ToArray());
Assert.IsTrue(segmentEnumerator.MoveNext());
CollectionAssert.AreEqual(origBuffer2, segmentEnumerator.Current.ToArray());
Assert.IsTrue(segmentEnumerator.MoveNext());
CollectionAssert.AreEqual(origBuffer3, segmentEnumerator.Current.ToArray());
Assert.IsFalse(segmentEnumerator.MoveNext());
}
[TestCase]
public void NullPayloadNotAllowed()
{
var context = new DefaultDeserializationContext();
Assert.Throws(typeof(InvalidOperationException), () => context.Initialize(fakeBufferReaderManager.CreateNullPayloadBufferReader()));
}
[TestCase]
public void PayloadAsNewByteBuffer_ZeroSegmentPayload()
{
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateMultiSegmentBufferReader(new List<byte[]> {}));
Assert.AreEqual(0, context.PayloadLength);
var payload = context.PayloadAsNewBuffer();
Assert.AreEqual(0, payload.Length);
}
[TestCase(0)]
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
[TestCase(1000)]
public void PayloadAsNewByteBuffer_SingleSegmentPayload(int segmentLength)
{
var origBuffer = GetTestBuffer(segmentLength);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer));
Assert.AreEqual(origBuffer.Length, context.PayloadLength);
var payload = context.PayloadAsNewBuffer();
CollectionAssert.AreEqual(origBuffer, payload);
}
[TestCase(0, 5, 10)]
[TestCase(1, 1, 1)]
[TestCase(10, 100, 1000)]
[TestCase(100, 100, 10)]
[TestCase(1000, 1000, 1000)]
public void PayloadAsNewByteBuffer_MultiSegmentPayload(int segmentLen1, int segmentLen2, int segmentLen3)
{
var origBuffer1 = GetTestBuffer(segmentLen1);
var origBuffer2 = GetTestBuffer(segmentLen2);
var origBuffer3 = GetTestBuffer(segmentLen3);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateMultiSegmentBufferReader(new List<byte[]> { origBuffer1, origBuffer2, origBuffer3 }));
var payload = context.PayloadAsNewBuffer();
var concatenatedOrigBuffers = new List<byte>();
concatenatedOrigBuffers.AddRange(origBuffer1);
concatenatedOrigBuffers.AddRange(origBuffer2);
concatenatedOrigBuffers.AddRange(origBuffer3);
Assert.AreEqual(concatenatedOrigBuffers.Count, context.PayloadLength);
Assert.AreEqual(concatenatedOrigBuffers.Count, payload.Length);
CollectionAssert.AreEqual(concatenatedOrigBuffers, payload);
}
[TestCase]
public void GetPayloadMultipleTimesIsIllegal()
{
var origBuffer = GetTestBuffer(100);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer));
Assert.AreEqual(origBuffer.Length, context.PayloadLength);
var payload = context.PayloadAsNewBuffer();
CollectionAssert.AreEqual(origBuffer, payload);
// Getting payload multiple times is illegal
Assert.Throws(typeof(InvalidOperationException), () => context.PayloadAsNewBuffer());
Assert.Throws(typeof(InvalidOperationException), () => context.PayloadAsReadOnlySequence());
}
[TestCase]
public void ResetContextAndReinitialize()
{
var origBuffer = GetTestBuffer(100);
var context = new DefaultDeserializationContext();
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer));
Assert.AreEqual(origBuffer.Length, context.PayloadLength);
// Reset invalidates context
context.Reset();
Assert.AreEqual(0, context.PayloadLength);
Assert.Throws(typeof(NullReferenceException), () => context.PayloadAsNewBuffer());
Assert.Throws(typeof(NullReferenceException), () => context.PayloadAsReadOnlySequence());
// Previously reset context can be initialized again
var origBuffer2 = GetTestBuffer(50);
context.Initialize(fakeBufferReaderManager.CreateSingleSegmentBufferReader(origBuffer2));
Assert.AreEqual(origBuffer2.Length, context.PayloadLength);
CollectionAssert.AreEqual(origBuffer2, context.PayloadAsNewBuffer());
}
private byte[] GetTestBuffer(int length)
{
var testBuffer = new byte[length];
for (int i = 0; i < testBuffer.Length; i++)
{
testBuffer[i] = (byte) i;
}
return testBuffer;
}
}
}
| |
//
// 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.Management.Internal.Resources.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Internal.Resources
{
/// <summary>
/// Operations for managing resource groups.
/// </summary>
internal partial class ResourceGroupOperations : IServiceOperations<ResourceManagementClient>, IResourceGroupOperations
{
/// <summary>
/// Initializes a new instance of the ResourceGroupOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ResourceGroupOperations(ResourceManagementClient client)
{
this._client = client;
}
private ResourceManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient.
/// </summary>
public ResourceManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Begin deleting resource group.To determine whether the operation
/// has finished processing the request, call
/// GetLongRunningOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be deleted. The name is
/// case insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> BeginDeletingAsync(string resourceGroupName, 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");
}
// 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);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", 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);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
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 (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Checks whether resource group exists.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to check. The name is case
/// insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupExistsResult> CheckExistenceAsync(string resourceGroupName, 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");
}
// 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);
TracingAdapter.Enter(invocationId, this, "CheckExistenceAsync", 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);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Head;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.NotFound)
{
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
ResourceGroupExistsResult result = null;
// Deserialize Response
result = new ResourceGroupExistsResult();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Exists = true;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be created or updated.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create or update resource
/// group service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupCreateOrUpdateResult> CreateOrUpdateAsync(string resourceGroupName, ResourceGroup 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 (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
// 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("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);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject resourceGroupValue = new JObject();
requestDoc = resourceGroupValue;
resourceGroupValue["location"] = parameters.Location;
if (parameters.Properties != null)
{
resourceGroupValue["properties"] = JObject.Parse(parameters.Properties);
}
if (parameters.Tags != null)
{
if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
resourceGroupValue["tags"] = tagsDictionary;
}
}
if (parameters.ProvisioningState != null)
{
resourceGroupValue["provisioningState"] = parameters.ProvisioningState;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// 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
ResourceGroupCreateOrUpdateResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupCreateOrUpdateResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
result.ResourceGroup = resourceGroupInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupInstance.Location = locationInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
resourceGroupInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken provisioningStateValue2 = responseDoc["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
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 resource group and all of its resources.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be deleted. The name is
/// case insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, CancellationToken cancellationToken)
{
ResourceManagementClient 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);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse response = await client.ResourceGroups.BeginDeletingAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
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 != Microsoft.Azure.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>
/// Get a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupGetResult> GetAsync(string resourceGroupName, 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");
}
// 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);
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);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
result.ResourceGroup = resourceGroupInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupInstance.Location = locationInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
resourceGroupInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken provisioningStateValue2 = responseDoc["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
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 a collection of resource groups.
/// </summary>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns all resource
/// groups.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource groups.
/// </returns>
public async Task<ResourceGroupListResult> ListAsync(ResourceGroupListParameters parameters, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
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";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.TagName != null)
{
odataFilter.Add("tagname eq '" + Uri.EscapeDataString(parameters.TagName) + "'");
}
if (parameters != null && parameters.TagValue != null)
{
odataFilter.Add("tagvalue eq '" + Uri.EscapeDataString(parameters.TagValue) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
if (parameters != null && parameters.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()));
}
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupListResult();
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))
{
ResourceGroupExtended resourceGroupJsonFormatInstance = new ResourceGroupExtended();
result.ResourceGroups.Add(resourceGroupJsonFormatInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupJsonFormatInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupJsonFormatInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupJsonFormatInstance.Location = locationInstance;
}
JToken propertiesValue2 = valueValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupJsonFormatInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
resourceGroupJsonFormatInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken provisioningStateValue2 = valueValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
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>
/// Get a list of deployments.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of resource groups.
/// </returns>
public async Task<ResourceGroupListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupListResult();
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))
{
ResourceGroupExtended resourceGroupJsonFormatInstance = new ResourceGroupExtended();
result.ResourceGroups.Add(resourceGroupJsonFormatInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupJsonFormatInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupJsonFormatInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupJsonFormatInstance.Location = locationInstance;
}
JToken propertiesValue2 = valueValue["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupJsonFormatInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
resourceGroupJsonFormatInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken provisioningStateValue2 = valueValue["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupJsonFormatInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
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>
/// Resource groups can be updated through a simple PATCH operation to
/// a group address. The format of the request is the same as that for
/// creating a resource groups, though if a field is unspecified
/// current value will be carried over.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to be created or updated.
/// The name is case insensitive.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the update state resource group
/// service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Resource group information.
/// </returns>
public async Task<ResourceGroupPatchResult> PatchAsync(string resourceGroupName, ResourceGroup 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 (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
// 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("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject resourceGroupValue = new JObject();
requestDoc = resourceGroupValue;
resourceGroupValue["location"] = parameters.Location;
if (parameters.Properties != null)
{
resourceGroupValue["properties"] = JObject.Parse(parameters.Properties);
}
if (parameters.Tags != null)
{
if (parameters.Tags is ILazyCollection == false || ((ILazyCollection)parameters.Tags).IsInitialized)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
resourceGroupValue["tags"] = tagsDictionary;
}
}
if (parameters.ProvisioningState != null)
{
resourceGroupValue["provisioningState"] = parameters.ProvisioningState;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceGroupPatchResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceGroupPatchResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
result.ResourceGroup = resourceGroupInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
resourceGroupInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
resourceGroupInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
resourceGroupInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
resourceGroupInstance.Location = locationInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue2.ToString(Newtonsoft.Json.Formatting.Indented);
resourceGroupInstance.Properties = propertiesInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
resourceGroupInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken provisioningStateValue2 = responseDoc["provisioningState"];
if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
{
string provisioningStateInstance2 = ((string)provisioningStateValue2);
resourceGroupInstance.ProvisioningState = provisioningStateInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Security.Cryptography
{
/// <summary>
/// Provides support for computing a hash or HMAC value incrementally across several segments.
/// </summary>
public sealed class IncrementalHash : IDisposable
{
private const int NTE_BAD_ALGID = unchecked((int)0x80090008);
private readonly HashAlgorithmName _algorithmName;
private HashAlgorithm _hash;
private bool _disposed;
private bool _resetPending;
private IncrementalHash(HashAlgorithmName name, HashAlgorithm hash)
{
Debug.Assert(name != null);
Debug.Assert(!string.IsNullOrEmpty(name.Name));
Debug.Assert(hash != null);
_algorithmName = name;
_hash = hash;
}
/// <summary>
/// Get the name of the algorithm being performed.
/// </summary>
public HashAlgorithmName AlgorithmName
{
get { return _algorithmName; }
}
/// <summary>
/// Append the entire contents of <paramref name="data"/> to the data already processed in the hash or HMAC.
/// </summary>
/// <param name="data">The data to process.</param>
/// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public void AppendData(byte[] data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
AppendData(data, 0, data.Length);
}
/// <summary>
/// Append <paramref name="count"/> bytes of <paramref name="data"/>, starting at <paramref name="offset"/>,
/// to the data already processed in the hash or HMAC.
/// </summary>
/// <param name="data">The data to process.</param>
/// <param name="offset">The offset into the byte array from which to begin using data.</param>
/// <param name="count">The number of bytes in the array to use as data.</param>
/// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="offset"/> is out of range. This parameter requires a non-negative number.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="count"/> is out of range. This parameter requires a non-negative number less than
/// the <see cref="Array.Length"/> value of <paramref name="data"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="count"/> is greater than
/// <paramref name="data"/>.<see cref="Array.Length"/> - <paramref name="offset"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public void AppendData(byte[] data, int offset, int count)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0 || (count > data.Length))
throw new ArgumentOutOfRangeException(nameof(count));
if ((data.Length - count) < offset)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (_disposed)
throw new ObjectDisposedException(typeof(IncrementalHash).Name);
Debug.Assert(_hash != null);
if (_resetPending)
{
_hash.Initialize();
_resetPending = false;
}
_hash.TransformBlock(data, offset, count, null, 0);
}
/// <summary>
/// Retrieve the hash or HMAC for the data accumulated from prior calls to
/// <see cref="AppendData(byte[])"/>, and return to the state the object
/// was in at construction.
/// </summary>
/// <returns>The computed hash or HMAC.</returns>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public byte[] GetHashAndReset()
{
if (_disposed)
throw new ObjectDisposedException(typeof(IncrementalHash).Name);
Debug.Assert(_hash != null);
if (_resetPending)
{
// No point in setting _resetPending to false, we're about to set it to true.
_hash.Initialize();
}
_hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
byte[] hashValue = _hash.Hash;
_resetPending = true;
return hashValue;
}
/// <summary>
/// Release all resources used by the current instance of the
/// <see cref="IncrementalHash"/> class.
/// </summary>
public void Dispose()
{
_disposed = true;
if (_hash != null)
{
_hash.Dispose();
_hash = null;
}
}
/// <summary>
/// Create an <see cref="IncrementalHash"/> for the algorithm specified by <paramref name="hashAlgorithm"/>.
/// </summary>
/// <param name="hashAlgorithm">The name of the hash algorithm to perform.</param>
/// <returns>
/// An <see cref="IncrementalHash"/> instance ready to compute the hash algorithm specified
/// by <paramref name="hashAlgorithm"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/>.<see cref="HashAlgorithmName.Name"/> is <c>null</c>, or
/// the empty string.
/// </exception>
/// <exception cref="CryptographicException"><paramref name="hashAlgorithm"/> is not a known hash algorithm.</exception>
public static IncrementalHash CreateHash(HashAlgorithmName hashAlgorithm)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
return new IncrementalHash(hashAlgorithm, GetHashAlgorithm(hashAlgorithm));
}
/// <summary>
/// Create an <see cref="IncrementalHash"/> for the Hash-based Message Authentication Code (HMAC)
/// algorithm utilizing the hash algorithm specified by <paramref name="hashAlgorithm"/>, and a
/// key specified by <paramref name="key"/>.
/// </summary>
/// <param name="hashAlgorithm">The name of the hash algorithm to perform within the HMAC.</param>
/// <param name="key">
/// The secret key for the HMAC. The key can be any length, but a key longer than the output size
/// of the hash algorithm specified by <paramref name="hashAlgorithm"/> will be hashed (using the
/// algorithm specified by <paramref name="hashAlgorithm"/>) to derive a correctly-sized key. Therefore,
/// the recommended size of the secret key is the output size of the hash specified by
/// <paramref name="hashAlgorithm"/>.
/// </param>
/// <returns>
/// An <see cref="IncrementalHash"/> instance ready to compute the hash algorithm specified
/// by <paramref name="hashAlgorithm"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/>.<see cref="HashAlgorithmName.Name"/> is <c>null</c>, or
/// the empty string.
/// </exception>
/// <exception cref="CryptographicException"><paramref name="hashAlgorithm"/> is not a known hash algorithm.</exception>
public static IncrementalHash CreateHMAC(HashAlgorithmName hashAlgorithm, byte[] key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
return new IncrementalHash(hashAlgorithm, GetHMAC(hashAlgorithm, key));
}
private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm)
{
if (hashAlgorithm == HashAlgorithmName.MD5)
return new MD5CryptoServiceProvider();
if (hashAlgorithm == HashAlgorithmName.SHA1)
return new SHA1CryptoServiceProvider();
if (hashAlgorithm == HashAlgorithmName.SHA256)
return new SHA256CryptoServiceProvider();
if (hashAlgorithm == HashAlgorithmName.SHA384)
return new SHA384CryptoServiceProvider();
if (hashAlgorithm == HashAlgorithmName.SHA512)
return new SHA512CryptoServiceProvider();
throw new CryptographicException(NTE_BAD_ALGID);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351")] // We are providing the implementations for these algorithms
private static HashAlgorithm GetHMAC(HashAlgorithmName hashAlgorithm, byte[] key)
{
if (hashAlgorithm == HashAlgorithmName.MD5)
return new HMACMD5(key);
if (hashAlgorithm == HashAlgorithmName.SHA1)
return new HMACSHA1(key);
if (hashAlgorithm == HashAlgorithmName.SHA256)
return new HMACSHA256(key);
if (hashAlgorithm == HashAlgorithmName.SHA384)
return new HMACSHA384(key);
if (hashAlgorithm == HashAlgorithmName.SHA512)
return new HMACSHA512(key);
throw new CryptographicException(NTE_BAD_ALGID);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using mshtml;
namespace OpenLiveWriter.Mshtml
{
/// <summary>
/// This class is a convenience wrapper for the MSHTML IMarkupServices interface.
/// </summary>
public class MshtmlMarkupServices
{
private readonly IMarkupServicesRaw MarkupServices;
public MshtmlMarkupServices(IMarkupServicesRaw markupServices)
{
MarkupServices = markupServices;
}
/// <summary>
/// Marks the beginning of a reversible unit of work.
/// </summary>
/// <param name="title">the title of a reversible unit of work</param>
public void BeginUndoUnit(string title)
{
MarkupServices.BeginUndoUnit(title);
}
/// <summary>
/// Creates a duplicate of an element.
/// </summary>
/// <param name="e">the element to clone</param>
/// <returns>a clone of the element</returns>
public IHTMLElement CloneElement(IHTMLElement e)
{
IHTMLElement clone;
MarkupServices.CloneElement(e, out clone);
return clone;
}
/// <summary>
/// Copies the content between markers to a target location.
/// </summary>
/// <param name="start">start point of the text to be copied</param>
/// <param name="end">end point of the text to be copied</param>
/// <param name="target">target point of insertion</param>
public void Copy(MarkupPointer start, MarkupPointer end, MarkupPointer target)
{
MarkupServices.Copy(start.PointerRaw, end.PointerRaw, target.PointerRaw);
}
/// <summary>
/// Creates an element with the specified tag.
/// </summary>
/// <param name="tagID">specifies the type of tag to create</param>
/// <param name="attributes">specifies the attributes of the element</param>
/// <returns>the newly created element</returns>
public IHTMLElement CreateElement(_ELEMENT_TAG_ID tagID, string attributes)
{
IHTMLElement element;
MarkupServices.CreateElement(tagID, attributes, out element);
return element;
}
/// <summary>
/// Creates an instance of a MarkupContainer object.
/// </summary>
/// <returns>An empty MarkupContainer</returns>
public MarkupContainer CreateMarkupContainer()
{
IMarkupContainerRaw container;
MarkupServices.CreateMarkupContainer(out container);
return new MarkupContainer(this, container);
}
/// <summary>
/// Creates an instance of a MarkupPointer object.
/// </summary>
/// <returns></returns>
public MarkupPointer CreateMarkupPointer()
{
IMarkupPointerRaw pointer;
MarkupServices.CreateMarkupPointer(out pointer);
return new MarkupPointer(this, pointer);
}
/// <summary>
/// Creates an instance of a MarkupPointer object from a pointer raw.
/// </summary>
/// <returns></returns>
public MarkupPointer CreateMarkupPointer(IMarkupPointerRaw rawPtr)
{
IMarkupPointerRaw pointer;
MarkupServices.CreateMarkupPointer(out pointer);
pointer.MoveToPointer(rawPtr);
return new MarkupPointer(this, pointer);
}
/// <summary>
/// Creates an instance of the IMarkupPointer object with an initial position
/// at the same location as another pointer.
/// </summary>
/// <param name="initialPosition"></param>
/// <returns></returns>
public MarkupPointer CreateMarkupPointer(MarkupPointer initialPosition)
{
MarkupPointer pointer = CreateMarkupPointer();
pointer.MoveToPointer(initialPosition);
return pointer;
}
/// <summary>
/// Create an unpositioned MarkupRange.
/// </summary>
/// <returns></returns>
public MarkupRange CreateMarkupRange()
{
MarkupPointer start = CreateMarkupPointer();
MarkupPointer end = CreateMarkupPointer();
end.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;
return CreateMarkupRange(start, end);
}
/// <summary>
/// Create a MarkupRange from a selection object.
/// </summary>
public MarkupRange CreateMarkupRange(IHTMLSelectionObject selection)
{
if (selection == null)
{
return null;
}
// see what type of range is selected
object range = selection.createRange();
if (range is IHTMLTxtRange)
{
return CreateMarkupRange(range as IHTMLTxtRange);
}
else if (range is IHTMLControlRange)
{
// we only support single-selection so a "control-range" can always
// be converted into a single-element text range
IHTMLControlRange controlRange = range as IHTMLControlRange;
if (controlRange.length == 1)
{
IHTMLElement selectedElement = controlRange.item(0);
MarkupRange markupRange = CreateMarkupRange(selectedElement);
//return the precisely positioned text range
return markupRange;
}
else
{
Debug.Fail("Length of control range not equal to 1 (value was " + controlRange.length.ToString(CultureInfo.InvariantCulture));
return null;
}
}
else // null or unexpected range type
{
return null;
}
}
/// <summary>
/// Create a MarkupRange from that surrounds an Element.
/// </summary>
/// <returns></returns>
public MarkupRange CreateMarkupRange(IHTMLElement element)
{
return CreateMarkupRange(element, true);
}
/// <summary>
/// Create a MarkupRange from that surrounds an Element.
/// </summary>
/// <returns></returns>
public MarkupRange CreateMarkupRange(IHTMLElement element, bool outside)
{
_ELEMENT_ADJACENCY beginAdj = outside ? _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin : _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin;
_ELEMENT_ADJACENCY endAdj = outside ? _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd : _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd;
MarkupPointer Begin = CreateMarkupPointer(element, beginAdj);
MarkupPointer End = CreateMarkupPointer(element, endAdj);
End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;
MarkupRange markupRange = new MarkupRange(Begin, End, this);
return markupRange;
}
/// <summary>
/// Create a MarkupRange from a TextRange.
/// </summary>
/// <param name="textRange"></param>
/// <returns></returns>
public MarkupRange CreateMarkupRange(IHTMLTxtRange textRange)
{
MarkupPointer Begin = CreateMarkupPointer();
MarkupPointer End = CreateMarkupPointer();
End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;
MovePointersToRange(textRange, Begin, End);
MarkupRange markupRange = new MarkupRange(Begin, End, this);
return markupRange;
}
/// <summary>
/// Create a MarkupRange from a set of MarkupPointers.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public MarkupRange CreateMarkupRange(MarkupPointer start, MarkupPointer end)
{
MarkupRange markupRange = new MarkupRange(start, end, this);
return markupRange;
}
/// <summary>
/// Create a TextRange that spans a set of pointers.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public IHTMLTxtRange CreateTextRange(MarkupPointer start, MarkupPointer end)
{
Debug.Assert(start.Positioned && end.Positioned, "pointers are not positioned");
IHTMLTxtRange range = start.Container.CreateTextRange(start, end);
return range;
}
/// <summary>
/// Marks the end of a reversible unit of work.
/// </summary>
public void EndUndoUnit()
{
MarkupServices.EndUndoUnit();
}
/// <summary>
/// Creates an instance of the IMarkupPointer object with an initial position
/// adjacent to the specified HTML element.
/// </summary>
/// <param name="e"></param>
/// <param name="eAdj"></param>
/// <returns></returns>
public MarkupPointer CreateMarkupPointer(IHTMLElement e, _ELEMENT_ADJACENCY eAdj)
{
MarkupPointer pointer = CreateMarkupPointer();
pointer.MoveAdjacentToElement(e, eAdj);
return pointer;
}
/// <summary>
/// Retrieves an element's tag identifier (ID).
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public _ELEMENT_TAG_ID GetElementTagId(IHTMLElement e)
{
_ELEMENT_TAG_ID tagId;
MarkupServices.GetElementTagId(e, out tagId);
return tagId;
}
/// <summary>
/// Returns the tag name given the identifier (ID).
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public string GetNameForTagId(_ELEMENT_TAG_ID tagId)
{
IntPtr p;
MarkupServices.GetNameForTagID(tagId, out p);
return Marshal.PtrToStringBSTR(p);
}
/// <summary>
/// Retrieve the HTML content between two pointers.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public string GetHtmlText(MarkupPointer start, MarkupPointer end)
{
string html = CreateTextRange(start, end).htmlText;
return html;
}
/// <summary>
/// Retrieve the text content between two pointers (html markup is stripped).
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public string GetText(MarkupPointer start, MarkupPointer end)
{
string text = CreateTextRange(start, end).text;
return text;
}
/// <summary>
/// Inserts an element between the target pointers.
/// </summary>
/// <param name="element">the element to insert</param>
/// <param name="start">start point of insertion</param>
/// <param name="end">end point of insertion</param>
public void InsertElement(IHTMLElement element, MarkupPointer start, MarkupPointer end)
{
MarkupServices.InsertElement(element, start.PointerRaw, end.PointerRaw);
}
/// <summary>
/// Insert text at the given pointer.
/// </summary>
/// <param name="text">the text to insert</param>
/// <param name="start">the point of insertion</param>
public void InsertText(string text, MarkupPointer insertionPoint)
{
MarkupServices.InsertText(text, text.Length, insertionPoint.PointerRaw);
}
/// <summary>
/// Insert html at the given pointer.
/// </summary>
/// <param name="html"></param>
/// <param name="insertionPoint"></param>
public void InsertHtml(string html, MarkupPointer insertionPoint)
{
MarkupRange content = CreateMarkupRange();
ParseString(html, content.Start, content.End);
Move(content.Start, content.End, insertionPoint);
}
public IMarkupServicesRaw MarkupServicesRaw
{
get
{
return MarkupServices;
}
}
/// <summary>
/// Move the content between markers to a target location.
/// </summary>
/// <param name="start">start point of the text to be moved</param>
/// <param name="end">end point of the text to be moved</param>
/// <param name="target">target point of insertion</param>
public void Move(MarkupPointer start, MarkupPointer end, MarkupPointer target)
{
Trace.Assert(start.Positioned && end.Positioned && target.Positioned, string.Format(CultureInfo.InvariantCulture, "Invalid pointer being used for insert. start:({0}),end:({1}),target:({2})", start.Positioned, end.Positioned, target.Positioned));
MarkupServices.Move(start.PointerRaw, end.PointerRaw, target.PointerRaw);
}
/// <summary>
/// Positions a DisplayPointer at the specified MarkupPointer.
/// </summary>
/// <param name="displayPointer"></param>
/// <param name="p"></param>
public void MoveDisplayPointerToMarkupPointer(IDisplayPointerRaw displayPointer, MarkupPointer p)
{
DisplayServices.TraceMoveToMarkupPointer(displayPointer, p);
}
/// <summary>
/// Positions a MarkupPointer at the specfied caret.
/// </summary>
/// <param name="caret"></param>
/// <param name="p"></param>
public void MoveMarkupPointerToCaret(IHTMLCaretRaw caret, MarkupPointer p)
{
caret.MoveMarkupPointerToCaret(p.PointerRaw);
}
/// <summary>
/// Positions pointers at the edges of an existing range.
/// </summary>
/// <param name="range">the text range to move to</param>
/// <param name="start">the pointer to position at the start of the range</param>
/// <param name="end">the pointer to position at the end of the range</param>
public void MovePointersToRange(IHTMLTxtRange range, MarkupPointer start, MarkupPointer end)
{
MarkupServices.MovePointersToRange(range, start.PointerRaw, end.PointerRaw);
}
/// <summary>
/// Positions pointers at the edges of an existing range.
/// </summary>
/// <param name="start">the pointer positioned at the start of the range</param>
/// <param name="end">the pointer position at the end of the range</param>
/// <param name="range">the text range to move</param>
public void MoveRangeToPointers(MarkupPointer start, MarkupPointer end, IHTMLTxtRange range)
{
MarkupServices.MoveRangeToPointers(start.PointerRaw, end.PointerRaw, range);
}
/// <summary>
/// Creates a MarkupContainer that contains the results of parsing the contents of a string.
/// </summary>
/// <param name="html">html content to parse</param>
/// <param name="start">pointer to position at the beginning of the parsed content (null is allowed)</param>
/// <param name="end">pointer to position at the end of the parsed content (null is allowed)</param>
/// <returns></returns>
public MarkupContainer ParseString(string html, MarkupPointer start, MarkupPointer end)
{
if (start == null)
start = CreateMarkupPointer();
if (end == null)
end = CreateMarkupPointer();
IMarkupContainerRaw container;
MarkupServices.ParseString(html, 0, out container, start.PointerRaw, end.PointerRaw);
return new MarkupContainer(this, container);
}
/// <summary>
/// Returns a container that contains the results of parsing the contents of a string.
/// </summary>
/// <param name="html">the HTML to content parse into a container</param>
/// <returns></returns>
public MarkupContainer ParseString(string html)
{
MarkupPointer start = CreateMarkupPointer();
MarkupPointer end = CreateMarkupPointer();
MarkupContainer container = ParseString(html, start, end);
return container;
}
/// <summary>
/// Removes content between two pointers.
/// </summary>
/// <param name="start">start point of text to remove</param>
/// <param name="end">end point of text to remove</param>
public void Remove(MarkupPointer start, MarkupPointer end)
{
MarkupServices.Remove(start.PointerRaw, end.PointerRaw);
}
/// <summary>
/// Removes the given element without removing the content contained within it.
/// </summary>
/// <param name="e"></param>
public void RemoveElement(IHTMLElement e)
{
MarkupServices.RemoveElement(e);
}
/// <summary>
/// Replaces an element with a new element while preserving the content inside the old element.
/// </summary>
/// <param name="oldElement"></param>
/// <param name="newElement"></param>
public void ReplaceElement(IHTMLElement oldElement, IHTMLElement newElement)
{
MarkupRange range = CreateMarkupRange();
range.MoveToElement(oldElement, true);
InsertElement(newElement, range.Start, range.End);
RemoveElement(oldElement);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Its.Domain.Serialization;
using Microsoft.Its.Domain.Testing;
using Microsoft.Its.Recipes;
using NUnit.Framework;
using Sample.Domain;
using Sample.Domain.Ordering;
using Sample.Domain.Ordering.Commands;
using Sample.Domain.Projections;
using Assert = NUnit.Framework.Assert;
using Its.Log.Instrumentation;
namespace Microsoft.Its.Domain.Sql.Tests
{
[TestFixture]
public class ReadModelCatchupTests : ReadModelCatchupTest
{
}
[Category("Catchups")]
[TestFixture]
public abstract class ReadModelCatchupTest : EventStoreDbTest
{
private readonly TimeSpan MaxWaitTime = TimeSpan.FromSeconds(5);
[Test]
public async Task ReadModelCatchup_only_queries_events_since_the_last_consumed_event_id()
{
var bus = new FakeEventBus();
var repository = new SqlEventSourcedRepository<Order>(bus);
// save the order with no projectors running
var order = new Order();
order.Apply(new AddItem
{
Price = 1m,
ProductName = "Widget"
});
await repository.Save(order);
// subscribe one projector for catchup
var projector1 = new Projector1();
using (var catchup = CreateReadModelCatchup(projector1))
{
catchup.Progress.ForEachAsync(s => Console.WriteLine(s));
await catchup.Run();
}
order.Apply(new AddItem
{
Price = 1m,
ProductName = "Widget"
});
await repository.Save(order);
// subscribe both projectors
var projector2 = new Projector2();
using (var catchup = CreateReadModelCatchup(projector1, projector2))
{
catchup.Progress.ForEachAsync(s => Console.WriteLine(s));
await catchup.Run();
}
projector1.CallCount.Should().Be(2, "A given event should only be passed to a given projector once");
projector2.CallCount.Should().Be(2, "A projector should be passed events it has not previously seen.");
}
[Test]
public async Task ReadModelCatchup_does_not_query_events_that_no_subscribed_projector_is_interested_in()
{
Events.Write(100, _ => Events.Any());
Events.Write(1, _ => new Order.Created());
var projector2 = Projector.Create<CustomerAccount.Created>(e => { });
StorableEvent extraneousEvent = null;
using (var catchup = CreateReadModelCatchup(projector2))
using (var eventStore = new EventStoreDbContext())
{
var eventsQueried = 0;
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s =>
{
var eventId = s.CurrentEventId;
var @event = eventStore.Events.Single(e => e.Id == eventId);
if (@event.StreamName != "CustomerAccount" || @event.Type != "Created")
{
extraneousEvent = @event;
catchup.Dispose();
}
eventsQueried++;
});
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
if (extraneousEvent != null)
{
Assert.Fail(string.Format("Found an event that should not have been queried from the event store: {0}:{1} (#{2})",
extraneousEvent.StreamName,
extraneousEvent.Type,
extraneousEvent.Id));
}
}
[Test]
public async Task ReadModelCatchup_queries_events_that_match_both_aggregate_and_event_type()
{
const int numOfOrderCreatedEvents = 5;
Events.Write(numOfOrderCreatedEvents, _ => new Order.Created());
Events.Write(7, _ => new CustomerAccount.Created());
Events.Write(8, _ => new Order.Cancelled());
var projector = new DuckTypeProjector<Order.Created>(e => { });
var eventsQueried = 0;
using (var catchup = CreateReadModelCatchup(projector))
{
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s => { eventsQueried++; });
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
eventsQueried.Should().Be(numOfOrderCreatedEvents);
}
[Test]
public async Task ReadModelCatchup_queries_all_events_if_IEvent_is_subscribed()
{
Events.Write(100, _ => Events.Any());
var projector = Projector.Create<IEvent>(e => { }).Named(MethodBase.GetCurrentMethod().Name);
var eventsQueried = 0;
using (var catchup = CreateReadModelCatchup(projector))
{
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s => { eventsQueried++; });
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
eventsQueried.Should().Be(100);
}
[Test]
public async Task ReadModelCatchup_queries_all_events_if_Event_is_subscribed()
{
Events.Write(100, _ => Events.Any());
var projector = Projector.Create<Event>(e => { }).Named(MethodBase.GetCurrentMethod().Name);
var eventsQueried = 0;
using (var catchup = CreateReadModelCatchup(projector))
{
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s => { eventsQueried++; });
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
eventsQueried.Should().Be(100);
}
[Test]
public async Task ReadModelCatchup_queries_all_events_for_the_aggregate_if_IEvent_T_is_subscribed()
{
var orderEvents = 0;
Events.Write(100, _ =>
{
var @event = Events.Any();
if (@event.AggregateType() == typeof (Order))
{
orderEvents++;
}
return @event;
});
var projector = Projector.Create<IEvent<Order>>(e => { }).Named(MethodBase.GetCurrentMethod().Name);
var eventsQueried = 0;
using (var catchup = CreateReadModelCatchup(projector))
{
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s => { eventsQueried++; });
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
eventsQueried.Should().Be(orderEvents);
}
[Test]
public async Task ReadModelCatchup_queries_all_events_for_the_aggregate_if_Event_T_is_subscribed()
{
var orderEvents = 0;
Events.Write(100, _ =>
{
var @event = Events.Any();
if (@event.AggregateType() == typeof (Order))
{
orderEvents++;
}
return @event;
});
var projector = Projector.Create<IEvent<Order>>(e => { }).Named(MethodBase.GetCurrentMethod().Name);
var eventsQueried = 0;
using (var catchup = CreateReadModelCatchup(projector))
{
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s =>
{
eventsQueried++;
});
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
eventsQueried.Should().Be(orderEvents);
}
[Test]
public async Task ReadModelCatchup_queries_event_subtypes_correctly()
{
var subclassedEventsWritten = 0;
Events.Write(100, _ =>
{
var @event = Any.Bool()
? Events.Any()
: new CustomerAccount.OrderShipConfirmationEmailSent();
if (@event is EmailSent)
{
subclassedEventsWritten++;
}
return @event;
});
var projector = Projector.Create<EmailSent>(e => { }).Named(MethodBase.GetCurrentMethod().Name);
var eventsQueried = 0;
using (var catchup = CreateReadModelCatchup(projector))
{
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s => { eventsQueried++; });
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
eventsQueried.Should().Be(subclassedEventsWritten);
}
[Test]
public async Task ReadModelCatchup_queries_scheduled_commands_if_IScheduledCommand_is_subscribed()
{
var scheduledCommandsWritten = 0;
var scheduledCommandsQueried = 0;
Events.Write(50, _ =>
{
if (Any.Bool())
{
return Events.Any();
}
scheduledCommandsWritten++;
return new CommandScheduled<Order>
{
Command = new Ship(),
DueTime = DateTimeOffset.UtcNow
};
});
var projector = Projector.Create<IScheduledCommand>(e => { }).Named(MethodBase.GetCurrentMethod().Name);
var eventsQueried = 0;
using (var catchup = CreateReadModelCatchup(projector))
using (var eventStore = new EventStoreDbContext())
{
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s =>
{
var eventId = s.CurrentEventId;
var @event = eventStore.Events.Single(e => e.Id == eventId);
if (@event.Type.StartsWith("Scheduled:"))
{
scheduledCommandsQueried++;
}
eventsQueried++;
});
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
scheduledCommandsQueried.Should().Be(scheduledCommandsWritten);
}
[Test]
public async Task ReadModelCatchup_queries_scheduled_commands_if_IScheduledCommandT_is_subscribed()
{
var scheduledCommandsWritten = 0;
var scheduledCommandsQueried = 0;
Events.Write(50, _ =>
{
if (Any.Bool())
{
return Events.Any();
}
scheduledCommandsWritten++;
return new CommandScheduled<Order>
{
Command = new Ship(),
DueTime = DateTimeOffset.UtcNow
};
});
var projector = Projector.Create<IScheduledCommand<Order>>(e => { }).Named(MethodBase.GetCurrentMethod().Name);
var eventsQueried = 0;
using (var catchup = CreateReadModelCatchup(projector))
using (var eventStore = new EventStoreDbContext())
{
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s =>
{
var eventId = s.CurrentEventId;
var @event = eventStore.Events.Single(e => e.Id == eventId);
if (@event.Type.StartsWith("Scheduled:"))
{
scheduledCommandsQueried++;
}
eventsQueried++;
});
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
scheduledCommandsQueried.Should().Be(scheduledCommandsWritten);
}
[Test]
public async Task ReadModelCatchup_queries_scheduled_commands_if_CommandScheduled_is_subscribed()
{
var scheduledCommandsWritten = 0;
var scheduledCommandsQueried = 0;
Events.Write(50, _ =>
{
if (Any.Bool())
{
return Events.Any();
}
scheduledCommandsWritten++;
return new CommandScheduled<Order>
{
Command = new Ship(),
DueTime = DateTimeOffset.UtcNow
};
});
var projector = Projector.Create<CommandScheduled<Order>>(e => { }).Named(MethodBase.GetCurrentMethod().Name);
var eventsQueried = 0;
using (var catchup = CreateReadModelCatchup(projector))
using (var eventStore = new EventStoreDbContext())
{
catchup.Progress
.Where(s => !s.IsStartOfBatch)
.ForEachAsync(s =>
{
var eventId = s.CurrentEventId;
var @event = eventStore.Events.Single(e => e.Id == eventId);
if (@event.Type.StartsWith("Scheduled:"))
{
scheduledCommandsQueried++;
}
eventsQueried++;
});
await catchup.Run()
.ContinueWith(r => catchup.Dispose());
Console.WriteLine(new { eventsQueried });
}
scheduledCommandsQueried.Should().Be(scheduledCommandsWritten);
}
[Test]
public async Task ReadModelCatchup_StartAtEventId_can_be_used_to_avoid_requery_of_previous_events()
{
var lastEventId = Events.Write(50, _ => Events.Any());
var eventsProjected = 0;
var projector = Projector.Create<Event>(e => { eventsProjected++; })
.Named(MethodBase.GetCurrentMethod().Name);
using (var catchup = new ReadModelCatchup(projector)
{
StartAtEventId = lastEventId - 20
})
{
await catchup.Run();
}
eventsProjected.Should().Be(21);
}
[Test]
public async Task When_Run_is_called_while_already_running_then_it_skips_the_run()
{
var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus());
await repository.Save(new Order());
var mre = new ManualResetEventSlim();
var barrier = new Barrier(2);
var progress = new List<ReadModelCatchupStatus>();
Events.Write(10);
var projector = new Projector<Order.ItemAdded>(() => new ReadModelDbContext())
{
OnUpdate = (work, e) =>
{
barrier.SignalAndWait(1000);
mre.Wait(5000);
}
};
using (var catchup = CreateReadModelCatchup(projector))
using (catchup.Progress.Subscribe(s =>
{
progress.Add(s);
Console.WriteLine("progress: " + s);
}))
{
#pragma warning disable 4014
// don't await
Task.Run(() => catchup.Run());
#pragma warning restore 4014
// make sure the first catchup is blocked inside the projector
barrier.SignalAndWait(1000);
// try to start another catchup
var result = await catchup.Run();
result.Should().Be(ReadModelCatchupResult.CatchupAlreadyInProgress);
await Task.Delay(2000);
}
mre.Set();
progress.Should().ContainSingle(s => s.IsStartOfBatch);
}
[Test]
public async Task When_a_projector_update_fails_then_an_entry_is_added_to_EventHandlingErrors()
{
// arrange
var errorMessage = Any.Paragraph(10);
var productName = Any.Paragraph();
var projector = new Projector<Order.ItemAdded>(() => new ReadModelDbContext())
{
OnUpdate = (work, e) => { throw new Exception(errorMessage); }
};
var order = new Order();
var repository = new SqlEventSourcedRepository<Order>();
order.Apply(new AddItem
{
Price = 1m,
ProductName = productName
});
await repository.Save(order);
// act
using (var catchup = CreateReadModelCatchup(projector))
{
await catchup.Run();
}
// assert
using (var db = new ReadModelDbContext())
{
var error = db.Set<EventHandlingError>().Single(e => e.AggregateId == order.Id);
error.StreamName.Should().Be("Order");
error.EventTypeName.Should().Be("ItemAdded");
error.SerializedEvent.Should().Contain(productName);
error.Error.Should().Contain(errorMessage);
}
}
[Test]
public async Task Events_that_cannot_be_deserialized_to_the_expected_type_are_logged_as_EventHandlingErrors()
{
var badEvent = new StorableEvent
{
Actor = Any.Email(),
StreamName = typeof (Order).Name,
Type = typeof (Order.ItemAdded).Name,
Body = new { Price = "oops this is not a number" }.ToJson(),
SequenceNumber = Any.PositiveInt(),
AggregateId = Any.Guid(),
UtcTime = DateTime.UtcNow
};
using (var eventStore = new EventStoreDbContext())
{
eventStore.Events.Add(badEvent);
await eventStore.SaveChangesAsync();
}
using (var catchup = CreateReadModelCatchup(new Projector1()))
{
await catchup.Run();
}
using (var readModels = new ReadModelDbContext())
{
var failure = readModels.Set<EventHandlingError>()
.OrderByDescending(e => e.Id)
.First(e => e.AggregateId == badEvent.AggregateId);
failure.Error.Should().Contain("JsonReaderException");
failure.SerializedEvent.Should().Contain(badEvent.Body);
failure.Actor.Should().Be(badEvent.Actor);
failure.OriginalId.Should().Be(badEvent.Id);
failure.AggregateId.Should().Be(badEvent.AggregateId);
failure.SequenceNumber.Should().Be(badEvent.SequenceNumber);
failure.StreamName.Should().Be(badEvent.StreamName);
failure.EventTypeName.Should().Be(badEvent.Type);
}
}
[Test]
public async Task When_an_exception_is_thrown_during_a_read_model_update_then_it_is_logged_on_its_bus()
{
var projector = new Projector<Order.ItemAdded>(() => new ReadModelDbContext())
{
OnUpdate = (work, e) => { throw new Exception("oops!"); }
};
var itemAdded = new Order.ItemAdded
{
AggregateId = Any.Guid(),
SequenceNumber = 1,
ProductName = Any.AlphanumericString(10, 20),
Price = Any.Decimal(0.01m),
Quantity = 100
};
var errors = new List<Domain.EventHandlingError>();
using (var catchup = CreateReadModelCatchup(projector))
using (var db = new EventStoreDbContext())
{
db.Events.Add(itemAdded.ToStorableEvent());
db.SaveChanges();
catchup.EventBus.Errors.Subscribe(errors.Add);
await catchup.Run();
}
var error = errors.Single(e => e.AggregateId == itemAdded.AggregateId);
error.SequenceNumber.Should().Be(itemAdded.SequenceNumber);
error.Event
.ShouldHave()
.Properties(p => p.SequenceNumber)
.EqualTo(itemAdded);
}
[Ignore("Test needs rebuilding")]
[Test]
public async Task Database_command_timeouts_during_catchup_do_not_interrupt_catchup()
{
// reset read model tracking to 0
new ReadModelDbContext().DisposeAfter(c =>
{
var projectorName = ReadModelInfo.NameForProjector(new Projector<Order.CustomerInfoChanged>(() => new ReadModelDbContext()));
c.Set<ReadModelInfo>()
.SingleOrDefault(i => i.Name == projectorName)
.IfNotNull()
.ThenDo(i => { i.CurrentAsOfEventId = 0; });
c.SaveChanges();
});
var exceptions = new Stack<Exception>(Enumerable.Range(1, 2)
.Select(_ => new InvalidOperationException("Invalid attempt to call IsDBNull when reader is closed.")));
var count = 0;
var flakyEvents = new FlakyEventStream(
Enumerable.Range(1, 1000)
.Select(i => new StorableEvent
{
AggregateId = Any.Guid(),
Body = new Order.CustomerInfoChanged { CustomerName = i.ToString() }.ToJson(),
SequenceNumber = i,
StreamName = typeof (Order).Name,
Timestamp = DateTimeOffset.Now,
Type = typeof (Order.CustomerInfoChanged).Name,
Id = i
}).ToArray(),
startFlakingOnEnumeratorNumber: 2,
doSomethingFlaky: i =>
{
if (count++ > 50)
{
count = 0;
if (exceptions.Any())
{
throw exceptions.Pop();
}
}
});
var names = new HashSet<string>();
var projector = new Projector<Order.CustomerInfoChanged>(() => new ReadModelDbContext())
{
OnUpdate = (work, e) => names.Add(e.CustomerName)
};
using (var catchup = CreateReadModelCatchup(projector))
{
await catchup.Run();
}
projector.CallCount.Should().Be(1000);
names.Count.Should().Be(1000);
}
[Test]
public async Task Insertion_of_new_events_during_catchup_does_not_interrupt_catchup()
{
var barrier = new Barrier(2);
// preload some events for the catchup. replay will hit the barrier on the last one.
var order = new Order();
Action addEvent = () => order.Apply(new AddItem
{
Quantity = 1,
ProductName = "Penny candy",
Price = .01m
});
Enumerable.Range(1, 100).ForEach(_ => addEvent());
var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus());
await repository.Save(order);
// queue the catchup on a background task
#pragma warning disable 4014
// don't await
Task.Run(() =>
#pragma warning restore 4014
{
var projector = new Projector1
{
OnUpdate = (work, e) =>
{
if (e.SequenceNumber == 10)
{
Console.WriteLine("pausing read model catchup");
barrier.SignalAndWait(MaxWaitTime); //1
barrier.SignalAndWait(MaxWaitTime); //2
Console.WriteLine("resuming read model catchup");
}
}
};
using (var db = new EventStoreDbContext())
using (var catchup = CreateReadModelCatchup(projector))
{
var events = db.Events.Where(e => e.Id > HighestEventId);
Console.WriteLine(string.Format("starting read model catchup for {0} events", events.Count()));
catchup.Run().Wait();
Console.WriteLine("done with read model catchup");
barrier.SignalAndWait(MaxWaitTime); //3
}
});
Console.WriteLine("queued read model catchup task");
barrier.SignalAndWait(MaxWaitTime); //1
new EventStoreDbContext().DisposeAfter(c =>
{
Console.WriteLine("adding one more event, bypassing read model tracking");
c.Events.Add(new Order.ItemAdded
{
AggregateId = Guid.NewGuid(),
SequenceNumber = 1
}.ToStorableEvent());
c.SaveChanges();
Console.WriteLine("done adding one more event");
});
barrier.SignalAndWait(MaxWaitTime); //2
barrier.SignalAndWait(MaxWaitTime); //3
// check that everything worked:
var projector2 = new Projector1();
var projectorName = ReadModelInfo.NameForProjector(projector2);
using (var readModels = new ReadModelDbContext())
{
var readModelInfo = readModels.Set<ReadModelInfo>().Single(i => i.Name == projectorName);
readModelInfo.CurrentAsOfEventId.Should().Be(HighestEventId + 101);
using (var catchup = CreateReadModelCatchup(projector2))
{
await catchup.Run();
}
readModels.Entry(readModelInfo).Reload();
readModelInfo.CurrentAsOfEventId.Should().Be(HighestEventId + 102);
}
}
[Test]
public async Task When_not_using_Update_then_failed_writes_do_not_interrupt_catchup()
{
// arrange
// preload some events for the catchup. replay will hit the barrier on the last one.
var order = new Order();
var productName = Any.Paragraph(3);
Action addEvent = () => order.Apply(new AddItem
{
Quantity = 1,
ProductName = productName,
Price = .01m
});
Enumerable.Range(1, 30).ForEach(_ => addEvent());
var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus());
await repository.Save(order);
var count = 0;
var projector = new Projector1
{
OnUpdate = (work, e) =>
{
using (var db = new ReadModelDbContext())
{
// throw one exception in the middle
if (count++ == 15)
{
throw new Exception("drat!");
}
db.SaveChanges();
}
}
};
// act
using (var catchup = CreateReadModelCatchup(projector))
{
await catchup.Run();
}
// assert
count.Should().Be(30);
}
[Test]
public async Task When_using_Update_then_failed_writes_do_not_interrupt_catchup()
{
// preload some events for the catchup. replay will hit the barrier on the last one.
var order = new Order();
var productName = Any.Paragraph(4);
Action addEvent = () => order.Apply(new AddItem
{
Quantity = 1,
ProductName = productName,
Price = .01m
});
Enumerable.Range(1, 30).ForEach(_ => addEvent());
var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus());
await repository.Save(order);
var count = 0;
Projector1 projector = null;
projector = new Projector1
{
OnUpdate = (_, e) =>
{
using (var work = projector.Update())
{
var db = work.Resource<ReadModelDbContext>();
if (count++ == 15)
{
// do something that will trigger a db exception when the UnitOfWork is committed
var inventory = db.Set<ProductInventory>();
inventory.Add(new ProductInventory
{
ProductName = e.ProductName,
QuantityReserved = e.Quantity
});
inventory.Add(new ProductInventory
{
ProductName = e.ProductName,
QuantityReserved = e.Quantity
});
}
work.VoteCommit();
}
}
};
// act
using (var catchup = CreateReadModelCatchup(projector))
{
await catchup.Run();
}
// assert
count.Should().Be(30);
}
[Test]
public async Task When_using_Update_then_failed_writes_are_logged_to_EventHandlingErrors()
{
// preload some events for the catchup. replay will hit the barrier on the last one.
var order = new Order();
var productName = Any.Paragraph(4);
order.Apply(new AddItem
{
Quantity = 1,
ProductName = productName,
Price = .01m
});
var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus());
await repository.Save(order);
Projector1 projector = null;
projector = new Projector1
{
OnUpdate = (_, e) =>
{
using (var work = projector.Update())
{
var db = work.Resource<ReadModelDbContext>();
// do something that will trigger a db exception when the UnitOfWork is committed
var inventory = db.Set<ProductInventory>();
inventory.Add(new ProductInventory
{
ProductName = e.ProductName,
QuantityReserved = e.Quantity
});
inventory.Add(new ProductInventory
{
ProductName = e.ProductName,
QuantityReserved = e.Quantity
});
work.VoteCommit();
}
}
};
// act
using (var catchup = CreateReadModelCatchup(projector))
{
await catchup.Run();
}
// assert
using (var db = new ReadModelDbContext())
{
var error = db.Set<EventHandlingError>().Single(e => e.AggregateId == order.Id);
error.Error.Should()
.Contain(
string.Format(
"Violation of PRIMARY KEY constraint 'PK_dbo.ProductInventories'. Cannot insert duplicate key in object 'dbo.ProductInventories'. The duplicate key value is ({0})",
productName));
}
}
[Test]
public void When_using_a_custom_DbContext_then_it_is_available_in_UnitOfWork_resources()
{
var projector = new Projector<Order.CreditCardCharged>(() => new ReadModels1DbContext())
{
OnUpdate = (work, charged) => { work.Resource<ReadModels1DbContext>().Should().NotBeNull(); }
};
projector.UpdateProjection(new Order.CreditCardCharged
{
Amount = Any.PositiveInt()
});
}
[Test]
public void When_two_projectors_have_the_same_name_then_the_catchup_throws_on_creation()
{
var projector1 = Projector.Create<Order.Cancelled>(e => { });
var projector2 = Projector.Create<Order.Cancelled>(e => { });
Action create = () => CreateReadModelCatchup(projector1, projector2);
create.ShouldThrow<ArgumentException>()
.And
.Message.Should().Contain(string.Format("Duplicate read model names:\n{0}",
EventHandler.FullName(projector1)));
}
[Test]
public async Task Run_returns_CatchupRanAndHandledNewEvents_if_the_catchup_was_not_currently_running()
{
Events.Write(5);
using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { })))
{
(await catchup.Run()).Should().Be(ReadModelCatchupResult.CatchupRanAndHandledNewEvents);
}
}
[Test]
public async Task Run_returns_CatchupRanAndHandledNewEvents_if_the_catchup_was_not_currently_running_and_there_were_no_events()
{
using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { })))
{
(await catchup.Run()).Should().Be(ReadModelCatchupResult.CatchupRanButNoNewEvents);
}
}
[Test]
public async Task Run_returns_CatchupAlreadyInProgress_if_the_catchup_was_currently_running()
{
Events.Write(1);
var barrier = new Barrier(2);
using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e =>
{
barrier.SignalAndWait(1000);
})))
{
#pragma warning disable 4014
// don't await catchup
Task.Run(() => catchup.Run());
#pragma warning restore 4014
barrier.SignalAndWait(500);
(await catchup.Run()).Should().Be(ReadModelCatchupResult.CatchupAlreadyInProgress);
}
}
[Test]
public async Task When_Progress_is_awaited_then_it_completes_when_the_catchup_is_disposed()
{
Events.Write(5);
long lastEventId = 0;
using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { })))
{
catchup.Progress.Subscribe(s =>
{
Console.WriteLine(s);
lastEventId = s.CurrentEventId;
});
#pragma warning disable 4014
// don't await
Task.Run(() => catchup.Run())
.ContinueWith(r => catchup.Dispose());
#pragma warning restore 4014
await catchup.Progress;
}
lastEventId.Should().Be(HighestEventId + 5);
}
[Test]
public async Task SingleBatchAsync_can_be_used_to_observe_the_status_during_a_single_catchup_batch()
{
Events.Write(5);
using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { })))
{
var statuses = await catchup.SingleBatchAsync().ToArray();
var ids = statuses.Select(s => s.CurrentEventId).ToArray();
Console.WriteLine(new { ids }.ToLogString());
ids.ShouldBeEquivalentTo(new[]
{
HighestEventId + 1,
HighestEventId + 1,
HighestEventId + 2,
HighestEventId + 3,
HighestEventId + 4,
HighestEventId + 5
});
}
}
[Test]
public async Task A_non_running_catchup_can_be_run_by_awaiting_SingleBatchAsync()
{
Events.Write(10);
using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { })))
{
var status = await catchup.SingleBatchAsync();
Console.WriteLine(status);
status.IsEndOfBatch.Should().BeTrue();
status.BatchCount.Should().Be(10);
status.CurrentEventId.Should().Be(HighestEventId + 10);
}
}
[Test]
public async Task A_single_catchup_batch_can_be_triggered_and_awaited_using_SingleBatchAsync()
{
Events.Write(10);
using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { })))
{
var status = await catchup.SingleBatchAsync().Do(s => Console.WriteLine(s));
status.IsEndOfBatch.Should().BeTrue();
status.BatchCount.Should().Be(10);
status.CurrentEventId.Should().Be(HighestEventId + 10);
}
}
[Test]
public async Task The_current_batch_in_progress_can_be_awaited_using_SingleBatchAsync()
{
Events.Write(10);
using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e =>
{
// slow this down just enough for the batch to still be running when we await below
Thread.Sleep(1000);
})))
{
#pragma warning disable 4014
// don't await
Task.Run(() => catchup.Run());
#pragma warning restore 4014
Thread.Sleep(1000);
var status = await catchup.SingleBatchAsync();
status.IsEndOfBatch.Should().BeTrue();
status.BatchCount.Should().Be(10);
status.CurrentEventId.Should().Be(HighestEventId + 10);
}
}
[Test]
public async Task When_a_Progress_subscriber_throws_then_catchup_continues()
{
Events.Write(10);
var projectedEventCount = 0;
using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e =>
{
projectedEventCount++;
})))
{
catchup.Progress.Subscribe(e =>
{
throw new Exception("oops!");
});
await catchup.Run();
}
projectedEventCount.Should().Be(10);
}
[Test]
public async Task Two_different_projectors_can_catch_up_to_two_different_event_stores_using_separate_catchups()
{
// arrange
var projector1CallCount = 0;
var projector2CallCount = 0;
var projector1 = Projector.Create<Order.ItemAdded>(e => projector1CallCount++).Named(MethodBase.GetCurrentMethod().Name + "1");
var projector2 = Projector.Create<Order.ItemAdded>(e => projector2CallCount++).Named(MethodBase.GetCurrentMethod().Name + "2");
var startProjector2AtId = new OtherEventStoreDbContext().DisposeAfter(db => GetHighestEventId(db)) + 1;
Events.Write(5, createEventStore: () => new EventStoreDbContext());
Events.Write(5, createEventStore: () => new OtherEventStoreDbContext());
using (
var eventStoreCatchup = new ReadModelCatchup(projector1)
{
StartAtEventId = HighestEventId + 1,
Name = "eventStoreCatchup",
CreateEventStoreDbContext = () => new EventStoreDbContext()
})
using (
var otherEventStoreCatchup = new ReadModelCatchup(projector2)
{
StartAtEventId = startProjector2AtId,
Name = "otherEventStoreCatchup",
CreateEventStoreDbContext = () => new OtherEventStoreDbContext()
})
{
// act
await eventStoreCatchup.SingleBatchAsync();
await otherEventStoreCatchup.SingleBatchAsync();
}
// assert
projector1CallCount.Should().Be(5, "projector1 should get all events from event stream");
projector2CallCount.Should().Be(5, "projector2 should get all events from event stream");
}
public class Projector1 : IUpdateProjectionWhen<Order.ItemAdded>
{
public int CallCount { get; set; }
public void UpdateProjection(Order.ItemAdded @event)
{
using (var work = this.Update())
{
CallCount++;
OnUpdate(work, @event);
work.VoteCommit();
}
}
public Action<UnitOfWork<ReadModelUpdate>, Order.ItemAdded> OnUpdate = (work, e) => { };
}
public class Projector2 : IUpdateProjectionWhen<Order.ItemAdded>
{
public int CallCount { get; set; }
public void UpdateProjection(Order.ItemAdded @event)
{
using (var work = this.Update())
{
CallCount++;
OnUpdate(work, @event);
work.VoteCommit();
}
}
public Action<UnitOfWork<ReadModelUpdate>, Order.ItemAdded> OnUpdate = (work, e) => { };
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_SingleDimensionArray_ConstantIndex()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[0]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[0]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_SingleDimensionArray_NonConstantIndex()
{
string source = @"
class C
{
public void F(string[] args, int x)
{
var a = /*<bind>*/args[x]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[x]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_SingleDimensionArray_FunctionCallArrayReference()
{
string source = @"
class C
{
public void F()
{
var a = /*<bind>*/F2()[0]/*</bind>*/;
}
public string[] F2() => null;
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'F2()[0]')
Array reference:
IInvocationOperation ( System.String[] C.F2()) (OperationKind.Invocation, Type: System.String[]) (Syntax: 'F2()')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_MultiDimensionArray_ConstantIndices()
{
string source = @"
class C
{
public void F(string[,] args)
{
var a = /*<bind>*/args[0, 1]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[0, 1]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[,]) (Syntax: 'args')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_MultiDimensionArray_NonConstantIndices()
{
string source = @"
class C
{
public void F(string[,] args, int x, int y)
{
var a = /*<bind>*/args[x, y]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[x, y]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[,]) (Syntax: 'args')
Indices(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_MultiDimensionArray_InvocationInIndex()
{
string source = @"
class C
{
public void F(string[,] args)
{
int x = 0;
var a = /*<bind>*/args[x, F2()]/*</bind>*/;
}
public int F2() => 0;
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[x, F2()]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[,]) (Syntax: 'args')
Indices(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
IInvocationOperation ( System.Int32 C.F2()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F2()')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_JaggedArray_ConstantIndices()
{
string source = @"
class C
{
public void F(string[][] args)
{
var a = /*<bind>*/args[0][0]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[0][0]')
Array reference:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String[]) (Syntax: 'args[0]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[][]) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_JaggedArray_NonConstantIndices()
{
string source = @"
class C
{
public void F(string[][] args)
{
int x = 0;
var a = /*<bind>*/args[F2()][x]/*</bind>*/;
}
public int F2() => 0;
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[F2()][x]')
Array reference:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String[]) (Syntax: 'args[F2()]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[][]) (Syntax: 'args')
Indices(1):
IInvocationOperation ( System.Int32 C.F2()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F2()')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
Indices(1):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_JaggedArrayOfMultidimensionalArrays()
{
string source = @"
class C
{
public void F(string[][,] args)
{
int x = 0;
var a = /*<bind>*/args[x][0, F2()]/*</bind>*/;
}
public int F2() => 0;
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[x][0, F2()]')
Array reference:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String[,]) (Syntax: 'args[x]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[][,]) (Syntax: 'args')
Indices(1):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IInvocationOperation ( System.Int32 C.F2()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F2()')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_ImplicitConversionInIndexExpression()
{
string source = @"
class C
{
public void F(string[] args, byte b)
{
var a = /*<bind>*/args[b]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[b]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'b')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'b')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_ExplicitConversionInIndexExpression()
{
string source = @"
class C
{
public void F(string[] args, double d)
{
var a = /*<bind>*/args[(int)d]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[(int)d]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32) (Syntax: '(int)d')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'd')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_ImplicitUserDefinedConversionInIndexExpression()
{
string source = @"
class C
{
public void F(string[] args, C c)
{
var a = /*<bind>*/args[c]/*</bind>*/;
}
public static implicit operator int(C c)
{
return 0;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[c]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 C.op_Implicit(C c)) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_ExplicitUserDefinedConversionInIndexExpression()
{
string source = @"
class C
{
public void F(string[] args, C c)
{
var a = /*<bind>*/args[(int)c]/*</bind>*/;
}
public static explicit operator int(C c)
{
return 0;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[(int)c]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 C.op_Explicit(C c)) (OperationKind.Conversion, Type: System.Int32) (Syntax: '(int)c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Explicit(C c))
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReference_ExplicitUserDefinedConversionInArrayReference()
{
string source = @"
class C
{
public void F(C c, int x)
{
var a = /*<bind>*/((string[])c)[x]/*</bind>*/;
}
public static explicit operator string[](C c)
{
return null;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: '((string[])c)[x]')
Array reference:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.String[] C.op_Explicit(C c)) (OperationKind.Conversion, Type: System.String[]) (Syntax: '(string[])c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.String[] C.op_Explicit(C c))
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
Indices(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_NoConversionInIndexExpression()
{
string source = @"
class C
{
public void F(string[] args, C c)
{
var a = /*<bind>*/args[c]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[c]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[], IsInvalid) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'C' to 'int'
// var a = /*<bind>*/args[c]/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "args[c]").WithArguments("C", "int").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_MissingExplicitCastInIndexExpression()
{
string source = @"
class C
{
public void F(string[] args, C c)
{
var a = /*<bind>*/args[c]/*</bind>*/;
}
public static explicit operator int(C c)
{
return 0;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[c]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[], IsInvalid) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 C.op_Explicit(C c)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Explicit(C c))
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0266: Cannot implicitly convert type 'C' to 'int'. An explicit conversion exists (are you missing a cast?)
// var a = /*<bind>*/args[c]/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "args[c]").WithArguments("C", "int").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_NoArrayReference()
{
string source = @"
class C
{
public void F()
{
var a = /*<bind>*/[0]/*</bind>*/;
}
public string[] F2() => null;
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '[0]')
Children(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term '['
// var a = /*<bind>*/[0]/*</bind>*/;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "[").WithArguments("[").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_NoIndices()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0443: Syntax error; value expected
// var a = /*<bind>*/args[]/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(6, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_BadIndexing()
{
string source = @"
class C
{
public void F(C c)
{
var a = /*<bind>*/c[0]/*</bind>*/;
}
public string[] F2() => null;
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'c[0]')
Children(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0021: Cannot apply indexing with [] to an expression of type 'C'
// var a = /*<bind>*/c[0]/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[0]").WithArguments("C").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_BadIndexCount()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[0, 0]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[0, 0]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[], IsInvalid) (Syntax: 'args')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0022: Wrong number of indices inside []; expected 1
// var a = /*<bind>*/args[0, 0]/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadIndexCount, "args[0, 0]").WithArguments("1").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_ExtraElementAccessOperator()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[0][]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Char, IsInvalid) (Syntax: 'args[0][]')
Children(2):
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[0]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0443: Syntax error; value expected
// var a = /*<bind>*/args[0][]/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(6, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_IndexErrorExpression()
{
string source = @"
class C
{
public void F()
{
var a = /*<bind>*/ErrorExpression[0]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'ErrorExpression[0]')
Children(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'ErrorExpression')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'ErrorExpression' does not exist in the current context
// var a = /*<bind>*/ErrorExpression[0]/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "ErrorExpression").WithArguments("ErrorExpression").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_InvalidIndexerExpression()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[ErrorExpression]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[ErrorExpression]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'ErrorExpression')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'ErrorExpression')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'ErrorExpression' does not exist in the current context
// var a = /*<bind>*/args[ErrorExpression]/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "ErrorExpression").WithArguments("ErrorExpression").WithLocation(6, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_SyntaxErrorInIndexer_MissingValue()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[0,]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[0,]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0443: Syntax error; value expected
// var a = /*<bind>*/args[0,]/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(6, 34)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_SyntaxErrorInIndexer_MissingBracket()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[/*</bind>*/')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[], IsInvalid) (Syntax: 'args')
Indices(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1003: Syntax error, ']' expected
// var a = /*<bind>*/args[/*</bind>*/;
Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("]", ";").WithLocation(6, 43),
// CS0022: Wrong number of indices inside []; expected 1
// var a = /*<bind>*/args[/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadIndexCount, "args[/*</bind>*/").WithArguments("1").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_SyntaxErrorInIndexer_MissingBracketAfterIndex()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[0/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[0/*</bind>*/')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1003: Syntax error, ']' expected
// var a = /*<bind>*/args[0/*</bind>*/;
Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("]", ";").WithLocation(6, 44)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_SyntaxErrorInIndexer_DeeplyNestedParameterReference()
{
string source = @"
class C
{
public void F(string[] args, int x, int y)
{
var a = /*<bind>*/args[y][][][][x]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args[y][][][][x]')
Children(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args[y][][][]')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args[y][][]')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: System.Char, IsInvalid) (Syntax: 'args[y][]')
Children(2):
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[y]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0443: Syntax error; value expected
// var a = /*<bind>*/args[y][][][][x]/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(6, 35),
// CS0443: Syntax error; value expected
// var a = /*<bind>*/args[y][][][][x]/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(6, 37),
// CS0443: Syntax error; value expected
// var a = /*<bind>*/args[y][][][][x]/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(6, 39)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_NamedArgumentForArray()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[name: 0]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[name: 0]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[], IsInvalid) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1742: An array access may not have a named argument specifier
// var a = /*<bind>*/args[name: 0]/*</bind>*/;
Diagnostic(ErrorCode.ERR_NamedArgumentForArray, "args[name: 0]").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceError_RefAndOutArguments()
{
string source = @"
class C
{
public void F(string[,] args, ref int x, out int y)
{
var a = /*<bind>*/args[ref x, out y]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args[ref x, out y]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[,]) (Syntax: 'args')
Indices(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1615: Argument 1 may not be passed with the 'ref' keyword
// var a = /*<bind>*/args[ref x, out y]/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "ref").WithLocation(6, 36),
// CS0269: Use of unassigned out parameter 'y'
// var a = /*<bind>*/args[ref x, out y]/*</bind>*/;
Diagnostic(ErrorCode.ERR_UseDefViolationOut, "y").WithArguments("y").WithLocation(6, 43),
// CS0177: The out parameter 'y' must be assigned to before control leaves the current method
// public void F(string[,] args, ref int x, out int y)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "F").WithArguments("y").WithLocation(4, 17)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")]
public void ArrayElementReferenceWarning_NegativeIndexExpression()
{
string source = @"
class C
{
public void F(string[] args)
{
var a = /*<bind>*/args[-1]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args[-1]')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args')
Indices(1):
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.UnaryOperator, Type: System.Int32, Constant: -1) (Syntax: '-1')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0251: Indexing an array with a negative index (array indices always start at zero)
// var a = /*<bind>*/args[-1]/*</bind>*/;
Diagnostic(ErrorCode.WRN_NegativeArrayIndex, "-1").WithLocation(6, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
| |
// 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.Globalization;
using System.Reflection;
using NUnit.Framework;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine;
namespace Microsoft.Build.UnitTests
{
[TestFixture]
public class ParserTest
{
/// <summary>
/// </summary>
/// <owner>DavidLe</owner>
[Test]
public void SimpleParseTest()
{
Console.WriteLine("SimpleParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
tree = p.Parse("$(foo)", null, ParserOptions.AllowAll);
tree = p.Parse("$(foo)=='hello'", null, ParserOptions.AllowAll);
tree = p.Parse("$(foo)==''", null, ParserOptions.AllowAll);
tree = p.Parse("$(debug) and $(buildlab) and $(full)", null, ParserOptions.AllowAll);
tree = p.Parse("$(debug) or $(buildlab) or $(full)", null, ParserOptions.AllowAll);
tree = p.Parse("$(debug) and $(buildlab) or $(full)", null, ParserOptions.AllowAll);
tree = p.Parse("$(full) or $(debug) and $(buildlab)", null, ParserOptions.AllowAll);
tree = p.Parse("%(culture)", null, ParserOptions.AllowAll);
tree = p.Parse("%(culture)=='french'", null, ParserOptions.AllowAll);
tree = p.Parse("'foo_%(culture)'=='foo_french'", null, ParserOptions.AllowAll);
tree = p.Parse("true", null, ParserOptions.AllowAll);
tree = p.Parse("false", null, ParserOptions.AllowAll);
tree = p.Parse("0", null, ParserOptions.AllowAll);
tree = p.Parse("0.0 == 0", null, ParserOptions.AllowAll);
}
/// <summary>
/// </summary>
/// <owner>DavidLe</owner>
[Test]
public void ComplexParseTest()
{
Console.WriteLine("ComplexParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
tree = p.Parse("$(foo)", null, ParserOptions.AllowAll);
tree = p.Parse("($(foo) or $(bar)) and $(baz)", null, ParserOptions.AllowAll);
tree = p.Parse("$(foo) <= 5 and $(bar) >= 15", null, ParserOptions.AllowAll);
tree = p.Parse("(($(foo) <= 5 and $(bar) >= 15) and $(baz) == simplestring) and 'a more complex string' != $(quux)", null, ParserOptions.AllowAll);
tree = p.Parse("(($(foo) or $(bar) == false) and !($(baz) == simplestring))", null, ParserOptions.AllowAll);
tree = p.Parse("(($(foo) or Exists('c:\\foobar.txt')) and !(($(baz) == simplestring)))", null, ParserOptions.AllowAll);
tree = p.Parse("'CONTAINS%27QUOTE%27' == '$(TestQuote)'", null, ParserOptions.AllowAll);
}
/// <summary>
/// </summary>
/// <owner>DavidLe</owner>
[Test]
public void NotParseTest()
{
Console.WriteLine("NegationParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
tree = p.Parse("!true", null, ParserOptions.AllowAll);
tree = p.Parse("!(true)", null, ParserOptions.AllowAll);
tree = p.Parse("!($(foo) <= 5)", null, ParserOptions.AllowAll);
tree = p.Parse("!(%(foo) <= 5)", null, ParserOptions.AllowAll);
tree = p.Parse("!($(foo) <= 5 and $(bar) >= 15)", null, ParserOptions.AllowAll);
}
/// <summary>
/// </summary>
/// <owner>DavidLe</owner>
[Test]
public void FunctionCallParseTest()
{
Console.WriteLine("FunctionCallParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
tree = p.Parse("SimpleFunctionCall()", null, ParserOptions.AllowAll);
tree = p.Parse("SimpleFunctionCall( 1234 )", null, ParserOptions.AllowAll);
tree = p.Parse("SimpleFunctionCall( true )", null, ParserOptions.AllowAll);
tree = p.Parse("SimpleFunctionCall( $(property) )", null, ParserOptions.AllowAll);
tree = p.Parse("SimpleFunctionCall( $(property), 1234, abcd, 'abcd efgh' )", null, ParserOptions.AllowAll);
}
/// <owner>DavidLe</owner>
[Test]
public void ItemListParseTest()
{
Console.WriteLine("FunctionCallParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
bool fExceptionCaught;
fExceptionCaught = false;
try
{
tree = p.Parse("@(foo) == 'a.cs;b.cs'", null, ParserOptions.AllowProperties);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'a.cs;b.cs' == @(foo)", null, ParserOptions.AllowProperties);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'@(foo)' == 'a.cs;b.cs'", null, ParserOptions.AllowProperties);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'otherstuff@(foo)' == 'a.cs;b.cs'", null, ParserOptions.AllowProperties);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'@(foo)otherstuff' == 'a.cs;b.cs'", null, ParserOptions.AllowProperties);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("somefunction(@(foo), 'otherstuff')", null, ParserOptions.AllowProperties);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
}
/// <owner>RGoel</owner>
[Test]
public void MetadataParseTest()
{
Console.WriteLine("FunctionCallParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
bool fExceptionCaught;
fExceptionCaught = false;
try
{
tree = p.Parse("%(foo) == 'a.cs;b.cs'", null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'a.cs;b.cs' == %(foo)", null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'%(foo)' == 'a.cs;b.cs'", null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'otherstuff%(foo)' == 'a.cs;b.cs'", null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'%(foo)otherstuff' == 'a.cs;b.cs'", null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("somefunction(%(foo), 'otherstuff')", null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
}
/// <summary>
/// </summary>
/// <owner>DavidLe</owner>
[Test]
public void NegativeTests()
{
Console.WriteLine("NegativeTests()");
Parser p = new Parser();
GenericExpressionNode tree;
bool fExceptionCaught;
try
{
fExceptionCaught = false;
// Note no close quote ----------------------------------------------------V
tree = p.Parse("'a more complex' == 'asdf", null, ParserOptions.AllowAll);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
try
{
fExceptionCaught = false;
// Note no close quote ----------------------------------------------------V
tree = p.Parse("(($(foo) <= 5 and $(bar) >= 15) and $(baz) == 'simple string) and 'a more complex string' != $(quux)", null, ParserOptions.AllowAll);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("($(foo) == 'simple string') $(bar)", null, ParserOptions.AllowAll);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("=='x'", null, ParserOptions.AllowAll);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("==", null, ParserOptions.AllowAll);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse(">", null, ParserOptions.AllowAll);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("true!=false==", null, ParserOptions.AllowAll);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("true!=false==true", null, ParserOptions.AllowAll);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("1==(2", null, ParserOptions.AllowAll);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
}
/// <summary>
/// This test verifies that we trigger warnings for expressions that
/// could be incorrectly evaluated
/// </summary>
/// <owner>VladF</owner>
[Test]
public void VerifyWarningForOrder()
{
// Create a project file that has an expression
MockLogger ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@"
<Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`$(a) == 1 and $(b) == 2 or $(c) == 3`/>
</Target>
</Project>
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));
// Make sure the log contains the correct strings.
Assertion.Assert("Need to warn for this expression - (a) == 1 and $(b) == 2 or $(c) == 3.",
ml.FullLog.Contains("MSB4130:"));
ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@"
<Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`$(a) == 1 or $(b) == 2 and $(c) == 3`/>
</Target>
</Project>
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));
// Make sure the log contains the correct strings.
Assertion.Assert("Need to warn for this expression - (a) == 1 or $(b) == 2 and $(c) == 3.",
ml.FullLog.Contains("MSB4130:"));
ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@"
<Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`($(a) == 1 or $(b) == 2 and $(c) == 3) or $(d) == 4`/>
</Target>
</Project>
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));
// Make sure the log contains the correct strings.
Assertion.Assert("Need to warn for this expression - ($(a) == 1 or $(b) == 2 and $(c) == 3) or $(d) == 4.",
ml.FullLog.Contains("MSB4130:"));
}
/// <summary>
/// This test verifies that we don't trigger warnings for expressions that
/// couldn't be incorrectly evaluated
/// </summary>
/// <owner>VladF</owner>
[Test]
public void VerifyNoWarningForOrder()
{
// Create a project file that has an expression
MockLogger ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@"
<Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`$(a) == 1 and $(b) == 2 and $(c) == 3`/>
</Target>
</Project>
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));
// Make sure the log contains the correct strings.
Assertion.Assert("No need to warn for this expression - (a) == 1 and $(b) == 2 and $(c) == 3.",
!ml.FullLog.Contains("MSB4130:"));
ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@"
<Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`$(a) == 1 or $(b) == 2 or $(c) == 3`/>
</Target>
</Project>
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));
// Make sure the log contains the correct strings.
Assertion.Assert("No need to warn for this expression - (a) == 1 or $(b) == 2 or $(c) == 3.",
!ml.FullLog.Contains("MSB4130:"));
ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@"
<Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`($(a) == 1 and $(b) == 2) or $(c) == 3`/>
</Target>
</Project>
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));
// Make sure the log contains the correct strings.
Assertion.Assert("No need to warn for this expression - ($(a) == 1 and $(b) == 2) or $(c) == 3.",
!ml.FullLog.Contains("MSB4130:"));
ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@"
<Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`($(a) == 1 or $(b) == 2) and $(c) == 3`/>
</Target>
</Project>
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));
// Make sure the log contains the correct strings.
Assertion.Assert("No need to warn for this expression - ($(a) == 1 or $(b) == 2) and $(c) == 3.",
!ml.FullLog.Contains("MSB4130:"));
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Nodes
{
/// <summary>
///
/// </summary>
[DataNode("Solution")]
[DataNode("EmbeddedSolution")]
[DebuggerDisplay("{Name}")]
public class SolutionNode : DataNode
{
#region Fields
private Guid m_Guid = Guid.NewGuid();
private string m_Name = "unknown";
private string m_Path = "";
private string m_FullPath = "";
private string m_ActiveConfig;
private string m_Version = "1.0.0";
private OptionsNode m_Options;
private FilesNode m_Files;
private readonly ConfigurationNodeCollection m_Configurations = new ConfigurationNodeCollection();
private readonly Dictionary<string, ProjectNode> m_Projects = new Dictionary<string, ProjectNode>();
private readonly Dictionary<string, DatabaseProjectNode> m_DatabaseProjects = new Dictionary<string, DatabaseProjectNode>();
private readonly List<ProjectNode> m_ProjectsOrder = new List<ProjectNode>();
private readonly Dictionary<string, SolutionNode> m_Solutions = new Dictionary<string, SolutionNode>();
private CleanupNode m_Cleanup;
#endregion
#region Properties
public override IDataNode Parent
{
get
{
return base.Parent;
}
set
{
if (value is SolutionNode)
{
SolutionNode solution = (SolutionNode)value;
foreach (ConfigurationNode conf in solution.Configurations)
{
m_Configurations[conf.Name] = (ConfigurationNode) conf.Clone();
}
}
base.Parent = value;
}
}
public CleanupNode Cleanup
{
get
{
return m_Cleanup;
}
set
{
m_Cleanup = value;
}
}
public Guid Guid
{
get
{
return m_Guid;
}
set
{
m_Guid = value;
}
}
/// <summary>
/// Gets or sets the active config.
/// </summary>
/// <value>The active config.</value>
public string ActiveConfig
{
get
{
return m_ActiveConfig;
}
set
{
m_ActiveConfig = value;
}
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return m_Name;
}
}
/// <summary>
/// Gets the path.
/// </summary>
/// <value>The path.</value>
public string Path
{
get
{
return m_Path;
}
}
/// <summary>
/// Gets the full path.
/// </summary>
/// <value>The full path.</value>
public string FullPath
{
get
{
return m_FullPath;
}
}
/// <summary>
/// Gets the version.
/// </summary>
/// <value>The version.</value>
public string Version
{
get
{
return m_Version;
}
}
/// <summary>
/// Gets the options.
/// </summary>
/// <value>The options.</value>
public OptionsNode Options
{
get
{
return m_Options;
}
}
/// <summary>
/// Gets the files.
/// </summary>
/// <value>The files.</value>
public FilesNode Files
{
get
{
return m_Files;
}
}
/// <summary>
/// Gets the configurations.
/// </summary>
/// <value>The configurations.</value>
public ConfigurationNodeCollection Configurations
{
get
{
ConfigurationNodeCollection tmp = new ConfigurationNodeCollection();
tmp.AddRange(ConfigurationsTable);
return tmp;
}
}
/// <summary>
/// Gets the configurations table.
/// </summary>
/// <value>The configurations table.</value>
public ConfigurationNodeCollection ConfigurationsTable
{
get
{
return m_Configurations;
}
}
/// <summary>
/// Gets the database projects.
/// </summary>
public ICollection<DatabaseProjectNode> DatabaseProjects
{
get
{
return m_DatabaseProjects.Values;
}
}
/// <summary>
/// Gets the nested solutions.
/// </summary>
public ICollection<SolutionNode> Solutions
{
get
{
return m_Solutions.Values;
}
}
/// <summary>
/// Gets the nested solutions hash table.
/// </summary>
public Dictionary<string, SolutionNode> SolutionsTable
{
get
{
return m_Solutions;
}
}
/// <summary>
/// Gets the projects.
/// </summary>
/// <value>The projects.</value>
public ICollection<ProjectNode> Projects
{
get
{
List<ProjectNode> tmp = new List<ProjectNode>(m_Projects.Values);
tmp.Sort();
return tmp;
}
}
/// <summary>
/// Gets the projects table.
/// </summary>
/// <value>The projects table.</value>
public Dictionary<string, ProjectNode> ProjectsTable
{
get
{
return m_Projects;
}
}
/// <summary>
/// Gets the projects table.
/// </summary>
/// <value>The projects table.</value>
public List<ProjectNode> ProjectsTableOrder
{
get
{
return m_ProjectsOrder;
}
}
#endregion
#region Public Methods
/// <summary>
/// Parses the specified node.
/// </summary>
/// <param name="node">The node.</param>
public override void Parse(XmlNode node)
{
m_Name = Helper.AttributeValue(node, "name", m_Name);
m_ActiveConfig = Helper.AttributeValue(node, "activeConfig", m_ActiveConfig);
m_Path = Helper.AttributeValue(node, "path", m_Path);
m_Version = Helper.AttributeValue(node, "version", m_Version);
m_FullPath = m_Path;
try
{
m_FullPath = Helper.ResolvePath(m_FullPath);
}
catch
{
throw new WarningException("Could not resolve solution path: {0}", m_Path);
}
Kernel.Instance.CurrentWorkingDirectory.Push();
try
{
Helper.SetCurrentDir(m_FullPath);
if( node == null )
{
throw new ArgumentNullException("node");
}
foreach(XmlNode child in node.ChildNodes)
{
IDataNode dataNode = Kernel.Instance.ParseNode(child, this);
if(dataNode is OptionsNode)
{
m_Options = (OptionsNode)dataNode;
}
else if(dataNode is FilesNode)
{
m_Files = (FilesNode)dataNode;
}
else if(dataNode is ConfigurationNode)
{
ConfigurationNode configurationNode = (ConfigurationNode) dataNode;
m_Configurations[configurationNode.NameAndPlatform] = configurationNode;
// If the active configuration is null, then we populate it.
if (ActiveConfig == null)
{
ActiveConfig = configurationNode.Name;
}
}
else if(dataNode is ProjectNode)
{
m_Projects[((ProjectNode)dataNode).Name] = (ProjectNode) dataNode;
m_ProjectsOrder.Add((ProjectNode)dataNode);
}
else if(dataNode is SolutionNode)
{
m_Solutions[((SolutionNode)dataNode).Name] = (SolutionNode) dataNode;
}
else if (dataNode is ProcessNode)
{
ProcessNode p = (ProcessNode)dataNode;
Kernel.Instance.ProcessFile(p, this);
}
else if (dataNode is DatabaseProjectNode)
{
m_DatabaseProjects[((DatabaseProjectNode)dataNode).Name] = (DatabaseProjectNode) dataNode;
}
else if(dataNode is CleanupNode)
{
if(m_Cleanup != null)
throw new WarningException("There can only be one Cleanup node.");
m_Cleanup = (CleanupNode)dataNode;
}
}
}
finally
{
Kernel.Instance.CurrentWorkingDirectory.Pop();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QuantConnect.Data.Market;
using QuantConnect.Data.Auxiliary;
namespace QuantConnect.ToolBox.RandomDataGenerator
{
/// <summary>
/// Generates random splits, random dividends, and map file
/// </summary>
public class DividendSplitMapGenerator
{
/// <summary>
/// The final factor to adjust all prices with in order to maintain price continuity.
/// </summary>
/// <remarks>
/// Set default equal to 1 so that we can use it even in the event of no splits
/// </remarks>
public decimal FinalSplitFactor = 1m;
/// <summary>
/// Stores <see cref="MapFileRow"/> instances
/// </summary>
public List<MapFileRow> MapRows = new();
/// <summary>
/// Stores <see cref="CorporateFactorRow"/> instances
/// </summary>
public List<CorporateFactorRow> DividendsSplits = new List<CorporateFactorRow>();
/// <summary>
/// Current Symbol value. Can be renamed
/// </summary>
public Symbol CurrentSymbol { get; private set; }
private readonly RandomValueGenerator _randomValueGenerator;
private readonly Random _random;
private readonly RandomDataGeneratorSettings _settings;
private readonly DateTime _delistDate;
private readonly bool _willBeDelisted;
private readonly BaseSymbolGenerator _symbolGenerator;
public DividendSplitMapGenerator(
Symbol symbol,
RandomDataGeneratorSettings settings,
RandomValueGenerator randomValueGenerator,
BaseSymbolGenerator symbolGenerator,
Random random,
DateTime delistDate,
bool willBeDelisted)
{
CurrentSymbol = symbol;
_settings = settings;
_randomValueGenerator = randomValueGenerator;
_random = random;
_delistDate = delistDate;
_willBeDelisted = willBeDelisted;
_symbolGenerator = symbolGenerator;
}
/// <summary>
/// Generates the splits, dividends, and maps.
/// Writes necessary output to public variables
/// </summary>
/// <param name="tickHistory"></param>
public void GenerateSplitsDividends(IEnumerable<Tick> tickHistory)
{
var previousMonth = -1;
var monthsTrading = 0;
var hasRename = _randomValueGenerator.NextBool(_settings.HasRenamePercentage);
var hasSplits = _randomValueGenerator.NextBool(_settings.HasSplitsPercentage);
var hasDividends = _randomValueGenerator.NextBool(_settings.HasDividendsPercentage);
var dividendEveryQuarter = _randomValueGenerator.NextBool(_settings.DividendEveryQuarterPercentage);
var previousX = _random.NextDouble();
var previousSplitFactor = hasSplits ? (decimal)_random.NextDouble() : 1;
var previousPriceFactor = hasDividends ? (decimal)Math.Tanh(previousX) : 1;
var splitDates = new List<DateTime>();
var dividendDates = new List<DateTime>();
var firstTick = true;
// Iterate through all ticks and generate splits and dividend data
if (_settings.SecurityType == SecurityType.Equity)
{
foreach (var tick in tickHistory)
{
// On the first trading day write relevant starting data to factor and map files
if (firstTick)
{
DividendsSplits.Add(new CorporateFactorRow(tick.Time,
previousPriceFactor,
previousSplitFactor,
tick.Value));
MapRows.Add(new MapFileRow(tick.Time, CurrentSymbol.Value));
}
// Add the split to the DividendsSplits list if we have a pending
// split. That way, we can use the correct referencePrice in the split event.
if (splitDates.Count != 0)
{
var deleteDates = new List<DateTime>();
foreach (var splitDate in splitDates)
{
if (tick.Time > splitDate)
{
DividendsSplits.Add(new CorporateFactorRow(
splitDate,
previousPriceFactor,
previousSplitFactor,
tick.Value / FinalSplitFactor));
FinalSplitFactor *= previousSplitFactor;
deleteDates.Add(splitDate);
}
}
// Deletes dates we've already looped over
splitDates.RemoveAll(x => deleteDates.Contains(x));
}
if (dividendDates.Count != 0)
{
var deleteDates = new List<DateTime>();
foreach (var dividendDate in dividendDates)
{
if (tick.Time > dividendDate)
{
DividendsSplits.Add(new CorporateFactorRow(
dividendDate,
previousPriceFactor,
previousSplitFactor,
tick.Value / FinalSplitFactor));
deleteDates.Add(dividendDate);
}
}
dividendDates.RemoveAll(x => deleteDates.Contains(x));
}
if (tick.Time.Month != previousMonth)
{
// Every quarter, try to generate dividend events
if (hasDividends && (tick.Time.Month - 1) % 3 == 0)
{
// Make it so there's a 10% chance that dividends occur if there is no dividend every quarter
if (dividendEveryQuarter || _randomValueGenerator.NextBool(10.0))
{
do
{
previousX += _random.NextDouble() / 10;
previousPriceFactor = (decimal)Math.Tanh(previousX);
} while (previousPriceFactor >= 1.0m || previousPriceFactor <= 0m);
dividendDates.Add(_randomValueGenerator.NextDate(tick.Time, tick.Time.AddMonths(1), (DayOfWeek)_random.Next(1, 5)));
}
}
// Have a 5% chance of a split every month
if (hasSplits && _randomValueGenerator.NextBool(5.0))
{
do
{
if (previousSplitFactor < 1)
{
previousSplitFactor += (decimal)(_random.NextDouble() - _random.NextDouble());
}
else
{
previousSplitFactor *= (decimal)_random.NextDouble() * _random.Next(1, 5);
}
} while (previousSplitFactor < 0);
splitDates.Add(_randomValueGenerator.NextDate(tick.Time, tick.Time.AddMonths(1), (DayOfWeek)_random.Next(1, 5)));
}
// 10% chance of being renamed every month
if (hasRename && _randomValueGenerator.NextBool(10.0))
{
var randomDate = _randomValueGenerator.NextDate(tick.Time, tick.Time.AddMonths(1), (DayOfWeek)_random.Next(1, 5));
MapRows.Add(new MapFileRow(randomDate, CurrentSymbol.Value));
CurrentSymbol = _symbolGenerator.NextSymbol(_settings.SecurityType, _settings.Market);
}
previousMonth = tick.Time.Month;
monthsTrading++;
}
if (monthsTrading >= 6 && _willBeDelisted && tick.Time > _delistDate)
{
MapRows.Add(new MapFileRow(tick.Time, CurrentSymbol.Value));
break;
}
firstTick = false;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions.Compiler
{
internal partial class LambdaCompiler
{
private void EmitBinaryExpression(Expression expr)
{
EmitBinaryExpression(expr, CompilationFlags.EmitAsNoTail);
}
private void EmitBinaryExpression(Expression expr, CompilationFlags flags)
{
BinaryExpression b = (BinaryExpression)expr;
Debug.Assert(b.NodeType != ExpressionType.AndAlso && b.NodeType != ExpressionType.OrElse && b.NodeType != ExpressionType.Coalesce);
if (b.Method != null)
{
EmitBinaryMethod(b, flags);
return;
}
// For EQ and NE, if there is a user-specified method, use it.
// Otherwise implement the C# semantics that allow equality
// comparisons on non-primitive nullable structs that don't
// overload "=="
if ((b.NodeType == ExpressionType.Equal || b.NodeType == ExpressionType.NotEqual) &&
(b.Type == typeof(bool) || b.Type == typeof(bool?)))
{
// If we have x==null, x!=null, null==x or null!=x where x is
// nullable but not null, then generate a call to x.HasValue.
Debug.Assert(!b.IsLiftedToNull || b.Type == typeof(bool?));
if (ConstantCheck.IsNull(b.Left) && !ConstantCheck.IsNull(b.Right) && b.Right.Type.IsNullableType())
{
EmitNullEquality(b.NodeType, b.Right, b.IsLiftedToNull);
return;
}
if (ConstantCheck.IsNull(b.Right) && !ConstantCheck.IsNull(b.Left) && b.Left.Type.IsNullableType())
{
EmitNullEquality(b.NodeType, b.Left, b.IsLiftedToNull);
return;
}
// For EQ and NE, we can avoid some conversions if we're
// ultimately just comparing two managed pointers.
EmitExpression(GetEqualityOperand(b.Left));
EmitExpression(GetEqualityOperand(b.Right));
}
else
{
// Otherwise generate it normally
EmitExpression(b.Left);
EmitExpression(b.Right);
}
EmitBinaryOperator(b.NodeType, b.Left.Type, b.Right.Type, b.Type, b.IsLiftedToNull);
}
private void EmitNullEquality(ExpressionType op, Expression e, bool isLiftedToNull)
{
Debug.Assert(e.Type.IsNullableType());
Debug.Assert(op == ExpressionType.Equal || op == ExpressionType.NotEqual);
// If we are lifted to null then just evaluate the expression for its side effects, discard,
// and generate null. If we are not lifted to null then generate a call to HasValue.
if (isLiftedToNull)
{
EmitExpressionAsVoid(e);
_ilg.EmitDefault(typeof(bool?), this);
}
else
{
EmitAddress(e, e.Type);
_ilg.EmitHasValue(e.Type);
if (op == ExpressionType.Equal)
{
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
}
}
}
private void EmitBinaryMethod(BinaryExpression b, CompilationFlags flags)
{
if (b.IsLifted)
{
ParameterExpression p1 = Expression.Variable(b.Left.Type.GetNonNullableType(), name: null);
ParameterExpression p2 = Expression.Variable(b.Right.Type.GetNonNullableType(), name: null);
MethodCallExpression mc = Expression.Call(null, b.Method, p1, p2);
Type resultType;
if (b.IsLiftedToNull)
{
resultType = mc.Type.GetNullableType();
}
else
{
switch (b.NodeType)
{
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
if (mc.Type != typeof(bool))
{
throw Error.ArgumentMustBeBoolean(nameof(b));
}
resultType = typeof(bool);
break;
default:
resultType = mc.Type.GetNullableType();
break;
}
}
var variables = new ParameterExpression[] { p1, p2 };
var arguments = new Expression[] { b.Left, b.Right };
ValidateLift(variables, arguments);
EmitLift(b.NodeType, resultType, mc, variables, arguments);
}
else
{
EmitMethodCallExpression(Expression.Call(null, b.Method, b.Left, b.Right), flags);
}
}
private void EmitBinaryOperator(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull)
{
Debug.Assert(op != ExpressionType.Coalesce);
if (op == ExpressionType.ArrayIndex)
{
Debug.Assert(rightType == typeof(int));
EmitGetArrayElement(leftType);
}
else if (leftType.IsNullableType() || rightType.IsNullableType())
{
EmitLiftedBinaryOp(op, leftType, rightType, resultType, liftedToNull);
}
else
{
EmitUnliftedBinaryOp(op, leftType, rightType);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void EmitUnliftedBinaryOp(ExpressionType op, Type leftType, Type rightType)
{
Debug.Assert(!leftType.IsNullableType());
Debug.Assert(!rightType.IsNullableType());
if (op == ExpressionType.Equal || op == ExpressionType.NotEqual)
{
EmitUnliftedEquality(op, leftType);
return;
}
Debug.Assert(leftType.IsPrimitive);
switch (op)
{
case ExpressionType.Add:
_ilg.Emit(OpCodes.Add);
break;
case ExpressionType.AddChecked:
if (leftType.IsFloatingPoint())
{
_ilg.Emit(OpCodes.Add);
}
else if (leftType.IsUnsigned())
{
_ilg.Emit(OpCodes.Add_Ovf_Un);
}
else
{
_ilg.Emit(OpCodes.Add_Ovf);
}
break;
case ExpressionType.Subtract:
_ilg.Emit(OpCodes.Sub);
break;
case ExpressionType.SubtractChecked:
if (leftType.IsFloatingPoint())
{
_ilg.Emit(OpCodes.Sub);
}
else if (leftType.IsUnsigned())
{
_ilg.Emit(OpCodes.Sub_Ovf_Un);
// Guaranteed to fit within result type: no conversion
return;
}
else
{
_ilg.Emit(OpCodes.Sub_Ovf);
}
break;
case ExpressionType.Multiply:
_ilg.Emit(OpCodes.Mul);
break;
case ExpressionType.MultiplyChecked:
if (leftType.IsFloatingPoint())
{
_ilg.Emit(OpCodes.Mul);
}
else if (leftType.IsUnsigned())
{
_ilg.Emit(OpCodes.Mul_Ovf_Un);
}
else
{
_ilg.Emit(OpCodes.Mul_Ovf);
}
break;
case ExpressionType.Divide:
_ilg.Emit(leftType.IsUnsigned() ? OpCodes.Div_Un : OpCodes.Div);
break;
case ExpressionType.Modulo:
_ilg.Emit(leftType.IsUnsigned() ? OpCodes.Rem_Un : OpCodes.Rem);
// Guaranteed to fit within result type: no conversion
return;
case ExpressionType.And:
case ExpressionType.AndAlso:
_ilg.Emit(OpCodes.And);
// Not an arithmetic operation: no conversion
return;
case ExpressionType.Or:
case ExpressionType.OrElse:
_ilg.Emit(OpCodes.Or);
// Not an arithmetic operation: no conversion
return;
case ExpressionType.LessThan:
_ilg.Emit(leftType.IsUnsigned() ? OpCodes.Clt_Un : OpCodes.Clt);
// Not an arithmetic operation: no conversion
return;
case ExpressionType.LessThanOrEqual:
_ilg.Emit(leftType.IsUnsigned() || leftType.IsFloatingPoint() ? OpCodes.Cgt_Un : OpCodes.Cgt);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
// Not an arithmetic operation: no conversion
return;
case ExpressionType.GreaterThan:
_ilg.Emit(leftType.IsUnsigned() ? OpCodes.Cgt_Un : OpCodes.Cgt);
// Not an arithmetic operation: no conversion
return;
case ExpressionType.GreaterThanOrEqual:
_ilg.Emit(leftType.IsUnsigned() || leftType.IsFloatingPoint() ? OpCodes.Clt_Un : OpCodes.Clt);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
// Not an arithmetic operation: no conversion
return;
case ExpressionType.ExclusiveOr:
_ilg.Emit(OpCodes.Xor);
// Not an arithmetic operation: no conversion
return;
case ExpressionType.LeftShift:
Debug.Assert(rightType == typeof(int));
EmitShiftMask(leftType);
_ilg.Emit(OpCodes.Shl);
break;
case ExpressionType.RightShift:
Debug.Assert(rightType == typeof(int));
EmitShiftMask(leftType);
_ilg.Emit(leftType.IsUnsigned() ? OpCodes.Shr_Un : OpCodes.Shr);
// Guaranteed to fit within result type: no conversion
return;
default:
throw ContractUtils.Unreachable;
}
EmitConvertArithmeticResult(op, leftType);
}
// Shift operations have undefined behavior if the shift amount exceeds
// the number of bits in the value operand. See CLI III.3.58 and C# 7.9
// for the bit mask used below.
private void EmitShiftMask(Type leftType)
{
int mask = leftType.IsInteger64() ? 0x3F : 0x1F;
_ilg.EmitPrimitive(mask);
_ilg.Emit(OpCodes.And);
}
// Binary/unary operations on 8 and 16 bit operand types will leave a
// 32-bit value on the stack, because that's how IL works. For these
// cases, we need to cast it back to the resultType, possibly using a
// checked conversion if the original operator was convert
private void EmitConvertArithmeticResult(ExpressionType op, Type resultType)
{
Debug.Assert(!resultType.IsNullableType());
switch (resultType.GetTypeCode())
{
case TypeCode.Byte:
_ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_U1 : OpCodes.Conv_U1);
break;
case TypeCode.SByte:
_ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_I1 : OpCodes.Conv_I1);
break;
case TypeCode.UInt16:
_ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_U2 : OpCodes.Conv_U2);
break;
case TypeCode.Int16:
_ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_I2 : OpCodes.Conv_I2);
break;
}
}
private void EmitUnliftedEquality(ExpressionType op, Type type)
{
Debug.Assert(op == ExpressionType.Equal || op == ExpressionType.NotEqual);
Debug.Assert(type.IsPrimitive || !type.IsValueType || type.IsEnum);
_ilg.Emit(OpCodes.Ceq);
if (op == ExpressionType.NotEqual)
{
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void EmitLiftedBinaryOp(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull)
{
Debug.Assert(leftType.IsNullableType() || rightType.IsNullableType());
switch (op)
{
case ExpressionType.And:
if (leftType == typeof(bool?))
{
EmitLiftedBooleanAnd();
}
else
{
EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType);
}
break;
case ExpressionType.Or:
if (leftType == typeof(bool?))
{
EmitLiftedBooleanOr();
}
else
{
EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType);
}
break;
case ExpressionType.ExclusiveOr:
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.LeftShift:
case ExpressionType.RightShift:
EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType);
break;
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
Debug.Assert(leftType == rightType);
if (liftedToNull)
{
Debug.Assert(resultType == typeof(bool?));
EmitLiftedToNullRelational(op, leftType);
}
else
{
Debug.Assert(resultType == typeof(bool));
EmitLiftedRelational(op, leftType);
}
break;
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
default:
throw ContractUtils.Unreachable;
}
}
private void EmitLiftedRelational(ExpressionType op, Type type)
{
// Equal is (left.GetValueOrDefault() == right.GetValueOrDefault()) & (left.HasValue == right.HasValue)
// NotEqual is !((left.GetValueOrDefault() == right.GetValueOrDefault()) & (left.HasValue == right.HasValue))
// Others are (left.GetValueOrDefault() op right.GetValueOrDefault()) & (left.HasValue & right.HasValue)
bool invert = op == ExpressionType.NotEqual;
if (invert)
{
op = ExpressionType.Equal;
}
LocalBuilder locLeft = GetLocal(type);
LocalBuilder locRight = GetLocal(type);
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitGetValueOrDefault(type);
Type unnullable = type.GetNonNullableType();
EmitUnliftedBinaryOp(op, unnullable, unnullable);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(type);
FreeLocal(locLeft);
FreeLocal(locRight);
_ilg.Emit(op == ExpressionType.Equal ? OpCodes.Ceq : OpCodes.And);
_ilg.Emit(OpCodes.And);
if (invert)
{
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
}
}
private void EmitLiftedToNullRelational(ExpressionType op, Type type)
{
// (left.HasValue & right.HasValue) ? left.GetValueOrDefault() op right.GetValueOrDefault() : default(bool?)
Label notNull = _ilg.DefineLabel();
Label end = _ilg.DefineLabel();
LocalBuilder locLeft = GetLocal(type);
LocalBuilder locRight = GetLocal(type);
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.And);
_ilg.Emit(OpCodes.Brtrue_S, notNull);
_ilg.EmitDefault(typeof(bool?), this);
_ilg.Emit(OpCodes.Br_S, end);
_ilg.MarkLabel(notNull);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitGetValueOrDefault(type);
FreeLocal(locLeft);
FreeLocal(locRight);
Type unnullable = type.GetNonNullableType();
EmitUnliftedBinaryOp(op, unnullable, unnullable);
_ilg.Emit(OpCodes.Newobj, Nullable_Boolean_Ctor);
_ilg.MarkLabel(end);
}
private void EmitLiftedBinaryArithmetic(ExpressionType op, Type leftType, Type rightType, Type resultType)
{
bool leftIsNullable = leftType.IsNullableType();
bool rightIsNullable = rightType.IsNullableType();
Debug.Assert(leftIsNullable || rightIsNullable);
Label labIfNull = _ilg.DefineLabel();
Label labEnd = _ilg.DefineLabel();
LocalBuilder locLeft = GetLocal(leftType);
LocalBuilder locRight = GetLocal(rightType);
LocalBuilder locResult = GetLocal(resultType);
// store values (reverse order since they are already on the stack)
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Stloc, locLeft);
// test for null
// don't use short circuiting
if (leftIsNullable)
{
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(leftType);
}
if (rightIsNullable)
{
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(rightType);
if (leftIsNullable)
{
_ilg.Emit(OpCodes.And);
}
}
_ilg.Emit(OpCodes.Brfalse_S, labIfNull);
// do op on values
if (leftIsNullable)
{
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(leftType);
}
else
{
_ilg.Emit(OpCodes.Ldloc, locLeft);
}
if (rightIsNullable)
{
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitGetValueOrDefault(rightType);
}
else
{
_ilg.Emit(OpCodes.Ldloc, locRight);
}
//RELEASING locLeft locRight
FreeLocal(locLeft);
FreeLocal(locRight);
EmitBinaryOperator(op, leftType.GetNonNullableType(), rightType.GetNonNullableType(), resultType.GetNonNullableType(), liftedToNull: false);
// construct result type
ConstructorInfo ci = resultType.GetConstructor(new Type[] { resultType.GetNonNullableType() });
_ilg.Emit(OpCodes.Newobj, ci);
_ilg.Emit(OpCodes.Stloc, locResult);
_ilg.Emit(OpCodes.Br_S, labEnd);
// if null then create a default one
_ilg.MarkLabel(labIfNull);
_ilg.Emit(OpCodes.Ldloca, locResult);
_ilg.Emit(OpCodes.Initobj, resultType);
_ilg.MarkLabel(labEnd);
_ilg.Emit(OpCodes.Ldloc, locResult);
//RELEASING locResult
FreeLocal(locResult);
}
private void EmitLiftedBooleanAnd()
{
Type type = typeof(bool?);
Label returnRight = _ilg.DefineLabel();
Label exit = _ilg.DefineLabel();
// store values (reverse order since they are already on the stack)
LocalBuilder locLeft = GetLocal(type);
LocalBuilder locRight = GetLocal(type);
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(type);
// if left == true
_ilg.Emit(OpCodes.Brtrue_S, returnRight);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Or);
// if !(left != null | right == true)
_ilg.Emit(OpCodes.Brfalse_S, returnRight);
_ilg.Emit(OpCodes.Ldloc, locLeft);
FreeLocal(locLeft);
_ilg.Emit(OpCodes.Br_S, exit);
_ilg.MarkLabel(returnRight);
_ilg.Emit(OpCodes.Ldloc, locRight);
FreeLocal(locRight);
_ilg.MarkLabel(exit);
}
private void EmitLiftedBooleanOr()
{
Type type = typeof(bool?);
Label returnLeft = _ilg.DefineLabel();
Label exit = _ilg.DefineLabel();
// store values (reverse order since they are already on the stack)
LocalBuilder locLeft = GetLocal(type);
LocalBuilder locRight = GetLocal(type);
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(type);
// if left == true
_ilg.Emit(OpCodes.Brtrue_S, returnLeft);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Or);
// if !(right == true | left != null)
_ilg.Emit(OpCodes.Brfalse_S, returnLeft);
_ilg.Emit(OpCodes.Ldloc, locRight);
FreeLocal(locRight);
_ilg.Emit(OpCodes.Br_S, exit);
_ilg.MarkLabel(returnLeft);
_ilg.Emit(OpCodes.Ldloc, locLeft);
FreeLocal(locLeft);
_ilg.MarkLabel(exit);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Summary: Test suite for the below scenario:
// An array of tasks that can have different workloads
// WaitAny and WaitAll
// - with/without timeout is performed on them
// - the allowed delta for cases with timeout:10 ms
// Scheduler used : current ( ThreadPool)
//
// Observations:
// 1. The input data for tasks does not contain any Exceptional or Cancelled tasks.
// 2. WaitAll on array with cancelled tasks can be found at: Functional\TPL\YetiTests\TaskWithYeti\TaskWithYeti.cs
// 3. WaitAny/WaitAll with token tests can be found at:Functional\TPL\YetiTests\TaskCancellation\TaskCancellation.cs
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Threading.Tasks.Tests.WaitAllAny
{
#region Helper Classes / Methods
/// <summary>
/// the waiting type
/// </summary>
public enum API
{
WaitAll,
WaitAny,
}
/// <summary>
/// Waiting type
/// </summary>
public enum WaitBy
{
None,
TimeSpan,
Millisecond,
}
/// <summary>
/// Every task has an workload associated
/// These are the workload types used in the task tree
/// The workload is not common for the whole tree - Every node can have its own workload
/// </summary>
public enum WorkloadType
{
Exceptional = -2,
Cancelled = -1,
VeryLight = 1000, // the number is the N input to the ZetaSequence workload
Light = 10000,
Medium = 1000000,
Heavy = 100000000,
VeryHeavy = 1000000000,
}
public class TestParameters_WaitAllAny
{
public readonly TaskInfo[] AllTaskInfos;
public readonly API Api;
public readonly WaitBy WaitBy;
public readonly int WaitTime;
public TestParameters_WaitAllAny(API api, int waitTime, WaitBy waitBy, TaskInfo[] allTasks)
{
Api = api;
WaitBy = waitBy;
WaitTime = waitTime;
AllTaskInfos = allTasks;
}
}
/// <summary>
/// The Tree node Data type
///
/// While the tree is not restricted to this data type
/// the implemented tests are using the TaskInfo_WaitAllAny data type for their scenarios
/// </summary>
public class TaskInfo
{
private static double s_UNINITIALED_RESULT = -1;
public TaskInfo(WorkloadType workType)
{
CancellationTokenSource = new CancellationTokenSource();
CancellationToken = CancellationTokenSource.Token;
Result = s_UNINITIALED_RESULT;
WorkType = workType;
}
#region Properties
/// <summary>
/// The task associated with the current node
/// </summary>
public Task Task { get; set; }
/// <summary>
/// The token associated with the current node's task
/// </summary>
public CancellationToken CancellationToken { get; set; }
/// <summary>
/// Every node has a cancellation source - its token participate in the task creation
/// </summary>
public CancellationTokenSource CancellationTokenSource { get; set; }
/// <summary>
/// While a tasks is correct execute a result is produced
/// this is the result
/// </summary>
public double Result { get; private set; }
public WorkloadType WorkType { get; private set; }
#endregion
#region Helper Methods
/// <summary>
/// The Task workload execution
/// </summary>
public void RunWorkload()
{
//Thread = Thread.CurrentThread;
if (WorkType == WorkloadType.Exceptional)
{
ThrowException();
}
else if (WorkType == WorkloadType.Cancelled)
{
CancelSelf(CancellationTokenSource, CancellationToken);
}
else
{
// run the workload
if (Result == s_UNINITIALED_RESULT)
{
Result = ZetaSequence((int)WorkType, CancellationToken);
}
else // task re-entry, mark it failed
{
Result = s_UNINITIALED_RESULT;
}
}
}
public static double ZetaSequence(int n, CancellationToken token)
{
double result = 0;
for (int i = 1; i < n; i++)
{
if (token.IsCancellationRequested)
return s_UNINITIALED_RESULT;
result += 1.0 / ((double)i * (double)i);
}
return result;
}
/// <summary>
/// Cancel self workload. The CancellationToken has been wired such that the source passed to this method
/// is a source that can actually causes the Task CancellationToken to be canceled. The source could be the
/// Token's original source, or one of the sources in case of Linked Tokens
/// </summary>
/// <param name="cts"></param>
public static void CancelSelf(CancellationTokenSource cts, CancellationToken ct)
{
cts.Cancel();
throw new OperationCanceledException(ct);
}
public static void ThrowException()
{
throw new TPLTestException();
}
#endregion
}
public sealed class TaskWaitAllAnyTest
{
#region Private Fields
private const int MAX_DELAY_TIMEOUT = 10;
private readonly API _api; // the API_WaitAllAny to be tested
private readonly WaitBy _waitBy; // the format of Wait
private readonly int _waitTimeout; // the timeout in ms to be waited
private readonly TaskInfo[] _taskInfos; // task info for each task
private readonly Task[] _tasks; // _tasks to be waited
private bool _taskWaitAllReturn; // result to record the WaitAll(timeout) return value
private int _taskWaitAnyReturn; // result to record the WaitAny(timeout) return value
private AggregateException _caughtException; // exception thrown during wait
#endregion
public TaskWaitAllAnyTest(TestParameters_WaitAllAny parameters)
{
_api = parameters.Api;
_waitBy = parameters.WaitBy;
_waitTimeout = parameters.WaitTime;
_taskInfos = parameters.AllTaskInfos;
_tasks = new Task[parameters.AllTaskInfos.Length];
}
/// <summary>
/// The method that will run the scenario
/// </summary>
/// <returns></returns>
internal void RealRun()
{
//create the tasks
CreateTask();
Stopwatch sw = Stopwatch.StartNew();
//start the wait in a try/catch
try
{
switch (_api)
{
case API.WaitAll:
switch (_waitBy)
{
case WaitBy.None:
Task.WaitAll(_tasks);
_taskWaitAllReturn = true;
break;
case WaitBy.Millisecond:
_taskWaitAllReturn = Task.WaitAll(_tasks, _waitTimeout);
break;
case WaitBy.TimeSpan:
_taskWaitAllReturn = Task.WaitAll(_tasks, new TimeSpan(0, 0, 0, 0, _waitTimeout));
break;
}
break;
case API.WaitAny:
switch (_waitBy)
{
case WaitBy.None:
//save the returned task index
_taskWaitAnyReturn = Task.WaitAny(_tasks);
break;
case WaitBy.Millisecond:
//save the returned task index
_taskWaitAnyReturn = Task.WaitAny(_tasks, _waitTimeout);
break;
case WaitBy.TimeSpan:
//save the returned task index
_taskWaitAnyReturn = Task.WaitAny(_tasks, new TimeSpan(0, 0, 0, 0, _waitTimeout));
break;
}
break;
}
}
catch (AggregateException exp)
{
_caughtException = exp;
}
finally
{
sw.Stop();
}
long maxTimeout = (long)(_waitTimeout + MAX_DELAY_TIMEOUT);
if (_waitTimeout != -1 && sw.ElapsedMilliseconds > maxTimeout)
{
Debug.WriteLine("ElapsedMilliseconds way more than requested Timeout.");
Debug.WriteLine("Max Timeout: {0}ms + {1}ms, Actual Time: {2}ms",
_waitTimeout, MAX_DELAY_TIMEOUT, sw.ElapsedMilliseconds);
}
Verify();
CleanUpTasks();
}
private void CleanUpTasks()
{
foreach (TaskInfo taskInfo in _taskInfos)
{
if (taskInfo.Task.Status == TaskStatus.Running)
{
taskInfo.CancellationTokenSource.Cancel();
try { taskInfo.Task.GetAwaiter().GetResult(); }
catch (OperationCanceledException) { }
}
}
}
/// <summary>
/// create an array of tasks
/// </summary>
private void CreateTask()
{
for (int i = 0; i < _taskInfos.Length; i++)
{
int iCopy = i;
_taskInfos[i].Task = Task.Factory.StartNew(
delegate (object o)
{
_taskInfos[iCopy].RunWorkload();
}, string.Concat("Task_", iCopy), _taskInfos[iCopy].CancellationTokenSource.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Current);
_tasks[i] = _taskInfos[i].Task;
}
}
/// <summary>
/// the scenario verification
///
/// - all the tasks should be coplted in case of waitAll with -1 timeout
/// - the returned index form WaitAny should correspond to a completed task
/// - in case of Cancelled and Exception tests the right exceptions should be got for WaitAll
/// </summary>
/// <returns></returns>
private void Verify()
{
// verification for WaitAll
bool allShouldFinish = (_api == API.WaitAll && _taskWaitAllReturn);
// verification for WaitAny
Task thisShouldFinish = (_api == API.WaitAny && _taskWaitAnyReturn != -1) ? _taskInfos[_taskWaitAnyReturn].Task : null;
Dictionary<int, Task> faultyTasks = new Dictionary<int, Task>();
bool expCaught = false;
for (int i = 0; i < _taskInfos.Length; i++)
{
TaskInfo ti = _taskInfos[i];
if (allShouldFinish && !ti.Task.IsCompleted)
Assert.True(false, string.Format("WaitAll contract is broken -- Task at Index = {0} does not finish", i));
if (thisShouldFinish == ti.Task && !ti.Task.IsCompleted)
Assert.True(false, string.Format("WaitAny contract is broken -- Task at Index = {0} does not finish", i));
WorkloadType workType = ti.WorkType;
if (workType == WorkloadType.Exceptional)
{
// verify whether exception has(not) been propogated
expCaught = VerifyException((ex) =>
{
TPLTestException expectedExp = ex as TPLTestException;
return expectedExp != null && expectedExp.FromTaskId == ti.Task.Id;
});
if (_api == API.WaitAll)
{
if (!expCaught)
Assert.True(false, string.Format("excepted TPLTestException in Task at Index = {0} NOT caught", i));
}
else // must be API_WaitAllAny.WaitAny
{
//waitAny will not fail if a number of tasks were exceptional
if (expCaught)
Assert.True(false, string.Format("Unexcepted TPLTestException in Task at Index = {0} caught", i));
//need to check it eventually to prevent it from crashing the finalizer
faultyTasks.Add(i, ti.Task);
}
}
else if (workType == WorkloadType.Cancelled)
{
expCaught = VerifyException((ex) =>
{
TaskCanceledException expectedExp = ex as TaskCanceledException;
return expectedExp != null && expectedExp.Task == ti.Task;
});
if (_api == API.WaitAll)
Assert.True(expCaught, "excepted TaskCanceledException in Task at Index = " + i + " NOT caught");
else // must be API_WaitAllAny.WaitAny
{
if (expCaught) //waitAny will not fail if a number of tasks were cancelled
Assert.False(expCaught, "Unexcepted TaskCanceledException in Task at Index = " + i + " caught");
}
}
else if (ti.Task.IsCompleted && !CheckResult(ti.Result))
Assert.True(false, string.Format("Failed result verification in Task at Index = {0}", i));
else if (ti.Task.Status == TaskStatus.WaitingToRun && ti.Result != -1)
Assert.True(false, string.Format("Result must remain uninitialized for unstarted task"));
}
if (!expCaught && _caughtException != null)
Assert.True(false, string.Format("Caught unexpected exception of {0}", _caughtException));
// second pass on the faulty tasks
if (faultyTasks.Count > 0)
{
List<WaitHandle> faultyTaskHandles = new List<WaitHandle>();
foreach (var task in faultyTasks.Values)
faultyTaskHandles.Add(((IAsyncResult)task).AsyncWaitHandle);
WaitHandle.WaitAll(faultyTaskHandles.ToArray());
foreach (var tasks in faultyTasks)
{
if (!(tasks.Value.Exception.InnerException is TPLTestException))
Assert.True(false, string.Format("Unexcepted Exception in Task at Index = {0} caught", tasks.Key));
}
}
}
/// <summary>
/// verify the exception using a custom defined predicate
/// It walks the whole inner exceptions list saved in _caughtException
/// </summary>
private bool VerifyException(Predicate<Exception> isExpectedExp)
{
if (_caughtException == null)
{
return false;
}
foreach (Exception ex in _caughtException.InnerExceptions)
{
if (isExpectedExp(ex)) return true;
}
return false;
}
/// <summary>
/// Verify the result for a correct running task
/// </summary>
private bool CheckResult(double result)
{
//Function point comparison cant be done by rounding off to nearest decimal points since
//1.64 could be represented as 1.63999999 or as 1.6499999999. To perform floating point comparisons,
//a range has to be defined and check to ensure that the result obtained is within the specified range
double minLimit = 1.63;
double maxLimit = 1.65;
return result > minLimit && result < maxLimit;
}
}
#endregion
public sealed class TaskWaitAllAny
{
[Fact]
[OuterLoop]
public static void TaskWaitAllAny0()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny1()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny2()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny3()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny4()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny5()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny6()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny7()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny8()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 0, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny9()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 0, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny10()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 0, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny11()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.Light);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 0, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny12()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny13()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny14()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny15()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny16()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny17()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny18()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny19()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny20()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny21()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny22()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny23()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny24()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node2 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny25()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny26()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 7, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny27()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 7, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny28()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 7, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny29()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node6 = new TaskInfo(WorkloadType.Light);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 7, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny30()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny31()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo node8 = new TaskInfo(WorkloadType.Medium);
TaskInfo node9 = new TaskInfo(WorkloadType.Light);
TaskInfo node10 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node11 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node12 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node13 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node14 = new TaskInfo(WorkloadType.Medium);
TaskInfo node15 = new TaskInfo(WorkloadType.Medium);
TaskInfo node16 = new TaskInfo(WorkloadType.Light);
TaskInfo node17 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node18 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node19 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node20 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node21 = new TaskInfo(WorkloadType.Medium);
TaskInfo node22 = new TaskInfo(WorkloadType.Medium);
TaskInfo node23 = new TaskInfo(WorkloadType.Light);
TaskInfo node24 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node25 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node26 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node27 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node28 = new TaskInfo(WorkloadType.Medium);
TaskInfo node29 = new TaskInfo(WorkloadType.Medium);
TaskInfo node30 = new TaskInfo(WorkloadType.Light);
TaskInfo node31 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node32 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node33 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node34 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node35 = new TaskInfo(WorkloadType.Medium);
TaskInfo node36 = new TaskInfo(WorkloadType.Medium);
TaskInfo node37 = new TaskInfo(WorkloadType.Light);
TaskInfo node38 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node39 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node40 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node41 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node42 = new TaskInfo(WorkloadType.Medium);
TaskInfo node43 = new TaskInfo(WorkloadType.Medium);
TaskInfo node44 = new TaskInfo(WorkloadType.Light);
TaskInfo node45 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node46 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node47 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node48 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node49 = new TaskInfo(WorkloadType.Medium);
TaskInfo node50 = new TaskInfo(WorkloadType.Medium);
TaskInfo node51 = new TaskInfo(WorkloadType.Light);
TaskInfo node52 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node53 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node54 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node55 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node56 = new TaskInfo(WorkloadType.Medium);
TaskInfo node57 = new TaskInfo(WorkloadType.Medium);
TaskInfo node58 = new TaskInfo(WorkloadType.Light);
TaskInfo node59 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node60 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node61 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node62 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node63 = new TaskInfo(WorkloadType.Medium);
TaskInfo node64 = new TaskInfo(WorkloadType.Medium);
TaskInfo node65 = new TaskInfo(WorkloadType.Light);
TaskInfo node66 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, node8, node9, node10, node11, node12, node13, node14, node15, node16, node17, node18, node19, node20, node21, node22, node23, node24, node25, node26, node27, node28, node29, node30, node31, node32, node33, node34, node35, node36, node37, node38, node39, node40, node41, node42, node43, node44, node45, node46, node47, node48, node49, node50, node51, node52, node53, node54, node55, node56, node57, node58, node59, node60, node61, node62, node63, node64, node65, node66, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny32()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny33()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny34()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny35()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny36()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.Light);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny37()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny38()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 0, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny39()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node3 = new TaskInfo(WorkloadType.Light);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 0, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny40()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 0, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny41()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 0, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny42()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny43()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny44()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny45()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo node8 = new TaskInfo(WorkloadType.Medium);
TaskInfo node9 = new TaskInfo(WorkloadType.Light);
TaskInfo node10 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node11 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node12 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node13 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node14 = new TaskInfo(WorkloadType.Medium);
TaskInfo node15 = new TaskInfo(WorkloadType.Medium);
TaskInfo node16 = new TaskInfo(WorkloadType.Light);
TaskInfo node17 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node18 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node19 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node20 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node21 = new TaskInfo(WorkloadType.Medium);
TaskInfo node22 = new TaskInfo(WorkloadType.Medium);
TaskInfo node23 = new TaskInfo(WorkloadType.Light);
TaskInfo node24 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node25 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node26 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node27 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node28 = new TaskInfo(WorkloadType.Medium);
TaskInfo node29 = new TaskInfo(WorkloadType.Medium);
TaskInfo node30 = new TaskInfo(WorkloadType.Light);
TaskInfo node31 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node32 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node33 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node34 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node35 = new TaskInfo(WorkloadType.Medium);
TaskInfo node36 = new TaskInfo(WorkloadType.Medium);
TaskInfo node37 = new TaskInfo(WorkloadType.Light);
TaskInfo node38 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node39 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node40 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node41 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node42 = new TaskInfo(WorkloadType.Medium);
TaskInfo node43 = new TaskInfo(WorkloadType.Medium);
TaskInfo node44 = new TaskInfo(WorkloadType.Light);
TaskInfo node45 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node46 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node47 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node48 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node49 = new TaskInfo(WorkloadType.Medium);
TaskInfo node50 = new TaskInfo(WorkloadType.Medium);
TaskInfo node51 = new TaskInfo(WorkloadType.Light);
TaskInfo node52 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node53 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node54 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node55 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node56 = new TaskInfo(WorkloadType.Medium);
TaskInfo node57 = new TaskInfo(WorkloadType.Medium);
TaskInfo node58 = new TaskInfo(WorkloadType.Light);
TaskInfo node59 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node60 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node61 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node62 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node63 = new TaskInfo(WorkloadType.Medium);
TaskInfo node64 = new TaskInfo(WorkloadType.Medium);
TaskInfo node65 = new TaskInfo(WorkloadType.Light);
TaskInfo node66 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node67 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node68 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node69 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, node8, node9, node10, node11, node12, node13, node14, node15, node16, node17, node18, node19, node20, node21, node22, node23, node24, node25, node26, node27, node28, node29, node30, node31, node32, node33, node34, node35, node36, node37, node38, node39, node40, node41, node42, node43, node44, node45, node46, node47, node48, node49, node50, node51, node52, node53, node54, node55, node56, node57, node58, node59, node60, node61, node62, node63, node64, node65, node66, node67, node68, node69, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 197, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny46()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny47()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny48()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny49()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny50()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny51()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny52()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.Medium);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny53()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny54()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny55()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 7, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny56()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 7, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny57()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 7, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny58()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 7, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
#if !OLD_MSTEST
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace FluentAssertions.Specs
{
[TestClass]
public class DictionaryEquivalencySpecs
{
#region Non-Generic Dictionaries
[TestMethod]
public void When_asserting_equivalence_of_dictionaries_it_should_respect_the_declared_type()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
IDictionary dictionary1 = new NonGenericDictionary { { 2001, new Car() } };
IDictionary dictionary2 = new NonGenericDictionary { { 2001, new Customer() } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => dictionary1.ShouldBeEquivalentTo(dictionary2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("*Wheels*not have*VehicleId*not have*");
}
[TestMethod]
public void When_asserting_equivalence_of_dictionaries_and_configured_to_respect_runtime_type_it_should_respect_the_runtime_type()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
IDictionary dictionary1 = new NonGenericDictionary { { 2001, new Car() } };
IDictionary dictionary2 = new NonGenericDictionary { { 2001, new Customer() } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
dictionary1.ShouldBeEquivalentTo(dictionary2,
opts => opts.RespectingRuntimeTypes());
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>("the types have different properties");
}
[TestMethod]
public void When_a_non_generic_dictionary_is_typed_as_object_it_should_respect_the_runtime_type()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
object object1 = new NonGenericDictionary();
object object2 = new NonGenericDictionary();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => object1.ShouldBeEquivalentTo(object2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_a_non_generic_dictionary_is_typed_as_object_and_runtime_typing_is_specified_the_runtime_type_should_be_respected()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
object object1 = new NonGenericDictionary { { "greeting", "hello" } };
object object2 = new NonGenericDictionary { { "greeting", "hello" } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => object1.ShouldBeEquivalentTo(object2, opts => opts.RespectingRuntimeTypes());
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow("the runtime type is a dictionary and the dictionaries are equivalent");
}
[TestMethod]
public void When_asserting_equivalence_of_non_generic_dictionaries_the_lack_of_type_information_should_be_preserved_for_other_equivalency_steps()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
Guid userId = Guid.NewGuid();
var dictionary1 = new NonGenericDictionary { { userId, new List<string> { "Admin", "Special" } } };
var dictionary2 = new NonGenericDictionary { { userId, new List<string> { "Admin", "Other" } } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => dictionary1.ShouldBeEquivalentTo(dictionary2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("*Other*Special*");
}
private class NonGenericDictionary : IDictionary
{
private readonly IDictionary dictionary = new Dictionary<object, object>();
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void CopyTo(Array array, int index)
{
dictionary.CopyTo(array, index);
}
public int Count
{
get
{
return dictionary.Count;
}
}
public bool IsSynchronized
{
get
{
return dictionary.IsSynchronized;
}
}
public object SyncRoot
{
get
{
return dictionary.SyncRoot;
}
}
public void Add(object key, object value)
{
dictionary.Add(key, value);
}
public void Clear()
{
dictionary.Clear();
}
public bool Contains(object key)
{
return dictionary.Contains(key);
}
public IDictionaryEnumerator GetEnumerator()
{
return dictionary.GetEnumerator();
}
public void Remove(object key)
{
dictionary.Remove(key);
}
public bool IsFixedSize
{
get
{
return dictionary.IsFixedSize;
}
}
public bool IsReadOnly
{
get
{
return dictionary.IsReadOnly;
}
}
public object this[object key]
{
get
{
return dictionary[key];
}
set
{
dictionary[key] = value;
}
}
public ICollection Keys
{
get
{
return dictionary.Keys;
}
}
public ICollection Values
{
get
{
return dictionary.Values;
}
}
}
#endregion
[TestMethod]
public void When_an_object_implements_two_IDictionary_interfaces_it_should_fail_descriptively()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var object1 = new ClassWithTwoDictionaryImplementations();
var object2 = new ClassWithTwoDictionaryImplementations();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => object1.ShouldBeEquivalentTo(object2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Subject implements multiple dictionary types. "
+ "It is not known which type should be use for equivalence.*");
}
[TestMethod]
public void When_two_dictionaries_asserted_to_be_equivalent_have_different_lengths_it_should_fail_descriptively()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var dictionary1 = new Dictionary<string, string> { { "greeting", "hello" } };
var dictionary2 = new Dictionary<string, string> { { "greeting", "hello" }, {"farewell", "goodbye"} };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act1 = () => dictionary1.ShouldBeEquivalentTo(dictionary2);
Action act2 = () => dictionary2.ShouldBeEquivalentTo(dictionary1);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act1.ShouldThrow<AssertFailedException>().WithMessage("Expected subject to be a dictionary with 2 item(s), but found 1 item(s)*");
act2.ShouldThrow<AssertFailedException>().WithMessage("Expected subject to be a dictionary with 1 item(s), but found 2 item(s)*");
}
[TestMethod]
public void When_a_dictionary_does_not_implement_IDictionary_it_should_still_be_treated_as_a_dictionary()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
IDictionary<string, int> dictionary = new GenericDictionaryNotImplementingIDictionary<string, int> { { "hi", 1 } };
ICollection<KeyValuePair<string, int>> collection = new List<KeyValuePair<string, int>> { new KeyValuePair<string, int>( "hi", 1 ) };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => dictionary.ShouldBeEquivalentTo(collection);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("*is a dictionary and cannot be compared with a non-dictionary type.*");
}
[TestMethod]
public void When_asserting_equivalence_of_generic_dictionaries_and_the_expectation_key_type_is_assignable_from_the_subjects_it_should_pass_if_compatible()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var dictionary1 = new Dictionary<string, string> { { "greeting", "hello" } };
var dictionary2 = new Dictionary<object, string> { { "greeting", "hello" } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => dictionary1.ShouldBeEquivalentTo(dictionary2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow("the keys are still strings");
}
[TestMethod]
public void When_asserting_equivalence_of_generic_dictionaries_and_the_expectation_key_type_is_assignable_from_the_subjects_it_should_fail_if_incompatible()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var dictionary1 = new Dictionary<string, string> { { "greeting", "hello" } };
var dictionary2 = new Dictionary<object, string> { { new object(), "hello" } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => dictionary1.ShouldBeEquivalentTo(dictionary2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage("Subject contains unexpected key \"greeting\"*");
}
[TestMethod]
public void When_asserting_equivalence_of_generic_dictionaries_and_the_expectation_key_type_is_not_assignable_from_the_subjects_it_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var dictionary1 = new Dictionary<string, string> { { "greeting", "hello" } };
var dictionary2 = new Dictionary<int, string> { { 1234, "hello" } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => dictionary1.ShouldBeEquivalentTo(dictionary2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
String.Format(
"*The subject dictionary has keys of type System.String; however, the expected dictionary is not keyed with any compatible types.*{0}*",
typeof(IDictionary<int, string>)));
}
[TestMethod]
public void When_a_generic_dictionary_is_typed_as_object_it_should_respect_the_runtime_typed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
object object1 = new Dictionary<string, string> { { "greeting", "hello" } };
object object2 = new Dictionary<string, string> { { "greeting", "hello" } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => object1.ShouldBeEquivalentTo(object2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_a_generic_dictionary_is_typed_as_object_and_runtime_typing_has_is_specified_it_should_use_the_runtime_type()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
object object1 = new Dictionary<string, string> { { "greeting", "hello" } };
object object2 = new Dictionary<string, string> { { "greeting", "hello" } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => object1.ShouldBeEquivalentTo(object2, opts => opts.RespectingRuntimeTypes());
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow("the runtime type is a dictionary and the dictionaries are equivalent");
}
[TestMethod]
public void When_asserting_the_equivalence_of_generic_dictionaries_it_should_respect_the_declared_type()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var dictionary1 = new Dictionary<int, CustomerType> { { 0, new DerivedCustomerType("123") } };
var dictionary2 = new Dictionary<int, CustomerType> { { 0, new CustomerType("123") } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => dictionary1.ShouldBeEquivalentTo(dictionary2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow("the objects are equivalent according to the members on the declared type");
}
[TestMethod]
public void When_asserting_equivalence_of_generic_dictionaries_and_configured_to_use_runtime_properties_it_should_respect_the_runtime_type()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var dictionary1 = new Dictionary<int, CustomerType> { { 0, new DerivedCustomerType("123") } };
var dictionary2 = new Dictionary<int, CustomerType> { { 0, new CustomerType("123") } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
dictionary1.ShouldBeEquivalentTo(dictionary2,
opts => opts.RespectingRuntimeTypes());
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>("the runtime types have different properties");
}
[TestMethod]
public void When_asserting_equivalence_of_generic_dictionaries_the_type_information_should_be_preserved_for_other_equivalency_steps()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
Guid userId = Guid.NewGuid();
var dictionary1 = new Dictionary<Guid, IEnumerable<string>> { { userId, new List<string> { "Admin", "Special" } } };
var dictionary2 = new Dictionary<Guid, IEnumerable<string>> { { userId, new List<string> { "Admin", "Other" } } };
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => dictionary1.ShouldBeEquivalentTo(dictionary2);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
private class GenericDictionaryNotImplementingIDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return dictionary.GetEnumerator();
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
((ICollection<KeyValuePair<TKey, TValue>>)dictionary).Add(item);
}
public void Clear()
{
dictionary.Clear();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return ((ICollection<KeyValuePair<TKey, TValue>>)dictionary).Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<TKey, TValue>>)dictionary).CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
return ((ICollection<KeyValuePair<TKey, TValue>>)dictionary).Remove(item);
}
public int Count
{
get
{
return dictionary.Count;
}
}
public bool IsReadOnly
{
get
{
return ((ICollection<KeyValuePair<TKey, TValue>>)dictionary).IsReadOnly;
}
}
public bool ContainsKey(TKey key)
{
return dictionary.ContainsKey(key);
}
public void Add(TKey key, TValue value)
{
dictionary.Add(key, value);
}
public bool Remove(TKey key)
{
return dictionary.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
return dictionary.TryGetValue(key, out value);
}
public TValue this[TKey key]
{
get
{
return dictionary[key];
}
set
{
dictionary[key] = value;
}
}
public ICollection<TKey> Keys
{
get
{
return dictionary.Keys;
}
}
public ICollection<TValue> Values
{
get
{
return dictionary.Values;
}
}
}
/// <summary>
/// FakeItEasy can probably handle this in a couple lines, but then it would not be portable.
/// </summary>
private class ClassWithTwoDictionaryImplementations : Dictionary<int, object>, IDictionary<string, object>
{
IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
{
return
((ICollection<KeyValuePair<int, object>>)this).Select(
item =>
new KeyValuePair<string, object>(
item.Key.ToString(CultureInfo.InvariantCulture),
item.Value)).GetEnumerator();
}
public void Add(KeyValuePair<string, object> item)
{
((ICollection<KeyValuePair<int, object>>)this).Add(new KeyValuePair<int, object>(Parse(item.Key), item.Value));
}
public bool Contains(KeyValuePair<string, object> item)
{
return
((ICollection<KeyValuePair<int, object>>)this).Contains(
new KeyValuePair<int, object>(Parse(item.Key), item.Value));
}
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<int, object>>)this).Select(
item =>
new KeyValuePair<string, object>(item.Key.ToString(CultureInfo.InvariantCulture), item.Value))
.ToArray()
.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<string, object> item)
{
return
((ICollection<KeyValuePair<int, object>>)this).Remove(
new KeyValuePair<int, object>(Parse(item.Key), item.Value));
}
bool ICollection<KeyValuePair<string, object>>.IsReadOnly
{
get
{
return ((ICollection<KeyValuePair<int, object>>)this).IsReadOnly;
}
}
public bool ContainsKey(string key)
{
return ContainsKey(Parse(key));
}
public void Add(string key, object value)
{
Add(Parse(key), value);
}
public bool Remove(string key)
{
return Remove(Parse(key));
}
public bool TryGetValue(string key, out object value)
{
return TryGetValue(Parse(key), out value);
}
public object this[string key]
{
get
{
return this[Parse(key)];
}
set
{
this[Parse(key)] = value;
}
}
ICollection<string> IDictionary<string, object>.Keys
{
get
{
return Keys.Select(_ => _.ToString(CultureInfo.InvariantCulture)).ToList();
}
}
ICollection<object> IDictionary<string, object>.Values
{
get
{
return Values;
}
}
private int Parse(string key)
{
return Int32.Parse(key);
}
}
#region (Nested) Dictionaries
[TestMethodAttribute]
public void
When_a_dictionary_property_is_detected_it_should_ignore_the_order_of_the_pairs
()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var expected = new
{
Customers = new Dictionary<string, string>
{
{"Key2", "Value2"},
{"Key1", "Value1"}
}
};
var subject = new
{
Customers = new Dictionary<string, string>
{
{"Key1", "Value1"},
{"Key2", "Value2"}
}
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(expected);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethodAttribute]
public void
When_the_other_property_is_not_a_dictionary_it_should_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var expected = new
{
Customers = "I am a string"
};
var subject = new
{
Customers = new Dictionary<string, string>
{
{"Key2", "Value2"},
{"Key1", "Value1"}
}
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(expected);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Member*Customers*dictionary*non-dictionary*");
}
[TestMethod]
public void When_the_other_property_is_null_it_should_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var expected = new ClassWithMemberDictionary
{
Dictionary = null
};
var subject = new ClassWithMemberDictionary
{
Dictionary = new Dictionary<string, string>
{
{"Key2", "Value2"},
{"Key1", "Value1"}
}
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(expected);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("*member*Dictionary to be <null>, but found *{*}*");
}
[TestMethod]
public void When_the_both_properties_are_null_it_should_not_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var expected = new ClassWithMemberDictionary
{
Dictionary = null
};
var subject = new ClassWithMemberDictionary
{
Dictionary = null
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(expected);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow<AssertFailedException>();
}
[TestMethodAttribute]
public void
When_the_other_dictionary_does_not_contain_enough_items_it_should_throw
()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var expected = new
{
Customers = new Dictionary<string, string>
{
{"Key1", "Value1"},
{"Key2", "Value2"}
}
};
var subject = new
{
Customers = new Dictionary<string, string>
{
{"Key1", "Value1"},
}
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(expected);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(
"Expected*Customers*dictionary*2 item(s)*but*1 item(s)*");
}
[TestMethod]
public void When_two_equivalent_dictionaries_are_compared_directly_it_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var result = new Dictionary<string, int>
{
{ "C", 0 },
{ "B", 0 },
{ "A", 0 }
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => result.ShouldBeEquivalentTo(new Dictionary<string, int>
{
{ "A", 0 },
{ "B", 0 },
{ "C", 0 }
});
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_two_equivalent_dictionaries_are_compared_directly_as_if_it_is_a_collection_it_should_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var result = new Dictionary<string, int?>
{
{ "C", null },
{ "B", 0 },
{ "A", 0 }
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => result.ShouldAllBeEquivalentTo(new Dictionary<string, int?>
{
{ "A", 0 },
{ "B", 0 },
{ "C", null }
});
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_two_nested_dictionaries_do_not_match_it_should_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var projection = new
{
ReferencedEquipment = new Dictionary<int, string>
{
{ 1, "Bla1" }
}
};
var persistedProjection = new
{
ReferencedEquipment = new Dictionary<int, string>
{
{ 1, "Bla2" }
}
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => persistedProjection.ShouldBeEquivalentTo(projection);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(
"Expected*ReferencedEquipment[1]*Bla1*Bla2*2*index 3*");
}
[TestMethod]
public void When_two_nested_dictionaries_contain_null_values_it_should_not_crash()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var projection = new
{
ReferencedEquipment = new Dictionary<int, string>
{
{ 1, null }
}
};
var persistedProjection = new
{
ReferencedEquipment = new Dictionary<int, string>
{
{ 1, null }
}
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => persistedProjection.ShouldBeEquivalentTo(projection);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_the_dictionary_values_are_handled_by_the_enumerable_equivalency_step_the_type_information_should_be_preserved()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
Guid userId = Guid.NewGuid();
var actual = new UserRolesLookupElement();
actual.Add(userId, "Admin", "Special");
var expected = new UserRolesLookupElement();
expected.Add(userId, "Admin", "Other");
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => actual.ShouldBeEquivalentTo(expected);
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected*Roles[*][1]*Other*Special*");
}
public class UserRolesLookupElement
{
private readonly Dictionary<Guid, List<string>> innerRoles = new Dictionary<Guid, List<string>>();
public virtual Dictionary<Guid, IEnumerable<string>> Roles
{
get { return innerRoles.ToDictionary(x => x.Key, y => y.Value.Select(z => z)); }
}
public void Add(Guid userId, params string[] roles)
{
innerRoles[userId] = roles.ToList();
}
}
public class ClassWithMemberDictionary
{
public Dictionary<string, string> Dictionary { get; set; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private partial class CSharpCodeGenerator
{
private class ExpressionCodeGenerator : CSharpCodeGenerator
{
public ExpressionCodeGenerator(
InsertionPoint insertionPoint,
SelectionResult selectionResult,
AnalyzerResult analyzerResult) :
base(insertionPoint, selectionResult, analyzerResult)
{
}
public static bool IsExtractMethodOnExpression(SelectionResult code)
{
return code.SelectionInExpression;
}
protected override SyntaxToken CreateMethodName()
{
var methodName = "NewMethod";
var containingScope = this.CSharpSelectionResult.GetContainingScope();
methodName = GetMethodNameBasedOnExpression(methodName, containingScope);
var semanticModel = this.SemanticDocument.SemanticModel;
var nameGenerator = new UniqueNameGenerator(semanticModel);
return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(containingScope, methodName));
}
private static string GetMethodNameBasedOnExpression(string methodName, SyntaxNode expression)
{
if (expression.Parent != null &&
expression.Parent.Kind() == SyntaxKind.EqualsValueClause &&
expression.Parent.Parent != null &&
expression.Parent.Parent.Kind() == SyntaxKind.VariableDeclarator)
{
var name = ((VariableDeclaratorSyntax)expression.Parent.Parent).Identifier.ValueText;
return (name != null && name.Length > 0) ? MakeMethodName("Get", name) : methodName;
}
if (expression is MemberAccessExpressionSyntax)
{
expression = ((MemberAccessExpressionSyntax)expression).Name;
}
if (expression is NameSyntax)
{
SimpleNameSyntax unqualifiedName;
switch (expression.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
unqualifiedName = (SimpleNameSyntax)expression;
break;
case SyntaxKind.QualifiedName:
unqualifiedName = ((QualifiedNameSyntax)expression).Right;
break;
case SyntaxKind.AliasQualifiedName:
unqualifiedName = ((AliasQualifiedNameSyntax)expression).Name;
break;
default:
throw new System.NotSupportedException("Unexpected name kind: " + expression.Kind().ToString());
}
var unqualifiedNameIdentifierValueText = unqualifiedName.Identifier.ValueText;
return (unqualifiedNameIdentifierValueText != null && unqualifiedNameIdentifierValueText.Length > 0) ? MakeMethodName("Get", unqualifiedNameIdentifierValueText) : methodName;
}
return methodName;
}
protected override IEnumerable<StatementSyntax> GetInitialStatementsForMethodDefinitions()
{
Contract.ThrowIfFalse(IsExtractMethodOnExpression(this.CSharpSelectionResult));
ExpressionSyntax expression = null;
// special case for array initializer
var returnType = (ITypeSymbol)this.AnalyzerResult.ReturnType;
var containingScope = this.CSharpSelectionResult.GetContainingScope();
if (returnType.TypeKind == TypeKind.Array && containingScope is InitializerExpressionSyntax)
{
var typeSyntax = returnType.GenerateTypeSyntax();
expression = SyntaxFactory.ArrayCreationExpression(typeSyntax as ArrayTypeSyntax, containingScope as InitializerExpressionSyntax);
}
else
{
expression = containingScope as ExpressionSyntax;
}
if (this.AnalyzerResult.HasReturnType)
{
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
SyntaxFactory.ReturnStatement(
WrapInCheckedExpressionIfNeeded(expression)));
}
else
{
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
SyntaxFactory.ExpressionStatement(
WrapInCheckedExpressionIfNeeded(expression)));
}
}
private ExpressionSyntax WrapInCheckedExpressionIfNeeded(ExpressionSyntax expression)
{
var kind = this.CSharpSelectionResult.UnderCheckedExpressionContext();
if (kind == SyntaxKind.None)
{
return expression;
}
return SyntaxFactory.CheckedExpression(kind, expression);
}
protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken)
{
var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken);
if (callSiteContainer != null)
{
return callSiteContainer;
}
else
{
return GetCallSiteContainerFromExpression();
}
}
private SyntaxNode GetCallSiteContainerFromExpression()
{
var container = this.CSharpSelectionResult.GetInnermostStatementContainer();
Contract.ThrowIfNull(container);
Contract.ThrowIfFalse(container.IsStatementContainerNode() ||
container is TypeDeclarationSyntax ||
container is ConstructorDeclarationSyntax ||
container is CompilationUnitSyntax);
return container;
}
protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite()
{
var scope = (SyntaxNode)this.CSharpSelectionResult.GetContainingScopeOf<StatementSyntax>();
if (scope == null)
{
scope = this.CSharpSelectionResult.GetContainingScopeOf<FieldDeclarationSyntax>();
}
if (scope == null)
{
scope = this.CSharpSelectionResult.GetContainingScopeOf<ConstructorInitializerSyntax>();
}
if (scope == null)
{
// This is similar to FieldDeclaration case but we only want to do this if the member has an expression body.
scope = this.CSharpSelectionResult.GetContainingScopeOf<ArrowExpressionClauseSyntax>().Parent;
}
return scope;
}
protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite()
{
return GetFirstStatementOrInitializerSelectedAtCallSite();
}
protected override async Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(
SyntaxAnnotation callSiteAnnotation, CancellationToken cancellationToken)
{
var enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite();
var callSignature = CreateCallSignature().WithAdditionalAnnotations(callSiteAnnotation);
var invocation = callSignature.IsKind(SyntaxKind.AwaitExpression) ? ((AwaitExpressionSyntax)callSignature).Expression : callSignature;
var sourceNode = this.CSharpSelectionResult.GetContainingScope();
Contract.ThrowIfTrue(
sourceNode.Parent is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)sourceNode.Parent).Name == sourceNode,
"invalid scope. given scope is not an expression");
// To lower the chances that replacing sourceNode with callSignature will break the user's
// code, we make the enclosing statement semantically explicit. This ends up being a little
// bit more work because we need to annotate the sourceNode so that we can get back to it
// after rewriting the enclosing statement.
var updatedDocument = this.SemanticDocument.Document;
var sourceNodeAnnotation = new SyntaxAnnotation();
var enclosingStatementAnnotation = new SyntaxAnnotation();
var newEnclosingStatement = enclosingStatement
.ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation))
.WithAdditionalAnnotations(enclosingStatementAnnotation);
updatedDocument = await updatedDocument.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(false);
var updatedRoot = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
newEnclosingStatement = updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode();
// because of the complexifiction we cannot guarantee that there is only one annotation.
// however complexification of names is prepended, so the last annotation should be the original one.
sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode();
// we want to replace the old identifier with a invocation expression, but because of MakeExplicit we might have
// a member access now instead of the identifier. So more syntax fiddling is needed.
if (sourceNode.Parent.Kind() == SyntaxKind.SimpleMemberAccessExpression &&
((ExpressionSyntax)sourceNode).IsRightSideOfDot())
{
var explicitMemberAccess = (MemberAccessExpressionSyntax)sourceNode.Parent;
var replacementMemberAccess = explicitMemberAccess.CopyAnnotationsTo(
SyntaxFactory.MemberAccessExpression(
sourceNode.Parent.Kind(),
explicitMemberAccess.Expression,
(SimpleNameSyntax)((InvocationExpressionSyntax)invocation).Expression));
var newInvocation = SyntaxFactory.InvocationExpression(
replacementMemberAccess,
((InvocationExpressionSyntax)invocation).ArgumentList);
var newCallSignature = callSignature != invocation ?
callSignature.ReplaceNode(invocation, newInvocation) : invocation.CopyAnnotationsTo(newInvocation);
sourceNode = sourceNode.Parent;
callSignature = newCallSignature;
}
return newEnclosingStatement.ReplaceNode(sourceNode, callSignature);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Brew;
using Brew.TypeConverters;
namespace Brew.Webforms.Widgets {
/// <summary>
/// Extend a Control, WebControl or HtmlControl with the jQuery UI Dialog http://jqueryui.com/demos/dialog/
/// </summary>
[ParseChildren(typeof(DialogButton), DefaultProperty = "Buttons", ChildrenAsProperties = true)]
public class Dialog : Widget {
public Dialog() : base("dialog") {
this.Buttons = new DialogButtonList();
EventHandler handler = delegate(object s, EventArgs e) {
var js = new JavaScriptSerializer();
var dict = new Dictionary<String, String>();
foreach (var button in this.Buttons) {
var key = button.Text;
String value = button.Action;
if (String.IsNullOrEmpty(key)) {
key = "Button " + this.Buttons.IndexOf(button);
}
if (button.CloseDialog) {
value = "window.__brew && window.__brew.closedialog";
}
dict.Add(key, value);
this._Buttons = js.Serialize(dict);
}
};
this.Buttons.Modified += handler;
}
public override List<WidgetEvent> GetEvents() {
return new List<WidgetEvent>() {
new WidgetEvent("create"),
new WidgetEvent("beforeClose"),
new WidgetEvent("dragStart"),
new WidgetEvent("focus"),
new WidgetEvent("open"),
new WidgetEvent("drag"),
new WidgetEvent("dragStop"),
new WidgetEvent("resizeStart"),
new WidgetEvent("resize"),
new WidgetEvent("resizeStop"),
new WidgetEvent("close")
};
}
public override List<WidgetOption> GetOptions() {
return new List<WidgetOption>() {
new WidgetOption { Name = "autoOpen", DefaultValue = true },
new WidgetOption { Name = "buttons", DefaultValue = "{}", PropertyName = "_Buttons" },
new WidgetOption { Name = "closeOnEscape", DefaultValue = true },
new WidgetOption { Name = "closeText", DefaultValue = "close" },
new WidgetOption { Name = "dialogClass", DefaultValue = "" },
new WidgetOption { Name = "draggable", DefaultValue = true },
new WidgetOption { Name = "height", DefaultValue = 0 },
new WidgetOption { Name = "hide", DefaultValue = null },
new WidgetOption { Name = "maxHeight", DefaultValue = 0 },
new WidgetOption { Name = "maxWidth", DefaultValue = 0 },
new WidgetOption { Name = "minHeight", DefaultValue = 150 },
new WidgetOption { Name = "minWidth", DefaultValue = 150 },
new WidgetOption { Name = "modal", DefaultValue = false },
new WidgetOption { Name = "position", DefaultValue = "center" },
new WidgetOption { Name = "resizable", DefaultValue = true },
new WidgetOption { Name = "show", DefaultValue = null },
new WidgetOption { Name = "stack", DefaultValue = true },
new WidgetOption { Name = "title", DefaultValue = "" },
new WidgetOption { Name = "width", DefaultValue = 300 },
new WidgetOption { Name = "zIndex", DefaultValue = 1000 },
new WidgetOption { Name = "trigger", DefaultValue = "" }
};
}
/// <summary>
/// This event is triggered when the dialog is closed.
/// Reference: http://jqueryui.com/demos/dialog/#close
/// </summary>
[Category("Action")]
[Description("This event is triggered when the dialog is closed.")]
public event EventHandler Close;
/// <summary>
/// Specifies which buttons should be displayed on the dialog. The property key is the text of the button. The value is the callback function for when the button is clicked. The context of the callback is the dialog element; if you need access to the button, it is available as the target of the event object.
/// Reference: http://jqueryui.com/demos/dialog/#buttons
/// </summary>
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TemplateContainer(typeof(DialogButton))]
[Description("Specifies which buttons should be displayed on the dialog. The property key is the text of the button. The value is the callback function for when the button is clicked. The context of the callback is the dialog element; if you need access to the button, it is available as the target of the event object.")]
[Category("Appearance")]
public DialogButtonList Buttons { get; private set; }
/// <summary>
/// The jQuery selector or Control ID for the element to be used as a trigger to open the dialog.
/// </summary>
[Category("Behavior")]
[DefaultValue("")]
[Description("The jQuery selector or Control ID for the element to be used as a trigger to open the dialog.")]
public string Trigger { get; set; }
protected override void OnPreRender(EventArgs e) {
if (this.Trigger != null) {
var control = FindControl(this.Trigger);
if (control != null) {
this.Trigger = "#" + control.ClientID;
}
}
base.OnPreRender(e);
}
#region . Options .
/// <summary>
/// When autoOpen is true the dialog will open automatically when dialog is called. If false it will stay hidden until .dialog("open") is called on it.
/// Reference: http://jqueryui.com/demos/dialog/#autoOpen
/// </summary>
[Category("Behavior")]
[DefaultValue(true)]
[Description("When autoOpen is true the dialog will open automatically when dialog is called. If false it will stay hidden until .dialog(\"open\") is called on it.")]
public bool AutoOpen { get; set; }
[TypeConverter(typeof(Brew.TypeConverters.JsonObjectConverter))]
public string _Buttons { get; set; }
/// <summary>
/// Specifies whether the dialog should close when it has focus and the user presses the esacpe (ESC) key.
/// Reference: http://jqueryui.com/demos/dialog/#closeOnEscape
/// </summary>
[Category("Behavior")]
[DefaultValue(true)]
[Description("Specifies whether the dialog should close when it has focus and the user presses the esacpe (ESC) key.")]
public bool CloseOnEscape { get; set; }
/// <summary>
/// Specifies the text for the close button. Note that the close text is visibly hidden when using a standard theme.
/// Reference: http://jqueryui.com/demos/dialog/#closeText
/// </summary>
[Category("Appearance")]
[DefaultValue("close")]
[Description("Specifies the text for the close button. Note that the close text is visibly hidden when using a standard theme.")]
public string CloseText { get; set; }
/// <summary>
/// The specified class name(s) will be added to the dialog, for additional theming.
/// Reference: http://jqueryui.com/demos/dialog/#dialogClass
/// </summary>
[Category("Appearance")]
[DefaultValue("")]
[Description("The specified class name(s) will be added to the dialog, for additional theming.")]
public string DialogClass { get; set; }
/// <summary>
/// If set to true, the dialog will be draggable will be draggable by the titlebar.
/// Reference: http://jqueryui.com/demos/dialog/#draggable
/// </summary>
[Category("Behavior")]
[DefaultValue(true)]
[Description("If set to true, the dialog will be draggable will be draggable by the titlebar.")]
public bool Draggable { get; set; }
/// <summary>
/// The height of the dialog, in pixels. Specifying 'auto' is also supported to make the dialog adjust based on its content.
/// Reference: http://jqueryui.com/demos/dialog/#height
/// </summary>
[TypeConverter(typeof(StringToObjectConverter))]
[Category("Layout")]
[DefaultValue("auto")]
[Description("The height of the dialog, in pixels. Specifying 'auto' is also supported to make the dialog adjust based on its content.")]
public dynamic Height { get; set; }
/// <summary>
/// The effect to be used when the dialog is closed.
/// Reference: http://jqueryui.com/demos/dialog/#hide
/// </summary>
[Category("Behavior")]
[DefaultValue(null)]
[Description("The effect to be used when the dialog is closed.")]
public string Hide { get; set; }
/// <summary>
/// The maximum height to which the dialog can be resized, in pixels.
/// Reference: http://jqueryui.com/demos/dialog/#maxHeight
/// </summary>
[TypeConverter(typeof(StringToObjectConverter))]
[Category("Layout")]
[DefaultValue(false)]
[Description("The maximum height to which the dialog can be resized, in pixels.")]
public dynamic MaxHeight { get; set; }
/// <summary>
/// The maximum width to which the dialog can be resized, in pixels.
/// Reference: http://jqueryui.com/demos/dialog/#maxWidth
/// </summary>
[TypeConverter(typeof(StringToObjectConverter))]
[Category("Layout")]
[DefaultValue(false)]
[Description("The maximum width to which the dialog can be resized, in pixels.")]
public dynamic MaxWidth { get; set; }
/// <summary>
/// The minimum height to which the dialog can be resized, in pixels.
/// Reference: http://jqueryui.com/demos/dialog/#minHeight
/// </summary>
[TypeConverter(typeof(StringToObjectConverter))]
[Category("Layout")]
[DefaultValue(150)]
[Description("The minimum height to which the dialog can be resized, in pixels.")]
public dynamic MinHeight { get; set; }
/// <summary>
/// The minimum width to which the dialog can be resized, in pixels.
/// Reference: http://jqueryui.com/demos/dialog/#minWidth
/// </summary>
[TypeConverter(typeof(StringToObjectConverter))]
[Category("Layout")]
[DefaultValue(150)]
[Description("The minimum width to which the dialog can be resized, in pixels.")]
public dynamic MinWidth { get; set; }
/// <summary>
/// If set to true, the dialog will have modal behavior; other items on the page will be disabled (i.e. cannot be interacted with). Modal dialogs create an overlay below the dialog but above other page elements.
/// Reference: http://jqueryui.com/demos/dialog/#modal
/// </summary>
[Category("Behavior")]
[DefaultValue(false)]
[Description("If set to true, the dialog will have modal behavior; other items on the page will be disabled (i.e. cannot be interacted with). Modal dialogs create an overlay below the dialog but above other page elements.")]
public bool Modal { get; set; }
/// <summary>
/// Specifies where the dialog should be displayed. Possible values: 1) a single string representing position within viewport: 'center', 'left', 'right', 'top', 'bottom'. 2) an array containing an x,y coordinate pair in pixel offset from left, top corner of viewport (e.g. [350,100]) 3) an array containing x,y position string values (e.g. ['right','top'] for top right corner).
/// Reference: http://jqueryui.com/demos/dialog/#position
/// </summary>
[TypeConverter(typeof(JsonObjectConverter))]
[Category("Layout")]
[DefaultValue("center")]
[Description("Specifies where the dialog should be displayed. Possible values: 1) a single string representing position within viewport: 'center', 'left', 'right', 'top', 'bottom'. 2) an array containing an x,y coordinate pair in pixel offset from left, top corner of viewport (e.g. [350,100]) 3) an array containing x,y position string values (e.g. ['right','top'] for top right corner).")]
public string Position { get; set; }
/// <summary>
/// If set to true, the dialog will be resizeable.
/// Reference: http://jqueryui.com/demos/dialog/#resizable
/// </summary>
[Category("Behavior")]
[DefaultValue(true)]
[Description("If set to true, the dialog will be resizeable.")]
public bool Resizable { get; set; }
/// <summary>
/// The effect to be used when the dialog is opened.
/// Reference: http://jqueryui.com/demos/dialog/#show
/// </summary>
[Category("Appearance")]
[DefaultValue(null)]
[Description("The effect to be used when the dialog is opened.")]
public string Show { get; set; }
/// <summary>
/// Specifies whether the dialog will stack on top of other dialogs. This will cause the dialog to move to the front of other dialogs when it gains focus.
/// Reference: http://jqueryui.com/demos/dialog/#stack
/// </summary>
[Category("Behavior")]
[DefaultValue(true)]
[Description("Specifies whether the dialog will stack on top of other dialogs. This will cause the dialog to move to the front of other dialogs when it gains focus.")]
public bool Stack { get; set; }
/// <summary>
/// Specifies the title of the dialog. Any valid HTML may be set as the title. The title can also be specified by the title attribute on the dialog source element.
/// Reference: http://jqueryui.com/demos/dialog/#title
/// </summary>
[Category("Appearance")]
[DefaultValue("")]
[Description("Specifies the title of the dialog. Any valid HTML may be set as the title. The title can also be specified by the title attribute on the dialog source element.")]
public string Title { get; set; }
/// <summary>
/// The width of the dialog, in pixels.
/// Reference: http://jqueryui.com/demos/dialog/#width
/// </summary>
[TypeConverter(typeof(StringToObjectConverter))]
[Category("Layout")]
[DefaultValue(300)]
[Description("The width of the dialog, in pixels.")]
public dynamic Width { get; set; }
/// <summary>
/// The starting z-index for the dialog.
/// Reference: http://jqueryui.com/demos/dialog/#zIndex
/// </summary>
[Category("Behavior")]
[DefaultValue(1000)]
[Description("The starting z-index for the dialog.")]
public int ZIndex { get; set; }
#endregion
}
}
| |
/*****************************************************************************
* *
* OpenNI 1.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UserID = System.Int32;
namespace OpenNI
{
public class UserEventArgs : EventArgs
{
public UserEventArgs(UserID id)
{
this.id = id;
}
public UserID ID
{
get { return id; }
set { id = value; }
}
private UserID id;
}
public class NewUserEventArgs : UserEventArgs
{
public NewUserEventArgs(UserID id) : base(id) { }
}
public class UserLostEventArgs : UserEventArgs
{
public UserLostEventArgs(UserID id) : base(id) { }
}
public class UserExitEventArgs : UserEventArgs
{
public UserExitEventArgs(UserID id) : base(id) { }
}
public class UserReEnterEventArgs : UserEventArgs
{
public UserReEnterEventArgs(UserID id) : base(id) { }
}
public class UserGenerator : Generator
{
public UserGenerator(Context context, IntPtr nodeHandle, bool addRef) :
base(context, nodeHandle, addRef)
{
this.internalNewUser = new SafeNativeMethods.XnUserHandler(this.InternalNewUser);
this.internalLostUser = new SafeNativeMethods.XnUserHandler(this.InternalLostUser);
this.internalUserExit = new SafeNativeMethods.XnUserHandler(this.InternalUserExit);
this.internalUserReEnter = new SafeNativeMethods.XnUserHandler(this.InternalUserReEnter);
if (IsCapabilitySupported(Capabilities.Skeleton))
m_skeletonCapability = new SkeletonCapability(this);
else m_skeletonCapability = null;
if (IsCapabilitySupported(Capabilities.PoseDetection))
m_poseDetectionCapability = new PoseDetectionCapability(this);
else m_poseDetectionCapability = null;
}
public UserGenerator(Context context, Query query, EnumerationErrors errors) :
this(context, Create(context, query, errors), false)
{
}
public UserGenerator(Context context, Query query)
: this(context, query, null)
{
}
public UserGenerator(Context context)
: this(context, null, null)
{
}
private static IntPtr Create(Context context, Query query, EnumerationErrors errors)
{
IntPtr handle;
int status =
SafeNativeMethods.xnCreateUserGenerator(context.InternalObject,
out handle,
query == null ? IntPtr.Zero : query.InternalObject,
errors == null ? IntPtr.Zero : errors.InternalObject);
WrapperUtils.ThrowOnError(status);
return handle;
}
public int NumberOfUsers
{
get
{
return SafeNativeMethods.xnGetNumberOfUsers(this.InternalObject);
}
}
public UserID[] GetUsers()
{
ushort count = (ushort)NumberOfUsers;
UserID[] users = new UserID[count];
int status = SafeNativeMethods.xnGetUsers(this.InternalObject, users, ref count);
WrapperUtils.ThrowOnError(status);
return users;
}
public Point3D GetCoM(UserID id)
{
Point3D com = new Point3D();
int status = SafeNativeMethods.xnGetUserCoM(this.InternalObject, id, out com);
WrapperUtils.ThrowOnError(status);
return com;
}
public SceneMetaData GetUserPixels(UserID id)
{
SceneMetaData smd = new SceneMetaData();
using (IMarshaler marsh = smd.GetMarshaler(true))
{
int status = SafeNativeMethods.xnGetUserPixels(this.InternalObject, id, marsh.Native);
WrapperUtils.ThrowOnError(status);
}
return smd;
}
public SkeletonCapability SkeletonCapability
{
get
{
return m_skeletonCapability;
}
}
public PoseDetectionCapability PoseDetectionCapability
{
get
{
return m_poseDetectionCapability;
}
}
#region New User
private event EventHandler<NewUserEventArgs> newUserEvent;
public event EventHandler<NewUserEventArgs> NewUser
{
add
{
if (this.newUserEvent == null)
{
int status = SafeNativeMethods.xnRegisterUserCallbacks(this.InternalObject, this.internalNewUser, null, IntPtr.Zero, out newUserHandle);
WrapperUtils.ThrowOnError(status);
}
this.newUserEvent += value;
}
remove
{
this.newUserEvent -= value;
if (this.newUserEvent == null)
{
SafeNativeMethods.xnUnregisterUserCallbacks(this.InternalObject, this.newUserHandle);
}
}
}
private void InternalNewUser(IntPtr hNode, UserID id, IntPtr pCookie)
{
EventHandler<NewUserEventArgs> handlers = this.newUserEvent;
if (handlers != null)
handlers(this, new NewUserEventArgs(id));
}
private SafeNativeMethods.XnUserHandler internalNewUser;
private IntPtr newUserHandle;
#endregion
#region Lost User
private event EventHandler<UserLostEventArgs> lostUserEvent;
public event EventHandler<UserLostEventArgs> LostUser
{
add
{
if (this.lostUserEvent == null)
{
int status = SafeNativeMethods.xnRegisterUserCallbacks(this.InternalObject, null, this.internalLostUser, IntPtr.Zero, out lostUserHandle);
WrapperUtils.ThrowOnError(status);
}
this.lostUserEvent += value;
}
remove
{
this.lostUserEvent -= value;
if (this.lostUserEvent == null)
{
SafeNativeMethods.xnUnregisterUserCallbacks(this.InternalObject, this.lostUserHandle);
}
}
}
private void InternalLostUser(IntPtr hNode, UserID id, IntPtr pCookie)
{
EventHandler<UserLostEventArgs> handlers = this.lostUserEvent;
if (handlers != null)
handlers(this, new UserLostEventArgs(id));
}
private SafeNativeMethods.XnUserHandler internalLostUser;
private IntPtr lostUserHandle;
#endregion
#region User Exit
private event EventHandler<UserExitEventArgs> userExitEvent;
public event EventHandler<UserExitEventArgs> UserExit
{
add
{
if (this.userExitEvent == null)
{
int status = SafeNativeMethods.xnRegisterToUserExit(this.InternalObject, this.internalUserExit, IntPtr.Zero, out userExitHandle);
WrapperUtils.ThrowOnError(status);
}
this.userExitEvent += value;
}
remove
{
this.userExitEvent -= value;
if (this.userExitEvent == null)
{
SafeNativeMethods.xnUnregisterFromUserExit(this.InternalObject, this.userExitHandle);
}
}
}
private void InternalUserExit(IntPtr hNode, UserID id, IntPtr pCookie)
{
EventHandler<UserExitEventArgs> handlers = this.userExitEvent;
if (handlers != null)
handlers(this, new UserExitEventArgs(id));
}
private SafeNativeMethods.XnUserHandler internalUserExit;
private IntPtr userExitHandle;
#endregion
#region User ReEnter
private event EventHandler<UserReEnterEventArgs> userReEnterEvent;
public event EventHandler<UserReEnterEventArgs> UserReEnter
{
add
{
if (this.userReEnterEvent == null)
{
int status = SafeNativeMethods.xnRegisterToUserReEnter(this.InternalObject, this.internalUserReEnter, IntPtr.Zero, out userReEnterHandle);
WrapperUtils.ThrowOnError(status);
}
this.userReEnterEvent += value;
}
remove
{
this.userReEnterEvent -= value;
if (this.userReEnterEvent == null)
{
SafeNativeMethods.xnUnregisterFromUserReEnter(this.InternalObject, this.userReEnterHandle);
}
}
}
private void InternalUserReEnter(IntPtr hNode, UserID id, IntPtr pCookie)
{
EventHandler<UserReEnterEventArgs> handlers = this.userReEnterEvent;
if (handlers != null)
handlers(this, new UserReEnterEventArgs(id));
}
private SafeNativeMethods.XnUserHandler internalUserReEnter;
private IntPtr userReEnterHandle;
#endregion
/// @todo this is a temporary solution for capability not being disposed by anyone external
public override void Dispose()
{
if (m_skeletonCapability != null)
{
m_skeletonCapability.InternalDispose();
m_skeletonCapability = null;
}
if (m_poseDetectionCapability != null)
{
m_poseDetectionCapability.InternalDispose();
m_poseDetectionCapability = null;
}
base.Dispose();
}
// protected members
// internal capabilities to avoid doing "new" all the time. They are initialized in
// the construction and are null if not supported.
// NOTE: everyone getting a capability will get THE SAME capability! i.e. dispose should not be
// called!
protected SkeletonCapability m_skeletonCapability;
protected PoseDetectionCapability m_poseDetectionCapability;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.CSharp.Debugging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging
{
public class NameResolverTests
{
private void Test(string text, string searchText, params string[] expectedNames)
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(text))
{
var nameResolver = new BreakpointResolver(workspace.CurrentSolution, searchText);
var results = nameResolver.DoAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
Assert.Equal(expectedNames, results.Select(r => r.LocationNameOpt));
}
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestCSharpLanguageDebugInfoCreateNameResolver()
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(" "))
{
var debugInfo = new CSharpBreakpointResolutionService();
var results = debugInfo.ResolveBreakpointsAsync(workspace.CurrentSolution, "foo", CancellationToken.None).WaitAndGetResult(CancellationToken.None);
Assert.Equal(0, results.Count());
}
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestSimpleNameInClass()
{
var text =
@"class C
{
void Foo()
{
}
}";
Test(text, "Foo", "C.Foo()");
Test(text, "foo");
Test(text, "C.Foo", "C.Foo()");
Test(text, "N.C.Foo");
Test(text, "Foo<T>");
Test(text, "C<T>.Foo");
Test(text, "Foo()", "C.Foo()");
Test(text, "Foo(int i)");
Test(text, "Foo(int)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestSimpleNameInNamespace()
{
var text =
@"
namespace N
{
class C
{
void Foo()
{
}
}
}";
Test(text, "Foo", "N.C.Foo()");
Test(text, "foo");
Test(text, "C.Foo", "N.C.Foo()");
Test(text, "N.C.Foo", "N.C.Foo()");
Test(text, "Foo<T>");
Test(text, "C<T>.Foo");
Test(text, "Foo()", "N.C.Foo()");
Test(text, "C.Foo()", "N.C.Foo()");
Test(text, "N.C.Foo()", "N.C.Foo()");
Test(text, "Foo(int i)");
Test(text, "Foo(int)");
Test(text, "Foo(a)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestSimpleNameInGenericClassNamespace()
{
var text =
@"
namespace N
{
class C<T>
{
void Foo()
{
}
}
}";
Test(text, "Foo", "N.C<T>.Foo()");
Test(text, "foo");
Test(text, "C.Foo", "N.C<T>.Foo()");
Test(text, "N.C.Foo", "N.C<T>.Foo()");
Test(text, "Foo<T>");
Test(text, "C<T>.Foo", "N.C<T>.Foo()");
Test(text, "C<T>.Foo()", "N.C<T>.Foo()");
Test(text, "Foo()", "N.C<T>.Foo()");
Test(text, "C.Foo()", "N.C<T>.Foo()");
Test(text, "N.C.Foo()", "N.C<T>.Foo()");
Test(text, "Foo(int i)");
Test(text, "Foo(int)");
Test(text, "Foo(a)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestGenericNameInClassNamespace()
{
var text =
@"
namespace N
{
class C
{
void Foo<T>()
{
}
}
}";
Test(text, "Foo", "N.C.Foo<T>()");
Test(text, "foo");
Test(text, "C.Foo", "N.C.Foo<T>()");
Test(text, "N.C.Foo", "N.C.Foo<T>()");
Test(text, "Foo<T>", "N.C.Foo<T>()");
Test(text, "Foo<X>", "N.C.Foo<T>()");
Test(text, "Foo<T,X>");
Test(text, "C<T>.Foo");
Test(text, "C<T>.Foo()");
Test(text, "Foo()", "N.C.Foo<T>()");
Test(text, "C.Foo()", "N.C.Foo<T>()");
Test(text, "N.C.Foo()", "N.C.Foo<T>()");
Test(text, "Foo(int i)");
Test(text, "Foo(int)");
Test(text, "Foo(a)");
Test(text, "Foo<T>(int i)");
Test(text, "Foo<T>(int)");
Test(text, "Foo<T>(a)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestOverloadsInSingleClass()
{
var text =
@"class C
{
void Foo()
{
}
void Foo(int i)
{
}
}";
Test(text, "Foo", "C.Foo()", "C.Foo(int)");
Test(text, "foo");
Test(text, "C.Foo", "C.Foo()", "C.Foo(int)");
Test(text, "N.C.Foo");
Test(text, "Foo<T>");
Test(text, "C<T>.Foo");
Test(text, "Foo()", "C.Foo()");
Test(text, "Foo(int i)", "C.Foo(int)");
Test(text, "Foo(int)", "C.Foo(int)");
Test(text, "Foo(i)", "C.Foo(int)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestMethodsInMultipleClasses()
{
var text =
@"namespace N
{
class C
{
void Foo()
{
}
}
}
namespace N1
{
class C
{
void Foo(int i)
{
}
}
}";
Test(text, "Foo", "N1.C.Foo(int)", "N.C.Foo()");
Test(text, "foo");
Test(text, "C.Foo", "N1.C.Foo(int)", "N.C.Foo()");
Test(text, "N.C.Foo", "N.C.Foo()");
Test(text, "N1.C.Foo", "N1.C.Foo(int)");
Test(text, "Foo<T>");
Test(text, "C<T>.Foo");
Test(text, "Foo()", "N.C.Foo()");
Test(text, "Foo(int i)", "N1.C.Foo(int)");
Test(text, "Foo(int)", "N1.C.Foo(int)");
Test(text, "Foo(i)", "N1.C.Foo(int)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestMethodsWithDifferentArityInMultipleClasses()
{
var text =
@"namespace N
{
class C
{
void Foo()
{
}
}
}
namespace N1
{
class C
{
void Foo<T>(int i)
{
}
}
}";
Test(text, "Foo", "N1.C.Foo<T>(int)", "N.C.Foo()");
Test(text, "foo");
Test(text, "C.Foo", "N1.C.Foo<T>(int)", "N.C.Foo()");
Test(text, "N.C.Foo", "N.C.Foo()");
Test(text, "N1.C.Foo", "N1.C.Foo<T>(int)");
Test(text, "Foo<T>", "N1.C.Foo<T>(int)");
Test(text, "C<T>.Foo");
Test(text, "Foo()", "N.C.Foo()");
Test(text, "Foo<T>()");
Test(text, "Foo(int i)", "N1.C.Foo<T>(int)");
Test(text, "Foo(int)", "N1.C.Foo<T>(int)");
Test(text, "Foo(i)", "N1.C.Foo<T>(int)");
Test(text, "Foo<T>(int i)", "N1.C.Foo<T>(int)");
Test(text, "Foo<T>(int)", "N1.C.Foo<T>(int)");
Test(text, "Foo<T>(i)", "N1.C.Foo<T>(int)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestOverloadsWithMultipleParametersInSingleClass()
{
var text =
@"class C
{
void Foo(int a)
{
}
void Foo(int a, string b = ""bb"")
{
}
void Foo(__arglist)
{
}
}";
Test(text, "Foo", "C.Foo(int)", "C.Foo(int, [string])", "C.Foo(__arglist)");
Test(text, "foo");
Test(text, "C.Foo", "C.Foo(int)", "C.Foo(int, [string])", "C.Foo(__arglist)");
Test(text, "N.C.Foo");
Test(text, "Foo<T>");
Test(text, "C<T>.Foo");
Test(text, "Foo()", "C.Foo(__arglist)");
Test(text, "Foo(int i)", "C.Foo(int)");
Test(text, "Foo(int)", "C.Foo(int)");
Test(text, "Foo(int x = 42)", "C.Foo(int)");
Test(text, "Foo(i)", "C.Foo(int)");
Test(text, "Foo(int i, int b)", "C.Foo(int, [string])");
Test(text, "Foo(int, bool)", "C.Foo(int, [string])");
Test(text, "Foo(i, s)", "C.Foo(int, [string])");
Test(text, "Foo(,)", "C.Foo(int, [string])");
Test(text, "Foo(int x = 42,)", "C.Foo(int, [string])");
Test(text, "Foo(int x = 42, y = 42)", "C.Foo(int, [string])");
Test(text, "Foo([attr] x = 42, y = 42)", "C.Foo(int, [string])");
Test(text, "Foo(int i, int b, char c)");
Test(text, "Foo(int, bool, char)");
Test(text, "Foo(i, s, c)");
Test(text, "Foo(__arglist)", "C.Foo(int)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void AccessorTests()
{
var text =
@"class C
{
int Property1 { get { return 42; } }
int Property2 { set { } }
int Property3 { get; set;}
}";
Test(text, "Property1", "C.Property1");
Test(text, "Property2", "C.Property2");
Test(text, "Property3", "C.Property3");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void NegativeTests()
{
var text =
@"using System.Runtime.CompilerServices;
abstract class C
{
public abstract void AbstractMethod(int a);
int Field;
delegate void Delegate();
event Delegate Event;
[IndexerName(""ABCD"")]
int this[int i] { get { return i; } }
void Foo() { }
void Foo(int x = 1, int y = 2) { }
~C() { }
}";
Test(text, "AbstractMethod");
Test(text, "Field");
Test(text, "Delegate");
Test(text, "Event");
Test(text, "this");
Test(text, "C.this[int]");
Test(text, "C.get_Item");
Test(text, "C.get_Item(i)");
Test(text, "C[i]");
Test(text, "ABCD");
Test(text, "C.ABCD(int)");
Test(text, "42");
Test(text, "Foo", "C.Foo()", "C.Foo([int], [int])"); // just making sure it would normally resolve before trying bad syntax
Test(text, "Foo Foo");
Test(text, "Foo()asdf");
Test(text, "Foo(),");
Test(text, "Foo(),f");
Test(text, "Foo().Foo");
Test(text, "Foo(");
Test(text, "(Foo");
Test(text, "Foo)");
Test(text, "(Foo)");
Test(text, "Foo(x = 42, y = 42)", "C.Foo([int], [int])"); // just making sure it would normally resolve before trying bad syntax
Test(text, "int x = 42");
Test(text, "Foo(int x = 42, y = 42");
Test(text, "C");
Test(text, "C.C");
Test(text, "~");
Test(text, "~C");
Test(text, "C.~C()");
Test(text, "");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestInstanceConstructors()
{
var text =
@"class C
{
public C() { }
}
class G<T>
{
public G() { }
~G() { }
}";
Test(text, "C", "C.C()");
Test(text, "C.C", "C.C()");
Test(text, "C.C()", "C.C()");
Test(text, "C()", "C.C()");
Test(text, "C<T>");
Test(text, "C<T>()");
Test(text, "C(int i)");
Test(text, "C(int)");
Test(text, "C(i)");
Test(text, "G", "G<T>.G()");
Test(text, "G()", "G<T>.G()");
Test(text, "G.G", "G<T>.G()");
Test(text, "G.G()", "G<T>.G()");
Test(text, "G<T>.G", "G<T>.G()");
Test(text, "G<t>.G()", "G<T>.G()");
Test(text, "G<T>");
Test(text, "G<T>()");
Test(text, "G.G<T>");
Test(text, ".ctor");
Test(text, ".ctor()");
Test(text, "C.ctor");
Test(text, "C.ctor()");
Test(text, "G.ctor");
Test(text, "G<T>.ctor()");
Test(text, "Finalize", "G<T>.~G()");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestStaticConstructors()
{
var text =
@"class C
{
static C()
{
}
}";
Test(text, "C", "C.C()");
Test(text, "C.C", "C.C()");
Test(text, "C.C()", "C.C()");
Test(text, "C()", "C.C()");
Test(text, "C<T>");
Test(text, "C<T>()");
Test(text, "C(int i)");
Test(text, "C(int)");
Test(text, "C(i)");
Test(text, "C.cctor");
Test(text, "C.cctor()");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestAllConstructors()
{
var text =
@"class C
{
static C()
{
}
public C(int i)
{
}
}";
Test(text, "C", "C.C(int)", "C.C()");
Test(text, "C.C", "C.C(int)", "C.C()");
Test(text, "C.C()", "C.C()");
Test(text, "C()", "C.C()");
Test(text, "C<T>");
Test(text, "C<T>()");
Test(text, "C(int i)", "C.C(int)");
Test(text, "C(int)", "C.C(int)");
Test(text, "C(i)", "C.C(int)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestPartialMethods()
{
var text =
@"partial class C
{
partial int M1();
partial void M2() { }
partial void M2();
partial int M3();
partial int M3(int x) { return 0; }
partial void M4() { }
}";
Test(text, "M1");
Test(text, "C.M1");
Test(text, "M2", "C.M2()");
Test(text, "M3", "C.M3(int)");
Test(text, "M3()");
Test(text, "M3(y)", "C.M3(int)");
Test(text, "M4", "C.M4()");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestLeadingAndTrailingText()
{
var text =
@"class C
{
void Foo() { };
}";
Test(text, "Foo;", "C.Foo()");
Test(text, "Foo();", "C.Foo()");
Test(text, " Foo;", "C.Foo()");
Test(text, " Foo;;");
Test(text, " Foo; ;");
Test(text, "Foo(); ", "C.Foo()");
Test(text, " Foo ( ) ; ", "C.Foo()");
Test(text, "Foo(); // comment", "C.Foo()");
Test(text, "/*comment*/Foo(/* params */); /* comment", "C.Foo()");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestEscapedKeywords()
{
var text =
@"struct @true { }
class @foreach
{
void where(@true @this) { }
void @false() { }
}";
Test(text, "where", "@foreach.where(@true)");
Test(text, "@where", "@foreach.where(@true)");
Test(text, "@foreach.where", "@foreach.where(@true)");
Test(text, "foreach.where");
Test(text, "@foreach.where(true)");
Test(text, "@foreach.where(@if)", "@foreach.where(@true)");
Test(text, "false");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestAliasQualifiedNames()
{
var text =
@"extern alias A
class C
{
void Foo(D d) { }
}";
Test(text, "A::Foo");
Test(text, "A::Foo(A::B)");
Test(text, "A::Foo(A::B)");
Test(text, "A::C.Foo");
Test(text, "C.Foo(A::Q)", "C.Foo(D)");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestNestedTypesAndNamespaces()
{
var text =
@"namespace N1
{
class C
{
void Foo() { }
}
namespace N2
{
class C { }
}
namespace N3
{
class D { }
}
namespace N4
{
class C
{
void Foo(double x) { }
class D
{
void Foo() { }
class E
{
void Foo() { }
}
}
}
}
namespace N5 { }
}";
Test(text, "Foo", "N1.N4.C.Foo(double)", "N1.N4.C.D.Foo()", "N1.N4.C.D.E.Foo()", "N1.C.Foo()");
Test(text, "C.Foo", "N1.N4.C.Foo(double)", "N1.C.Foo()");
Test(text, "D.Foo", "N1.N4.C.D.Foo()");
Test(text, "N1.N4.C.D.Foo", "N1.N4.C.D.Foo()");
Test(text, "N1.Foo");
Test(text, "N3.C.Foo");
Test(text, "N5.C.Foo");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)]
public void TestInterfaces()
{
var text =
@"interface I1
{
void Foo();
}
class C1 : I1
{
void I1.Foo() { }
}";
Test(text, "Foo", "C1.Foo()");
Test(text, "I1.Foo");
Test(text, "C1.Foo", "C1.Foo()");
Test(text, "C1.I1.Moo");
}
}
}
| |
//The MIT License(MIT)
//copyright(c) 2016 Alberto Rodriguez
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
using System.Collections.Generic;
using System.Linq;
using LiveCharts.Charts;
using LiveCharts.Configurations;
using LiveCharts.Definitions.Series;
using LiveCharts.Dtos;
using LiveCharts.Helpers;
namespace LiveCharts
{
/// <summary>
/// Creates a collection of chart values
/// </summary>
/// <typeparam name="T">Type to plot, notice you could need to configure the type.</typeparam>
public class ChartValues<T> : NoisyCollection<T>, IChartValues
{
#region Constructors
/// <summary>
/// Initializes a new instance of chart values
/// </summary>
public ChartValues()
{
Trackers = new Dictionary<ISeriesView, PointTracker>();
NoisyCollectionChanged += OnChanged;
}
/// <summary>
/// Initializes a new instance of chart values, with a given collection
/// </summary>
public ChartValues(IEnumerable<T> collection) : base(collection)
{
Trackers = new Dictionary<ISeriesView, PointTracker>();
NoisyCollectionChanged += OnChanged;
}
#endregion
#region Properties
private IPointEvaluator<T> DefaultConfiguration { get; set; }
private Dictionary<ISeriesView, PointTracker> Trackers { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Evaluates the limits in the chart values
/// </summary>
public void Initialize(ISeriesView seriesView)
{
var config = GetConfig(seriesView);
if (config == null) return;
var xMin = double.PositiveInfinity;
var xMax = double.NegativeInfinity;
var yMin = double.PositiveInfinity;
var yMax = double.NegativeInfinity;
var wMin = double.PositiveInfinity;
var wMax = double.NegativeInfinity;
var tracker = GetTracker(seriesView);
var cp = new ChartPoint();
var source = this.ToArray();
var ax = seriesView.Model.Chart.AxisX[seriesView.ScalesXAt];
var ay = seriesView.Model.Chart.AxisY[seriesView.ScalesYAt];
double fx = double.IsNaN(ax.MinValue) ? double.NegativeInfinity : ax.MinValue,
tx = double.IsNaN(ax.MaxValue) ? double.PositiveInfinity : ax.MaxValue,
fy = double.IsNaN(ay.MinValue) ? double.NegativeInfinity : ay.MinValue,
ty = double.IsNaN(ay.MaxValue) ? double.PositiveInfinity : ay.MaxValue;
var isHorizontal = seriesView.Model.SeriesOrientation == SeriesOrientation.Horizontal;
for (var index = 0; index < source.Length; index++)
{
var item = source[index];
config.Evaluate(index, item, cp);
if (isHorizontal)
{
if (cp.X < fx || cp.X > tx) continue;
}
else
{
if (cp.Y < fy || cp.Y > ty) continue;
}
if (seriesView is IFinancialSeriesView)
{
if (cp.X < xMin) xMin = cp.X;
if (cp.X > xMax) xMax = cp.X;
if (cp.Low < yMin) yMin = cp.Low;
if (cp.High > yMax) yMax = cp.High;
if (cp.Weight < wMin) wMin = cp.Weight;
if (cp.Weight > wMax) wMax = cp.Weight;
}
else if (seriesView is IScatterSeriesView || seriesView is IHeatSeriesView)
{
if (cp.X < xMin) xMin = cp.X;
if (cp.X > xMax) xMax = cp.X;
if (cp.Y < yMin) yMin = cp.Y;
if (cp.Y > yMax) yMax = cp.Y;
if (cp.Weight < wMin) wMin = cp.Weight;
if (cp.Weight > wMax) wMax = cp.Weight;
}
else
{
if (cp.X < xMin) xMin = cp.X;
if (cp.X > xMax) xMax = cp.X;
if (cp.Y < yMin) yMin = cp.Y;
if (cp.Y > yMax) yMax = cp.Y;
}
}
tracker.XLimit = new CoreLimit(double.IsInfinity(xMin)
? 0
: xMin, double.IsInfinity(yMin) ? 1 : xMax);
tracker.YLimit = new CoreLimit(double.IsInfinity(yMin)
? 0
: yMin, double.IsInfinity(yMax) ? 1 : yMax);
tracker.WLimit = new CoreLimit(double.IsInfinity(wMin)
? 0
: wMin, double.IsInfinity(wMax) ? 1 : wMax);
}
/// <summary>
/// Gets the current chart points in the view, the view is required as an argument, because an instance of IChartValues could hold many ISeriesView instances.
/// </summary>
/// <param name="seriesView">The series view</param>
/// <returns></returns>
public IEnumerable<ChartPoint> GetPoints(ISeriesView seriesView)
{
if (seriesView == null) yield break;
var config = GetConfig(seriesView);
var isClass = typeof(T).IsClass;
var isObservable = isClass && typeof(IObservableChartPoint).IsAssignableFrom(typeof(T));
var tracker = GetTracker(seriesView);
var gci = tracker.Gci;
var source = this.ToList(); //copy it, to prevent async issues
for (var index = 0; index < source.Count; index++)
{
var value = source[index];
if (isObservable)
{
var observable = (IObservableChartPoint)value;
if (observable != null)
{
observable.PointChanged -= ObservableOnPointChanged;
observable.PointChanged += ObservableOnPointChanged;
}
}
var cp = GetChartPoint(isClass, tracker, index, value);
cp.Gci = gci;
cp.Instance = value;
cp.Key = index;
cp.SeriesView = seriesView;
config.Evaluate(index, value, cp);
yield return cp;
}
}
/// <summary>
/// Initializes the garbage collector
/// </summary>
public void InitializeStep(ISeriesView series)
{
ValidateGarbageCollector(series);
GetTracker(series).Gci++;
}
/// <summary>
/// Collects the unnecessary values
/// </summary>
public void CollectGarbage(ISeriesView seriesView)
{
var isclass = typeof (T).IsClass;
var tracker = GetTracker(seriesView);
foreach (var garbage in GetGarbagePoints(seriesView).ToList())
{
if (garbage.View != null) //yes null, double.Nan Values, will generate null views.
garbage.View.RemoveFromView(seriesView.Model.Chart);
if (!isclass)
{
tracker.Indexed.Remove(garbage.Key);
}
else
{
tracker.Referenced.Remove(garbage.Instance);
}
}
}
/// <summary>
/// Gets series that owns the values
/// </summary>
/// <param name="view"></param>
/// <returns></returns>
public PointTracker GetTracker(ISeriesView view)
{
PointTracker tracker;
if (Trackers.TryGetValue(view, out tracker)) return tracker;
tracker = new PointTracker();
Trackers[view] = tracker;
return tracker;
}
#endregion
#region Privates
private IPointEvaluator<T> GetConfig(ISeriesView view)
{
//Trying to get the user defined configuration...
//series == null means that chart values are null, and LiveCharts
//could not set the Series Instance tho the current chart values...
if (view == null || view.Model.SeriesCollection == null) return null;
var config =
(view.Configuration ?? view.Model.SeriesCollection.Configuration) as IPointEvaluator<T>;
if (config != null) return config;
return DefaultConfiguration ??
(DefaultConfiguration =
ChartCore.Configurations.GetConfig<T>(view.Model.SeriesOrientation) as IPointEvaluator<T>);
}
private static ChartPoint GetChartPoint(bool isClass, PointTracker tracker, int index, T value)
{
ChartPoint cp;
if (!isClass)
{
if (tracker.Indexed.TryGetValue(index, out cp)) return cp;
cp = new ChartPoint
{
Instance = value,
Key = index
};
tracker.Indexed[index] = cp;
}
else
{
if (tracker.Referenced.TryGetValue(value, out cp)) return cp;
cp = new ChartPoint
{
Instance = value,
Key = index
};
tracker.Referenced[value] = cp;
}
return cp;
}
private void ObservableOnPointChanged()
{
Trackers.Keys.ForEach(x => x.Model.Chart.Updater.Run());
}
private IEnumerable<ChartPoint> GetGarbagePoints(ISeriesView view)
{
var tracker = GetTracker(view);
return tracker.Indexed.Values.Where(x => IsGarbage(x, tracker)).Concat(
tracker.Referenced.Values.Where(x => IsGarbage(x, tracker)));
}
private void ValidateGarbageCollector(ISeriesView view)
{
var tracker = GetTracker(view);
if (tracker.Gci != int.MaxValue) return;
tracker.Gci = 0;
foreach (var point in tracker.Indexed.Values.Concat(tracker.Referenced.Values))
point.Gci = 0;
}
private static bool IsGarbage(ChartPoint point, PointTracker tracker)
{
return point.Gci < tracker.Gci
|| double.IsNaN(point.X) || double.IsNaN(point.Y);
}
private void OnChanged(IEnumerable<T> oldItems, IEnumerable<T> newItems)
{
if (Trackers.Keys.All(x => x != null && x.Model.Chart != null))
Trackers.Keys.ForEach(x => x.Model.Chart.Updater.Run());
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Orleans.Configuration;
using Orleans.Providers.Azure;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Serialization.TypeSystem;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Orleans.Storage
{
/// <summary>
/// Simple storage provider for writing grain state data to Azure blob storage in JSON format.
/// </summary>
public class AzureBlobGrainStorage : IGrainStorage, ILifecycleParticipant<ISiloLifecycle>
{
private JsonSerializerSettings jsonSettings;
private BlobContainerClient container;
private ILogger logger;
private readonly string name;
private AzureBlobStorageOptions options;
private Serializer serializer;
private readonly IServiceProvider services;
/// <summary> Default constructor </summary>
public AzureBlobGrainStorage(
string name,
AzureBlobStorageOptions options,
Serializer serializer,
IServiceProvider services,
ILogger<AzureBlobGrainStorage> logger)
{
this.name = name;
this.options = options;
this.serializer = serializer;
this.services = services;
this.logger = logger;
}
/// <summary> Read state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ReadStateAsync"/>
public async Task ReadStateAsync(string grainType, GrainReference grainId, IGrainState grainState)
{
var blobName = GetBlobName(grainType, grainId);
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_Reading, "Reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
try
{
var blob = container.GetBlobClient(blobName);
byte[] contents;
try
{
using var stream = new MemoryStream();
var response = await blob.DownloadToAsync(stream).ConfigureAwait(false);
grainState.ETag = response.Headers.ETag.ToString();
contents = stream.ToArray();
}
catch (RequestFailedException exception) when (exception.IsBlobNotFound())
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_BlobNotFound, "BlobNotFound reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
return;
}
catch (RequestFailedException exception) when (exception.IsContainerNotFound())
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ContainerNotFound, "ContainerNotFound reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
return;
}
if (contents == null || contents.Length == 0)
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_BlobEmpty, "BlobEmpty reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
grainState.RecordExists = false;
return;
}
else
{
grainState.RecordExists = true;
}
var loadedState = this.ConvertFromStorageFormat(contents, grainState.Type);
grainState.State = loadedState ?? Activator.CreateInstance(grainState.Type);
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_DataRead, "Read: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
}
catch (Exception ex)
{
logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_ReadError,
string.Format("Error reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message),
ex);
throw;
}
}
private static string GetBlobName(string grainType, GrainReference grainId)
{
return string.Format("{0}-{1}.json", grainType, grainId.ToKeyString());
}
/// <summary> Write state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.WriteStateAsync"/>
public async Task WriteStateAsync(string grainType, GrainReference grainId, IGrainState grainState)
{
var blobName = GetBlobName(grainType, grainId);
try
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_Writing, "Writing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
var (contents, mimeType) = ConvertToStorageFormat(grainState.State);
var blob = container.GetBlobClient(blobName);
await WriteStateAndCreateContainerIfNotExists(grainType, grainId, grainState, contents, mimeType, blob);
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_DataRead, "Written: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
}
catch (Exception ex)
{
logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_WriteError,
string.Format("Error writing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message),
ex);
throw;
}
}
/// <summary> Clear / Delete state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ClearStateAsync"/>
public async Task ClearStateAsync(string grainType, GrainReference grainId, IGrainState grainState)
{
var blobName = GetBlobName(grainType, grainId);
try
{
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ClearingData, "Clearing: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name);
var blob = container.GetBlobClient(blobName);
await DoOptimisticUpdate(() => blob.DeleteIfExistsAsync(DeleteSnapshotsOption.None, conditions: new BlobRequestConditions { IfMatch = new ETag(grainState.ETag) }),
blob, grainState.ETag).ConfigureAwait(false);
grainState.ETag = null;
grainState.RecordExists = false;
if (this.logger.IsEnabled(LogLevel.Trace))
{
var properties = await blob.GetPropertiesAsync();
this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Cleared, "Cleared: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4}", grainType, grainId, properties.Value.ETag, blobName, container.Name);
}
}
catch (Exception ex)
{
logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_ClearError,
string.Format("Error clearing: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message),
ex);
throw;
}
}
private async Task WriteStateAndCreateContainerIfNotExists(string grainType, GrainReference grainId, IGrainState grainState, byte[] contents, string mimeType, BlobClient blob)
{
try
{
using var stream = new MemoryStream(contents);
var result = await DoOptimisticUpdate(() => blob.UploadAsync(stream,
conditions: new BlobRequestConditions { IfMatch = grainState.ETag != null ? new ETag(grainState.ETag) : (ETag?)null },
httpHeaders: new BlobHttpHeaders { ContentType = mimeType }),
blob, grainState.ETag).ConfigureAwait(false);
grainState.ETag = result.Value.ETag.ToString();
grainState.RecordExists = true;
}
catch (RequestFailedException exception) when (exception.IsContainerNotFound())
{
// if the container does not exist, create it, and make another attempt
if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ContainerNotFound, "Creating container: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blob.Name, container.Name);
await container.CreateIfNotExistsAsync().ConfigureAwait(false);
await WriteStateAndCreateContainerIfNotExists(grainType, grainId, grainState, contents, mimeType, blob).ConfigureAwait(false);
}
}
private static async Task<TResult> DoOptimisticUpdate<TResult>(Func<Task<TResult>> updateOperation, BlobClient blob, string currentETag)
{
try
{
return await updateOperation.Invoke().ConfigureAwait(false);
}
catch (RequestFailedException ex) when (ex.IsPreconditionFailed() || ex.IsConflict())
{
throw new InconsistentStateException($"Blob storage condition not Satisfied. BlobName: {blob.Name}, Container: {blob.BlobContainerName}, CurrentETag: {currentETag}", "Unknown", currentETag, ex);
}
}
public void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe(OptionFormattingUtilities.Name<AzureBlobGrainStorage>(this.name), this.options.InitStage, Init);
}
/// <summary> Initialization function for this storage provider. </summary>
private async Task Init(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
try
{
this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureTableGrainStorage initializing: {this.options.ToString()}");
this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableGrainStorage is using DataConnectionString: {0}", ConfigUtilities.RedactConnectionStringInfo(this.options.ConnectionString));
this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.services), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling);
this.options.ConfigureJsonSerializerSettings?.Invoke(this.jsonSettings);
var client = this.options.ServiceUri != null ? new BlobServiceClient(this.options.ServiceUri, this.options.TokenCredential) : new BlobServiceClient(this.options.ConnectionString);
container = client.GetBlobContainerClient(this.options.ContainerName);
await container.CreateIfNotExistsAsync().ConfigureAwait(false);
stopWatch.Stop();
this.logger.LogInformation((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds.");
}
catch (Exception ex)
{
stopWatch.Stop();
this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex);
throw;
}
}
/// <summary>
/// Serialize to the configured storage format, either binary or JSON.
/// </summary>
/// <param name="grainState">The grain state data to be serialized</param>
/// <remarks>
/// See:
/// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
/// for more on the JSON serializer.
/// </remarks>
private (byte[], string) ConvertToStorageFormat(object grainState)
{
byte[] data;
string mimeType;
if (this.options.UseJson)
{
data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(grainState, this.jsonSettings));
mimeType = "application/json";
}
else
{
data = this.serializer.SerializeToArray(grainState);
mimeType = "application/octet-stream";
}
return (data, mimeType);
}
/// <summary>
/// Deserialize from the configured storage format, either binary or JSON.
/// </summary>
/// <param name="contents">The serialized contents.</param>
/// <param name="stateType">The state type.</param>
/// <remarks>
/// See:
/// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
/// for more on the JSON serializer.
/// </remarks>
private object ConvertFromStorageFormat(byte[] contents, Type stateType)
{
object result;
if (this.options.UseJson)
{
var str = Encoding.UTF8.GetString(contents);
result = JsonConvert.DeserializeObject(str, stateType, this.jsonSettings);
}
else
{
result = this.serializer.Deserialize<object>(contents);
}
return result;
}
}
public static class AzureBlobGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
var optionsMonitor = services.GetRequiredService<IOptionsMonitor<AzureBlobStorageOptions>>();
return ActivatorUtilities.CreateInstance<AzureBlobGrainStorage>(services, name, optionsMonitor.Get(name));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;
using Microsoft.VisualStudio.Debugger.Interop;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using MICore;
using System.Globalization;
using Microsoft.Win32;
namespace Microsoft.MIDebugEngine
{
// AD7Engine is the primary entrypoint object for the sample engine.
//
// It implements:
//
// IDebugEngine2: This interface represents a debug engine (DE). It is used to manage various aspects of a debugging session,
// from creating breakpoints to setting and clearing exceptions.
//
// IDebugEngineLaunch2: Used by a debug engine (DE) to launch and terminate programs.
//
// IDebugProgram3: This interface represents a program that is running in a process. Since this engine only debugs one process at a time and each
// process only contains one program, it is implemented on the engine.
//
// IDebugEngineProgram2: This interface provides simultanious debugging of multiple threads in a debuggee.
[ComVisible(true)]
[Guid("9DA963FB-2C68-41BE-B6E7-1B560A9FB5BD")]
sealed public class AD7Engine : IDebugEngine2, IDebugEngineLaunch2, IDebugProgram3, IDebugEngineProgram2, IDebugMemoryBytes2, IDebugEngine110
{
// used to send events to the debugger. Some examples of these events are thread create, exception thrown, module load.
private EngineCallback _engineCallback;
// The sample debug engine is split into two parts: a managed front-end and a mixed-mode back end. DebuggedProcess is the primary
// object in the back-end. AD7Engine holds a reference to it.
private DebuggedProcess _debuggedProcess;
// This object facilitates calling from this thread into the worker thread of the engine. This is necessary because the Win32 debugging
// api requires thread affinity to several operations.
private WorkerThread _pollThread;
// This object manages breakpoints in the sample engine.
private BreakpointManager _breakpointManager;
// A unique identifier for the program being debugged.
private Guid _ad7ProgramId;
private string _registryRoot;
private IDebugSettingsCallback110 _settingsCallback;
public AD7Engine()
{
//This call is to initialize the global service provider while we are still on the main thread.
//Do not remove this this, even though the return value goes unused.
var globalProvider = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider;
_breakpointManager = new BreakpointManager(this);
}
~AD7Engine()
{
if (_pollThread != null)
{
_pollThread.Close();
}
}
internal EngineCallback Callback
{
get { return _engineCallback; }
}
internal DebuggedProcess DebuggedProcess
{
get { return _debuggedProcess; }
}
internal uint CurrentRadix()
{
uint radix;
if (_settingsCallback != null && _settingsCallback.GetDisplayRadix(out radix) == Constants.S_OK)
{
if (radix != _debuggedProcess.MICommandFactory.Radix)
{
_debuggedProcess.WorkerThread.RunOperation(async () =>
{
await _debuggedProcess.MICommandFactory.SetRadix(radix);
});
}
}
return _debuggedProcess.MICommandFactory.Radix;
}
internal bool ProgramCreateEventSent
{
get;
private set;
}
public string GetAddressDescription(ulong ip)
{
return EngineUtils.GetAddressDescription(_debuggedProcess, ip);
}
public object GetMetric(string metric)
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(_registryRoot + @"\AD7Metrics\Engine\" + EngineConstants.EngineId.ToUpper(CultureInfo.InvariantCulture)))
{
if (key == null)
{
return null;
}
return key.GetValue(metric);
}
}
#region IDebugEngine2 Members
// Attach the debug engine to a program.
int IDebugEngine2.Attach(IDebugProgram2[] rgpPrograms, IDebugProgramNode2[] rgpProgramNodes, uint celtPrograms, IDebugEventCallback2 ad7Callback, enum_ATTACH_REASON dwReason)
{
Debug.Assert(_ad7ProgramId == Guid.Empty);
if (celtPrograms != 1)
{
Debug.Fail("SampleEngine only expects to see one program in a process");
throw new ArgumentException();
}
try
{
AD_PROCESS_ID processId = EngineUtils.GetProcessId(rgpPrograms[0]);
EngineUtils.RequireOk(rgpPrograms[0].GetProgramId(out _ad7ProgramId));
// Attach can either be called to attach to a new process, or to complete an attach
// to a launched process
if (_pollThread == null)
{
// We are being asked to debug a process when we currently aren't debugging anything
_pollThread = new WorkerThread();
_engineCallback = new EngineCallback(this, ad7Callback);
// Complete the win32 attach on the poll thread
_pollThread.RunOperation(new Operation(delegate
{
throw new NotImplementedException();
}));
_pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError;
}
else
{
if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id))
{
Debug.Fail("Asked to attach to a process while we are debugging");
return Constants.E_FAIL;
}
}
AD7EngineCreateEvent.Send(this);
AD7ProgramCreateEvent.Send(this);
this.ProgramCreateEventSent = true;
return Constants.S_OK;
}
catch (MIException e)
{
return e.HResult;
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
// Requests that all programs being debugged by this DE stop execution the next time one of their threads attempts to run.
// This is normally called in response to the user clicking on the pause button in the debugger.
// When the break is complete, an AsyncBreakComplete event will be sent back to the debugger.
int IDebugEngine2.CauseBreak()
{
return ((IDebugProgram2)this).CauseBreak();
}
// Called by the SDM to indicate that a synchronous debug event, previously sent by the DE to the SDM,
// was received and processed. The only event the sample engine sends in this fashion is Program Destroy.
// It responds to that event by shutting down the engine.
int IDebugEngine2.ContinueFromSynchronousEvent(IDebugEvent2 eventObject)
{
try
{
if (eventObject is AD7ProgramCreateEvent)
{
Exception exception = null;
try
{
// At this point breakpoints and exception settings have been sent down, so we can resume the target
_pollThread.RunOperation(() =>
{
return _debuggedProcess.ResumeFromLaunch();
});
}
catch (Exception e)
{
exception = e;
// Return from the catch block so that we can let the exception unwind - the stack can get kind of big
}
if (exception != null)
{
// If something goes wrong, report the error and then stop debugging. The SDM will drop errors
// from ContinueFromSynchronousEvent, so we want to deal with them ourself.
SendStartDebuggingError(exception);
_debuggedProcess.Terminate();
}
return Constants.S_OK;
}
else if (eventObject is AD7ProgramDestroyEvent)
{
Dispose();
}
else
{
Debug.Fail("Unknown syncronious event");
}
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return Constants.S_OK;
}
private void Dispose()
{
WorkerThread pollThread = _pollThread;
DebuggedProcess debuggedProcess = _debuggedProcess;
_engineCallback = null;
_debuggedProcess = null;
_pollThread = null;
_ad7ProgramId = Guid.Empty;
if(debuggedProcess != null)
debuggedProcess.Close();
if(pollThread != null)
pollThread.Close();
}
// Creates a pending breakpoint in the engine. A pending breakpoint is contains all the information needed to bind a breakpoint to
// a location in the debuggee.
int IDebugEngine2.CreatePendingBreakpoint(IDebugBreakpointRequest2 pBPRequest, out IDebugPendingBreakpoint2 ppPendingBP)
{
Debug.Assert(_breakpointManager != null);
ppPendingBP = null;
try
{
_breakpointManager.CreatePendingBreakpoint(pBPRequest, out ppPendingBP);
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return Constants.S_OK;
}
// Informs a DE that the program specified has been atypically terminated and that the DE should
// clean up all references to the program and send a program destroy event.
int IDebugEngine2.DestroyProgram(IDebugProgram2 pProgram)
{
// Tell the SDM that the engine knows that the program is exiting, and that the
// engine will send a program destroy. We do this because the Win32 debug api will always
// tell us that the process exited, and otherwise we have a race condition.
return (AD7_HRESULT.E_PROGRAM_DESTROY_PENDING);
}
// Gets the GUID of the DE.
int IDebugEngine2.GetEngineId(out Guid guidEngine)
{
guidEngine = new Guid(EngineConstants.EngineId);
return Constants.S_OK;
}
// Removes the list of exceptions the IDE has set for a particular run-time architecture or language.
int IDebugEngine2.RemoveAllSetExceptions(ref Guid guidType)
{
if(_debuggedProcess != null)
_debuggedProcess.ExceptionManager.RemoveAllSetExceptions(guidType);
return Constants.S_OK;
}
// Removes the specified exception so it is no longer handled by the debug engine.
// The sample engine does not support exceptions in the debuggee so this method is not actually implemented.
int IDebugEngine2.RemoveSetException(EXCEPTION_INFO[] pException)
{
if(_debuggedProcess != null)
_debuggedProcess.ExceptionManager.RemoveSetException(ref pException[0]);
return Constants.S_OK;
}
// Specifies how the DE should handle a given exception.
// The sample engine does not support exceptions in the debuggee so this method is not actually implemented.
int IDebugEngine2.SetException(EXCEPTION_INFO[] pException)
{
if(_debuggedProcess != null)
_debuggedProcess.ExceptionManager.SetException(ref pException[0]);
return Constants.S_OK;
}
// Sets the locale of the DE.
// This method is called by the session debug manager (SDM) to propagate the locale settings of the IDE so that
// strings returned by the DE are properly localized. The sample engine is not localized so this is not implemented.
int IDebugEngine2.SetLocale(ushort wLangID)
{
return Constants.S_OK;
}
// A metric is a registry value used to change a debug engine's behavior or to advertise supported functionality.
// This method can forward the call to the appropriate form of the Debugging SDK Helpers function, SetMetric.
int IDebugEngine2.SetMetric(string pszMetric, object varValue)
{
// The sample engine does not need to understand any metric settings.
return Constants.S_OK;
}
// Sets the registry root currently in use by the DE. Different installations of Visual Studio can change where their registry information is stored
// This allows the debugger to tell the engine where that location is.
int IDebugEngine2.SetRegistryRoot(string registryRoot)
{
_registryRoot = registryRoot;
Logger.EnsureInitialized(registryRoot);
return Constants.S_OK;
}
#endregion
#region IDebugEngineLaunch2 Members
// Determines if a process can be terminated.
int IDebugEngineLaunch2.CanTerminateProcess(IDebugProcess2 process)
{
Debug.Assert(_pollThread != null);
Debug.Assert(_engineCallback != null);
Debug.Assert(_debuggedProcess != null);
try
{
AD_PROCESS_ID processId = EngineUtils.GetProcessId(process);
if (EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id))
{
return Constants.S_OK;
}
else
{
return Constants.S_FALSE;
}
}
catch (MIException e)
{
return e.HResult;
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
// Launches a process by means of the debug engine.
// Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger
// to the suspended program. However, there are circumstances in which the debug engine may need to launch a program
// (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language),
// in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method
// The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state.
int IDebugEngineLaunch2.LaunchSuspended(string pszServer, IDebugPort2 port, string exe, string args, string dir, string env, string options, enum_LAUNCH_FLAGS launchFlags, uint hStdInput, uint hStdOutput, uint hStdError, IDebugEventCallback2 ad7Callback, out IDebugProcess2 process)
{
Debug.Assert(_pollThread == null);
Debug.Assert(_engineCallback == null);
Debug.Assert(_debuggedProcess == null);
Debug.Assert(_ad7ProgramId == Guid.Empty);
process = null;
_engineCallback = new EngineCallback(this, ad7Callback);
Exception exception;
try
{
// Note: LaunchOptions.GetInstance can be an expensive operation and may push a wait message loop
LaunchOptions launchOptions = LaunchOptions.GetInstance(_registryRoot, exe, args, dir, options, _engineCallback, TargetEngine.Native);
// We are being asked to debug a process when we currently aren't debugging anything
_pollThread = new WorkerThread();
var cancellationTokenSource = new CancellationTokenSource();
using (cancellationTokenSource)
{
_pollThread.RunOperation(ResourceStrings.InitializingDebugger, cancellationTokenSource, (MICore.WaitLoop waitLoop) =>
{
try
{
_debuggedProcess = new DebuggedProcess(true, launchOptions, _engineCallback, _pollThread, _breakpointManager, this, _registryRoot);
}
finally
{
// If there is an exception from the DebuggeedProcess constructor, it is our responsibility to dispose the DeviceAppLauncher,
// otherwise the DebuggedProcess object takes ownership.
if (_debuggedProcess == null && launchOptions.DeviceAppLauncher != null)
{
launchOptions.DeviceAppLauncher.Dispose();
}
}
_pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError;
return _debuggedProcess.Initialize(waitLoop, cancellationTokenSource.Token);
});
}
EngineUtils.RequireOk(port.GetProcess(_debuggedProcess.Id, out process));
return Constants.S_OK;
}
catch (Exception e)
{
exception = e;
// Return from the catch block so that we can let the exception unwind - the stack can get kind of big
}
// If we just return the exception as an HRESULT, we will loose our message, so we instead send up an error event, and then
// return E_ABORT.
Logger.Flush();
SendStartDebuggingError(exception);
Dispose();
return Constants.E_ABORT;
}
private void SendStartDebuggingError(Exception exception)
{
if (exception is OperationCanceledException)
{
return; // don't show a message in this case
}
string description = EngineUtils.GetExceptionDescription(exception);
string message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_UnableToStartDebugging, description);
var initializationException = exception as MIDebuggerInitializeFailedException;
if (initializationException != null)
{
string outputMessage = string.Join("\r\n", initializationException.OutputLines) + "\r\n";
// NOTE: We can't write to the output window by sending an AD7 event because this may be called before the session create event
VsOutputWindow.WriteLaunchError(outputMessage);
}
_engineCallback.OnErrorImmediate(message);
}
// Resume a process launched by IDebugEngineLaunch2.LaunchSuspended
int IDebugEngineLaunch2.ResumeProcess(IDebugProcess2 process)
{
Debug.Assert(_pollThread != null);
Debug.Assert(_engineCallback != null);
Debug.Assert(_debuggedProcess != null);
Debug.Assert(_ad7ProgramId == Guid.Empty);
try
{
AD_PROCESS_ID processId = EngineUtils.GetProcessId(process);
if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id))
{
return Constants.S_FALSE;
}
// Send a program node to the SDM. This will cause the SDM to turn around and call IDebugEngine2.Attach
// which will complete the hookup with AD7
IDebugPort2 port;
EngineUtils.RequireOk(process.GetPort(out port));
IDebugDefaultPort2 defaultPort = (IDebugDefaultPort2)port;
IDebugPortNotify2 portNotify;
EngineUtils.RequireOk(defaultPort.GetPortNotify(out portNotify));
EngineUtils.RequireOk(portNotify.AddProgramNode(new AD7ProgramNode(_debuggedProcess.Id)));
if (_ad7ProgramId == Guid.Empty)
{
Debug.Fail("Unexpected problem -- IDebugEngine2.Attach wasn't called");
return Constants.E_FAIL;
}
// NOTE: We wait for the program create event to be continued before we really resume the process
return Constants.S_OK;
}
catch (MIException e)
{
return e.HResult;
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
// This function is used to terminate a process that the SampleEngine launched
// The debugger will call IDebugEngineLaunch2::CanTerminateProcess before calling this method.
int IDebugEngineLaunch2.TerminateProcess(IDebugProcess2 process)
{
Debug.Assert(_pollThread != null);
Debug.Assert(_engineCallback != null);
Debug.Assert(_debuggedProcess != null);
try
{
AD_PROCESS_ID processId = EngineUtils.GetProcessId(process);
if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id))
{
return Constants.S_FALSE;
}
_pollThread.RunOperation(() => _debuggedProcess.CmdTerminate());
_debuggedProcess.Terminate();
return Constants.S_OK;
}
catch (MIException e)
{
return e.HResult;
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
#endregion
#region IDebugProgram2 Members
// Determines if a debug engine (DE) can detach from the program.
public int CanDetach()
{
// The sample engine always supports detach
return Constants.S_OK;
}
// The debugger calls CauseBreak when the user clicks on the pause button in VS. The debugger should respond by entering
// breakmode.
public int CauseBreak()
{
_pollThread.RunOperation(() => _debuggedProcess.CmdBreak());
return Constants.S_OK;
}
// Continue is called from the SDM when it wants execution to continue in the debugee
// but have stepping state remain. An example is when a tracepoint is executed,
// and the debugger does not want to actually enter break mode.
public int Continue(IDebugThread2 pThread)
{
AD7Thread thread = (AD7Thread)pThread;
_pollThread.RunOperation(() => _debuggedProcess.Continue(thread.GetDebuggedThread()));
return Constants.S_OK;
}
// Detach is called when debugging is stopped and the process was attached to (as opposed to launched)
// or when one of the Detach commands are executed in the UI.
public int Detach()
{
_breakpointManager.ClearBoundBreakpoints();
_pollThread.RunOperation(new Operation(delegate
{
_debuggedProcess.Detach();
}));
return Constants.S_OK;
}
// Enumerates the code contexts for a given position in a source file.
public int EnumCodeContexts(IDebugDocumentPosition2 docPosition, out IEnumDebugCodeContexts2 ppEnum)
{
string documentName;
EngineUtils.CheckOk(docPosition.GetFileName(out documentName));
// Get the location in the document
TEXT_POSITION[] startPosition = new TEXT_POSITION[1];
TEXT_POSITION[] endPosition = new TEXT_POSITION[1];
EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition));
List<IDebugCodeContext2> codeContexts = new List<IDebugCodeContext2>();
List<ulong> addresses = null;
uint line = startPosition[0].dwLine + 1;
_debuggedProcess.WorkerThread.RunOperation(async () =>
{
addresses = await DebuggedProcess.StartAddressesForLine(documentName, line);
});
if (addresses != null && addresses.Count > 0)
{
foreach (var a in addresses)
{
var codeCxt = new AD7MemoryAddress(this, a, null);
TEXT_POSITION pos;
pos.dwLine = line;
pos.dwColumn = 0;
MITextPosition textPosition = new MITextPosition(documentName, pos, pos);
codeCxt.SetDocumentContext(new AD7DocumentContext(textPosition, codeCxt));
codeContexts.Add(codeCxt);
}
if (codeContexts.Count > 0)
{
ppEnum = new AD7CodeContextEnum(codeContexts.ToArray());
return Constants.S_OK;
}
}
ppEnum = null;
return Constants.E_FAIL;
}
// EnumCodePaths is used for the step-into specific feature -- right click on the current statment and decide which
// function to step into. This is not something that the SampleEngine supports.
public int EnumCodePaths(string hint, IDebugCodeContext2 start, IDebugStackFrame2 frame, int fSource, out IEnumCodePaths2 pathEnum, out IDebugCodeContext2 safetyContext)
{
pathEnum = null;
safetyContext = null;
return Constants.E_NOTIMPL;
}
// EnumModules is called by the debugger when it needs to enumerate the modules in the program.
public int EnumModules(out IEnumDebugModules2 ppEnum)
{
DebuggedModule[] modules = _debuggedProcess.GetModules();
AD7Module[] moduleObjects = new AD7Module[modules.Length];
for (int i = 0; i < modules.Length; i++)
{
moduleObjects[i] = new AD7Module(modules[i], _debuggedProcess);
}
ppEnum = new Microsoft.MIDebugEngine.AD7ModuleEnum(moduleObjects);
return Constants.S_OK;
}
// EnumThreads is called by the debugger when it needs to enumerate the threads in the program.
public int EnumThreads(out IEnumDebugThreads2 ppEnum)
{
DebuggedThread[] threads = null;
DebuggedProcess.WorkerThread.RunOperation(async () => threads = await DebuggedProcess.ThreadCache.GetThreads());
AD7Thread[] threadObjects = new AD7Thread[threads.Length];
for (int i = 0; i < threads.Length; i++)
{
Debug.Assert(threads[i].Client != null);
threadObjects[i] = (AD7Thread)threads[i].Client;
}
ppEnum = new Microsoft.MIDebugEngine.AD7ThreadEnum(threadObjects);
return Constants.S_OK;
}
// The properties returned by this method are specific to the program. If the program needs to return more than one property,
// then the IDebugProperty2 object returned by this method is a container of additional properties and calling the
// IDebugProperty2::EnumChildren method returns a list of all properties.
// A program may expose any number and type of additional properties that can be described through the IDebugProperty2 interface.
// An IDE might display the additional program properties through a generic property browser user interface.
// The sample engine does not support this
public int GetDebugProperty(out IDebugProperty2 ppProperty)
{
throw new NotImplementedException();
}
// The debugger calls this when it needs to obtain the IDebugDisassemblyStream2 for a particular code-context.
// The sample engine does not support dissassembly so it returns E_NOTIMPL
// In order for this to be called, the Disassembly capability must be set in the registry for this Engine
public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 codeContext, out IDebugDisassemblyStream2 disassemblyStream)
{
disassemblyStream = new AD7DisassemblyStream(dwScope, codeContext);
return Constants.S_OK;
}
// This method gets the Edit and Continue (ENC) update for this program. A custom debug engine always returns E_NOTIMPL
public int GetENCUpdate(out object update)
{
// The sample engine does not participate in managed edit & continue.
update = null;
return Constants.S_OK;
}
// Gets the name and identifier of the debug engine (DE) running this program.
public int GetEngineInfo(out string engineName, out Guid engineGuid)
{
engineName = ResourceStrings.EngineName;
engineGuid = new Guid(EngineConstants.EngineId);
return Constants.S_OK;
}
// The memory bytes as represented by the IDebugMemoryBytes2 object is for the program's image in memory and not any memory
// that was allocated when the program was executed.
public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes)
{
ppMemoryBytes = this;
return Constants.S_OK;
}
// Gets the name of the program.
// The name returned by this method is always a friendly, user-displayable name that describes the program.
public int GetName(out string programName)
{
// The Sample engine uses default transport and doesn't need to customize the name of the program,
// so return NULL.
programName = null;
return Constants.S_OK;
}
// Gets a GUID for this program. A debug engine (DE) must return the program identifier originally passed to the IDebugProgramNodeAttach2::OnAttach
// or IDebugEngine2::Attach methods. This allows identification of the program across debugger components.
public int GetProgramId(out Guid guidProgramId)
{
Debug.Assert(_ad7ProgramId != Guid.Empty);
guidProgramId = _ad7ProgramId;
return Constants.S_OK;
}
public int Step(IDebugThread2 pThread, enum_STEPKIND kind, enum_STEPUNIT unit)
{
AD7Thread thread = (AD7Thread)pThread;
_debuggedProcess.WorkerThread.RunOperation(() => _debuggedProcess.Step(thread.GetDebuggedThread().Id, kind, unit));
return Constants.S_OK;
}
// Terminates the program.
public int Terminate()
{
// Because the sample engine is a native debugger, it implements IDebugEngineLaunch2, and will terminate
// the process in IDebugEngineLaunch2.TerminateProcess
return Constants.S_OK;
}
// Writes a dump to a file.
public int WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl)
{
// The sample debugger does not support creating or reading mini-dumps.
return Constants.E_NOTIMPL;
}
#endregion
#region IDebugProgram3 Members
// ExecuteOnThread is called when the SDM wants execution to continue and have
// stepping state cleared.
public int ExecuteOnThread(IDebugThread2 pThread)
{
AD7Thread thread = (AD7Thread)pThread;
_pollThread.RunOperation(() => _debuggedProcess.Execute(thread.GetDebuggedThread()));
return Constants.S_OK;
}
#endregion
#region IDebugEngineProgram2 Members
// Stops all threads running in this program.
// This method is called when this program is being debugged in a multi-program environment. When a stopping event from some other program
// is received, this method is called on this program. The implementation of this method should be asynchronous;
// that is, not all threads should be required to be stopped before this method returns. The implementation of this method may be
// as simple as calling the IDebugProgram2::CauseBreak method on this program.
//
// The sample engine only supports debugging native applications and therefore only has one program per-process
public int Stop()
{
throw new NotImplementedException();
}
// WatchForExpressionEvaluationOnThread is used to cooperate between two different engines debugging
// the same process. The sample engine doesn't cooperate with other engines, so it has nothing
// to do here.
public int WatchForExpressionEvaluationOnThread(IDebugProgram2 pOriginatingProgram, uint dwTid, uint dwEvalFlags, IDebugEventCallback2 pExprCallback, int fWatch)
{
return Constants.S_OK;
}
// WatchForThreadStep is used to cooperate between two different engines debugging the same process.
// The sample engine doesn't cooperate with other engines, so it has nothing to do here.
public int WatchForThreadStep(IDebugProgram2 pOriginatingProgram, uint dwTid, int fWatch, uint dwFrame)
{
return Constants.S_OK;
}
#endregion
#region IDebugMemoryBytes2 Members
public int GetSize(out ulong pqwSize)
{
throw new NotImplementedException();
}
public int ReadAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory, out uint pdwRead, ref uint pdwUnreadable)
{
pdwUnreadable = 0;
AD7MemoryAddress addr = (AD7MemoryAddress)pStartContext;
uint bytesRead = 0;
int hr = Constants.S_OK;
DebuggedProcess.WorkerThread.RunOperation(async () =>
{
bytesRead = await DebuggedProcess.ReadProcessMemory(addr.Address, dwCount, rgbMemory);
});
if (bytesRead == uint.MaxValue)
{
bytesRead = 0;
}
if (bytesRead < dwCount) // copied from Concord
{
// assume 4096 sized pages: ARM has 4K or 64K pages
uint pageSize = 4096;
ulong readEnd = addr.Address + bytesRead;
ulong nextPageStart = (readEnd + pageSize - 1) / pageSize * pageSize;
if (nextPageStart == readEnd)
{
nextPageStart = readEnd + pageSize;
}
// if we have crossed a page boundry - Unreadable = bytes till end of page
uint maxUnreadable = dwCount - bytesRead;
if (addr.Address + dwCount > nextPageStart)
{
pdwUnreadable = (uint)Math.Min(maxUnreadable, nextPageStart - readEnd);
}
else
{
pdwUnreadable = (uint)Math.Min(maxUnreadable, pageSize);
}
}
pdwRead = bytesRead;
return hr;
}
public int WriteAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory)
{
throw new NotImplementedException();
}
#endregion
#region IDebugEngine110
public int SetMainThreadSettingsCallback110(IDebugSettingsCallback110 pCallback)
{
_settingsCallback = pCallback;
return Constants.S_OK;
}
#endregion
#region Deprecated interface methods
// These methods are not called by the Visual Studio debugger, so they don't need to be implemented
int IDebugEngine2.EnumPrograms(out IEnumDebugPrograms2 programs)
{
Debug.Fail("This function is not called by the debugger");
programs = null;
return Constants.E_NOTIMPL;
}
public int Attach(IDebugEventCallback2 pCallback)
{
Debug.Fail("This function is not called by the debugger");
return Constants.E_NOTIMPL;
}
public int GetProcess(out IDebugProcess2 process)
{
Debug.Fail("This function is not called by the debugger");
process = null;
return Constants.E_NOTIMPL;
}
public int Execute()
{
Debug.Fail("This function is not called by the debugger.");
return Constants.E_NOTIMPL;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Security.Tests
{
public class ServerAsyncAuthenticateTest : IDisposable
{
private readonly ITestOutputHelper _log;
private readonly ITestOutputHelper _logVerbose;
private readonly X509Certificate2 _serverCertificate;
public ServerAsyncAuthenticateTest()
{
_log = TestLogging.GetInstance();
_logVerbose = VerboseTestLogging.GetInstance();
_serverCertificate = Configuration.Certificates.GetServerCertificate();
}
public void Dispose()
{
_serverCertificate.Dispose();
}
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_EachSupportedProtocol_Success(SslProtocols protocol)
{
await ServerAsyncSslHelper(protocol, protocol);
}
[Theory]
[ClassData(typeof(SslProtocolSupport.UnsupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_EachServerUnsupportedProtocol_Fail(SslProtocols protocol)
{
await Assert.ThrowsAsync<NotSupportedException>(() =>
{
return ServerAsyncSslHelper(
SslProtocolSupport.SupportedSslProtocols,
protocol,
expectedToFail: true);
});
}
[ActiveIssue(11170, Xunit.PlatformID.OSX)]
[Theory]
[MemberData(nameof(ProtocolMismatchData))]
public async Task ServerAsyncAuthenticate_MismatchProtocols_Fails(
SslProtocols serverProtocol,
SslProtocols clientProtocol,
Type expectedException)
{
await Assert.ThrowsAsync(
expectedException,
() =>
{
return ServerAsyncSslHelper(
serverProtocol,
clientProtocol,
expectedToFail: true);
});
}
[Fact]
public async Task ServerAsyncAuthenticate_UnsuportedAllServer_Fail()
{
await Assert.ThrowsAsync<NotSupportedException>(() =>
{
return ServerAsyncSslHelper(
SslProtocolSupport.SupportedSslProtocols,
SslProtocolSupport.UnsupportedSslProtocols,
expectedToFail: true);
});
}
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_AllClientVsIndividualServerSupportedProtocols_Success(
SslProtocols serverProtocol)
{
await ServerAsyncSslHelper(SslProtocolSupport.SupportedSslProtocols, serverProtocol);
}
private static IEnumerable<object[]> ProtocolMismatchData()
{
yield return new object[] { SslProtocols.Tls, SslProtocols.Tls11, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls, typeof(TimeoutException) };
yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls12, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls, typeof(TimeoutException) };
yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls11, typeof(TimeoutException) };
}
#region Helpers
private async Task ServerAsyncSslHelper(
SslProtocols clientSslProtocols,
SslProtocols serverSslProtocols,
bool expectedToFail = false)
{
_log.WriteLine(
"Server: " + serverSslProtocols + "; Client: " + clientSslProtocols +
" expectedToFail: " + expectedToFail);
int timeOut = expectedToFail ? TestConfiguration.FailingTestTimeoutMiliseconds
: TestConfiguration.PassingTestTimeoutMilliseconds;
IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);
var server = new TcpListener(endPoint);
server.Start();
using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6))
{
IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint;
Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port);
Task<TcpClient> serverAccept = server.AcceptTcpClientAsync();
// We expect that the network-level connect will always complete.
await Task.WhenAll(new Task[] { clientConnect, serverAccept }).TimeoutAfter(
TestConfiguration.PassingTestTimeoutMilliseconds);
using (TcpClient serverConnection = await serverAccept)
using (SslStream sslClientStream = new SslStream(clientConnection.GetStream()))
using (SslStream sslServerStream = new SslStream(
serverConnection.GetStream(),
false,
AllowAnyServerCertificate))
{
string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsClientAsync start.");
Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
serverName,
null,
clientSslProtocols,
false);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsServerAsync start.");
Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
_serverCertificate,
true,
serverSslProtocols,
false);
try
{
await clientAuthentication.TimeoutAfter(timeOut);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.clientAuthentication complete.");
}
catch (Exception ex)
{
// Ignore client-side errors: we're only interested in server-side behavior.
_log.WriteLine("Client exception: " + ex);
}
await serverAuthentication.TimeoutAfter(timeOut);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.serverAuthentication complete.");
_log.WriteLine(
"Server({0}) authenticated with encryption cipher: {1} {2}-bit strength",
serverEndPoint,
sslServerStream.CipherAlgorithm,
sslServerStream.CipherStrength);
Assert.True(
sslServerStream.CipherAlgorithm != CipherAlgorithmType.Null,
"Cipher algorithm should not be NULL");
Assert.True(sslServerStream.CipherStrength > 0, "Cipher strength should be greater than 0");
}
}
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
private bool AllowAnyServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
Assert.True(
(sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable,
"Client didn't supply a cert, the server required one, yet sslPolicyErrors is " + sslPolicyErrors);
return true; // allow everything
}
#endregion Helpers
}
}
| |
/**
100% Copied from the SteamVR Unity Plugin!
/SteamVR/Scripts/SteamVR_Utils.cs
(C) To Valve, for all code and OpenVR!
*/
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using Valve.VR;
static public class OVR_Utils
{
public static Quaternion Slerp(Quaternion A, Quaternion B, float t)
{
var cosom = Mathf.Clamp(A.x * B.x + A.y * B.y + A.z * B.z + A.w * B.w, -1.0f, 1.0f);
if (cosom < 0.0f)
{
B = new Quaternion(-B.x, -B.y, -B.z, -B.w);
cosom = -cosom;
}
float sclp, sclq;
if ((1.0f - cosom) > 0.0001f)
{
var omega = Mathf.Acos(cosom);
var sinom = Mathf.Sin(omega);
sclp = Mathf.Sin((1.0f - t) * omega) / sinom;
sclq = Mathf.Sin(t * omega) / sinom;
}
else
{
// "from" and "to" very close, so do linear interp
sclp = 1.0f - t;
sclq = t;
}
return new Quaternion(
sclp * A.x + sclq * B.x,
sclp * A.y + sclq * B.y,
sclp * A.z + sclq * B.z,
sclp * A.w + sclq * B.w);
}
public static Vector3 Lerp(Vector3 A, Vector3 B, float t)
{
return new Vector3(
Lerp(A.x, B.x, t),
Lerp(A.y, B.y, t),
Lerp(A.z, B.z, t));
}
public static float Lerp(float A, float B, float t)
{
return A + (B - A) * t;
}
public static double Lerp(double A, double B, double t)
{
return A + (B - A) * t;
}
public static float InverseLerp(Vector3 A, Vector3 B, Vector3 result)
{
return Vector3.Dot(result - A, B - A);
}
public static float InverseLerp(float A, float B, float result)
{
return (result - A) / (B - A);
}
public static double InverseLerp(double A, double B, double result)
{
return (result - A) / (B - A);
}
public static float Saturate(float A)
{
return (A < 0) ? 0 : (A > 1) ? 1 : A;
}
public static Vector2 Saturate(Vector2 A)
{
return new Vector2(Saturate(A.x), Saturate(A.y));
}
public static float Abs(float A)
{
return (A < 0) ? -A : A;
}
public static Vector2 Abs(Vector2 A)
{
return new Vector2(Abs(A.x), Abs(A.y));
}
private static float _copysign(float sizeval, float signval)
{
return Mathf.Sign(signval) == 1 ? Mathf.Abs(sizeval) : -Mathf.Abs(sizeval);
}
public static Quaternion GetRotation(this Matrix4x4 matrix)
{
Quaternion q = new Quaternion();
q.w = Mathf.Sqrt(Mathf.Max(0, 1 + matrix.m00 + matrix.m11 + matrix.m22)) / 2;
q.x = Mathf.Sqrt(Mathf.Max(0, 1 + matrix.m00 - matrix.m11 - matrix.m22)) / 2;
q.y = Mathf.Sqrt(Mathf.Max(0, 1 - matrix.m00 + matrix.m11 - matrix.m22)) / 2;
q.z = Mathf.Sqrt(Mathf.Max(0, 1 - matrix.m00 - matrix.m11 + matrix.m22)) / 2;
q.x = _copysign(q.x, matrix.m21 - matrix.m12);
q.y = _copysign(q.y, matrix.m02 - matrix.m20);
q.z = _copysign(q.z, matrix.m10 - matrix.m01);
return q;
}
public static Vector3 GetPosition(this Matrix4x4 matrix)
{
var x = matrix.m03;
var y = matrix.m13;
var z = matrix.m23;
return new Vector3(x, y, z);
}
public static Vector3 GetScale(this Matrix4x4 m)
{
var x = Mathf.Sqrt(m.m00 * m.m00 + m.m01 * m.m01 + m.m02 * m.m02);
var y = Mathf.Sqrt(m.m10 * m.m10 + m.m11 * m.m11 + m.m12 * m.m12);
var z = Mathf.Sqrt(m.m20 * m.m20 + m.m21 * m.m21 + m.m22 * m.m22);
return new Vector3(x, y, z);
}
[System.Serializable]
public struct RigidTransform
{
public Vector3 pos;
public Quaternion rot;
public static RigidTransform identity
{
get { return new RigidTransform(Vector3.zero, Quaternion.identity); }
}
public static RigidTransform FromLocal(Transform t)
{
return new RigidTransform(t.localPosition, t.localRotation);
}
public RigidTransform(Vector3 pos, Quaternion rot)
{
this.pos = pos;
this.rot = rot;
}
public RigidTransform(Transform t)
{
this.pos = t.position;
this.rot = t.rotation;
}
public RigidTransform(Transform from, Transform to)
{
var inv = Quaternion.Inverse(from.rotation);
rot = inv * to.rotation;
pos = inv * (to.position - from.position);
}
public RigidTransform(HmdMatrix34_t pose)
{
var m = Matrix4x4.identity;
m[0, 0] = pose.m0;
m[0, 1] = pose.m1;
m[0, 2] = -pose.m2;
m[0, 3] = pose.m3;
m[1, 0] = pose.m4;
m[1, 1] = pose.m5;
m[1, 2] = -pose.m6;
m[1, 3] = pose.m7;
m[2, 0] = -pose.m8;
m[2, 1] = -pose.m9;
m[2, 2] = pose.m10;
m[2, 3] = -pose.m11;
this.pos = m.GetPosition();
this.rot = m.GetRotation();
}
public RigidTransform(HmdMatrix44_t pose)
{
var m = Matrix4x4.identity;
m[0, 0] = pose.m0;
m[0, 1] = pose.m1;
m[0, 2] = -pose.m2;
m[0, 3] = pose.m3;
m[1, 0] = pose.m4;
m[1, 1] = pose.m5;
m[1, 2] = -pose.m6;
m[1, 3] = pose.m7;
m[2, 0] = -pose.m8;
m[2, 1] = -pose.m9;
m[2, 2] = pose.m10;
m[2, 3] = -pose.m11;
m[3, 0] = pose.m12;
m[3, 1] = pose.m13;
m[3, 2] = -pose.m14;
m[3, 3] = pose.m15;
this.pos = m.GetPosition();
this.rot = m.GetRotation();
}
public HmdMatrix44_t ToHmdMatrix44()
{
var m = Matrix4x4.TRS(pos, rot, Vector3.one);
var pose = new HmdMatrix44_t();
pose.m0 = m[0, 0];
pose.m1 = m[0, 1];
pose.m2 = -m[0, 2];
pose.m3 = m[0, 3];
pose.m4 = m[1, 0];
pose.m5 = m[1, 1];
pose.m6 = -m[1, 2];
pose.m7 = m[1, 3];
pose.m8 = -m[2, 0];
pose.m9 = -m[2, 1];
pose.m10 = m[2, 2];
pose.m11 = -m[2, 3];
pose.m12 = m[3, 0];
pose.m13 = m[3, 1];
pose.m14 = -m[3, 2];
pose.m15 = m[3, 3];
return pose;
}
public HmdMatrix34_t ToHmdMatrix34()
{
var m = Matrix4x4.TRS(pos, rot, Vector3.one);
var pose = new HmdMatrix34_t();
pose.m0 = m[0, 0];
pose.m1 = m[0, 1];
pose.m2 = -m[0, 2];
pose.m3 = m[0, 3];
pose.m4 = m[1, 0];
pose.m5 = m[1, 1];
pose.m6 = -m[1, 2];
pose.m7 = m[1, 3];
pose.m8 = -m[2, 0];
pose.m9 = -m[2, 1];
pose.m10 = m[2, 2];
pose.m11 = -m[2, 3];
return pose;
}
public override bool Equals(object o)
{
if (o is RigidTransform)
{
RigidTransform t = (RigidTransform)o;
return pos == t.pos && rot == t.rot;
}
return false;
}
public override int GetHashCode()
{
return pos.GetHashCode() ^ rot.GetHashCode();
}
public static bool operator ==(RigidTransform a, RigidTransform b)
{
return a.pos == b.pos && a.rot == b.rot;
}
public static bool operator !=(RigidTransform a, RigidTransform b)
{
return a.pos != b.pos || a.rot != b.rot;
}
public static RigidTransform operator *(RigidTransform a, RigidTransform b)
{
return new RigidTransform
{
rot = a.rot * b.rot,
pos = a.pos + a.rot * b.pos
};
}
public void Inverse()
{
rot = Quaternion.Inverse(rot);
pos = -(rot * pos);
}
public RigidTransform GetInverse()
{
var t = new RigidTransform(pos, rot);
t.Inverse();
return t;
}
public void Multiply(RigidTransform a, RigidTransform b)
{
rot = a.rot * b.rot;
pos = a.pos + a.rot * b.pos;
}
public Vector3 InverseTransformPoint(Vector3 point)
{
return Quaternion.Inverse(rot) * (point - pos);
}
public Vector3 TransformPoint(Vector3 point)
{
return pos + (rot * point);
}
public static Vector3 operator *(RigidTransform t, Vector3 v)
{
return t.TransformPoint(v);
}
public static RigidTransform Interpolate(RigidTransform a, RigidTransform b, float t)
{
return new RigidTransform(Vector3.Lerp(a.pos, b.pos, t), Quaternion.Slerp(a.rot, b.rot, t));
}
public void Interpolate(RigidTransform to, float t)
{
pos = OVR_Utils.Lerp(pos, to.pos, t);
rot = OVR_Utils.Slerp(rot, to.rot, t);
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace SharpShell.Interop
{
internal static class Uxtheme
{
[DllImport("uxtheme.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
public static extern IntPtr OpenThemeData(IntPtr hWnd, String classList);
[DllImport("uxtheme.dll", ExactSpelling = true)]
public extern static Int32 CloseThemeData(IntPtr hTheme);
[DllImport("uxtheme", ExactSpelling=true)]
public extern static Int32 GetThemePartSize(IntPtr hTheme, IntPtr hdc, int part, WindowPartState state, ref RECT pRect, int eSize, out SIZE size);
[DllImport("uxtheme", ExactSpelling=true)]
public extern static Int32 GetThemePartSize(IntPtr hTheme, IntPtr hdc, int part, WindowPartState state, IntPtr pRect, int eSize, out SIZE size);
[DllImport("uxtheme", ExactSpelling = true)]
public extern static Int32 GetThemeInt(IntPtr hTheme, int iPartId, int iStateId, int iPropId, out int piVal);
[DllImport("uxtheme", ExactSpelling = true)]
public extern static Int32 GetThemeMargins(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, int iPropId, IntPtr prc, out MARGINS pMargins);
[DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)]
public extern static Int32 GetThemeTextExtent(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, String text, int textLength, UInt32 textFlags, ref RECT boundingRect, out RECT extentRect);
[DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)]
public extern static Int32 GetThemeTextExtent(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, String text, int textLength, UInt32 textFlags, IntPtr boundingRect, out RECT extentRect);
[DllImport("uxtheme", ExactSpelling = true)]
public extern static Int32 DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId,
int iStateId, ref RECT pRect, IntPtr pClipRect);
[DllImport("uxtheme", ExactSpelling = true)]
public extern static int IsThemeBackgroundPartiallyTransparent(IntPtr hTheme, int iPartId, int iStateId);
[DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)]
public extern static Int32 DrawThemeText(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, String text, int textLength, UInt32 textFlags, UInt32 textFlags2, ref RECT pRect);
[DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)]
public static extern Int32 GetBufferedPaintBits(IntPtr hBufferedPaint, out IntPtr ppbBuffer, out int pcxRow);
[DllImport("uxtheme.dll", SetLastError = true)]
public static extern IntPtr BeginBufferedPaint(IntPtr hdc, ref RECT prcTarget, BP_BUFFERFORMAT dwFormat,
ref BP_PAINTPARAMS pPaintParams, out IntPtr phdc);
[DllImport("uxtheme.dll")]
public static extern IntPtr EndBufferedPaint(IntPtr hBufferedPaint, bool fUpdateTarget);
[DllImport("uxtheme.dll", SetLastError = true)]
[PreserveSig]
public static extern IntPtr BufferedPaintInit();
[DllImport("uxtheme.dll", SetLastError = true)]
[PreserveSig]
public static extern IntPtr BufferedPaintUnInit();
public enum WindowPartState : int
{
// Frame States
FS_ACTIVE = 1,
FS_INACTIVE = 2,
// Caption States
CS_ACTIVE = 1,
CS_INACTIVE = 2,
CS_DISABLED = 3,
// Max Caption States
MXCS_ACTIVE = 1,
MXCS_INACTIVE = 2,
MXCS_DISABLED = 3,
// Min Caption States
MNCS_ACTIVE = 1,
MNCS_INACTIVE = 2,
MNCS_DISABLED = 3,
// Horizontal Scrollbar States
HSS_NORMAL = 1,
HSS_HOT = 2,
HSS_PUSHED = 3,
HSS_DISABLED = 4,
// Horizontal Thumb States
HTS_NORMAL = 1,
HTS_HOT = 2,
HTS_PUSHED = 3,
HTS_DISABLED = 4,
// Vertical Scrollbar States
VSS_NORMAL = 1,
VSS_HOT = 2,
VSS_PUSHED = 3,
VSS_DISABLED = 4,
// Vertical Thumb States
VTS_NORMAL = 1,
VTS_HOT = 2,
VTS_PUSHED = 3,
VTS_DISABLED = 4,
// System Button States
SBS_NORMAL = 1,
SBS_HOT = 2,
SBS_PUSHED = 3,
SBS_DISABLED = 4,
// Minimize Button States
MINBS_NORMAL = 1,
MINBS_HOT = 2,
MINBS_PUSHED = 3,
MINBS_DISABLED = 4,
// Maximize Button States
MAXBS_NORMAL = 1,
MAXBS_HOT = 2,
MAXBS_PUSHED = 3,
MAXBS_DISABLED = 4,
// Restore Button States
RBS_NORMAL = 1,
RBS_HOT = 2,
RBS_PUSHED = 3,
RBS_DISABLED = 4,
// Help Button States
HBS_NORMAL = 1,
HBS_HOT = 2,
HBS_PUSHED = 3,
HBS_DISABLED = 4,
// Close Button States
CBS_NORMAL = 1,
CBS_HOT = 2,
CBS_PUSHED = 3,
CBS_DISABLED = 4
}
}
internal enum POPUPITEMSTATES
{
MPI_NORMAL = 1,
MPI_HOT = 2,
MPI_DISABLED = 3,
MPI_DISABLEDHOT = 4,
}
internal enum POPUPCHECKBACKGROUNDSTATES
{
MCB_DISABLED = 1,
MCB_NORMAL = 2,
MCB_BITMAP = 3,
}
internal enum POPUPCHECKSTATES
{
MC_CHECKMARKNORMAL = 1,
MC_CHECKMARKDISABLED = 2,
MC_BULLETNORMAL = 3,
MC_BULLETDISABLED = 4,
}
//todo tidy up and name properly.
[StructLayout(LayoutKind.Sequential)]
internal struct ICONINFO
{
public bool IsIcon;
public int xHotspot;
public int yHotspot;
public IntPtr MaskBitmap;
public IntPtr ColorBitmap;
}
[StructLayout(LayoutKind.Sequential)]
internal struct BLENDFUNCTION
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
[StructLayout(LayoutKind.Sequential)]
internal struct BP_PAINTPARAMS
{
public uint cbSize;
public uint dwFlags; // BPPF_ flags
public IntPtr prcExclude;
public IntPtr pBlendFunction;
}
internal enum BP_BUFFERFORMAT
{
BPBF_COMPATIBLEBITMAP, // Compatible bitmap
BPBF_DIB, // Device-independent bitmap
BPBF_TOPDOWNDIB, // Top-down device-independent bitmap
BPBF_TOPDOWNMONODIB // Top-down monochrome device-independent bitmap
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using BulletML;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using MonoGame.Extended;
using SpriterDotNet;
using SpriterDotNet.MonoGame;
using SpriterDotNet.Providers;
using SpriterDotNet.MonoGame.Content;
using XmasHell.Geometry;
using XmasHell.Physics;
using XmasHell.Spriter;
using XmasHell.BulletML;
using XmasHell.Extensions;
using FarseerPhysics.Dynamics;
using FarseerPhysics;
using FarseerPhysics.Factories;
using XmasHell.Physics.DebugView;
using XmasHell.Physics.Collision;
using XmasHell.Audio;
namespace XmasHell.Entities.Bosses
{
public enum ScreenSide
{
Left,
Top,
Right,
Bottom
};
// TODO: Inherit from AbstractEntity
public abstract class Boss : ISpriterPhysicsEntity, IDisposable
{
public XmasHell Game;
public readonly BossType BossType;
public Vector2 InitialPosition;
private bool _destroyed;
private bool _bossEntranceAnimation;
private bool _ready;
public bool Invincible;
public Vector2 Direction = Vector2.Zero; // values in radians
public float Speed;
public Vector2 Acceleration = Vector2.One;
public float AngularVelocity = 5f;
// Physics World
protected List<CollisionElement> HitBoxes;
public bool PhysicsEnabled = false;
public World PhysicsWorld;
public Body PhysicsBody;
protected Body LeftWallBody;
protected Body TopWallBody;
protected Body RightWallBody;
protected Body BottomWallBody;
private DebugView _debugView;
// Relative to position targeting
public bool TargetingPosition = false;
private Vector2 _initialPosition = Vector2.Zero;
private Vector2 _targetPosition = Vector2.Zero;
private TimeSpan _targetPositionTimer = TimeSpan.Zero;
private TimeSpan _targetPositionTime = TimeSpan.Zero;
private Vector2 _targetDirection = Vector2.Zero;
// Relative to angle targeting
public bool TargetingAngle = false;
private float _initialAngle = 0f;
private float _targetAngle = 0f;
private TimeSpan _targetAngleTimer = TimeSpan.Zero;
private TimeSpan _targetAngleTime = TimeSpan.Zero;
private readonly PositionDelegate _playerPositionDelegate;
private TimeSpan _hitTimer = TimeSpan.Zero;
public bool Tinted { get; protected set; }
public Color HitColor;
private readonly Line _leftWallLine;
private readonly Line _bottomWallLine;
private readonly Line _upWallLine;
private readonly Line _rightWallLine;
// Behaviours
protected readonly List<AbstractBossBehaviour> Behaviours;
protected int PreviousBehaviourIndex;
public int CurrentBehaviourIndex { get; protected set; }
// New position timer
public bool StartNewPositionTimer = false;
private TimeSpan NewPositionTimer = TimeSpan.Zero;
public float NewPositionTimerTime = 0f;
public event EventHandler<float> NewPositionTimerFinished = null;
private bool _randomPosition;
private bool _randomPositionLongDistance;
public Rectangle RandomMovingArea;
// Shoot timer
public bool StartShootTimer = false;
private TimeSpan ShootTimer = TimeSpan.Zero;
public float ShootTimerTime = 0f;
public event EventHandler<float> ShootTimerFinished = null;
public bool IsOutside = false;
// BulletML
protected readonly List<string> BulletPatternFiles;
// Spriter
protected string SpriterFilename;
protected static readonly Config DefaultAnimatorConfig = new Config
{
MetadataEnabled = true,
EventsEnabled = true,
PoolingEnabled = true,
TagsEnabled = false,
VarsEnabled = false,
SoundsEnabled = false
};
protected readonly IList<CustomSpriterAnimator> Animators = new List<CustomSpriterAnimator>();
public CustomSpriterAnimator CurrentAnimator;
#region Getters
public virtual Vector2 Position()
{
return CurrentAnimator.Position;
}
public virtual float Rotation()
{
return CurrentAnimator.Rotation;
}
public virtual Vector2 Origin()
{
return new Vector2(Width() / 2f, Height() / 2f);
}
public virtual Vector2 ScaleVector()
{
return CurrentAnimator.Scale;
}
public CustomSpriterAnimator GetCurrentAnimator()
{
return CurrentAnimator;
}
public float GetLifePercentage()
{
return CurrentBehaviourIndex >= Behaviours.Count ? 0 : Behaviours[CurrentBehaviourIndex].GetLifePercentage();
}
public Vector2 ActionPointPosition()
{
if (CurrentAnimator.FrameData != null)
{
foreach (var pointData in CurrentAnimator.FrameData.PointData)
{
if (pointData.Key.StartsWith("action_point"))
{
var actionPoint = new Vector2(pointData.Value.X, -pointData.Value.Y) * CurrentAnimator.Scale;
var rotatedActionPoint = MathExtension.RotatePoint(actionPoint, Rotation());
return Position() + rotatedActionPoint;
}
}
}
return Position();
}
public float ActionPointDirection()
{
if (CurrentAnimator.FrameData != null && CurrentAnimator.FrameData.PointData.ContainsKey("action_point"))
{
var actionPoint = CurrentAnimator.FrameData.PointData["action_point"];
return MathHelper.ToRadians(actionPoint.Angle - 90f) + Rotation();
}
return Rotation();
}
public virtual int Width()
{
if (CurrentAnimator.SpriteProvider != null)
{
return (int)CurrentAnimator.SpriteProvider.Get(0, 0).Height();
}
return 0;
}
public virtual int Height()
{
if (CurrentAnimator.SpriteProvider != null)
{
return (int)CurrentAnimator.SpriteProvider.Get(0, 0).Width();
}
return 0;
}
protected float GetSpritePartWidth(string name)
{
if (CurrentAnimator != null)
{
var spriteBodyPart = Array.Find(CurrentAnimator.Entity.Spriter.Folders[0].Files, (file) => file.Name == name);
return spriteBodyPart.Width;
}
return 0f;
}
protected float GetSpritePartHeight(string name)
{
if (CurrentAnimator != null)
{
var spriteBodyPart = Array.Find(CurrentAnimator.Entity.Spriter.Folders[0].Files, (file) => file.Name == name);
return spriteBodyPart.Height;
}
return 0f;
}
public bool IsReady()
{
return _ready;
}
public void EnableRandomPosition(bool value, bool longDistance = false)
{
_randomPosition = value;
_randomPositionLongDistance = longDistance;
}
#endregion
#region Setters
public void Position(Vector2 value)
{
CurrentAnimator.Position = value;
}
public void Rotation(float value)
{
CurrentAnimator.Rotation = value;
}
public void Scale(Vector2 value)
{
CurrentAnimator.Scale = value;
}
#endregion
protected Boss(XmasHell game, BossType type, PositionDelegate playerPositionDelegate)
{
Game = game;
BossType = type;
_playerPositionDelegate = playerPositionDelegate;
InitialPosition = GameConfig.BossDefaultPosition;
// Behaviours
Behaviours = new List<AbstractBossBehaviour>();
// BulletML
BulletPatternFiles = new List<string>();
HitColor = Color.White * 0.5f;
HitBoxes = new List<CollisionElement>();
// To compute line/wall intersection
_bottomWallLine = new Line(
new Vector2(0f, GameConfig.VirtualResolution.Y),
new Vector2(GameConfig.VirtualResolution.X, GameConfig.VirtualResolution.Y)
);
_leftWallLine = new Line(
new Vector2(0f, 0f),
new Vector2(0f, GameConfig.VirtualResolution.Y)
);
_rightWallLine = new Line(
new Vector2(GameConfig.VirtualResolution.X, 0f),
new Vector2(GameConfig.VirtualResolution.X, GameConfig.VirtualResolution.Y)
);
_upWallLine = new Line(
new Vector2(0f, 0f),
new Vector2(GameConfig.VirtualResolution.X, 0f)
);
}
public virtual void Initialize()
{
LoadBulletPatterns();
LoadSpriterSprite();
Reset();
}
private void Clear()
{
Game.SpriteBatchManager.BossBullets.Clear();
Game.GameManager.CollisionWorld.ClearBossHitboxes();
Game.GameManager.CollisionWorld.ClearBossBullets();
PhysicsBody?.Dispose();
PhysicsWorld?.Clear();
Game.GameManager.MoverManager.SetBounceBounds(null);
}
public virtual void Reset()
{
Clear();
Game.SpriteBatchManager.Boss = this;
InitializePhysics();
foreach (var behaviour in Behaviours)
behaviour.Reset();
_randomPosition = false;
_randomPositionLongDistance = false;
RandomMovingArea = new Rectangle(
(int)(Width() / 2f), (int)(Height() / 2f),
GameConfig.VirtualResolution.X - (int)(Width() / 2f),
500 - (int)(Height() / 2f)
);
_bossEntranceAnimation = true;
_ready = false;
_destroyed = false;
_targetDirection = Vector2.Zero;
_targetAngle = 0f;
Game.GameManager.MoverManager.Clear();
Invincible = true;
Tinted = false;
TargetingPosition = false;
TargetingAngle = false;
CurrentBehaviourIndex = 0;
PreviousBehaviourIndex = -1;
Position(new Vector2(InitialPosition.X, InitialPosition.Y - 500f));
Rotation(0);
Scale(Vector2.One);
Direction = Vector2.Zero;
Speed = GameConfig.BossDefaultSpeed;
CurrentAnimator.Play("Idle");
CurrentAnimator.Progress = 0;
CurrentAnimator.Speed = 1;
MoveToInitialPosition(GameConfig.BossEntranceAnimationTime, true);
}
public void Dispose()
{
Clear();
Game.SpriteBatchManager.Boss = null;
}
public bool Alive()
{
return !_destroyed;
}
protected virtual void LoadSpriterSprite()
{
if (SpriterFilename == string.Empty)
throw new Exception("You need to specify a path to the spriter file of this boss");
var factory = new DefaultProviderFactory<ISprite, SoundEffect>(DefaultAnimatorConfig, true);
var loader = new SpriterContentLoader(Game.Content, SpriterFilename);
loader.Fill(factory);
foreach (var entity in loader.Spriter.Entities)
{
var animator = new CustomSpriterAnimator(entity, factory);
Animators.Add(animator);
}
CurrentAnimator = Animators.First();
}
protected virtual void InitializePhysics(bool setupPhysicsWorld = false)
{
if (setupPhysicsWorld)
SetupPhysicsWorld();
}
public void AddHitBox(CollisionElement hitBox)
{
Game.GameManager.CollisionWorld.AddBossHitBox(hitBox);
HitBoxes.Add(hitBox);
}
public void RemoveHitBox(CollisionElement hitBox)
{
Game.GameManager.CollisionWorld.RemoveBossHitBox(hitBox);
HitBoxes.Remove(hitBox);
}
public void ClearHitBoxes()
{
Game.GameManager.CollisionWorld.ClearBossHitboxes();
HitBoxes.Clear();
}
protected virtual void SetupPhysicsWorld()
{
PhysicsWorld = new World(GameConfig.DefaultGravity);
_debugView = new DebugView(PhysicsWorld, Game, 1f);
// Walls
BottomWallBody = BodyFactory.CreateEdge(
PhysicsWorld,
ConvertUnits.ToSimUnits(0, GameConfig.VirtualResolution.Y),
ConvertUnits.ToSimUnits(GameConfig.VirtualResolution.X, GameConfig.VirtualResolution.Y)
);
LeftWallBody = BodyFactory.CreateEdge(
PhysicsWorld,
ConvertUnits.ToSimUnits(0, 0),
ConvertUnits.ToSimUnits(0, GameConfig.VirtualResolution.Y)
);
RightWallBody = BodyFactory.CreateEdge(
PhysicsWorld,
ConvertUnits.ToSimUnits(GameConfig.VirtualResolution.X, 0),
ConvertUnits.ToSimUnits(GameConfig.VirtualResolution.X, GameConfig.VirtualResolution.Y)
);
TopWallBody = BodyFactory.CreateEdge(
PhysicsWorld,
ConvertUnits.ToSimUnits(0, 0),
ConvertUnits.ToSimUnits(GameConfig.VirtualResolution.X, 0)
);
}
private void RestoreDefaultState()
{
Direction = Vector2.Zero;
Rotation(0);
CurrentAnimator.Play("Idle");
}
private void LoadBulletPatterns()
{
foreach (var bulletPatternFile in BulletPatternFiles)
{
if (Game.GameManager.MoverManager.FindPattern(bulletPatternFile) == null)
{
var pattern = new BulletPattern();
var stream = Assets.GetPattern(bulletPatternFile);
pattern.ParseStream(bulletPatternFile, stream);
Game.GameManager.MoverManager.AddPattern(bulletPatternFile, pattern);
}
}
}
public void Destroy()
{
if (_destroyed)
return;
Game.PlayerData.BossBeatenCounter(BossType, Game.PlayerData.BossBeatenCounter(BossType) + 1);
var bestTime = Game.PlayerData.BossBestTime(BossType);
var currentTime = Game.GameManager.GetCurrentTime();
if (bestTime == TimeSpan.Zero || bestTime > currentTime)
Game.PlayerData.BossBestTime(BossType, currentTime);
Game.GameManager.EndGame(true, true, 0f);
_destroyed = true;
UnlockBossDefeatAchievement();
SubmitScore();
}
protected virtual void PlayExplosionAnimation()
{
Game.GameManager.ParticleManager.EmitBossDestroyedParticles(CurrentAnimator.Position);
}
private void UnlockBossDefeatAchievement()
{
#if ANDROID
var gameHelper = Game.AndroidActivity.GameHelper;
gameHelper.UnlockAchievement(gameHelper.BossTypeToAchievementCode(BossType));
#endif
}
private void SubmitScore()
{
#if ANDROID
var currentTime = (long)Game.GameManager.GetCurrentTime().TotalMilliseconds;
if (currentTime > 0)
{
var gameHelper = Game.AndroidActivity.GameHelper;
gameHelper.SubmitScore(gameHelper.BossTypeToLeaderboardCode(BossType), currentTime);
}
#endif
}
// Move to a given position in "time" seconds
public void MoveTo(Vector2 position, float time, bool force = false)
{
if (TargetingPosition && !force)
return;
TargetingPosition = true;
_targetPositionTimer = TimeSpan.FromSeconds(time);
_targetPositionTime = TimeSpan.FromSeconds(time);
_targetPosition = position;
_initialPosition = CurrentAnimator.Position;
//_targetDirection = Vector2.Normalize(_targetPosition - _initialPosition);
}
// Move to a given position keeping the actual speed
public void MoveTo(Vector2 position, bool force = false)
{
if (TargetingPosition && !force)
return;
TargetingPosition = true;
_targetPosition = position;
_targetDirection = Vector2.Normalize(position - CurrentAnimator.Position);
}
public void MoveToCenter(float time, bool force = false)
{
MoveTo(new Vector2(GameConfig.VirtualResolution.X / 2f, GameConfig.VirtualResolution.Y / 2f), time, force);
}
public void MoveToCenter(bool force = false)
{
MoveTo(new Vector2(GameConfig.VirtualResolution.X / 2f, GameConfig.VirtualResolution.Y / 2f), force);
}
public void MoveToInitialPosition(float time, bool force = false)
{
MoveTo(InitialPosition, time, force);
}
public void MoveToInitialPosition(bool force = false)
{
MoveTo(InitialPosition, force);
}
public void MoveOutside(float time, bool force = true)
{
MoveTo(GetNearestOutsidePosition(), time, force);
}
public void MoveOutside(bool force = true)
{
MoveTo(GetNearestOutsidePosition(), force);
}
public ScreenSide GetRandomSide()
{
var randomIndex = Game.GameManager.Random.Next(0, 3);
if (randomIndex == 0)
return ScreenSide.Left;
else if (randomIndex == 1)
return ScreenSide.Top;
else if (randomIndex == 2)
return ScreenSide.Right;
else
return ScreenSide.Bottom;
}
public ScreenSide GetSideFromPosition(Vector2 position)
{
if (position.X <= 0)
return ScreenSide.Left;
else if (position.X >= Game.ViewportAdapter.VirtualWidth)
return ScreenSide.Right;
else if (position.Y <= 0)
return ScreenSide.Top;
else if (position.Y >= Game.ViewportAdapter.VirtualHeight)
return ScreenSide.Bottom;
else
return GetSideFromPosition(GetNearestOutsidePosition());
}
public float GetRandomVerticalPosition()
{
return Game.GameManager.Random.Next(0, Game.ViewportAdapter.VirtualHeight);
}
public float GetRandomHorizontalPosition()
{
return Game.GameManager.Random.Next(0, Game.ViewportAdapter.VirtualWidth);
}
public Vector2 GetRandomOutsidePosition(ScreenSide? side = null)
{
var randomPosition = Vector2.Zero;
side = side.HasValue ? side.Value : GetRandomSide();
switch(side)
{
case ScreenSide.Left:
randomPosition.Y = Game.GameManager.Random.Next(0, Game.ViewportAdapter.VirtualHeight);
break;
case ScreenSide.Right:
randomPosition.X = Game.ViewportAdapter.VirtualWidth;
randomPosition.Y = Game.GameManager.Random.Next(0, Game.ViewportAdapter.VirtualHeight);
break;
case ScreenSide.Top:
randomPosition.X = Game.GameManager.Random.Next(0, Game.ViewportAdapter.VirtualWidth);
randomPosition.Y = Game.ViewportAdapter.VirtualHeight;
break;
case ScreenSide.Bottom:
randomPosition.X = Game.GameManager.Random.Next(0, Game.ViewportAdapter.VirtualWidth);
break;
}
return randomPosition;
}
public Vector2 GetNearestOutsidePosition()
{
// Get the nearest border
var newPosition = Position();
ScreenSide side = GetNearestBorder();
switch (side)
{
case ScreenSide.Left:
newPosition.X = -Width();
break;
case ScreenSide.Top:
newPosition.Y = -Height();
break;
case ScreenSide.Right:
newPosition.X = Game.ViewportAdapter.VirtualWidth + Width();
break;
case ScreenSide.Bottom:
newPosition.Y = Game.ViewportAdapter.VirtualHeight + Height();
break;
default:
break;
}
return newPosition;
}
public float GetRandomOutsideAngle(ScreenSide side, int maxAngle, int? topAngle = null)
{
var randomAngle = Game.GameManager.Random.Next(-maxAngle, maxAngle);
if (topAngle.HasValue)
randomAngle -= topAngle.Value;
switch (side)
{
case ScreenSide.Left:
randomAngle -= 90;
break;
case ScreenSide.Right:
randomAngle += 90;
break;
case ScreenSide.Bottom:
randomAngle += 180;
break;
default:
break;
}
return randomAngle;
}
public ScreenSide GetNearestBorder()
{
if (Position().X < Game.ViewportAdapter.VirtualWidth / 2f)
{
if (Position().Y < Game.ViewportAdapter.VirtualHeight / 2f)
{
if (Position().Y < Position().X)
{
return ScreenSide.Top;
}
}
else
{
if (Game.ViewportAdapter.VirtualHeight - Position().Y < Position().X)
{
return ScreenSide.Bottom;
}
}
return ScreenSide.Left;
}
else
{
if (Position().Y < Game.ViewportAdapter.VirtualHeight / 2f)
{
if (Position().Y < Game.ViewportAdapter.VirtualWidth - Position().X)
{
return ScreenSide.Top;
}
}
else
{
if (Game.ViewportAdapter.VirtualHeight - Position().Y <
Game.ViewportAdapter.VirtualWidth - Position().X)
{
return ScreenSide.Bottom;
}
}
return ScreenSide.Right;
}
}
public void RotateTo(float angle, float time, bool force = false)
{
if (TargetingAngle && !force)
return;
TargetingAngle = true;
_targetAngle = angle;
_initialAngle = CurrentAnimator.Rotation;
_targetAngleTimer = TimeSpan.FromSeconds(time);
_targetAngleTime = TimeSpan.FromSeconds(time);
}
public void RotateTo(float angle, bool force = false)
{
if (TargetingAngle && !force)
return;
TargetingAngle = true;
_targetAngle = angle;
}
public void StopMoving()
{
TargetingPosition = false;
_targetPositionTime = TimeSpan.Zero;
_targetDirection = Vector2.Zero;
}
public Vector2 GetPlayerPosition()
{
return _playerPositionDelegate();
}
public Vector2 GetPlayerDirection()
{
var playerPosition = GetPlayerPosition();
var currentPosition = CurrentAnimator.Position;
var angle = (currentPosition - playerPosition).ToAngle();
angle += MathHelper.PiOver2;
return MathExtension.AngleToDirection(angle);
}
public float GetPlayerDirectionAngle()
{
var playerPosition = GetPlayerPosition();
var currentPosition = CurrentAnimator.Position;
var angle = (currentPosition - playerPosition).ToAngle();
return angle;
}
public bool GetLineWallIntersectionPosition(Line line, ref Vector2 newPosition)
{
// Make sure the line go out of the screen
var maxDistance = (float) Math.Sqrt(
GameConfig.VirtualResolution.X * GameConfig.VirtualResolution.X +
GameConfig.VirtualResolution.Y * GameConfig.VirtualResolution.Y
);
var direction = Vector2.Normalize(line.Second - line.First);
line.Second += (direction * maxDistance);
return
MathExtension.LinesIntersect(_bottomWallLine, line, ref newPosition) ||
MathExtension.LinesIntersect(_leftWallLine, line, ref newPosition) ||
MathExtension.LinesIntersect(_rightWallLine, line, ref newPosition) ||
MathExtension.LinesIntersect(_upWallLine, line, ref newPosition);
}
public void TakeDamage(float amount)
{
if (Invincible || _destroyed)
return;
var currentBehaviour = Behaviours[CurrentBehaviourIndex];
currentBehaviour.TakeDamage(amount);
_hitTimer = TimeSpan.FromMilliseconds(20);
var sounds = new List<SoundEffect>()
{
Assets.GetSound("Audio/SE/boss-hit1"),
Assets.GetSound("Audio/SE/boss-hit2"),
Assets.GetSound("Audio/SE/boss-hit3")
};
SoundManager.PlayRandomSound(sounds);
}
public void TriggerPattern(string patternName, BulletType type, bool clear = false, Vector2? position = null, float? direction = null)
{
Game.GameManager.MoverManager.TriggerPattern(patternName, type, clear, position, direction);
}
public virtual void Update(GameTime gameTime)
{
if (_destroyed)
{
if (Game.GameManager.TransitioningToEndGame() && Game.SpriteBatchManager.Boss != null)
{
PlayExplosionAnimation();
Dispose();
}
return;
}
if (_bossEntranceAnimation)
{
if (Position().EqualsWithTolerence(InitialPosition, 1E-02f))
{
Position(InitialPosition);
_ready = true;
_bossEntranceAnimation = false;
Invincible = false;
}
}
if (!_destroyed && PhysicsEnabled)
{
PhysicsWorld.Step((float)gameTime.ElapsedGameTime.TotalSeconds);
SynchronizeGraphicsWithPhysics();
}
if (_randomPosition && !TargetingPosition)
{
var newPosition = Vector2.Zero;
if (_randomPositionLongDistance)
{
var currentPosition = Position().ToPoint();
var minDistance = (RandomMovingArea.Width - RandomMovingArea.X) / 2;
// Choose a random long distance new X position
var leftSpace = currentPosition.X - RandomMovingArea.X;
var rightSpace = RandomMovingArea.Width - currentPosition.X;
if (leftSpace > minDistance)
{
if (rightSpace > minDistance)
{
if (Game.GameManager.Random.NextDouble() > 0.5)
newPosition.X = Game.GameManager.Random.Next(currentPosition.X + minDistance, RandomMovingArea.Width);
else
newPosition.X = Game.GameManager.Random.Next(RandomMovingArea.X, currentPosition.X - minDistance);
}
else
newPosition.X = Game.GameManager.Random.Next(RandomMovingArea.X, currentPosition.X - minDistance);
}
else
newPosition.X = Game.GameManager.Random.Next(currentPosition.X + minDistance, RandomMovingArea.Width);
// minDistance only depends on the random area X and width
if (RandomMovingArea.Height - RandomMovingArea.Y > minDistance)
{
// Choose a random long distance new Y position
var topSpace = currentPosition.Y - RandomMovingArea.Y;
var bottomSpace = RandomMovingArea.Height - currentPosition.Y;
if (topSpace > minDistance)
{
if (bottomSpace > minDistance)
{
if (Game.GameManager.Random.NextDouble() > 0.5)
newPosition.Y = Game.GameManager.Random.Next(currentPosition.Y + minDistance, RandomMovingArea.Height);
else
newPosition.Y = Game.GameManager.Random.Next(RandomMovingArea.Y, currentPosition.Y - minDistance);
}
else
newPosition.Y = Game.GameManager.Random.Next(RandomMovingArea.Y, currentPosition.Y - minDistance);
}
else
newPosition.Y = Game.GameManager.Random.Next(currentPosition.Y + minDistance, RandomMovingArea.Height);
}
else
newPosition.Y = Game.GameManager.Random.Next(RandomMovingArea.Y, RandomMovingArea.Height);
}
else
{
newPosition.X = Game.GameManager.Random.Next(RandomMovingArea.X, RandomMovingArea.Width);
newPosition.Y = Game.GameManager.Random.Next(RandomMovingArea.Y, RandomMovingArea.Height);
}
MoveTo(newPosition, 1.5f);
}
UpdatePosition(gameTime);
UpdateRotation(gameTime);
UpdateBehaviour(gameTime);
if (_destroyed)
return;
// Is outside of the screen?
IsOutside = Game.GameManager.IsOutside(Position());
// New position timer
if (StartNewPositionTimer && NewPositionTimerFinished != null)
{
if (NewPositionTimer.TotalMilliseconds > 0)
NewPositionTimer -= gameTime.ElapsedGameTime;
else
{
NewPositionTimer = TimeSpan.FromSeconds(NewPositionTimerTime);
NewPositionTimerFinished.Invoke(this, NewPositionTimerTime);
}
}
// Shoot timer
if (StartShootTimer && ShootTimerFinished != null)
{
if (ShootTimer.TotalMilliseconds > 0)
ShootTimer -= gameTime.ElapsedGameTime;
else
{
ShootTimer = TimeSpan.FromSeconds(ShootTimerTime);
ShootTimerFinished.Invoke(this, ShootTimerTime);
}
}
if (_hitTimer.TotalMilliseconds > 0)
_hitTimer -= gameTime.ElapsedGameTime;
Tinted = _hitTimer.TotalMilliseconds > 0;
CurrentAnimator.Update(gameTime.ElapsedGameTime.Milliseconds);
}
private void SynchronizeGraphicsWithPhysics()
{
if (PhysicsBody == null)
return;
Position(ConvertUnits.ToDisplayUnits(PhysicsBody.Position));
Rotation(PhysicsBody.Rotation);
}
private void UpdatePosition(GameTime gameTime)
{
if (TargetingPosition)
{
if (!_targetDirection.Equals(Vector2.Zero))
{
var currentPosition = CurrentAnimator.Position;
var distance = Vector2.Distance(currentPosition, _targetPosition);
var deltaDistance = Speed * gameTime.GetElapsedSeconds();
if (distance < deltaDistance)
{
TargetingPosition = false;
_targetDirection = Vector2.Zero;
CurrentAnimator.Position = _targetPosition;
}
else
{
// TODO: Perform some cubic interpolation
CurrentAnimator.Position = currentPosition + (_targetDirection * deltaDistance) * Acceleration;
}
}
else
{
var newPosition = Vector2.Zero;
var lerpAmount = (float) (_targetPositionTime.TotalSeconds/_targetPositionTimer.TotalSeconds);
newPosition.X = MathHelper.SmoothStep(_targetPosition.X, _initialPosition.X, lerpAmount);
newPosition.Y = MathHelper.SmoothStep(_targetPosition.Y, _initialPosition.Y, lerpAmount);
if (lerpAmount < 0.001f)
{
TargetingPosition = false;
_targetPositionTime = TimeSpan.Zero;
CurrentAnimator.Position = _targetPosition;
}
else
_targetPositionTime -= gameTime.ElapsedGameTime;
CurrentAnimator.Position = newPosition;
}
}
else
{
CurrentAnimator.Position += Speed * gameTime.GetElapsedSeconds() * Acceleration * Direction;
}
}
private void UpdateRotation(GameTime gameTime)
{
if (TargetingAngle)
{
// TODO: Add some logic to know if the boss has to turn to the left or to the right
if (_targetAngleTimer.TotalMilliseconds <= 0)
{
var currentRotation = CurrentAnimator.Rotation;
var distance = Math.Abs(currentRotation - _targetAngle);
var deltaDistance = AngularVelocity * gameTime.GetElapsedSeconds();
if (distance < deltaDistance)
{
TargetingAngle = false;
CurrentAnimator.Rotation = _targetAngle;
}
else
{
var factor = (currentRotation < _targetAngle) ? 1 : -1;
CurrentAnimator.Rotation = currentRotation + (factor * deltaDistance);
}
}
else
{
var lerpAmount = (float)(_targetAngleTime.TotalSeconds / _targetAngleTimer.TotalSeconds);
var newAngle = MathHelper.Lerp(_targetAngle, _initialAngle, lerpAmount);
if (lerpAmount < 0.001f)
{
TargetingAngle = false;
_targetAngleTimer = TimeSpan.Zero;
CurrentAnimator.Rotation = _targetAngle;
}
else
_targetAngleTime -= gameTime.ElapsedGameTime;
CurrentAnimator.Rotation = newAngle;
}
}
}
private void UpdateBehaviour(GameTime gameTime)
{
if (!_ready)
return;
UpdateBehaviourIndex();
if (_destroyed)
return;
if (CurrentBehaviourIndex != PreviousBehaviourIndex)
{
if (PreviousBehaviourIndex >= 0)
Behaviours[PreviousBehaviourIndex].Stop();
Game.GameManager.MoverManager.Clear();
RestoreDefaultState();
if (Behaviours.Count > 0)
Behaviours[CurrentBehaviourIndex].Start();
}
if (Behaviours.Count > 0)
Behaviours[CurrentBehaviourIndex].Update(gameTime);
PreviousBehaviourIndex = CurrentBehaviourIndex;
}
protected virtual void UpdateBehaviourIndex()
{
if (Behaviours.Count == 0)
return;
if (Behaviours[CurrentBehaviourIndex].IsBehaviourEnded())
{
CurrentBehaviourIndex++;
if (CurrentBehaviourIndex >= Behaviours.Count)
Destroy();
}
}
public virtual void Draw()
{
if (CurrentBehaviourIndex < Behaviours.Count)
Behaviours[CurrentBehaviourIndex].Draw(Game.SpriteBatch);
CurrentAnimator.Draw(Game.SpriteBatch);
if (CurrentBehaviourIndex < Behaviours.Count)
Behaviours[CurrentBehaviourIndex].DrawAfter(Game.SpriteBatch);
if (PhysicsEnabled && GameConfig.DebugPhysics)
{
var view = Game.Camera.GetViewMatrix();
var projection = Matrix.CreateOrthographicOffCenter(
0f,
ConvertUnits.ToSimUnits(Game.GraphicsDevice.Viewport.Width),
ConvertUnits.ToSimUnits(Game.GraphicsDevice.Viewport.Height), 0f, 0f, 1f
);
_debugView.Draw(ref projection, ref view);
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Interpreter;
namespace TestUtilities.Python {
public class MockInterpreterOptionsService : IInterpreterOptionsService, IInterpreterRegistryService {
readonly List<IPythonInterpreterFactoryProvider> _providers;
readonly IPythonInterpreterFactory _noInterpretersValue;
IPythonInterpreterFactory _defaultInterpreter;
readonly Dictionary<IPythonInterpreterFactory, IReadOnlyList<IPackageManager>> _packageManagers;
public MockInterpreterOptionsService() {
_providers = new List<IPythonInterpreterFactoryProvider>();
_noInterpretersValue = new MockPythonInterpreterFactory(new VisualStudioInterpreterConfiguration("2.7", "No Interpreters", version: new Version(2, 7)));
_packageManagers = new Dictionary<IPythonInterpreterFactory, IReadOnlyList<IPackageManager>>();
}
public void AddProvider(IPythonInterpreterFactoryProvider provider) {
_providers.Add(provider);
provider.InterpreterFactoriesChanged += provider_InterpreterFactoriesChanged;
var evt = InterpretersChanged;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
public void ClearProviders() {
foreach (var p in _providers) {
p.InterpreterFactoriesChanged -= provider_InterpreterFactoriesChanged;
}
_providers.Clear();
var evt = InterpretersChanged;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
void provider_InterpreterFactoriesChanged(object sender, EventArgs e) {
var evt = InterpretersChanged;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
public IEnumerable<IPythonInterpreterFactory> Interpreters {
get { return _providers.Where(p => p != null).SelectMany(p => p.GetInterpreterFactories()); }
}
public IEnumerable<InterpreterConfiguration> Configurations {
get { return _providers.Where(p => p != null).SelectMany(p => p.GetInterpreterFactories()).Select(x => x.Configuration); }
}
public IEnumerable<IPythonInterpreterFactory> InterpretersOrDefault {
get {
if (Interpreters.Any()) {
return Interpreters;
}
return Enumerable.Repeat(_noInterpretersValue, 1);
}
}
public IPythonInterpreterFactory NoInterpretersValue {
get { return _noInterpretersValue; }
}
public event EventHandler InterpretersChanged;
public void BeginSuppressInterpretersChangedEvent() {
throw new NotImplementedException();
}
public void EndSuppressInterpretersChangedEvent() {
throw new NotImplementedException();
}
public IPythonInterpreterFactory DefaultInterpreter {
get {
return _defaultInterpreter ?? _noInterpretersValue;
}
set {
if (value == _noInterpretersValue) {
value = null;
}
if (value != _defaultInterpreter) {
_defaultInterpreter = value;
var evt = DefaultInterpreterChanged;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
}
}
public string DefaultInterpreterId {
get {
return DefaultInterpreter?.Configuration?.Id;
}
set {
DefaultInterpreter = FindInterpreter(value);
}
}
public event EventHandler DefaultInterpreterChanged;
public bool IsInterpreterGeneratingDatabase(IPythonInterpreterFactory interpreter) {
throw new NotImplementedException();
}
public void RemoveConfigurableInterpreter(string id) {
throw new NotImplementedException();
}
public bool IsConfigurable(string id) {
return true;
//throw new NotImplementedException();
}
public IPythonInterpreterFactory FindInterpreter(string id) {
foreach (var interp in _providers) {
foreach (var config in interp.GetInterpreterConfigurations()) {
if (config.Id == id) {
return interp.GetInterpreterFactory(id);
}
}
}
return null;
}
public Task<object> LockInterpreterAsync(IPythonInterpreterFactory factory, object moniker, TimeSpan timeout) {
throw new NotImplementedException();
}
public bool IsInterpreterLocked(IPythonInterpreterFactory factory, object moniker) {
throw new NotImplementedException();
}
public bool UnlockInterpreter(object cookie) {
throw new NotImplementedException();
}
public InterpreterConfiguration FindConfiguration(string id) {
foreach (var interp in _providers) {
foreach (var config in interp.GetInterpreterConfigurations()) {
if (config.Id == id) {
return config;
}
}
}
return null;
}
public string AddConfigurableInterpreter(string name, InterpreterConfiguration config) {
throw new NotImplementedException();
}
public object GetProperty(string id, string propName) {
foreach (var interp in _providers) {
foreach (var config in interp.GetInterpreterConfigurations()) {
if (config.Id == id) {
return interp.GetProperty(id, propName);
}
}
}
return null;
}
public void AddPackageManagers(IPythonInterpreterFactory factory, IReadOnlyList<IPackageManager> packageManagers) {
_packageManagers[factory] = packageManagers;
}
public IEnumerable<IPackageManager> GetPackageManagers(IPythonInterpreterFactory factory) {
try {
return _packageManagers[factory];
} catch (KeyNotFoundException) {
return Enumerable.Empty<IPackageManager>();
}
}
}
}
| |
// 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.Reflection.Emit
{
public enum FlowControl
{
Branch = 0,
Break = 1,
Call = 2,
Cond_Branch = 3,
Meta = 4,
Next = 5,
[System.ObsoleteAttribute("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
Phi = 6,
Return = 7,
Throw = 8,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct OpCode
{
public System.Reflection.Emit.FlowControl FlowControl { get { throw null; } }
public string Name { get { throw null; } }
public System.Reflection.Emit.OpCodeType OpCodeType { get { throw null; } }
public System.Reflection.Emit.OperandType OperandType { get { throw null; } }
public int Size { get { throw null; } }
public System.Reflection.Emit.StackBehaviour StackBehaviourPop { get { throw null; } }
public System.Reflection.Emit.StackBehaviour StackBehaviourPush { get { throw null; } }
public short Value { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Reflection.Emit.OpCode obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { throw null; }
public static bool operator !=(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { throw null; }
public override string ToString() { throw null; }
}
public partial class OpCodes
{
internal OpCodes() { }
public static readonly System.Reflection.Emit.OpCode Add;
public static readonly System.Reflection.Emit.OpCode Add_Ovf;
public static readonly System.Reflection.Emit.OpCode Add_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode And;
public static readonly System.Reflection.Emit.OpCode Arglist;
public static readonly System.Reflection.Emit.OpCode Beq;
public static readonly System.Reflection.Emit.OpCode Beq_S;
public static readonly System.Reflection.Emit.OpCode Bge;
public static readonly System.Reflection.Emit.OpCode Bge_S;
public static readonly System.Reflection.Emit.OpCode Bge_Un;
public static readonly System.Reflection.Emit.OpCode Bge_Un_S;
public static readonly System.Reflection.Emit.OpCode Bgt;
public static readonly System.Reflection.Emit.OpCode Bgt_S;
public static readonly System.Reflection.Emit.OpCode Bgt_Un;
public static readonly System.Reflection.Emit.OpCode Bgt_Un_S;
public static readonly System.Reflection.Emit.OpCode Ble;
public static readonly System.Reflection.Emit.OpCode Ble_S;
public static readonly System.Reflection.Emit.OpCode Ble_Un;
public static readonly System.Reflection.Emit.OpCode Ble_Un_S;
public static readonly System.Reflection.Emit.OpCode Blt;
public static readonly System.Reflection.Emit.OpCode Blt_S;
public static readonly System.Reflection.Emit.OpCode Blt_Un;
public static readonly System.Reflection.Emit.OpCode Blt_Un_S;
public static readonly System.Reflection.Emit.OpCode Bne_Un;
public static readonly System.Reflection.Emit.OpCode Bne_Un_S;
public static readonly System.Reflection.Emit.OpCode Box;
public static readonly System.Reflection.Emit.OpCode Br;
public static readonly System.Reflection.Emit.OpCode Br_S;
public static readonly System.Reflection.Emit.OpCode Break;
public static readonly System.Reflection.Emit.OpCode Brfalse;
public static readonly System.Reflection.Emit.OpCode Brfalse_S;
public static readonly System.Reflection.Emit.OpCode Brtrue;
public static readonly System.Reflection.Emit.OpCode Brtrue_S;
public static readonly System.Reflection.Emit.OpCode Call;
public static readonly System.Reflection.Emit.OpCode Calli;
public static readonly System.Reflection.Emit.OpCode Callvirt;
public static readonly System.Reflection.Emit.OpCode Castclass;
public static readonly System.Reflection.Emit.OpCode Ceq;
public static readonly System.Reflection.Emit.OpCode Cgt;
public static readonly System.Reflection.Emit.OpCode Cgt_Un;
public static readonly System.Reflection.Emit.OpCode Ckfinite;
public static readonly System.Reflection.Emit.OpCode Clt;
public static readonly System.Reflection.Emit.OpCode Clt_Un;
public static readonly System.Reflection.Emit.OpCode Constrained;
public static readonly System.Reflection.Emit.OpCode Conv_I;
public static readonly System.Reflection.Emit.OpCode Conv_I1;
public static readonly System.Reflection.Emit.OpCode Conv_I2;
public static readonly System.Reflection.Emit.OpCode Conv_I4;
public static readonly System.Reflection.Emit.OpCode Conv_I8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8_Un;
public static readonly System.Reflection.Emit.OpCode Conv_R_Un;
public static readonly System.Reflection.Emit.OpCode Conv_R4;
public static readonly System.Reflection.Emit.OpCode Conv_R8;
public static readonly System.Reflection.Emit.OpCode Conv_U;
public static readonly System.Reflection.Emit.OpCode Conv_U1;
public static readonly System.Reflection.Emit.OpCode Conv_U2;
public static readonly System.Reflection.Emit.OpCode Conv_U4;
public static readonly System.Reflection.Emit.OpCode Conv_U8;
public static readonly System.Reflection.Emit.OpCode Cpblk;
public static readonly System.Reflection.Emit.OpCode Cpobj;
public static readonly System.Reflection.Emit.OpCode Div;
public static readonly System.Reflection.Emit.OpCode Div_Un;
public static readonly System.Reflection.Emit.OpCode Dup;
public static readonly System.Reflection.Emit.OpCode Endfilter;
public static readonly System.Reflection.Emit.OpCode Endfinally;
public static readonly System.Reflection.Emit.OpCode Initblk;
public static readonly System.Reflection.Emit.OpCode Initobj;
public static readonly System.Reflection.Emit.OpCode Isinst;
public static readonly System.Reflection.Emit.OpCode Jmp;
public static readonly System.Reflection.Emit.OpCode Ldarg;
public static readonly System.Reflection.Emit.OpCode Ldarg_0;
public static readonly System.Reflection.Emit.OpCode Ldarg_1;
public static readonly System.Reflection.Emit.OpCode Ldarg_2;
public static readonly System.Reflection.Emit.OpCode Ldarg_3;
public static readonly System.Reflection.Emit.OpCode Ldarg_S;
public static readonly System.Reflection.Emit.OpCode Ldarga;
public static readonly System.Reflection.Emit.OpCode Ldarga_S;
public static readonly System.Reflection.Emit.OpCode Ldc_I4;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_0;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_1;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_2;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_3;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_4;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_5;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_6;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_7;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_8;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_M1;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_S;
public static readonly System.Reflection.Emit.OpCode Ldc_I8;
public static readonly System.Reflection.Emit.OpCode Ldc_R4;
public static readonly System.Reflection.Emit.OpCode Ldc_R8;
public static readonly System.Reflection.Emit.OpCode Ldelem;
public static readonly System.Reflection.Emit.OpCode Ldelem_I;
public static readonly System.Reflection.Emit.OpCode Ldelem_I1;
public static readonly System.Reflection.Emit.OpCode Ldelem_I2;
public static readonly System.Reflection.Emit.OpCode Ldelem_I4;
public static readonly System.Reflection.Emit.OpCode Ldelem_I8;
public static readonly System.Reflection.Emit.OpCode Ldelem_R4;
public static readonly System.Reflection.Emit.OpCode Ldelem_R8;
public static readonly System.Reflection.Emit.OpCode Ldelem_Ref;
public static readonly System.Reflection.Emit.OpCode Ldelem_U1;
public static readonly System.Reflection.Emit.OpCode Ldelem_U2;
public static readonly System.Reflection.Emit.OpCode Ldelem_U4;
public static readonly System.Reflection.Emit.OpCode Ldelema;
public static readonly System.Reflection.Emit.OpCode Ldfld;
public static readonly System.Reflection.Emit.OpCode Ldflda;
public static readonly System.Reflection.Emit.OpCode Ldftn;
public static readonly System.Reflection.Emit.OpCode Ldind_I;
public static readonly System.Reflection.Emit.OpCode Ldind_I1;
public static readonly System.Reflection.Emit.OpCode Ldind_I2;
public static readonly System.Reflection.Emit.OpCode Ldind_I4;
public static readonly System.Reflection.Emit.OpCode Ldind_I8;
public static readonly System.Reflection.Emit.OpCode Ldind_R4;
public static readonly System.Reflection.Emit.OpCode Ldind_R8;
public static readonly System.Reflection.Emit.OpCode Ldind_Ref;
public static readonly System.Reflection.Emit.OpCode Ldind_U1;
public static readonly System.Reflection.Emit.OpCode Ldind_U2;
public static readonly System.Reflection.Emit.OpCode Ldind_U4;
public static readonly System.Reflection.Emit.OpCode Ldlen;
public static readonly System.Reflection.Emit.OpCode Ldloc;
public static readonly System.Reflection.Emit.OpCode Ldloc_0;
public static readonly System.Reflection.Emit.OpCode Ldloc_1;
public static readonly System.Reflection.Emit.OpCode Ldloc_2;
public static readonly System.Reflection.Emit.OpCode Ldloc_3;
public static readonly System.Reflection.Emit.OpCode Ldloc_S;
public static readonly System.Reflection.Emit.OpCode Ldloca;
public static readonly System.Reflection.Emit.OpCode Ldloca_S;
public static readonly System.Reflection.Emit.OpCode Ldnull;
public static readonly System.Reflection.Emit.OpCode Ldobj;
public static readonly System.Reflection.Emit.OpCode Ldsfld;
public static readonly System.Reflection.Emit.OpCode Ldsflda;
public static readonly System.Reflection.Emit.OpCode Ldstr;
public static readonly System.Reflection.Emit.OpCode Ldtoken;
public static readonly System.Reflection.Emit.OpCode Ldvirtftn;
public static readonly System.Reflection.Emit.OpCode Leave;
public static readonly System.Reflection.Emit.OpCode Leave_S;
public static readonly System.Reflection.Emit.OpCode Localloc;
public static readonly System.Reflection.Emit.OpCode Mkrefany;
public static readonly System.Reflection.Emit.OpCode Mul;
public static readonly System.Reflection.Emit.OpCode Mul_Ovf;
public static readonly System.Reflection.Emit.OpCode Mul_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode Neg;
public static readonly System.Reflection.Emit.OpCode Newarr;
public static readonly System.Reflection.Emit.OpCode Newobj;
public static readonly System.Reflection.Emit.OpCode Nop;
public static readonly System.Reflection.Emit.OpCode Not;
public static readonly System.Reflection.Emit.OpCode Or;
public static readonly System.Reflection.Emit.OpCode Pop;
public static readonly System.Reflection.Emit.OpCode Prefix1;
public static readonly System.Reflection.Emit.OpCode Prefix2;
public static readonly System.Reflection.Emit.OpCode Prefix3;
public static readonly System.Reflection.Emit.OpCode Prefix4;
public static readonly System.Reflection.Emit.OpCode Prefix5;
public static readonly System.Reflection.Emit.OpCode Prefix6;
public static readonly System.Reflection.Emit.OpCode Prefix7;
public static readonly System.Reflection.Emit.OpCode Prefixref;
public static readonly System.Reflection.Emit.OpCode Readonly;
public static readonly System.Reflection.Emit.OpCode Refanytype;
public static readonly System.Reflection.Emit.OpCode Refanyval;
public static readonly System.Reflection.Emit.OpCode Rem;
public static readonly System.Reflection.Emit.OpCode Rem_Un;
public static readonly System.Reflection.Emit.OpCode Ret;
public static readonly System.Reflection.Emit.OpCode Rethrow;
public static readonly System.Reflection.Emit.OpCode Shl;
public static readonly System.Reflection.Emit.OpCode Shr;
public static readonly System.Reflection.Emit.OpCode Shr_Un;
public static readonly System.Reflection.Emit.OpCode Sizeof;
public static readonly System.Reflection.Emit.OpCode Starg;
public static readonly System.Reflection.Emit.OpCode Starg_S;
public static readonly System.Reflection.Emit.OpCode Stelem;
public static readonly System.Reflection.Emit.OpCode Stelem_I;
public static readonly System.Reflection.Emit.OpCode Stelem_I1;
public static readonly System.Reflection.Emit.OpCode Stelem_I2;
public static readonly System.Reflection.Emit.OpCode Stelem_I4;
public static readonly System.Reflection.Emit.OpCode Stelem_I8;
public static readonly System.Reflection.Emit.OpCode Stelem_R4;
public static readonly System.Reflection.Emit.OpCode Stelem_R8;
public static readonly System.Reflection.Emit.OpCode Stelem_Ref;
public static readonly System.Reflection.Emit.OpCode Stfld;
public static readonly System.Reflection.Emit.OpCode Stind_I;
public static readonly System.Reflection.Emit.OpCode Stind_I1;
public static readonly System.Reflection.Emit.OpCode Stind_I2;
public static readonly System.Reflection.Emit.OpCode Stind_I4;
public static readonly System.Reflection.Emit.OpCode Stind_I8;
public static readonly System.Reflection.Emit.OpCode Stind_R4;
public static readonly System.Reflection.Emit.OpCode Stind_R8;
public static readonly System.Reflection.Emit.OpCode Stind_Ref;
public static readonly System.Reflection.Emit.OpCode Stloc;
public static readonly System.Reflection.Emit.OpCode Stloc_0;
public static readonly System.Reflection.Emit.OpCode Stloc_1;
public static readonly System.Reflection.Emit.OpCode Stloc_2;
public static readonly System.Reflection.Emit.OpCode Stloc_3;
public static readonly System.Reflection.Emit.OpCode Stloc_S;
public static readonly System.Reflection.Emit.OpCode Stobj;
public static readonly System.Reflection.Emit.OpCode Stsfld;
public static readonly System.Reflection.Emit.OpCode Sub;
public static readonly System.Reflection.Emit.OpCode Sub_Ovf;
public static readonly System.Reflection.Emit.OpCode Sub_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode Switch;
public static readonly System.Reflection.Emit.OpCode Tailcall;
public static readonly System.Reflection.Emit.OpCode Throw;
public static readonly System.Reflection.Emit.OpCode Unaligned;
public static readonly System.Reflection.Emit.OpCode Unbox;
public static readonly System.Reflection.Emit.OpCode Unbox_Any;
public static readonly System.Reflection.Emit.OpCode Volatile;
public static readonly System.Reflection.Emit.OpCode Xor;
public static bool TakesSingleByteArgument(System.Reflection.Emit.OpCode inst) { throw null; }
}
public enum OpCodeType
{
[System.ObsoleteAttribute("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
Annotation = 0,
Macro = 1,
Nternal = 2,
Objmodel = 3,
Prefix = 4,
Primitive = 5,
}
public enum OperandType
{
InlineBrTarget = 0,
InlineField = 1,
InlineI = 2,
InlineI8 = 3,
InlineMethod = 4,
InlineNone = 5,
[System.ObsoleteAttribute("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
InlinePhi = 6,
InlineR = 7,
InlineSig = 9,
InlineString = 10,
InlineSwitch = 11,
InlineTok = 12,
InlineType = 13,
InlineVar = 14,
ShortInlineBrTarget = 15,
ShortInlineI = 16,
ShortInlineR = 17,
ShortInlineVar = 18,
}
public enum PackingSize
{
Size1 = 1,
Size128 = 128,
Size16 = 16,
Size2 = 2,
Size32 = 32,
Size4 = 4,
Size64 = 64,
Size8 = 8,
Unspecified = 0,
}
public enum StackBehaviour
{
Pop0 = 0,
Pop1 = 1,
Pop1_pop1 = 2,
Popi = 3,
Popi_pop1 = 4,
Popi_popi = 5,
Popi_popi_popi = 7,
Popi_popi8 = 6,
Popi_popr4 = 8,
Popi_popr8 = 9,
Popref = 10,
Popref_pop1 = 11,
Popref_popi = 12,
Popref_popi_pop1 = 28,
Popref_popi_popi = 13,
Popref_popi_popi8 = 14,
Popref_popi_popr4 = 15,
Popref_popi_popr8 = 16,
Popref_popi_popref = 17,
Push0 = 18,
Push1 = 19,
Push1_push1 = 20,
Pushi = 21,
Pushi8 = 22,
Pushr4 = 23,
Pushr8 = 24,
Pushref = 25,
Varpop = 26,
Varpush = 27,
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace ClosedXML.Excel.CalcEngine
{
internal class Tally : IEnumerable<Object>
{
private readonly List<object> _list = new List<object>();
private readonly bool NumbersOnly;
private double[] _numericValues;
public Tally()
: this(false)
{ }
public Tally(bool numbersOnly)
: this(null, numbersOnly)
{ }
public Tally(IEnumerable<Expression> p)
: this(p, false)
{ }
public Tally(IEnumerable<Expression> p, bool numbersOnly)
{
if (p != null)
{
foreach (var e in p)
{
Add(e);
}
}
NumbersOnly = numbersOnly;
}
public void Add(Expression e)
{
// handle enumerables
var ienum = e as IEnumerable;
if (ienum != null)
{
foreach (var value in ienum)
{
_list.Add(value);
}
_numericValues = null;
return;
}
// handle expressions
var val = e.Evaluate();
var valEnumerable = val as IEnumerable;
if (valEnumerable == null || val is string)
_list.Add(val);
else
foreach (var v in valEnumerable)
_list.Add(v);
_numericValues = null;
}
public void AddValue(Object v)
{
_list.Add(v);
_numericValues = null;
}
public double Count()
{
return Count(NumbersOnly);
}
public double Count(bool numbersOnly)
{
if (numbersOnly)
return NumericValuesInternal().Length;
else
return _list.Count(o => !CalcEngineHelpers.ValueIsBlank(o));
}
private IEnumerable<double> NumericValuesEnumerable()
{
foreach (var value in _list)
{
var vEnumerable = value as IEnumerable;
if (vEnumerable == null || vEnumerable is string)
{
if (TryParseToDouble(value, out double tmp))
yield return tmp;
}
else
{
foreach (var v in vEnumerable)
{
if (TryParseToDouble(v, out double tmp))
yield return tmp;
}
}
}
}
private bool TryParseToDouble(object value, out double d)
{
if (value.IsNumber())
{
d = Convert.ToDouble(value);
return true;
}
else if (value is DateTime)
{
d = Convert.ToDouble(((DateTime)value).ToOADate());
return true;
}
else
{
return double.TryParse(value.ToString(), out d);
}
}
private double[] NumericValuesInternal()
=> LazyInitializer.EnsureInitialized(ref _numericValues, () => NumericValuesEnumerable().ToArray());
public IEnumerable<double> NumericValues()
=> NumericValuesInternal().AsEnumerable();
public double Product()
{
var nums = NumericValuesInternal();
return nums.Length == 0
? 0
: nums.Aggregate(1d, (a, b) => a * b);
}
public double Sum() => NumericValuesInternal().Sum();
public double Average()
{
var nums = NumericValuesInternal();
if (nums.Length == 0) throw new ApplicationException("No values");
return nums.Average();
}
public double Min()
{
var nums = NumericValuesInternal();
return nums.Length == 0 ? 0 : nums.Min();
}
public double Max()
{
var nums = NumericValuesInternal();
return nums.Length == 0 ? 0 : nums.Max();
}
public double Range() => Max() - Min();
private static double Sum2(IEnumerable<double> nums)
{
return nums.Sum(d => d * d);
}
public double VarP()
{
var nums = NumericValuesInternal();
var avg = nums.Average();
var sum2 = Sum2(nums);
var count = nums.Length;
return count <= 1 ? 0 : sum2 / count - avg * avg;
}
public double StdP()
{
var nums = NumericValuesInternal();
var avg = nums.Average();
var sum2 = nums.Sum(d => d * d);
var count = nums.Length;
return count <= 1 ? 0 : Math.Sqrt(sum2 / count - avg * avg);
}
public double Var()
{
var nums = NumericValuesInternal();
var avg = nums.Average();
var sum2 = Sum2(nums);
var count = nums.Length;
return count <= 1 ? 0 : (sum2 / count - avg * avg) * count / (count - 1);
}
public double Std()
{
var values = NumericValuesInternal();
var count = values.Length;
double ret = 0;
if (count != 0)
{
//Compute the Average
double avg = values.Average();
//Perform the Sum of (value-avg)_2_2
double sum = values.Sum(d => Math.Pow(d - avg, 2));
//Put it all together
ret = Math.Sqrt((sum) / (count - 1));
}
else
{
throw new ApplicationException("No values");
}
return ret;
}
public IEnumerator<object> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// 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.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.DistributedEmission.Iff
{
/// <summary>
/// Enumeration values for Type5Parameter1RRBResponse (der.iff.type.5.fop.param1, Parameter 1 - RRB Response,
/// section 8.3.5.2.2)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public struct Type5Parameter1RRBResponse
{
/// <summary>
/// Power Reduction
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Power Reduction")]
public enum PowerReductionValue : uint
{
/// <summary>
/// Off
/// </summary>
Off = 0,
/// <summary>
/// On
/// </summary>
On = 1
}
/// <summary>
/// Radar Enhancement
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Radar Enhancement")]
public enum RadarEnhancementValue : uint
{
/// <summary>
/// Off
/// </summary>
Off = 0,
/// <summary>
/// On
/// </summary>
On = 1
}
/// <summary>
/// Status
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Status")]
public enum StatusValue : uint
{
/// <summary>
/// Off
/// </summary>
Off = 0,
/// <summary>
/// On
/// </summary>
On = 1
}
/// <summary>
/// Damage
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Damage")]
public enum DamageValue : uint
{
/// <summary>
/// No damage
/// </summary>
NoDamage = 0,
/// <summary>
/// Damage
/// </summary>
Damage = 1
}
/// <summary>
/// Malfunction
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Malfunction")]
public enum MalfunctionValue : uint
{
/// <summary>
/// No malfunction
/// </summary>
NoMalfunction = 0,
/// <summary>
/// Malfunction
/// </summary>
Malfunction = 1
}
private byte code;
private Type5Parameter1RRBResponse.PowerReductionValue powerReduction;
private Type5Parameter1RRBResponse.RadarEnhancementValue radarEnhancement;
private Type5Parameter1RRBResponse.StatusValue status;
private Type5Parameter1RRBResponse.DamageValue damage;
private Type5Parameter1RRBResponse.MalfunctionValue malfunction;
/// <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 !=(Type5Parameter1RRBResponse left, Type5Parameter1RRBResponse 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 operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(Type5Parameter1RRBResponse left, Type5Parameter1RRBResponse right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
// If parameters are null return false (cast to object to prevent recursive loop!)
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
/// <summary>
/// Performs an explicit conversion from <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> to <see cref="System.UInt16"/>.
/// </summary>
/// <param name="obj">The <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> scheme instance.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator ushort(Type5Parameter1RRBResponse obj)
{
return obj.ToUInt16();
}
/// <summary>
/// Performs an explicit conversion from <see cref="System.UInt16"/> to <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/>.
/// </summary>
/// <param name="value">The ushort value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Type5Parameter1RRBResponse(ushort value)
{
return Type5Parameter1RRBResponse.FromUInt16(value);
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> instance from the byte array.
/// </summary>
/// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/>.</param>
/// <param name="index">The starting position within value.</param>
/// <returns>The <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> instance, represented by a byte array.</returns>
/// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception>
/// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception>
public static Type5Parameter1RRBResponse FromByteArray(byte[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (index < 0 ||
index > array.Length - 1 ||
index + 2 > array.Length - 1)
{
throw new IndexOutOfRangeException();
}
return FromUInt16(BitConverter.ToUInt16(array, index));
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> instance from the ushort value.
/// </summary>
/// <param name="value">The ushort value which represents the <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> instance.</param>
/// <returns>The <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> instance, represented by the ushort value.</returns>
public static Type5Parameter1RRBResponse FromUInt16(ushort value)
{
Type5Parameter1RRBResponse ps = new Type5Parameter1RRBResponse();
uint mask0 = 0x001f;
byte shift0 = 0;
uint newValue0 = value & mask0 >> shift0;
ps.Code = (byte)newValue0;
uint mask2 = 0x0800;
byte shift2 = 11;
uint newValue2 = value & mask2 >> shift2;
ps.PowerReduction = (Type5Parameter1RRBResponse.PowerReductionValue)newValue2;
uint mask3 = 0x1000;
byte shift3 = 12;
uint newValue3 = value & mask3 >> shift3;
ps.RadarEnhancement = (Type5Parameter1RRBResponse.RadarEnhancementValue)newValue3;
uint mask4 = 0x2000;
byte shift4 = 13;
uint newValue4 = value & mask4 >> shift4;
ps.Status = (Type5Parameter1RRBResponse.StatusValue)newValue4;
uint mask5 = 0x4000;
byte shift5 = 14;
uint newValue5 = value & mask5 >> shift5;
ps.Damage = (Type5Parameter1RRBResponse.DamageValue)newValue5;
uint mask6 = 0x8000;
byte shift6 = 15;
uint newValue6 = value & mask6 >> shift6;
ps.Malfunction = (Type5Parameter1RRBResponse.MalfunctionValue)newValue6;
return ps;
}
/// <summary>
/// Gets or sets the code.
/// </summary>
/// <value>The code.</value>
public byte Code
{
get { return this.code; }
set { this.code = value; }
}
/// <summary>
/// Gets or sets the powerreduction.
/// </summary>
/// <value>The powerreduction.</value>
public Type5Parameter1RRBResponse.PowerReductionValue PowerReduction
{
get { return this.powerReduction; }
set { this.powerReduction = value; }
}
/// <summary>
/// Gets or sets the radarenhancement.
/// </summary>
/// <value>The radarenhancement.</value>
public Type5Parameter1RRBResponse.RadarEnhancementValue RadarEnhancement
{
get { return this.radarEnhancement; }
set { this.radarEnhancement = value; }
}
/// <summary>
/// Gets or sets the status.
/// </summary>
/// <value>The status.</value>
public Type5Parameter1RRBResponse.StatusValue Status
{
get { return this.status; }
set { this.status = value; }
}
/// <summary>
/// Gets or sets the damage.
/// </summary>
/// <value>The damage.</value>
public Type5Parameter1RRBResponse.DamageValue Damage
{
get { return this.damage; }
set { this.damage = value; }
}
/// <summary>
/// Gets or sets the malfunction.
/// </summary>
/// <value>The malfunction.</value>
public Type5Parameter1RRBResponse.MalfunctionValue Malfunction
{
get { return this.malfunction; }
set { this.malfunction = value; }
}
/// <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)
{
if (obj == null)
{
return false;
}
if (!(obj is Type5Parameter1RRBResponse))
{
return false;
}
return this.Equals((Type5Parameter1RRBResponse)obj);
}
/// <summary>
/// Determines whether the specified <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> instance is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> instance to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Type5Parameter1RRBResponse other)
{
// If parameter is null return false (cast to object to prevent recursive loop!)
if ((object)other == null)
{
return false;
}
return
this.Code == other.Code &&
this.PowerReduction == other.PowerReduction &&
this.RadarEnhancement == other.RadarEnhancement &&
this.Status == other.Status &&
this.Damage == other.Damage &&
this.Malfunction == other.Malfunction;
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> to the byte array.
/// </summary>
/// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> instance.</returns>
public byte[] ToByteArray()
{
return BitConverter.GetBytes(this.ToUInt16());
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> to the ushort value.
/// </summary>
/// <returns>The ushort value representing the current <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type5Parameter1RRBResponse"/> instance.</returns>
public ushort ToUInt16()
{
ushort val = 0;
val |= (ushort)((uint)this.Code << 0);
val |= (ushort)((uint)this.PowerReduction << 11);
val |= (ushort)((uint)this.RadarEnhancement << 12);
val |= (ushort)((uint)this.Status << 13);
val |= (ushort)((uint)this.Damage << 14);
val |= (ushort)((uint)this.Malfunction << 15);
return val;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
int hash = 17;
// Overflow is fine, just wrap
unchecked
{
hash = (hash * 29) + this.Code.GetHashCode();
hash = (hash * 29) + this.PowerReduction.GetHashCode();
hash = (hash * 29) + this.RadarEnhancement.GetHashCode();
hash = (hash * 29) + this.Status.GetHashCode();
hash = (hash * 29) + this.Damage.GetHashCode();
hash = (hash * 29) + this.Malfunction.GetHashCode();
}
return hash;
}
}
}
| |
using System.Collections;
using System.Drawing;
namespace GuruComponents.CodeEditor.CodeEditor.Syntax
{
/// <summary>
/// BlockType class
/// </summary>
/// <remarks>
/// The BlockType class represents a specific code/text element<br/>
/// such as a string , comment or the code itself.<br/>
/// <br/>
/// a BlockType can contain keywords , operators , scopes and child BlockTypes.<br/>
/// <br/>
/// <br/>
/// For example , if we where to describe the language C#<br/>
/// we would have the following blocks:<br/>
/// <br/>
/// Code block - the BlockType containing all the keywords and operators.<br/>
/// Singleline comment block - a BlockType that starts on // terminates at the end of a line.<br/>
/// Multiline comment block - a BlockType that starts on /* can span multiple rows and terminates on */.<br/>
/// String block - a BlockType that starts on " terminates on " or at the end of a line.<br/>
/// Char block - a BlockType that starts on ' terminates on ' or at the end of a line.<br/>
/// <br/>
/// <b>CHILD BLOCKS:</b><br/>
/// The code block would have all the other blocks as childblocks , since they can only appear inside the<br/>
/// code block . A string can for example never exist inside a comment in C#.<br/>
/// a BlockType can also have itself as a child block.<br/>
/// For example , the C# Code block can have itself as a childblock and use the scope patterns "{" and "}"<br/>
/// this way we can accomplish FOLDING since the parser will know where a new scope starts and ends.<br/>
/// <br/>
/// <b>SCOPES:</b><br/>
/// Scopes describe what patterns starts and what patterns end a specific BlockType.<br/>
/// For example , the C# Multiline Comment have the scope patterns /* and */<br/>
/// <br/>
/// <b>KEYWORDS:</b><br/>
/// A Keyword is a pattern that can only exist between separator chars.<br/>
/// For example the keyword "for" in c# is valid if it is contained in this string " for ("<br/>
/// but it is not valid if the containing string is " MyFormat "<br/>
/// <br/>
/// <b>OPERATORS:</b><br/>
/// Operators is the same thing as keywords but are valid even if there are no separator chars around it.<br/>
/// In most cases operators are only one or two chars such as ":" or "->"<br/>
/// operators in this context should not be mixed up with code operators such as "and" or "xor" in VB6<br/>
/// in this context they are keywords.<br/>
///<br/>
/// <br/>
///</remarks>
public class BlockType
{
/// <summary>
/// A list of keyword groups.
/// For example , one keyword group could be "keywords" and another could be "datatypes"
/// theese groups could have different color shemes assigned to them.
/// </summary>
public PatternListList KeywordsList = null; //new PatternListList (this);
/// <summary>
/// A list of operator groups.
/// Each operator group can contain its own operator patterns and its own color shemes.
/// </summary>
public PatternListList OperatorsList = null; //new PatternListList (this);
/// <summary>
/// A list of scopes , most block only contain one scope , eg a scope with start and end patterns "/*" and "*/"
/// for multiline comments, but in some cases you will need more scopes , eg. PHP uses both "<?" , "?>" and "<?PHP" , "PHP?>"
/// </summary>
public ScopeCollection ScopePatterns = null;
/// <summary>
/// A list containing which BlockTypes are valid child blocks in a specific block.
/// eg. strings and comments are child blocks for a code block
/// </summary>
public BlockTypeCollection ChildBlocks = new BlockTypeCollection();
/// <summary>
/// The style to use when colorizing the content of a block,
/// meaning everything in this block except keywords , operators and childblocks.
/// </summary>
public TextStyle Style;
/// <summary>
/// The name of this block.
/// names are not required for block but can be a good help when interacting with the parser.
/// </summary>
public string Name = "";
/// <summary>
/// The background color of a block.
/// </summary>
public Color BackColor = Color.Transparent;
/// <summary>
/// Gets or Sets if the BlockType can span multiple lines or if it should terminate at the end of a line.
/// </summary>
public bool MultiLine = false;
/// <summary>
/// Gets or Sets if the parser should terminate any child block when it finds an end scope pattern for this block.
/// for example %> in asp terminates any asp block even if it appears inside an asp string.
/// </summary>
public bool TerminateChildren = false;
/// <summary>
/// Returns false if any color has been assigned to the backcolor property
/// </summary>
public bool Transparent
{
get { return (BackColor.A == 0); }
}
/// <summary>
/// Default BlockType constructor
/// </summary>
public BlockType(Language parent) : this()
{
this.Parent = parent;
this.Parent.ChangeVersion();
}
public BlockType()
{
this.KeywordsList = new PatternListList(this);
this.OperatorsList = new PatternListList(this);
Style = new TextStyle();
KeywordsList.Parent = this;
KeywordsList.IsKeyword = true;
OperatorsList.Parent = this;
OperatorsList.IsOperator = true;
ScopePatterns = new ScopeCollection(this);
}
#region PUBLIC PROPERTY PARENT
private Language _Parent;
public Language Parent
{
get { return _Parent; }
set { _Parent = value; }
}
#endregion
public Hashtable LookupTable = new Hashtable();
private ArrayList tmpSimplePatterns = new ArrayList();
public PatternCollection ComplexPatterns = new PatternCollection();
public void ResetLookupTable()
{
this.LookupTable.Clear();
this.tmpSimplePatterns.Clear();
this.ComplexPatterns.Clear();
}
public void AddToLookupTable(Pattern pattern)
{
if (pattern.IsComplex)
{
ComplexPatterns.Add(pattern);
return;
}
else
{
this.tmpSimplePatterns.Add(pattern);
}
}
public void BuildLookupTable()
{
IComparer comparer = new PatternComparer();
this.tmpSimplePatterns.Sort(comparer);
foreach (Pattern p in tmpSimplePatterns)
{
if (p.StringPattern.Length <= 2)
{
char c = p.StringPattern[0];
if (!p.Parent.CaseSensitive)
{
char c1 = char.ToLower(c);
if (LookupTable[c1] == null)
LookupTable[c1] = new PatternCollection();
PatternCollection patterns = LookupTable[c1] as PatternCollection;
if (!patterns.Contains(p))
patterns.Add(p);
char c2 = char.ToUpper(c);
if (LookupTable[c2] == null)
LookupTable[c2] = new PatternCollection();
patterns = LookupTable[c2] as PatternCollection;
if (!patterns.Contains(p))
patterns.Add(p);
}
else
{
if (LookupTable[c] == null)
LookupTable[c] = new PatternCollection();
PatternCollection patterns = LookupTable[c] as PatternCollection;
if (!patterns.Contains(p))
patterns.Add(p);
}
}
else
{
string c = p.StringPattern.Substring(0, 3).ToLower();
if (LookupTable[c] == null)
LookupTable[c] = new PatternCollection();
PatternCollection patterns = LookupTable[c] as PatternCollection;
if (!patterns.Contains(p))
patterns.Add(p);
}
}
}
}
public class PatternComparer : IComparer
{
#region Implementation of IComparer
public int Compare(object x, object y)
{
Pattern xx = x as Pattern;
Pattern yy = y as Pattern;
return yy.StringPattern.Length.CompareTo(xx.StringPattern.Length);
}
#endregion
}
}
| |
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
using System;
using Object = UnityEngine.Object;
namespace XNodeEditor {
[InitializeOnLoad]
public partial class NodeEditorWindow : EditorWindow {
public static NodeEditorWindow current;
/// <summary> Stores node positions for all nodePorts. </summary>
public Dictionary<XNode.NodePort, Rect> portConnectionPoints { get { return _portConnectionPoints; } }
private Dictionary<XNode.NodePort, Rect> _portConnectionPoints = new Dictionary<XNode.NodePort, Rect>();
[SerializeField] private NodePortReference[] _references = new NodePortReference[0];
[SerializeField] private Rect[] _rects = new Rect[0];
private Func<bool> isDocked {
get {
if (_isDocked == null) _isDocked = this.GetIsDockedDelegate();
return _isDocked;
}
}
private Func<bool> _isDocked;
[System.Serializable] private class NodePortReference {
[SerializeField] private XNode.Node _node;
[SerializeField] private string _name;
public NodePortReference(XNode.NodePort nodePort) {
_node = nodePort.node;
_name = nodePort.fieldName;
}
public XNode.NodePort GetNodePort() {
if (_node == null) {
return null;
}
return _node.GetPort(_name);
}
}
private void OnDisable() {
// Cache portConnectionPoints before serialization starts
int count = portConnectionPoints.Count;
_references = new NodePortReference[count];
_rects = new Rect[count];
int index = 0;
foreach (var portConnectionPoint in portConnectionPoints) {
_references[index] = new NodePortReference(portConnectionPoint.Key);
_rects[index] = portConnectionPoint.Value;
index++;
}
}
private void OnEnable() {
// Reload portConnectionPoints if there are any
int length = _references.Length;
if (length == _rects.Length) {
for (int i = 0; i < length; i++) {
XNode.NodePort nodePort = _references[i].GetNodePort();
if (nodePort != null)
_portConnectionPoints.Add(nodePort, _rects[i]);
}
}
}
public Dictionary<XNode.Node, Vector2> nodeSizes { get { return _nodeSizes; } }
private Dictionary<XNode.Node, Vector2> _nodeSizes = new Dictionary<XNode.Node, Vector2>();
public XNode.NodeGraph graph;
public Vector2 panOffset { get { return _panOffset; } set { _panOffset = value; Repaint(); } }
private Vector2 _panOffset;
public float zoom { get { return _zoom; } set { _zoom = Mathf.Clamp(value, NodeEditorPreferences.GetSettings().minZoom, NodeEditorPreferences.GetSettings().maxZoom); Repaint(); } }
private float _zoom = 1;
void OnFocus() {
current = this;
ValidateGraphEditor();
if (graphEditor != null) {
graphEditor.OnWindowFocus();
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
}
dragThreshold = Math.Max(1f, Screen.width / 1000f);
}
void OnLostFocus() {
if (graphEditor != null) graphEditor.OnWindowFocusLost();
}
[InitializeOnLoadMethod]
private static void OnLoad() {
Selection.selectionChanged -= OnSelectionChanged;
Selection.selectionChanged += OnSelectionChanged;
}
/// <summary> Handle Selection Change events</summary>
private static void OnSelectionChanged() {
XNode.NodeGraph nodeGraph = Selection.activeObject as XNode.NodeGraph;
if (nodeGraph && !AssetDatabase.Contains(nodeGraph)) {
Open(nodeGraph);
}
}
/// <summary> Make sure the graph editor is assigned and to the right object </summary>
private void ValidateGraphEditor() {
NodeGraphEditor graphEditor = NodeGraphEditor.GetEditor(graph, this);
if (this.graphEditor != graphEditor && graphEditor != null) {
this.graphEditor = graphEditor;
graphEditor.OnOpen();
}
}
/// <summary> Create editor window </summary>
public static NodeEditorWindow Init() {
NodeEditorWindow w = CreateInstance<NodeEditorWindow>();
w.titleContent = new GUIContent("xNode");
w.wantsMouseMove = true;
w.Show();
return w;
}
public void Save() {
if (AssetDatabase.Contains(graph)) {
EditorUtility.SetDirty(graph);
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
} else SaveAs();
}
public void SaveAs() {
string path = EditorUtility.SaveFilePanelInProject("Save NodeGraph", "NewNodeGraph", "asset", "");
if (string.IsNullOrEmpty(path)) return;
else {
XNode.NodeGraph existingGraph = AssetDatabase.LoadAssetAtPath<XNode.NodeGraph>(path);
if (existingGraph != null) AssetDatabase.DeleteAsset(path);
AssetDatabase.CreateAsset(graph, path);
EditorUtility.SetDirty(graph);
if (NodeEditorPreferences.GetSettings().autoSave) AssetDatabase.SaveAssets();
}
}
private void DraggableWindow(int windowID) {
GUI.DragWindow();
}
public Vector2 WindowToGridPosition(Vector2 windowPosition) {
return (windowPosition - (position.size * 0.5f) - (panOffset / zoom)) * zoom;
}
public Vector2 GridToWindowPosition(Vector2 gridPosition) {
return (position.size * 0.5f) + (panOffset / zoom) + (gridPosition / zoom);
}
public Rect GridToWindowRectNoClipped(Rect gridRect) {
gridRect.position = GridToWindowPositionNoClipped(gridRect.position);
return gridRect;
}
public Rect GridToWindowRect(Rect gridRect) {
gridRect.position = GridToWindowPosition(gridRect.position);
gridRect.size /= zoom;
return gridRect;
}
public Vector2 GridToWindowPositionNoClipped(Vector2 gridPosition) {
Vector2 center = position.size * 0.5f;
// UI Sharpness complete fix - Round final offset not panOffset
float xOffset = Mathf.Round(center.x * zoom + (panOffset.x + gridPosition.x));
float yOffset = Mathf.Round(center.y * zoom + (panOffset.y + gridPosition.y));
return new Vector2(xOffset, yOffset);
}
public void SelectNode(XNode.Node node, bool add) {
if (add) {
List<Object> selection = new List<Object>(Selection.objects);
selection.Add(node);
Selection.objects = selection.ToArray();
} else Selection.objects = new Object[] { node };
}
public void DeselectNode(XNode.Node node) {
List<Object> selection = new List<Object>(Selection.objects);
selection.Remove(node);
Selection.objects = selection.ToArray();
}
[OnOpenAsset(0)]
public static bool OnOpen(int instanceID, int line) {
XNode.NodeGraph nodeGraph = EditorUtility.InstanceIDToObject(instanceID) as XNode.NodeGraph;
if (nodeGraph != null) {
Open(nodeGraph);
return true;
}
return false;
}
/// <summary>Open the provided graph in the NodeEditor</summary>
public static NodeEditorWindow Open(XNode.NodeGraph graph) {
if (!graph) return null;
NodeEditorWindow w = GetWindow(typeof(NodeEditorWindow), false, "xNode", true) as NodeEditorWindow;
w.wantsMouseMove = true;
w.graph = graph;
return w;
}
/// <summary> Repaint all open NodeEditorWindows. </summary>
public static void RepaintAll() {
NodeEditorWindow[] windows = Resources.FindObjectsOfTypeAll<NodeEditorWindow>();
for (int i = 0; i < windows.Length; i++) {
windows[i].Repaint();
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Python.Parsing;
using Microsoft.PythonTools.Editor.Core;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudioTools;
using IServiceProvider = System.IServiceProvider;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.PythonTools.Commands {
/// <summary>
/// Provides the command to send selected text from a buffer to the remote REPL window.
///
/// The command supports either sending a selection or sending line-by-line. In line-by-line
/// mode the user should be able to just hold down on Alt-Enter and have an entire script
/// execute as if they ran it in the interactive window. Focus will continue to remain in
/// the active text view.
///
/// In selection mode the users selection is executed and focus is transfered to the interactive
/// window and their selection remains unchanged.
/// </summary>
class SendToReplCommand : Command {
protected readonly IServiceProvider _serviceProvider;
private static string[] _newLineChars = new[] { "\r\n", "\n", "\r" };
private static object _executedLastLine = new object();
public SendToReplCommand(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider;
}
public override async void DoCommand(object sender, EventArgs args) {
var activeView = CommonPackage.GetActiveTextView(_serviceProvider);
var project = activeView.GetProjectAtCaret(_serviceProvider);
var configuration = activeView.GetInterpreterConfigurationAtCaret(_serviceProvider);
ITextSelection selection = activeView.Selection;
ITextSnapshot snapshot = activeView.TextBuffer.CurrentSnapshot;
var workspace = _serviceProvider.GetWorkspace();
IVsInteractiveWindow repl;
try {
repl = ExecuteInReplCommand.EnsureReplWindow(_serviceProvider, configuration, project, workspace);
} catch (MissingInterpreterException ex) {
MessageBox.Show(ex.Message, Strings.ProductTitle);
return;
}
string input;
bool focusRepl = false, alwaysSubmit = false;
if (selection.StreamSelectionSpan.Length > 0) {
// Easy, just send the selection to the interactive window.
input = activeView.Selection.StreamSelectionSpan.GetText();
if (!input.EndsWithOrdinal("\n") && !input.EndsWithOrdinal("\r")) {
input += activeView.Options.GetNewLineCharacter();
}
focusRepl = true;
} else if (!activeView.Properties.ContainsProperty(_executedLastLine)) {
// No selection, and we haven't hit the end of the file in line-by-line mode.
// Send the current line, and then move the caret to the next non-blank line.
ITextSnapshotLine targetLine = snapshot.GetLineFromPosition(selection.Start.Position);
var targetSpan = targetLine.Extent;
// If the line is inside a code cell, expand the target span to
// contain the entire cell.
var cellStart = CodeCellAnalysis.FindStartOfCell(targetLine);
if (cellStart != null) {
var cellEnd = CodeCellAnalysis.FindEndOfCell(cellStart, targetLine);
targetSpan = new SnapshotSpan(cellStart.Start, cellEnd.End);
targetLine = CodeCellAnalysis.FindEndOfCell(cellEnd, targetLine, includeWhitespace: true);
alwaysSubmit = true;
}
input = targetSpan.GetText();
bool moved = false;
while (targetLine.LineNumber < snapshot.LineCount - 1) {
targetLine = snapshot.GetLineFromLineNumber(targetLine.LineNumber + 1);
// skip over blank lines, unless it's the last line, in which case we want to land on it no matter what
if (!string.IsNullOrWhiteSpace(targetLine.GetText()) ||
targetLine.LineNumber == snapshot.LineCount - 1) {
activeView.Caret.MoveTo(new SnapshotPoint(snapshot, targetLine.Start));
activeView.Caret.EnsureVisible();
moved = true;
break;
}
}
if (!moved) {
// There's no where for the caret to go, don't execute the line if
// we've already executed it.
activeView.Caret.PositionChanged += Caret_PositionChanged;
activeView.Properties[_executedLastLine] = _executedLastLine;
}
} else if ((repl.InteractiveWindow.CurrentLanguageBuffer?.CurrentSnapshot.Length ?? 0) != 0) {
// We reached the end of the file but have some text buffered. Execute it now.
input = activeView.Options.GetNewLineCharacter();
} else {
// We've hit the end of the current text view and executed everything
input = null;
}
if (input != null) {
repl.Show(focusRepl);
var inputs = repl.InteractiveWindow.Properties.GetOrCreateSingletonProperty(
() => new InteractiveInputs(repl.InteractiveWindow, _serviceProvider, alwaysSubmit)
);
await inputs.EnqueueAsync(input);
}
// Take focus back if REPL window has stolen it and we're in line-by-line mode.
if (!focusRepl && !activeView.HasAggregateFocus) {
var adapterService = _serviceProvider.GetComponentModel().GetService<VisualStudio.Editor.IVsEditorAdaptersFactoryService>();
var tv = adapterService.GetViewAdapter(activeView);
tv.SendExplicitFocus();
}
}
private static void Caret_PositionChanged(object sender, CaretPositionChangedEventArgs e) {
e.TextView.Properties.RemoveProperty(_executedLastLine);
e.TextView.Caret.PositionChanged -= Caret_PositionChanged;
}
public override int? EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText) {
var activeView = CommonPackage.GetActiveTextView(_serviceProvider);
InterpreterConfiguration config;
if ((config = activeView?.GetInterpreterConfigurationAtCaret(_serviceProvider)) != null) {
if (activeView.Selection.Mode == TextSelectionMode.Box ||
config?.IsRunnable() != true) {
cmd.cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED);
} else {
cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
}
} else {
cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE);
}
return VSConstants.S_OK;
}
public override EventHandler BeforeQueryStatus {
get {
return (sender, args) => {
((OleMenuCommand)sender).Visible = false;
((OleMenuCommand)sender).Supported = false;
};
}
}
public override int CommandId {
get { return (int)PkgCmdIDList.cmdidSendToRepl; }
}
class InteractiveInputs {
private readonly LinkedList<string> _pendingInputs = new LinkedList<string>();
private readonly IServiceProvider _serviceProvider;
private readonly IInteractiveWindow _window;
private readonly bool _submitAtEnd;
public InteractiveInputs(IInteractiveWindow window, IServiceProvider serviceProvider, bool submitAtEnd) {
_window = window;
_serviceProvider = serviceProvider;
_window.ReadyForInput += () => ProcessQueuedInputAsync().DoNotWait();
_submitAtEnd = submitAtEnd;
}
public async Task EnqueueAsync(string input) {
_pendingInputs.AddLast(input);
if (!_window.IsRunning) {
await ProcessQueuedInputAsync();
}
}
/// <summary>
/// Pends the next input line to the current input buffer, optionally executing it
/// if it forms a complete statement.
/// </summary>
private async Task ProcessQueuedInputAsync() {
if (_pendingInputs.First == null) {
return;
}
var textView = _window.TextView;
var eval = _window.GetPythonEvaluator();
bool supportsMultipleStatements = false;
if (eval != null) {
supportsMultipleStatements = await eval.GetSupportsMultipleStatementsAsync();
}
// Process all of our pending inputs until we get a complete statement
while (_pendingInputs.First != null) {
string current = _pendingInputs.First.Value;
_pendingInputs.RemoveFirst();
MoveCaretToEndOfCurrentInput();
var statements = RecombineInput(
current,
_window.CurrentLanguageBuffer?.CurrentSnapshot.GetText(),
supportsMultipleStatements,
await textView.GetLanguageVersionAsync(_serviceProvider),
textView.Options.GetNewLineCharacter()
);
if (statements.Count > 0) {
// If there was more than one statement then save those for execution later...
var input = statements[0];
for (int i = statements.Count - 1; i > 0; i--) {
_pendingInputs.AddFirst(statements[i]);
}
_window.InsertCode(input);
string fullCode = _window.CurrentLanguageBuffer.CurrentSnapshot.GetText();
if (_window.Evaluator.CanExecuteCode(fullCode)) {
// the code is complete, execute it now
_window.Operations.ExecuteInput();
return;
}
_window.InsertCode(textView.Options.GetNewLineCharacter());
if (_submitAtEnd && _pendingInputs.First == null) {
_window.Operations.ExecuteInput();
}
}
}
}
/// <summary>
/// Takes the new input and appends it to any existing input that's been entered so far. The combined
/// input is then split into multiple top-level statements that will be executed one-by-one.
///
/// Also handles any dedents necessary to make the input a valid input, which usually would only
/// apply if we have no input so far.
/// </summary>
private static List<string> RecombineInput(
string input,
string pendingInput,
bool supportsMultipleStatements,
PythonLanguageVersion version,
string newLineCharacter
) {
// Combine the current input text with the newly submitted text. This will prevent us
// from dedenting code when doing line-by-line submissions of things like:
// if True:
// x = 1
//
// So that we don't dedent "x = 1" when we submit it by its self.
var combinedText = (pendingInput ?? string.Empty) + input;
var oldLineCount = string.IsNullOrEmpty(pendingInput) ?
0 :
pendingInput.Split(_newLineChars, StringSplitOptions.None).Length - 1;
// The split and join will not alter the number of lines that are fed in and returned but
// may change the text by dedenting it if we hadn't submitted the "if True:" in the
// code above.
var split = ReplEditFilter.SplitAndDedent(combinedText);
IEnumerable<string> joinedLines;
if (!supportsMultipleStatements) {
joinedLines = ReplEditFilter.JoinToCompleteStatements(split, version, false);
} else {
joinedLines = new[] { string.Join(newLineCharacter, split) };
}
// Remove any of the lines that were previously inputted into the buffer and also
// remove any extra newlines in the submission.
List<string> res = new List<string>();
foreach (var inputLine in joinedLines) {
var actualLines = inputLine.Split(_newLineChars, StringSplitOptions.None);
var newLine = ReplEditFilter.FixEndingNewLine(
string.Join(newLineCharacter, actualLines.Skip(oldLineCount))
);
res.Add(newLine);
oldLineCount -= actualLines.Count();
if (oldLineCount < 0) {
oldLineCount = 0;
}
}
return res;
}
private void MoveCaretToEndOfCurrentInput() {
var textView = _window.TextView;
var curLangBuffer = _window.CurrentLanguageBuffer;
SnapshotPoint? curLangPoint = null;
// If anything is selected we need to clear it before inserting new code
textView.Selection.Clear();
// Find out if caret position is where code can be inserted.
// Caret must be in the area mappable to the language buffer.
if (!textView.Caret.InVirtualSpace) {
curLangPoint = textView.MapDownToBuffer(textView.Caret.Position.BufferPosition, curLangBuffer);
}
if (curLangPoint == null) {
// Sending to the interactive window is like appending the input to the end, we don't
// respect the current caret position or selection. We use InsertCode which uses the
// current caret position, so first we need to ensure the caret is in the input buffer,
// otherwise inserting code does nothing.
SnapshotPoint? viewPoint = textView.BufferGraph.MapUpToBuffer(
new SnapshotPoint(curLangBuffer.CurrentSnapshot, curLangBuffer.CurrentSnapshot.Length),
PointTrackingMode.Positive,
PositionAffinity.Successor,
textView.TextBuffer
);
if (!viewPoint.HasValue) {
// Unable to map language buffer to view.
// Try moving caret to the end of the view then.
viewPoint = new SnapshotPoint(
textView.TextBuffer.CurrentSnapshot,
textView.TextBuffer.CurrentSnapshot.Length
);
}
textView.Caret.MoveTo(viewPoint.Value);
}
}
}
}
}
| |
// TarEntry.cs
//
// Copyright (C) 2001 Mike Krueger
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using System.Text;
namespace ICSharpCode.SharpZipLib.Tar
{
/// <summary>
/// This class represents an entry in a Tar archive. It consists
/// of the entry's header, as well as the entry's File. Entries
/// can be instantiated in one of three ways, depending on how
/// they are to be used.
/// <p>
/// TarEntries that are created from the header bytes read from
/// an archive are instantiated with the TarEntry( byte[] )
/// constructor. These entries will be used when extracting from
/// or listing the contents of an archive. These entries have their
/// header filled in using the header bytes. They also set the File
/// to null, since they reference an archive entry not a file.</p>
/// <p>
/// TarEntries that are created from Files that are to be written
/// into an archive are instantiated with the TarEntry( File )
/// constructor. These entries have their header filled in using
/// the File's information. They also keep a reference to the File
/// for convenience when writing entries.</p>
/// <p>
/// Finally, TarEntries can be constructed from nothing but a name.
/// This allows the programmer to construct the entry by hand, for
/// instance when only an InputStream is available for writing to
/// the archive, and the header information is constructed from
/// other information. In this case the header fields are set to
/// defaults and the File is set to null.</p>
///
/// <see cref="TarHeader"/>
/// </summary>
public class TarEntry
{
/// <summary>
/// If this entry represents a File, this references it.
/// </summary>
string file;
/// <summary>
/// This is the entry's header information.
/// </summary>
TarHeader header;
/// <summary>
/// Only allow creation of Entries with the static CreateXYZ factory methods.
/// </summary>
TarEntry()
{
}
/// <summary>
/// Construct an entry from an archive's header bytes. File is set
/// to null.
/// </summary>
/// <param name = "headerBuf">
/// The header bytes from a tar archive entry.
/// </param>
public TarEntry(byte[] headerBuf)
{
this.Initialize();
this.header.ParseBuffer(headerBuf);
}
/// <summary>
/// Construct a TarEntry using the <paramref name="header">header</paramref> provided
/// </summary>
/// <param name="header">Header details for entry</param>
public TarEntry(TarHeader header)
{
file = null;
this.header = header;
}
/// <summary>
/// Construct an entry with only a <paramref name="name"></paramref>.
/// This allows the programmer to construct the entry's header "by hand".
/// </summary>
public static TarEntry CreateTarEntry(string name)
{
TarEntry entry = new TarEntry();
entry.Initialize();
entry.NameTarHeader(entry.header, name);
return entry;
}
/// <summary>
/// Construct an entry for a file. File is set to file, and the
/// header is constructed from information from the file.
/// </summary>
/// <param name = "fileName">
/// The file that the entry represents.
/// </param>
public static TarEntry CreateEntryFromFile(string fileName)
{
TarEntry entry = new TarEntry();
entry.Initialize();
entry.GetFileTarHeader(entry.header, fileName);
return entry;
}
/// <summary>
/// Initialization code common to all pseudo constructors.
/// </summary>
void Initialize()
{
this.file = null;
this.header = new TarHeader();
}
/// <summary>
/// Determine if the two entries are equal. Equality is determined
/// by the header names being equal.
/// </summary>
/// <returns>
/// True if the entries are equal.
/// </returns>
public override bool Equals(object it)
{
if (!(it is TarEntry))
{
return false;
}
return this.header.name.ToString().Equals(((TarEntry)it).header.name.ToString());
}
/// <summary>
/// Must be overridden when you override Equals.
/// </summary>
public override int GetHashCode()
{
return this.header.name.ToString().GetHashCode();
}
/// <summary>
/// Determine if the given entry is a descendant of this entry.
/// Descendancy is determined by the name of the descendant
/// starting with this entry's name.
/// </summary>
/// <param name = "desc">
/// Entry to be checked as a descendent of this.
/// </param>
/// <returns>
/// True if entry is a descendant of this.
/// </returns>
public bool IsDescendent(TarEntry desc)
{
return desc.header.name.ToString().StartsWith(this.header.name.ToString());
}
/// <summary>
/// Get this entry's header.
/// </summary>
/// <returns>
/// This entry's TarHeader.
/// </returns>
public TarHeader TarHeader
{
get {
return this.header;
}
}
/// <summary>
/// Get/Set this entry's name.
/// </summary>
public string Name
{
get {
return this.header.name.ToString();
}
set {
this.header.name = new StringBuilder(value);
}
}
/// <summary>
/// Get/set this entry's user id.
/// </summary>
public int UserId
{
get {
return this.header.userId;
}
set {
this.header.userId = value;
}
}
/// <summary>
/// Get/set this entry's group id.
/// </summary>
public int GroupId
{
get {
return this.header.groupId;
}
set {
this.header.groupId = value;
}
}
/// <summary>
/// Get/set this entry's user name.
/// </summary>
public string UserName
{
get {
return this.header.userName.ToString();
}
set {
this.header.userName = new StringBuilder(value);
}
}
/// <summary>
/// Get/set this entry's group name.
/// </summary>
public string GroupName
{
get {
return this.header.groupName.ToString();
}
set {
this.header.groupName = new StringBuilder(value);
}
}
/// <summary>
/// Convenience method to set this entry's group and user ids.
/// </summary>
/// <param name="userId">
/// This entry's new user id.
/// </param>
/// <param name="groupId">
/// This entry's new group id.
/// </param>
public void SetIds(int userId, int groupId)
{
UserId = userId;
GroupId = groupId;
}
/// <summary>
/// Convenience method to set this entry's group and user names.
/// </summary>
/// <param name="userName">
/// This entry's new user name.
/// </param>
/// <param name="groupName">
/// This entry's new group name.
/// </param>
public void SetNames(string userName, string groupName)
{
UserName = userName;
GroupName = groupName;
}
/// <summary>
/// Get/Set the modification time for this entry
/// </summary>
public DateTime ModTime {
get {
return this.header.modTime;
}
set {
this.header.modTime = value;
}
}
/// <summary>
/// Get this entry's file.
/// </summary>
/// <returns>
/// This entry's file.
/// </returns>
public string File {
get {
return this.file;
}
}
/// <summary>
/// Get/set this entry's recorded file size.
/// </summary>
public long Size {
get {
return this.header.size;
}
set {
this.header.size = value;
}
}
/// <summary>
/// Convenience method that will modify an entry's name directly
/// in place in an entry header buffer byte array.
/// </summary>
/// <param name="outbuf">
/// The buffer containing the entry header to modify.
/// </param>
/// <param name="newName">
/// The new name to place into the header buffer.
/// </param>
public void AdjustEntryName(byte[] outbuf, string newName)
{
int offset = 0;
offset = TarHeader.GetNameBytes(new StringBuilder(newName), outbuf, offset, TarHeader.NAMELEN);
}
/// <summary>
/// Return true if this entry represents a directory, false otherwise
/// </summary>
/// <returns>
/// True if this entry is a directory.
/// </returns>
public bool IsDirectory {
get {
if (this.file != null) {
return Directory.Exists(file);
}
if (this.header != null) {
if (this.header.typeFlag == TarHeader.LF_DIR || this.header.name.ToString().EndsWith( "/" )) {
return true;
}
}
return false;
}
}
/// <summary>
/// Fill in a TarHeader with information from a File.
/// </summary>
/// <param name="hdr">
/// The TarHeader to fill in.
/// </param>
/// <param name="file">
/// The file from which to get the header information.
/// </param>
public void GetFileTarHeader(TarHeader hdr, string file)
{
this.file = file;
// bugfix from torhovl from #D forum:
string name = file;
#if !COMPACT_FRAMEWORK
// -jr- 23-Jan-2004 HAK HAK HAK, GnuTar allows device names in path where the name is not local to the current directory
if (Environment.CurrentDirectory == Path.GetDirectoryName(name)) {
name = Path.GetFileName(name);
}
#endif
/*
if (Path.DirectorySeparatorChar == '\\')
{ // check if the OS is Windows
// Strip off drive letters!
if (name.Length > 2)
{
char ch1 = name[0];
char ch2 = name[1];
if (ch2 == ':' && Char.IsLetter(ch1))
{
name = name.Substring(2);
}
}
}
*/
name = name.Replace(Path.DirectorySeparatorChar, '/').ToLower();
// No absolute pathnames
// Windows (and Posix?) paths can start with UNC style "\\NetworkDrive\",
// so we loop on starting /'s.
while (name.StartsWith("/")) {
name = name.Substring(1);
}
hdr.linkName = new StringBuilder(String.Empty);
hdr.name = new StringBuilder(name);
if (Directory.Exists(file)) {
hdr.mode = 1003; // == octal 01753 -jr- no octal constants!! 040755; // Magic number for security access for a UNIX filesystem
hdr.typeFlag = TarHeader.LF_DIR;
if (hdr.name.Length == 0 || hdr.name[hdr.name.Length - 1] != '/') {
hdr.name.Append("/");
}
hdr.size = 0;
} else {
hdr.mode = 33216; // == octal 0100700 -jr- // 0100644; // Magic number for security access for a UNIX filesystem
hdr.typeFlag = TarHeader.LF_NORMAL;
hdr.size = new FileInfo(file.Replace('/', Path.DirectorySeparatorChar)).Length;
}
hdr.modTime = System.IO.File.GetLastWriteTime(file.Replace('/', Path.DirectorySeparatorChar)).ToUniversalTime();
hdr.checkSum = 0;
hdr.devMajor = 0;
hdr.devMinor = 0;
}
/// <summary>
/// If this entry represents a directory, return
/// an array of TarEntries for this entry's children.
/// </summary>
/// <returns>
/// An array of TarEntry's for this entry's children.
/// </returns>
public TarEntry[] GetDirectoryEntries()
{
if (this.file == null || !Directory.Exists(this.file)) {
return new TarEntry[0];
}
string[] list = Directory.GetFileSystemEntries(this.file);
TarEntry[] result = new TarEntry[list.Length];
for (int i = 0; i < list.Length; ++i) {
result[i] = TarEntry.CreateEntryFromFile(list[i]);
}
return result;
}
/// <summary>
/// Write an entry's header information to a header buffer.
/// </summary>
/// <param name = "outbuf">
/// The tar entry header buffer to fill in.
/// </param>
public void WriteEntryHeader(byte[] outbuf)
{
this.header.WriteHeader(outbuf);
}
/// <summary>
/// Fill in a TarHeader given only the entry's name.
/// </summary>
/// <param name="hdr">
/// The TarHeader to fill in.
/// </param>
/// <param name="name">
/// The tar entry name.
/// </param>
public void NameTarHeader(TarHeader hdr, string name)
{
bool isDir = name.EndsWith("/");
hdr.checkSum = 0;
hdr.name = new StringBuilder(name);
hdr.mode = isDir ? 1003 : 33216;
hdr.userId = 0;
hdr.groupId = 0;
hdr.size = 0;
hdr.checkSum = 0;
hdr.modTime = DateTime.UtcNow;
hdr.typeFlag = isDir ? TarHeader.LF_DIR : TarHeader.LF_NORMAL;
hdr.linkName = new StringBuilder(String.Empty);
hdr.userName = new StringBuilder(String.Empty);
hdr.groupName = new StringBuilder(String.Empty);
hdr.devMajor = 0;
hdr.devMinor = 0;
}
}
}
/* The original Java file had this header:
*
** Authored by Timothy Gerard Endres
** <mailto:time@gjt.org> <http://www.trustice.com>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
| |
namespace System.Diagnostics.Eventing
{
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Diagnostics.Eventing.Reader;
internal static class UnsafeNativeMethods
{
private const string FormatMessageDllName = "api-ms-win-core-localization-l1-2-0.dll";
private const string EventProviderDllName = "api-ms-win-eventing-provider-l1-1-0.dll";
private const string WEVTAPI = "wevtapi.dll";
private static readonly IntPtr s_NULL = IntPtr.Zero;
// WinError.h codes:
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
// Can occurs when filled buffers are trying to flush to disk, but disk IOs are not fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DRIVE = 0xF;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_BAD_LENGTH = 0x18;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_LOCK_VIOLATION = 0x21; // 33
internal const int ERROR_HANDLE_EOF = 0x26; // 38
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57; // 87
internal const int ERROR_BROKEN_PIPE = 0x6D; // 109
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; // 122
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long
internal const int ERROR_PIPE_BUSY = 0xE7; // 231
internal const int ERROR_NO_DATA = 0xE8; // 232
internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; // 233
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NO_MORE_ITEMS = 0x103; // 259
internal const int ERROR_PIPE_CONNECTED = 0x217; // 535
internal const int ERROR_PIPE_LISTENING = 0x218; // 536
internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation
internal const int ERROR_IO_PENDING = 0x3E5; // 997
internal const int ERROR_NOT_FOUND = 0x490; // 1168
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; // 534
internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; // 1815
// Event log specific codes:
internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027;
internal const int ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028;
internal const int ERROR_EVT_UNRESOLVED_VALUE_INSERT = 15029;
internal const int ERROR_EVT_UNRESOLVED_PARAMETER_INSERT = 15030;
internal const int ERROR_EVT_MAX_INSERTS_REACHED = 15031;
internal const int ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND = 15033;
internal const int ERROR_MUI_FILE_NOT_FOUND = 15100;
//
// ErrorCode & format
//
// for win32 error message formatting
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
[DllImport(FormatMessageDllName, CharSet = CharSet.Unicode, BestFitMapping = false)]
[SecurityCritical]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
int dwMessageId, int dwLanguageId, StringBuilder lpBuffer,
int nSize, IntPtr va_list_arguments);
// Gets an error message for a Win32 error code.
[SecurityCritical]
internal static String GetMessage(int errorCode)
{
StringBuilder sb = new StringBuilder(512);
int result = UnsafeNativeMethods.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
UnsafeNativeMethods.s_NULL, errorCode, 0, sb, sb.Capacity, UnsafeNativeMethods.s_NULL);
if (result != 0)
{
// result is the # of characters copied to the StringBuilder on NT,
// but on Win9x, it appears to be the number of MBCS buffer.
// Just give up and return the String as-is...
String s = sb.ToString();
return s;
}
else
{
return "UnknownError_Num " + errorCode;
}
}
//
// ETW Methods
//
//
// Callback
//
[SecurityCritical]
internal unsafe delegate void EtwEnableCallback(
[In] ref Guid sourceId,
[In] int isEnabled,
[In] byte level,
[In] long matchAnyKeywords,
[In] long matchAllKeywords,
[In] void* filterData,
[In] void* callbackContext
);
//
// Registration APIs
//
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventRegister(
[In] ref Guid providerId,
[In]EtwEnableCallback enableCallback,
[In]void* callbackContext,
[In][Out]ref long registrationHandle
);
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern int EventUnregister([In] long registrationHandle);
//
// Control (Is Enabled) APIs
//
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern int EventEnabled([In] long registrationHandle, [In] ref System.Diagnostics.Eventing.EventDescriptor eventDescriptor);
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventProviderEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern int EventProviderEnabled([In] long registrationHandle, [In] byte level, [In] long keywords);
//
// Writing (Publishing/Logging) APIs
//
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWrite(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] uint userDataCount,
[In] void* userData
);
//
// Writing (Publishing/Logging) APIs
//
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWrite(
[In] long registrationHandle,
[In] EventDescriptor* eventDescriptor,
[In] uint userDataCount,
[In] void* userData
);
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWriteTransfer(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] Guid* activityId,
[In] Guid* relatedActivityId,
[In] uint userDataCount,
[In] void* userData
);
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWriteString(
[In] long registrationHandle,
[In] byte level,
[In] long keywords,
[In] char* message
);
//
// ActivityId Control APIs
//
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventActivityIdControl([In] int ControlCode, [In][Out] ref Guid ActivityId);
//
// EventLog
//
[Flags]
internal enum EvtQueryFlags
{
EvtQueryChannelPath = 0x1,
EvtQueryFilePath = 0x2,
EvtQueryForwardDirection = 0x100,
EvtQueryReverseDirection = 0x200,
EvtQueryTolerateQueryErrors = 0x1000
}
/// <summary>
/// Evt Variant types
/// </summary>
internal enum EvtVariantType
{
EvtVarTypeNull = 0,
EvtVarTypeString = 1,
EvtVarTypeAnsiString = 2,
EvtVarTypeSByte = 3,
EvtVarTypeByte = 4,
EvtVarTypeInt16 = 5,
EvtVarTypeUInt16 = 6,
EvtVarTypeInt32 = 7,
EvtVarTypeUInt32 = 8,
EvtVarTypeInt64 = 9,
EvtVarTypeUInt64 = 10,
EvtVarTypeSingle = 11,
EvtVarTypeDouble = 12,
EvtVarTypeBoolean = 13,
EvtVarTypeBinary = 14,
EvtVarTypeGuid = 15,
EvtVarTypeSizeT = 16,
EvtVarTypeFileTime = 17,
EvtVarTypeSysTime = 18,
EvtVarTypeSid = 19,
EvtVarTypeHexInt32 = 20,
EvtVarTypeHexInt64 = 21,
// these types used internally
EvtVarTypeEvtHandle = 32,
EvtVarTypeEvtXml = 35,
//Array = 128
EvtVarTypeStringArray = 129,
EvtVarTypeUInt32Array = 136
}
internal enum EvtMasks
{
EVT_VARIANT_TYPE_MASK = 0x7f,
EVT_VARIANT_TYPE_ARRAY = 128
}
[StructLayout(LayoutKind.Sequential)]
internal struct SystemTime
{
[MarshalAs(UnmanagedType.U2)]
public short Year;
[MarshalAs(UnmanagedType.U2)]
public short Month;
[MarshalAs(UnmanagedType.U2)]
public short DayOfWeek;
[MarshalAs(UnmanagedType.U2)]
public short Day;
[MarshalAs(UnmanagedType.U2)]
public short Hour;
[MarshalAs(UnmanagedType.U2)]
public short Minute;
[MarshalAs(UnmanagedType.U2)]
public short Second;
[MarshalAs(UnmanagedType.U2)]
public short Milliseconds;
}
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
[SecurityCritical]
internal struct EvtVariant
{
[FieldOffset(0)]
public UInt32 UInteger;
[FieldOffset(0)]
public Int32 Integer;
[FieldOffset(0)]
public byte UInt8;
[FieldOffset(0)]
public short Short;
[FieldOffset(0)]
public ushort UShort;
[FieldOffset(0)]
public UInt32 Bool;
[FieldOffset(0)]
public Byte ByteVal;
[FieldOffset(0)]
public byte SByte;
[FieldOffset(0)]
public UInt64 ULong;
[FieldOffset(0)]
public Int64 Long;
[FieldOffset(0)]
public Single Single;
[FieldOffset(0)]
public Double Double;
[FieldOffset(0)]
public IntPtr StringVal;
[FieldOffset(0)]
public IntPtr AnsiString;
[FieldOffset(0)]
public IntPtr SidVal;
[FieldOffset(0)]
public IntPtr Binary;
[FieldOffset(0)]
public IntPtr Reference;
[FieldOffset(0)]
public IntPtr Handle;
[FieldOffset(0)]
public IntPtr GuidReference;
[FieldOffset(0)]
public UInt64 FileTime;
[FieldOffset(0)]
public IntPtr SystemTime;
[FieldOffset(0)]
public IntPtr SizeT;
[FieldOffset(8)]
public UInt32 Count; // number of elements (not length) in bytes.
[FieldOffset(12)]
public UInt32 Type;
}
internal enum EvtEventPropertyId
{
EvtEventQueryIDs = 0,
EvtEventPath = 1
}
/// <summary>
/// The query flags to get information about query
/// </summary>
internal enum EvtQueryPropertyId
{
EvtQueryNames = 0, //String; //Variant will be array of EvtVarTypeString
EvtQueryStatuses = 1 //UInt32; //Variant will be Array of EvtVarTypeUInt32
}
/// <summary>
/// Publisher Metadata properties
/// </summary>
internal enum EvtPublisherMetadataPropertyId
{
EvtPublisherMetadataPublisherGuid = 0, // EvtVarTypeGuid
EvtPublisherMetadataResourceFilePath = 1, // EvtVarTypeString
EvtPublisherMetadataParameterFilePath = 2, // EvtVarTypeString
EvtPublisherMetadataMessageFilePath = 3, // EvtVarTypeString
EvtPublisherMetadataHelpLink = 4, // EvtVarTypeString
EvtPublisherMetadataPublisherMessageID = 5, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferences = 6, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataChannelReferencePath = 7, // EvtVarTypeString
EvtPublisherMetadataChannelReferenceIndex = 8, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceID = 9, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceFlags = 10, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceMessageID = 11, // EvtVarTypeUInt32
EvtPublisherMetadataLevels = 12, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataLevelName = 13, // EvtVarTypeString
EvtPublisherMetadataLevelValue = 14, // EvtVarTypeUInt32
EvtPublisherMetadataLevelMessageID = 15, // EvtVarTypeUInt32
EvtPublisherMetadataTasks = 16, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataTaskName = 17, // EvtVarTypeString
EvtPublisherMetadataTaskEventGuid = 18, // EvtVarTypeGuid
EvtPublisherMetadataTaskValue = 19, // EvtVarTypeUInt32
EvtPublisherMetadataTaskMessageID = 20, // EvtVarTypeUInt32
EvtPublisherMetadataOpcodes = 21, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataOpcodeName = 22, // EvtVarTypeString
EvtPublisherMetadataOpcodeValue = 23, // EvtVarTypeUInt32
EvtPublisherMetadataOpcodeMessageID = 24, // EvtVarTypeUInt32
EvtPublisherMetadataKeywords = 25, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataKeywordName = 26, // EvtVarTypeString
EvtPublisherMetadataKeywordValue = 27, // EvtVarTypeUInt64
EvtPublisherMetadataKeywordMessageID = 28//, // EvtVarTypeUInt32
//EvtPublisherMetadataPropertyIdEND
}
internal enum EvtChannelReferenceFlags
{
EvtChannelReferenceImported = 1
}
internal enum EvtEventMetadataPropertyId
{
EventMetadataEventID, // EvtVarTypeUInt32
EventMetadataEventVersion, // EvtVarTypeUInt32
EventMetadataEventChannel, // EvtVarTypeUInt32
EventMetadataEventLevel, // EvtVarTypeUInt32
EventMetadataEventOpcode, // EvtVarTypeUInt32
EventMetadataEventTask, // EvtVarTypeUInt32
EventMetadataEventKeyword, // EvtVarTypeUInt64
EventMetadataEventMessageID,// EvtVarTypeUInt32
EventMetadataEventTemplate // EvtVarTypeString
//EvtEventMetadataPropertyIdEND
}
//CHANNEL CONFIGURATION
internal enum EvtChannelConfigPropertyId
{
EvtChannelConfigEnabled = 0, // EvtVarTypeBoolean
EvtChannelConfigIsolation, // EvtVarTypeUInt32, EVT_CHANNEL_ISOLATION_TYPE
EvtChannelConfigType, // EvtVarTypeUInt32, EVT_CHANNEL_TYPE
EvtChannelConfigOwningPublisher, // EvtVarTypeString
EvtChannelConfigClassicEventlog, // EvtVarTypeBoolean
EvtChannelConfigAccess, // EvtVarTypeString
EvtChannelLoggingConfigRetention, // EvtVarTypeBoolean
EvtChannelLoggingConfigAutoBackup, // EvtVarTypeBoolean
EvtChannelLoggingConfigMaxSize, // EvtVarTypeUInt64
EvtChannelLoggingConfigLogFilePath, // EvtVarTypeString
EvtChannelPublishingConfigLevel, // EvtVarTypeUInt32
EvtChannelPublishingConfigKeywords, // EvtVarTypeUInt64
EvtChannelPublishingConfigControlGuid, // EvtVarTypeGuid
EvtChannelPublishingConfigBufferSize, // EvtVarTypeUInt32
EvtChannelPublishingConfigMinBuffers, // EvtVarTypeUInt32
EvtChannelPublishingConfigMaxBuffers, // EvtVarTypeUInt32
EvtChannelPublishingConfigLatency, // EvtVarTypeUInt32
EvtChannelPublishingConfigClockType, // EvtVarTypeUInt32, EVT_CHANNEL_CLOCK_TYPE
EvtChannelPublishingConfigSidType, // EvtVarTypeUInt32, EVT_CHANNEL_SID_TYPE
EvtChannelPublisherList, // EvtVarTypeString | EVT_VARIANT_TYPE_ARRAY
EvtChannelConfigPropertyIdEND
}
//LOG INFORMATION
internal enum EvtLogPropertyId
{
EvtLogCreationTime = 0, // EvtVarTypeFileTime
EvtLogLastAccessTime, // EvtVarTypeFileTime
EvtLogLastWriteTime, // EvtVarTypeFileTime
EvtLogFileSize, // EvtVarTypeUInt64
EvtLogAttributes, // EvtVarTypeUInt32
EvtLogNumberOfLogRecords, // EvtVarTypeUInt64
EvtLogOldestRecordNumber, // EvtVarTypeUInt64
EvtLogFull, // EvtVarTypeBoolean
}
internal enum EvtExportLogFlags
{
EvtExportLogChannelPath = 1,
EvtExportLogFilePath = 2,
EvtExportLogTolerateQueryErrors = 0x1000
}
//RENDERING
internal enum EvtRenderContextFlags
{
EvtRenderContextValues = 0, // Render specific properties
EvtRenderContextSystem = 1, // Render all system properties (System)
EvtRenderContextUser = 2 // Render all user properties (User/EventData)
}
internal enum EvtRenderFlags
{
EvtRenderEventValues = 0, // Variants
EvtRenderEventXml = 1, // XML
EvtRenderBookmark = 2 // Bookmark
}
internal enum EvtFormatMessageFlags
{
EvtFormatMessageEvent = 1,
EvtFormatMessageLevel = 2,
EvtFormatMessageTask = 3,
EvtFormatMessageOpcode = 4,
EvtFormatMessageKeyword = 5,
EvtFormatMessageChannel = 6,
EvtFormatMessageProvider = 7,
EvtFormatMessageId = 8,
EvtFormatMessageXml = 9
}
internal enum EvtSystemPropertyId
{
EvtSystemProviderName = 0, // EvtVarTypeString
EvtSystemProviderGuid, // EvtVarTypeGuid
EvtSystemEventID, // EvtVarTypeUInt16
EvtSystemQualifiers, // EvtVarTypeUInt16
EvtSystemLevel, // EvtVarTypeUInt8
EvtSystemTask, // EvtVarTypeUInt16
EvtSystemOpcode, // EvtVarTypeUInt8
EvtSystemKeywords, // EvtVarTypeHexInt64
EvtSystemTimeCreated, // EvtVarTypeFileTime
EvtSystemEventRecordId, // EvtVarTypeUInt64
EvtSystemActivityID, // EvtVarTypeGuid
EvtSystemRelatedActivityID, // EvtVarTypeGuid
EvtSystemProcessID, // EvtVarTypeUInt32
EvtSystemThreadID, // EvtVarTypeUInt32
EvtSystemChannel, // EvtVarTypeString
EvtSystemComputer, // EvtVarTypeString
EvtSystemUserID, // EvtVarTypeSid
EvtSystemVersion, // EvtVarTypeUInt8
EvtSystemPropertyIdEND
}
//SESSION
internal enum EvtLoginClass
{
EvtRpcLogin = 1
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct EvtRpcLogin
{
[MarshalAs(UnmanagedType.LPWStr)]
public string Server;
[MarshalAs(UnmanagedType.LPWStr)]
public string User;
[MarshalAs(UnmanagedType.LPWStr)]
public string Domain;
[SecurityCritical]
public CoTaskMemUnicodeSafeHandle Password;
public int Flags;
}
//SEEK
[Flags]
internal enum EvtSeekFlags
{
EvtSeekRelativeToFirst = 1,
EvtSeekRelativeToLast = 2,
EvtSeekRelativeToCurrent = 3,
EvtSeekRelativeToBookmark = 4,
EvtSeekOriginMask = 7,
EvtSeekStrict = 0x10000
}
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtQuery(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string path,
[MarshalAs(UnmanagedType.LPWStr)]string query,
int flags);
//SEEK
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtSeek(
EventLogHandle resultSet,
long position,
EventLogHandle bookmark,
int timeout,
[MarshalAs(UnmanagedType.I4)]EvtSeekFlags flags
);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtNext(
EventLogHandle queryHandle,
int eventSize,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] events,
int timeout,
int flags,
ref int returned);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtCancel(EventLogHandle handle);
[DllImport(WEVTAPI)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtClose(IntPtr handle);
/*
[DllImport(WEVTAPI, EntryPoint = "EvtClose", SetLastError = true)]
public static extern bool EvtClose(
IntPtr eventHandle
);
*/
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetEventInfo(
EventLogHandle eventHandle,
//int propertyId
[MarshalAs(UnmanagedType.I4)]EvtEventPropertyId propertyId,
int bufferSize,
IntPtr bufferPtr,
out int bufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetQueryInfo(
EventLogHandle queryHandle,
[MarshalAs(UnmanagedType.I4)]EvtQueryPropertyId propertyId,
int bufferSize,
IntPtr buffer,
ref int bufferRequired
);
//PUBLISHER METADATA
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenPublisherMetadata(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string publisherId,
[MarshalAs(UnmanagedType.LPWStr)] string logFilePath,
int locale,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetPublisherMetadataProperty(
EventLogHandle publisherMetadataHandle,
[MarshalAs(UnmanagedType.I4)] EvtPublisherMetadataPropertyId propertyId,
int flags,
int publisherMetadataPropertyBufferSize,
IntPtr publisherMetadataPropertyBuffer,
out int publisherMetadataPropertyBufferUsed
);
//NEW
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetObjectArraySize(
EventLogHandle objectArray,
out int objectArraySize
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetObjectArrayProperty(
EventLogHandle objectArray,
int propertyId,
int arrayIndex,
int flags,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
//NEW 2
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenEventMetadataEnum(
EventLogHandle publisherMetadata,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
//public static extern IntPtr EvtNextEventMetadata(
internal static extern EventLogHandle EvtNextEventMetadata(
EventLogHandle eventMetadataEnum,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetEventMetadataProperty(
EventLogHandle eventMetadata,
[MarshalAs(UnmanagedType.I4)] EvtEventMetadataPropertyId propertyId,
int flags,
int eventMetadataPropertyBufferSize,
IntPtr eventMetadataPropertyBuffer,
out int eventMetadataPropertyBufferUsed
);
//Channel Configuration Native Api
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenChannelEnum(
EventLogHandle session,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtNextChannelPath(
EventLogHandle channelEnum,
int channelPathBufferSize,
//StringBuilder channelPathBuffer,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder channelPathBuffer,
out int channelPathBufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenPublisherEnum(
EventLogHandle session,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtNextPublisherId(
EventLogHandle publisherEnum,
int publisherIdBufferSize,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder publisherIdBuffer,
out int publisherIdBufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenChannelConfig(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]String channelPath,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtSaveChannelConfig(
EventLogHandle channelConfig,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtSetChannelConfigProperty(
EventLogHandle channelConfig,
[MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId,
int flags,
ref EvtVariant propertyValue
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetChannelConfigProperty(
EventLogHandle channelConfig,
[MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId,
int flags,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
//Log Information Native Api
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string path,
[MarshalAs(UnmanagedType.I4)]PathType flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetLogInfo(
EventLogHandle log,
[MarshalAs(UnmanagedType.I4)]EvtLogPropertyId propertyId,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
//LOG MANIPULATION
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtExportLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string channelPath,
[MarshalAs(UnmanagedType.LPWStr)]string query,
[MarshalAs(UnmanagedType.LPWStr)]string targetFilePath,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtArchiveExportedLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string logFilePath,
int locale,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtClearLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)]string channelPath,
[MarshalAs(UnmanagedType.LPWStr)]string targetFilePath,
int flags
);
//RENDERING
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtCreateRenderContext(
Int32 valuePathsCount,
[MarshalAs(UnmanagedType.LPArray,ArraySubType = UnmanagedType.LPWStr)]
String[] valuePaths,
[MarshalAs(UnmanagedType.I4)]EvtRenderContextFlags flags
);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtRender(
EventLogHandle context,
EventLogHandle eventHandle,
EvtRenderFlags flags,
int buffSize,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer,
out int buffUsed,
out int propCount
);
[DllImport(WEVTAPI, EntryPoint = "EvtRender", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtRender(
EventLogHandle context,
EventLogHandle eventHandle,
EvtRenderFlags flags,
int buffSize,
IntPtr buffer,
out int buffUsed,
out int propCount
);
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
internal struct EvtStringVariant
{
[MarshalAs(UnmanagedType.LPWStr), FieldOffset(0)]
public string StringVal;
[FieldOffset(8)]
public UInt32 Count;
[FieldOffset(12)]
public UInt32 Type;
};
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtFormatMessage(
EventLogHandle publisherMetadataHandle,
EventLogHandle eventHandle,
uint messageId,
int valueCount,
EvtStringVariant[] values,
[MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags,
int bufferSize,
[Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer,
out int bufferUsed
);
[DllImport(WEVTAPI, EntryPoint = "EvtFormatMessage", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtFormatMessageBuffer(
EventLogHandle publisherMetadataHandle,
EventLogHandle eventHandle,
uint messageId,
int valueCount,
IntPtr values,
[MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags,
int bufferSize,
IntPtr buffer,
out int bufferUsed
);
//SESSION
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenSession(
[MarshalAs(UnmanagedType.I4)]EvtLoginClass loginClass,
ref EvtRpcLogin login,
int timeout,
int flags
);
//BOOKMARK
[DllImport(WEVTAPI, EntryPoint = "EvtCreateBookmark", CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtCreateBookmark(
[MarshalAs(UnmanagedType.LPWStr)] string bookmarkXml
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtUpdateBookmark(
EventLogHandle bookmark,
EventLogHandle eventHandle
);
}
}
| |
// 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 gagvc = Google.Ads.GoogleAds.V9.Common;
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAssetServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetAssetRequestObject()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
GetAssetRequest request = new GetAssetRequest
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
};
gagvr::Asset expectedResponse = new gagvr::Asset
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
Type = gagve::AssetTypeEnum.Types.AssetType.LeadForm,
YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(),
MediaBundleAsset = new gagvc::MediaBundleAsset(),
ImageAsset = new gagvc::ImageAsset(),
TextAsset = new gagvc::TextAsset(),
LeadFormAsset = new gagvc::LeadFormAsset(),
BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(),
Id = -6774108720365892680L,
AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
PolicySummary = new gagvr::AssetPolicySummary(),
FinalUrls =
{
"final_urls3ed0b71b",
},
PromotionAsset = new gagvc::PromotionAsset(),
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
FinalUrlSuffix = "final_url_suffix046ed37a",
CalloutAsset = new gagvc::CalloutAsset(),
StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(),
SitelinkAsset = new gagvc::SitelinkAsset(),
PageFeedAsset = new gagvc::PageFeedAsset(),
DynamicEducationAsset = new gagvc::DynamicEducationAsset(),
MobileAppAsset = new gagvc::MobileAppAsset(),
HotelCalloutAsset = new gagvc::HotelCalloutAsset(),
CallAsset = new gagvc::CallAsset(),
PriceAsset = new gagvc::PriceAsset(),
CallToActionAsset = new gagvc::CallToActionAsset(),
};
mockGrpcClient.Setup(x => x.GetAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Asset response = client.GetAsset(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAssetRequestObjectAsync()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
GetAssetRequest request = new GetAssetRequest
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
};
gagvr::Asset expectedResponse = new gagvr::Asset
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
Type = gagve::AssetTypeEnum.Types.AssetType.LeadForm,
YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(),
MediaBundleAsset = new gagvc::MediaBundleAsset(),
ImageAsset = new gagvc::ImageAsset(),
TextAsset = new gagvc::TextAsset(),
LeadFormAsset = new gagvc::LeadFormAsset(),
BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(),
Id = -6774108720365892680L,
AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
PolicySummary = new gagvr::AssetPolicySummary(),
FinalUrls =
{
"final_urls3ed0b71b",
},
PromotionAsset = new gagvc::PromotionAsset(),
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
FinalUrlSuffix = "final_url_suffix046ed37a",
CalloutAsset = new gagvc::CalloutAsset(),
StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(),
SitelinkAsset = new gagvc::SitelinkAsset(),
PageFeedAsset = new gagvc::PageFeedAsset(),
DynamicEducationAsset = new gagvc::DynamicEducationAsset(),
MobileAppAsset = new gagvc::MobileAppAsset(),
HotelCalloutAsset = new gagvc::HotelCalloutAsset(),
CallAsset = new gagvc::CallAsset(),
PriceAsset = new gagvc::PriceAsset(),
CallToActionAsset = new gagvc::CallToActionAsset(),
};
mockGrpcClient.Setup(x => x.GetAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Asset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Asset responseCallSettings = await client.GetAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Asset responseCancellationToken = await client.GetAssetAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAsset()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
GetAssetRequest request = new GetAssetRequest
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
};
gagvr::Asset expectedResponse = new gagvr::Asset
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
Type = gagve::AssetTypeEnum.Types.AssetType.LeadForm,
YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(),
MediaBundleAsset = new gagvc::MediaBundleAsset(),
ImageAsset = new gagvc::ImageAsset(),
TextAsset = new gagvc::TextAsset(),
LeadFormAsset = new gagvc::LeadFormAsset(),
BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(),
Id = -6774108720365892680L,
AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
PolicySummary = new gagvr::AssetPolicySummary(),
FinalUrls =
{
"final_urls3ed0b71b",
},
PromotionAsset = new gagvc::PromotionAsset(),
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
FinalUrlSuffix = "final_url_suffix046ed37a",
CalloutAsset = new gagvc::CalloutAsset(),
StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(),
SitelinkAsset = new gagvc::SitelinkAsset(),
PageFeedAsset = new gagvc::PageFeedAsset(),
DynamicEducationAsset = new gagvc::DynamicEducationAsset(),
MobileAppAsset = new gagvc::MobileAppAsset(),
HotelCalloutAsset = new gagvc::HotelCalloutAsset(),
CallAsset = new gagvc::CallAsset(),
PriceAsset = new gagvc::PriceAsset(),
CallToActionAsset = new gagvc::CallToActionAsset(),
};
mockGrpcClient.Setup(x => x.GetAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Asset response = client.GetAsset(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAssetAsync()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
GetAssetRequest request = new GetAssetRequest
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
};
gagvr::Asset expectedResponse = new gagvr::Asset
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
Type = gagve::AssetTypeEnum.Types.AssetType.LeadForm,
YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(),
MediaBundleAsset = new gagvc::MediaBundleAsset(),
ImageAsset = new gagvc::ImageAsset(),
TextAsset = new gagvc::TextAsset(),
LeadFormAsset = new gagvc::LeadFormAsset(),
BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(),
Id = -6774108720365892680L,
AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
PolicySummary = new gagvr::AssetPolicySummary(),
FinalUrls =
{
"final_urls3ed0b71b",
},
PromotionAsset = new gagvc::PromotionAsset(),
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
FinalUrlSuffix = "final_url_suffix046ed37a",
CalloutAsset = new gagvc::CalloutAsset(),
StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(),
SitelinkAsset = new gagvc::SitelinkAsset(),
PageFeedAsset = new gagvc::PageFeedAsset(),
DynamicEducationAsset = new gagvc::DynamicEducationAsset(),
MobileAppAsset = new gagvc::MobileAppAsset(),
HotelCalloutAsset = new gagvc::HotelCalloutAsset(),
CallAsset = new gagvc::CallAsset(),
PriceAsset = new gagvc::PriceAsset(),
CallToActionAsset = new gagvc::CallToActionAsset(),
};
mockGrpcClient.Setup(x => x.GetAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Asset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Asset responseCallSettings = await client.GetAssetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Asset responseCancellationToken = await client.GetAssetAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAssetResourceNames()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
GetAssetRequest request = new GetAssetRequest
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
};
gagvr::Asset expectedResponse = new gagvr::Asset
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
Type = gagve::AssetTypeEnum.Types.AssetType.LeadForm,
YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(),
MediaBundleAsset = new gagvc::MediaBundleAsset(),
ImageAsset = new gagvc::ImageAsset(),
TextAsset = new gagvc::TextAsset(),
LeadFormAsset = new gagvc::LeadFormAsset(),
BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(),
Id = -6774108720365892680L,
AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
PolicySummary = new gagvr::AssetPolicySummary(),
FinalUrls =
{
"final_urls3ed0b71b",
},
PromotionAsset = new gagvc::PromotionAsset(),
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
FinalUrlSuffix = "final_url_suffix046ed37a",
CalloutAsset = new gagvc::CalloutAsset(),
StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(),
SitelinkAsset = new gagvc::SitelinkAsset(),
PageFeedAsset = new gagvc::PageFeedAsset(),
DynamicEducationAsset = new gagvc::DynamicEducationAsset(),
MobileAppAsset = new gagvc::MobileAppAsset(),
HotelCalloutAsset = new gagvc::HotelCalloutAsset(),
CallAsset = new gagvc::CallAsset(),
PriceAsset = new gagvc::PriceAsset(),
CallToActionAsset = new gagvc::CallToActionAsset(),
};
mockGrpcClient.Setup(x => x.GetAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Asset response = client.GetAsset(request.ResourceNameAsAssetName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAssetResourceNamesAsync()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
GetAssetRequest request = new GetAssetRequest
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
};
gagvr::Asset expectedResponse = new gagvr::Asset
{
ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
Type = gagve::AssetTypeEnum.Types.AssetType.LeadForm,
YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(),
MediaBundleAsset = new gagvc::MediaBundleAsset(),
ImageAsset = new gagvc::ImageAsset(),
TextAsset = new gagvc::TextAsset(),
LeadFormAsset = new gagvc::LeadFormAsset(),
BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(),
Id = -6774108720365892680L,
AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
PolicySummary = new gagvr::AssetPolicySummary(),
FinalUrls =
{
"final_urls3ed0b71b",
},
PromotionAsset = new gagvc::PromotionAsset(),
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
FinalUrlSuffix = "final_url_suffix046ed37a",
CalloutAsset = new gagvc::CalloutAsset(),
StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(),
SitelinkAsset = new gagvc::SitelinkAsset(),
PageFeedAsset = new gagvc::PageFeedAsset(),
DynamicEducationAsset = new gagvc::DynamicEducationAsset(),
MobileAppAsset = new gagvc::MobileAppAsset(),
HotelCalloutAsset = new gagvc::HotelCalloutAsset(),
CallAsset = new gagvc::CallAsset(),
PriceAsset = new gagvc::PriceAsset(),
CallToActionAsset = new gagvc::CallToActionAsset(),
};
mockGrpcClient.Setup(x => x.GetAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Asset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Asset responseCallSettings = await client.GetAssetAsync(request.ResourceNameAsAssetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Asset responseCancellationToken = await client.GetAssetAsync(request.ResourceNameAsAssetName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAssetsRequestObject()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
MutateAssetsRequest request = new MutateAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AssetOperation(),
},
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
ValidateOnly = true,
PartialFailure = false,
};
MutateAssetsResponse expectedResponse = new MutateAssetsResponse
{
Results =
{
new MutateAssetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAssetsResponse response = client.MutateAssets(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAssetsRequestObjectAsync()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
MutateAssetsRequest request = new MutateAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AssetOperation(),
},
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
ValidateOnly = true,
PartialFailure = false,
};
MutateAssetsResponse expectedResponse = new MutateAssetsResponse
{
Results =
{
new MutateAssetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAssetsResponse responseCallSettings = await client.MutateAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAssetsResponse responseCancellationToken = await client.MutateAssetsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAssets()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
MutateAssetsRequest request = new MutateAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AssetOperation(),
},
};
MutateAssetsResponse expectedResponse = new MutateAssetsResponse
{
Results =
{
new MutateAssetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAssetsResponse response = client.MutateAssets(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAssetsAsync()
{
moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict);
MutateAssetsRequest request = new MutateAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AssetOperation(),
},
};
MutateAssetsResponse expectedResponse = new MutateAssetsResponse
{
Results =
{
new MutateAssetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAssetsResponse responseCallSettings = await client.MutateAssetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAssetsResponse responseCancellationToken = await client.MutateAssetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Linq;
using Microsoft.DotNet.ProjectModel.Compilation;
namespace Microsoft.DotNet.Cli.Compiler.Common
{
public static class BindingRedirectGenerator
{
private const int TokenLength = 8;
private const string Namespace = "urn:schemas-microsoft-com:asm.v1";
private static readonly XName ConfigurationElementName = XName.Get("configuration");
private static readonly XName RuntimeElementName = XName.Get("runtime");
private static readonly XName AssemblyBindingElementName = XName.Get("assemblyBinding", Namespace);
private static readonly XName DependentAssemblyElementName = XName.Get("dependentAssembly", Namespace);
private static readonly XName AssemblyIdentityElementName = XName.Get("assemblyIdentity", Namespace);
private static readonly XName BindingRedirectElementName = XName.Get("bindingRedirect", Namespace);
private static readonly XName NameAttributeName = XName.Get("name");
private static readonly XName PublicKeyTokenAttributeName = XName.Get("publicKeyToken");
private static readonly XName CultureAttributeName = XName.Get("culture");
private static readonly XName OldVersionAttributeName = XName.Get("oldVersion");
private static readonly XName NewVersionAttributeName = XName.Get("newVersion");
private static SHA1 Sha1 { get; } = SHA1.Create();
public static XDocument GenerateBindingRedirects(this IEnumerable<LibraryExport> dependencies, XDocument document)
{
var redirects = CollectRedirects(dependencies);
if (!redirects.Any())
{
// No redirects required
return document;
}
document = document ?? new XDocument();
var configuration = GetOrAddElement(document, ConfigurationElementName);
var runtime = GetOrAddElement(configuration, RuntimeElementName);
var assemblyBindings = GetOrAddElement(runtime, AssemblyBindingElementName);
foreach (var redirect in redirects)
{
AddDependentAssembly(redirect, assemblyBindings);
}
return document;
}
private static void AddDependentAssembly(AssemblyRedirect redirect, XElement assemblyBindings)
{
var dependencyElement = assemblyBindings.Elements(DependentAssemblyElementName)
.FirstOrDefault(element => IsSameAssembly(redirect, element));
if (dependencyElement == null)
{
dependencyElement = new XElement(DependentAssemblyElementName,
new XElement(AssemblyIdentityElementName,
new XAttribute(NameAttributeName, redirect.From.Name),
new XAttribute(PublicKeyTokenAttributeName, redirect.From.PublicKeyToken),
new XAttribute(CultureAttributeName, redirect.From.Culture)
)
);
assemblyBindings.Add(dependencyElement);
}
dependencyElement.Add(new XElement(BindingRedirectElementName,
new XAttribute(OldVersionAttributeName, redirect.From.Version),
new XAttribute(NewVersionAttributeName, redirect.To.Version)
));
}
private static bool IsSameAssembly(AssemblyRedirect redirect, XElement dependentAssemblyElement)
{
var identity = dependentAssemblyElement.Element(AssemblyIdentityElementName);
if (identity == null)
{
return false;
}
return (string)identity.Attribute(NameAttributeName) == redirect.From.Name &&
(string)identity.Attribute(PublicKeyTokenAttributeName) == redirect.From.PublicKeyToken &&
(string)identity.Attribute(CultureAttributeName) == redirect.From.Culture;
}
private static XElement GetOrAddElement(XContainer parent, XName elementName)
{
XElement element;
if (parent.Element(elementName) != null)
{
element = parent.Element(elementName);
}
else
{
element = new XElement(elementName);
parent.Add(element);
}
return element;
}
internal static AssemblyRedirect[] CollectRedirects(IEnumerable<LibraryExport> dependencies)
{
var runtimeAssemblies = dependencies
.SelectMany(d => d.RuntimeAssemblyGroups.GetDefaultAssets())
.Select(GetAssemblyInfo);
return CollectRedirects(runtimeAssemblies);
}
internal static AssemblyRedirect[] CollectRedirects(IEnumerable<AssemblyReferenceInfo> runtimeAssemblies)
{
var assemblyLookup = runtimeAssemblies.ToLookup(r => r.Identity.ToLookupKey());
var redirectAssemblies = new HashSet<AssemblyRedirect>();
foreach (var assemblyReferenceInfo in assemblyLookup)
{
// Using .First here is not exactly valid, but we don't know which one gets copied to
// output so we just use first
var references = assemblyReferenceInfo.First().References;
foreach (var referenceIdentity in references)
{
var targetAssemblies = assemblyLookup[referenceIdentity.ToLookupKey()];
if (!targetAssemblies.Any())
{
continue;
}
var targetAssemblyIdentity = targetAssemblies.First();
if (targetAssemblyIdentity.Identity.Version != referenceIdentity.Version)
{
if (targetAssemblyIdentity.Identity.PublicKeyToken != null)
{
redirectAssemblies.Add(new AssemblyRedirect()
{
From = referenceIdentity,
To = targetAssemblyIdentity.Identity
});
}
}
}
}
return redirectAssemblies.ToArray();
}
private static AssemblyReferenceInfo GetAssemblyInfo(LibraryAsset arg)
{
using (var peReader = new PEReader(File.OpenRead(arg.ResolvedPath)))
{
var metadataReader = peReader.GetMetadataReader();
var definition = metadataReader.GetAssemblyDefinition();
var identity = new AssemblyIdentity(
metadataReader.GetString(definition.Name),
definition.Version,
metadataReader.GetString(definition.Culture),
GetPublicKeyToken(metadataReader.GetBlobBytes(definition.PublicKey))
);
var references = new List<AssemblyIdentity>(metadataReader.AssemblyReferences.Count);
foreach (var assemblyReferenceHandle in metadataReader.AssemblyReferences)
{
var assemblyReference = metadataReader.GetAssemblyReference(assemblyReferenceHandle);
references.Add(new AssemblyIdentity(
metadataReader.GetString(assemblyReference.Name),
assemblyReference.Version,
metadataReader.GetString(assemblyReference.Culture),
GetPublicKeyToken(metadataReader.GetBlobBytes(assemblyReference.PublicKeyOrToken))
));
}
return new AssemblyReferenceInfo(identity, references.ToArray());
}
}
private static string GetPublicKeyToken(byte[] bytes)
{
if (bytes.Length == 0)
{
return null;
}
byte[] token;
if (bytes.Length == TokenLength)
{
token = bytes;
}
else
{
token = new byte[TokenLength];
var sha1 = Sha1.ComputeHash(bytes);
Array.Copy(sha1, sha1.Length - TokenLength, token, 0, TokenLength);
Array.Reverse(token);
}
var hex = new StringBuilder(TokenLength * 2);
foreach (var b in token)
{
hex.AppendFormat("{0:x2}", b);
}
return hex.ToString();
}
internal struct AssemblyRedirect
{
public AssemblyRedirect(AssemblyIdentity from, AssemblyIdentity to)
{
From = from;
To = to;
}
public AssemblyIdentity From { get; set; }
public AssemblyIdentity To { get; set; }
}
internal struct AssemblyIdentity
{
public AssemblyIdentity(string name, Version version, string culture, string publicKeyToken)
{
Name = name;
Version = version;
Culture = string.IsNullOrEmpty(culture) ? "neutral" : culture;
PublicKeyToken = publicKeyToken;
}
public string Name { get; }
public Version Version { get; }
public string Culture { get; }
public string PublicKeyToken { get; }
public Tuple<string, string, string> ToLookupKey() => Tuple.Create(Name, Culture, PublicKeyToken);
public override string ToString()
{
return $"{Name} {Version} {Culture} {PublicKeyToken}";
}
}
internal struct AssemblyReferenceInfo
{
public AssemblyReferenceInfo(AssemblyIdentity identity, AssemblyIdentity[] references)
{
Identity = identity;
References = references;
}
public AssemblyIdentity Identity { get; }
public AssemblyIdentity[] References { get; }
public override string ToString()
{
return $"{Identity} Reference count: {References.Length}";
}
}
}
}
| |
// 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.Reflection;
using System.Threading;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
internal class JsonCollectionDataContract : JsonDataContract
{
private JsonCollectionDataContractCriticalHelper _helper;
public JsonCollectionDataContract(CollectionDataContract traditionalDataContract)
: base(new JsonCollectionDataContractCriticalHelper(traditionalDataContract))
{
_helper = base.Helper as JsonCollectionDataContractCriticalHelper;
}
internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate
{
get
{
if (_helper.JsonFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.JsonFormatReaderDelegate == null)
{
JsonFormatCollectionReaderDelegate tempDelegate;
if (DataContractSerializer.Option == SerializationOption.ReflectionOnly)
{
tempDelegate = new ReflectionJsonCollectionReader().ReflectionReadCollection;
}
#if NET_NATIVE
else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup)
{
tempDelegate = JsonDataContract.TryGetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).CollectionReaderDelegate;
tempDelegate = tempDelegate ?? new ReflectionJsonCollectionReader().ReflectionReadCollection;
if (tempDelegate == null)
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString()));
}
#endif
else
{
#if NET_NATIVE
tempDelegate = JsonDataContract.GetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).CollectionReaderDelegate;
#else
tempDelegate = new JsonFormatReaderGenerator().GenerateCollectionReader(TraditionalCollectionDataContract);
#endif
}
Interlocked.MemoryBarrier();
_helper.JsonFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.JsonFormatReaderDelegate;
}
}
internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate
{
get
{
if (_helper.JsonFormatGetOnlyReaderDelegate == null)
{
lock (this)
{
if (_helper.JsonFormatGetOnlyReaderDelegate == null)
{
CollectionKind kind = this.TraditionalCollectionDataContract.Kind;
if (this.TraditionalDataContract.UnderlyingType.IsInterface && (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable))
{
throw new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(this.TraditionalDataContract.UnderlyingType)));
}
JsonFormatGetOnlyCollectionReaderDelegate tempDelegate;
if (DataContractSerializer.Option == SerializationOption.ReflectionOnly)
{
tempDelegate = new ReflectionJsonCollectionReader().ReflectionReadGetOnlyCollection;
}
#if NET_NATIVE
else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup)
{
tempDelegate = JsonDataContract.TryGetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).GetOnlyCollectionReaderDelegate;
tempDelegate = tempDelegate ?? new ReflectionJsonCollectionReader().ReflectionReadGetOnlyCollection;
if (tempDelegate == null)
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString()));
}
#endif
else
{
#if NET_NATIVE
tempDelegate = JsonDataContract.GetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).GetOnlyCollectionReaderDelegate;
#else
tempDelegate = new JsonFormatReaderGenerator().GenerateGetOnlyCollectionReader(TraditionalCollectionDataContract);
#endif
}
Interlocked.MemoryBarrier();
_helper.JsonFormatGetOnlyReaderDelegate = tempDelegate;
}
}
}
return _helper.JsonFormatGetOnlyReaderDelegate;
}
}
internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate
{
get
{
if (_helper.JsonFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.JsonFormatWriterDelegate == null)
{
JsonFormatCollectionWriterDelegate tempDelegate;
if (DataContractSerializer.Option == SerializationOption.ReflectionOnly)
{
tempDelegate = new ReflectionJsonFormatWriter().ReflectionWriteCollection;
}
#if NET_NATIVE
else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup)
{
tempDelegate = JsonDataContract.TryGetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).CollectionWriterDelegate;
tempDelegate = tempDelegate ?? new ReflectionJsonFormatWriter().ReflectionWriteCollection;
if (tempDelegate == null)
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString()));
}
#endif
else
{
#if NET_NATIVE
tempDelegate = JsonDataContract.GetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).CollectionWriterDelegate;
#else
tempDelegate = new JsonFormatWriterGenerator().GenerateCollectionWriter(TraditionalCollectionDataContract);
#endif
}
Interlocked.MemoryBarrier();
_helper.JsonFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.JsonFormatWriterDelegate;
}
}
private CollectionDataContract TraditionalCollectionDataContract => _helper.TraditionalCollectionDataContract;
public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
jsonReader.Read();
object o = null;
if (context.IsGetOnlyCollection)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
JsonFormatGetOnlyReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract);
}
else
{
o = JsonFormatReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract);
}
jsonReader.ReadEndElement();
return o;
}
public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalCollectionDataContract);
}
private class JsonCollectionDataContractCriticalHelper : JsonDataContractCriticalHelper
{
private JsonFormatCollectionReaderDelegate _jsonFormatReaderDelegate;
private JsonFormatGetOnlyCollectionReaderDelegate _jsonFormatGetOnlyReaderDelegate;
private JsonFormatCollectionWriterDelegate _jsonFormatWriterDelegate;
private CollectionDataContract _traditionalCollectionDataContract;
public JsonCollectionDataContractCriticalHelper(CollectionDataContract traditionalDataContract)
: base(traditionalDataContract)
{
_traditionalCollectionDataContract = traditionalDataContract;
}
internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate
{
get { return _jsonFormatReaderDelegate; }
set { _jsonFormatReaderDelegate = value; }
}
internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate
{
get { return _jsonFormatGetOnlyReaderDelegate; }
set { _jsonFormatGetOnlyReaderDelegate = value; }
}
internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate
{
get { return _jsonFormatWriterDelegate; }
set { _jsonFormatWriterDelegate = value; }
}
internal CollectionDataContract TraditionalCollectionDataContract
{
get { return _traditionalCollectionDataContract; }
}
}
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.Management.Automation.Remoting.Server;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// This class is an implementation of the abstract class ServerRemoteSessionDataStructureHandler.
/// </summary>
internal class ServerRemoteSessionDSHandlerImpl : ServerRemoteSessionDataStructureHandler
{
private AbstractServerSessionTransportManager _transportManager;
private ServerRemoteSessionDSHandlerStateMachine _stateMachine;
private ServerRemoteSession _session;
internal override AbstractServerSessionTransportManager TransportManager
{
get
{
return _transportManager;
}
}
#region Constructors
/// <summary>
/// Constructs a ServerRemoteSession handler using the supplied transport manager. The
/// supplied transport manager will be used to send and receive data from the remote
/// client.
/// </summary>
/// <param name="session"></param>
/// <param name="transportManager"></param>
internal ServerRemoteSessionDSHandlerImpl(ServerRemoteSession session,
AbstractServerSessionTransportManager transportManager)
{
Dbg.Assert(null != session, "session cannot be null.");
Dbg.Assert(null != transportManager, "transportManager cannot be null.");
_session = session;
_stateMachine = new ServerRemoteSessionDSHandlerStateMachine(session);
_transportManager = transportManager;
_transportManager.DataReceived += session.DispatchInputQueueData;
}
#endregion Constructors
#region Overrides
/// <summary>
/// Calls the transport layer connect to make a connection to the listener.
/// </summary>
internal override void ConnectAsync()
{
// for the WSMan implementation, this is a no-op..and statemachine is coded accordingly
// to move to negotiation pending.
}
/// <summary>
/// This method sends the server side capability negotiation packet to the client.
/// </summary>
internal override void SendNegotiationAsync()
{
RemoteSessionCapability serverCapability = _session.Context.ServerCapability;
RemoteDataObject data = RemotingEncoder.GenerateServerSessionCapability(serverCapability,
Guid.Empty);
RemoteSessionStateMachineEventArgs negotiationSendCompletedArg =
new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSendCompleted);
_stateMachine.RaiseEvent(negotiationSendCompletedArg);
RemoteDataObject<PSObject> dataToBeSent = RemoteDataObject<PSObject>.CreateFrom(
data.Destination, data.DataType, data.RunspacePoolId, data.PowerShellId, (PSObject)data.Data);
// send data to client..flush is not true as we expect to send state changed
// information (from runspace creation)
_transportManager.SendDataToClient<PSObject>(dataToBeSent, false);
}
/// <summary>
/// This event indicates that the client capability negotiation packet has been received.
/// </summary>
internal override event EventHandler<RemoteSessionNegotiationEventArgs> NegotiationReceived;
/// <summary>
/// Event that raised when session datastructure handler is closing.
/// </summary>
internal override event EventHandler<EventArgs> SessionClosing;
internal override event EventHandler<RemoteDataEventArgs<string>> PublicKeyReceived;
/// <summary>
/// Send the encrypted session key to the client side
/// </summary>
/// <param name="encryptedSessionKey">encrypted session key
/// as a string</param>
internal override void SendEncryptedSessionKey(string encryptedSessionKey)
{
_transportManager.SendDataToClient<object>(RemotingEncoder.GenerateEncryptedSessionKeyResponse(
Guid.Empty, encryptedSessionKey), true);
}
/// <summary>
/// Send request to the client for sending a public key
/// </summary>
internal override void SendRequestForPublicKey()
{
_transportManager.SendDataToClient<object>(
RemotingEncoder.GeneratePublicKeyRequest(Guid.Empty), true);
}
/// <summary>
/// Raise the public key received event
/// </summary>
/// <param name="receivedData">received data</param>
/// <remarks>This method is a hook to be called
/// from the transport manager</remarks>
internal override void RaiseKeyExchangeMessageReceived(RemoteDataObject<PSObject> receivedData)
{
RaiseDataReceivedEvent(new RemoteDataEventArgs(receivedData));
}
/// <summary>
/// This method calls the transport level call to close the connection to the listener.
/// </summary>
/// <param name="reasonForClose">
/// Message describing why the session is closing
/// </param>
/// <exception cref="PSRemotingTransportException">
/// If the transport call fails.
/// </exception>
internal override void CloseConnectionAsync(Exception reasonForClose)
{
// Raise the closing event
SessionClosing.SafeInvoke(this, EventArgs.Empty);
_transportManager.Close(reasonForClose);
RemoteSessionStateMachineEventArgs closeCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CloseCompleted);
_stateMachine.RaiseEvent(closeCompletedArg);
}
/// <summary>
/// This event indicates that the client has requested to create a new runspace pool
/// on the server side
/// </summary>
internal override event EventHandler<RemoteDataEventArgs> CreateRunspacePoolReceived;
/// <summary>
/// A reference to the FSM object.
/// </summary>
internal override ServerRemoteSessionDSHandlerStateMachine StateMachine
{
get
{
return _stateMachine;
}
}
/// <summary>
/// This method is used by the input queue dispatching mechanism.
/// It examines the data and takes appropriate actions.
/// </summary>
/// <param name="dataArg">
/// The received client data.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
internal override void RaiseDataReceivedEvent(RemoteDataEventArgs dataArg)
{
if (dataArg == null)
{
throw PSTraceSource.NewArgumentNullException("dataArg");
}
RemoteDataObject<PSObject> rcvdData = dataArg.ReceivedData;
RemotingTargetInterface targetInterface = rcvdData.TargetInterface;
RemotingDataType dataType = rcvdData.DataType;
Dbg.Assert(targetInterface == RemotingTargetInterface.Session, "targetInterface must be Session");
switch (dataType)
{
case RemotingDataType.CreateRunspacePool:
{
// At this point, the negotiation is complete, so
// need to import the clients public key
CreateRunspacePoolReceived.SafeInvoke(this, dataArg);
}
break;
case RemotingDataType.CloseSession:
PSRemotingDataStructureException reasonOfClose = new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientRequestedToCloseSession);
RemoteSessionStateMachineEventArgs closeSessionArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, reasonOfClose);
_stateMachine.RaiseEvent(closeSessionArg);
break;
case RemotingDataType.SessionCapability:
RemoteSessionCapability capability = null;
try
{
capability = RemotingDecoder.GetSessionCapability(rcvdData.Data);
}
catch (PSRemotingDataStructureException dse)
{
// this will happen if expected properties are not
// received for session capability
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerNotFoundCapabilityProperties,
dse.Message, PSVersionInfo.BuildVersion, RemotingConstants.ProtocolVersion);
}
RemoteSessionStateMachineEventArgs capabilityArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationReceived);
capabilityArg.RemoteSessionCapability = capability;
_stateMachine.RaiseEvent(capabilityArg);
if (NegotiationReceived != null)
{
RemoteSessionNegotiationEventArgs negotiationArg = new RemoteSessionNegotiationEventArgs(capability);
negotiationArg.RemoteData = rcvdData;
NegotiationReceived.SafeInvoke(this, negotiationArg);
}
break;
case RemotingDataType.PublicKey:
{
string remotePublicKey = RemotingDecoder.GetPublicKey(rcvdData.Data);
PublicKeyReceived.SafeInvoke(this, new RemoteDataEventArgs<string>(remotePublicKey));
}
break;
default:
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedAction, dataType);
}
}
#endregion Overrides
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Text;
using BlogRunner.Core.Config;
using BlogRunner.Core;
using BlogRunner.Core.Tests;
using OpenLiveWriter.CoreServices;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using OpenLiveWriter.CoreServices.Diagnostics;
using System.Xml;
namespace BlogRunner
{
class Program
{
delegate Test[] TestFilter(params Test[] tests);
private static void AddTests(List<Test> tests, TestFilter filter)
{
// New tests go here
tests.AddRange(filter(
new SupportsMultipleCategoriesTest(),
new SupportsPostAsDraftTest(),
new SupportsFuturePostTest(),
new SupportsEmptyTitlesTest()
));
tests.Add(CreateCompositePostTest(filter,
new TitleEncodingTest(),
new SupportsEmbedsTest(),
new SupportsScriptsTest()
));
}
private static Test CreateCompositePostTest(TestFilter filter, params PostTest[] tests)
{
return new CompositePostTest(
(PostTest[])ArrayHelper.Narrow(
filter(tests),
typeof(PostTest)));
}
static int Main(string[] args)
{
try
{
ChangeErrorColors(ConsoleColor.Red);
BlogRunnerCommandLineOptions options = new BlogRunnerCommandLineOptions();
options.Parse(args, true);
try
{
if (options.GetFlagValue(BlogRunnerCommandLineOptions.OPTION_VERBOSE, false))
Debug.Listeners.Add(new ConsoleTraceListener(true));
string providersPath = Path.GetFullPath((string)options.GetValue(BlogRunnerCommandLineOptions.OPTION_PROVIDERS, null));
string configPath = Path.GetFullPath((string)options.GetValue(BlogRunnerCommandLineOptions.OPTION_CONFIG, null));
string outputPath = Path.GetFullPath((string)options.GetValue(BlogRunnerCommandLineOptions.OPTION_OUTPUT, providersPath));
List<string> providerIds = new List<string>(options.UnnamedArgs);
string errorLogPath = (string)options.GetValue(BlogRunnerCommandLineOptions.OPTION_ERRORLOG, null);
if (errorLogPath != null)
{
errorLogPath = Path.GetFullPath(errorLogPath);
Console.SetError(new CompositeTextWriter(
Console.Error,
File.CreateText(errorLogPath)));
}
ApplicationEnvironment.Initialize(Assembly.GetExecutingAssembly(),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"\Windows Live\Writer\"));
ApplicationDiagnostics.VerboseLogging = true;
Config config = Config.Load(configPath, providersPath);
XmlDocument providers = new XmlDocument();
providers.Load(providersPath);
foreach (XmlElement provider in providers.SelectNodes("/providers/provider"))
{
string providerId = provider.SelectSingleNode("id/text()").Value;
string clientType = provider.SelectSingleNode("clientType/text()").Value;
if (providerIds.Count > 0 && !providerIds.Contains(providerId))
continue;
Provider p = config.GetProviderById(providerId);
if (p == null)
continue;
p.ClientType = clientType;
TestResultImpl results = new TestResultImpl();
Blog b = p.Blog;
if (b != null)
{
Console.Write(provider.SelectSingleNode("name/text()").Value);
Console.Write(" (");
Console.Write(b.HomepageUrl);
Console.WriteLine(")");
List<Test> tests = new List<Test>();
AddTests(tests, delegate (Test[] testArr)
{
for (int i = 0; i < testArr.Length; i++)
{
Test t = testArr[i];
string testName = t.GetType().Name;
if (testName.EndsWith("Test"))
testName = testName.Substring(0, testName.Length - 4);
if (p.Exclude != null && Array.IndexOf(p.Exclude, testName) >= 0)
{
testArr[i] = null;
}
}
return (Test[])ArrayHelper.Compact(testArr);
});
TestRunner tr = new TestRunner(tests);
tr.RunTests(p, b, provider);
}
}
using (XmlTextWriter xw = new XmlTextWriter(outputPath, Encoding.UTF8))
{
xw.Formatting = Formatting.Indented;
xw.Indentation = 1;
xw.IndentChar = '\t';
providers.WriteTo(xw);
}
return 0;
}
catch (Exception e)
{
Console.Error.WriteLine(e.ToString());
return 1;
}
finally
{
if (options.GetFlagValue(BlogRunnerCommandLineOptions.OPTION_PAUSE, false))
{
Console.WriteLine();
Console.WriteLine();
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}
catch (Exception e)
{
Console.Error.WriteLine(e.ToString());
return 1;
}
}
private static void ChangeErrorColors(ConsoleColor color)
{
Console.SetError(new ColorChangeTextWriter(Console.Error, color));
}
private class ColorChangeTextWriter : TextWriter
{
private readonly TextWriter tw;
private readonly ConsoleColor color;
public ColorChangeTextWriter(TextWriter tw, ConsoleColor color)
{
this.tw = tw;
this.color = color;
}
public override System.Text.Encoding Encoding
{
get { return tw.Encoding; }
}
public override void Write(char value)
{
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = color;
try
{
tw.Write(value);
}
finally
{
Console.ForegroundColor = oldColor;
}
}
public override void Write(char[] buffer, int index, int count)
{
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = color;
try
{
tw.Write(buffer, index, count);
}
finally
{
Console.ForegroundColor = oldColor;
}
}
}
private class CompositeTextWriter : TextWriter
{
private readonly TextWriter[] writers;
public CompositeTextWriter(params TextWriter[] writers)
{
this.writers = writers;
}
public override Encoding Encoding
{
get { return Encoding.Unicode; }
}
public override void Write(char value)
{
foreach (TextWriter writer in writers)
{
writer.Write(value);
writer.Flush();
}
}
public override void Write(char[] buffer, int index, int count)
{
foreach (TextWriter writer in writers)
{
writer.Write(buffer, index, count);
writer.Flush();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using DotVVM.Framework.Compilation.Parser;
using DotVVM.Framework.Compilation.Parser.Dothtml.Parser;
using DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer;
using DotVVM.Framework.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DotVVM.Framework.Tests.Parser.Dothtml
{
[TestClass]
public class DothtmlParserTests
{
[TestMethod]
public void DothtmlParser_Valid_TextOnly()
{
var markup = @"this is a test";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(1, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DothtmlLiteralNode));
}
[TestMethod]
public void DothtmlParser_Valid_SingleElement()
{
var markup = @"this <b>is</b> a test";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(3, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("this ", ((DothtmlLiteralNode)nodes[0]).Value);
Assert.IsInstanceOfType(nodes[1], typeof(DothtmlElementNode));
Assert.AreEqual("b", ((DothtmlElementNode)nodes[1]).FullTagName);
Assert.IsInstanceOfType(nodes[2], typeof(DothtmlLiteralNode));
Assert.AreEqual(" a test", ((DothtmlLiteralNode)nodes[2]).Value);
}
[TestMethod]
public void DothtmlParser_Valid_NestedElements()
{
var markup = @"this <b>is<a>test</a></b> a test";
var nodes = ParseMarkup(markup).Content;
var innerContent = ((DothtmlElementNode)nodes[1]).Content;
Assert.AreEqual(2, innerContent.Count);
Assert.IsInstanceOfType(innerContent[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("is", ((DothtmlLiteralNode)innerContent[0]).Value);
Assert.IsInstanceOfType(innerContent[1], typeof(DothtmlElementNode));
Assert.AreEqual("a", ((DothtmlElementNode)innerContent[1]).FullTagName);
}
[TestMethod]
public void DothtmlParser_Valid_DoubleQuotedAttribute()
{
var markup = @"this <b>is<a href=""test of a test"">test</a></b> a test";
var nodes = ParseMarkup(markup).Content;
var innerElement = (DothtmlElementNode)((DothtmlElementNode)nodes[1]).Content[1];
Assert.AreEqual(1, innerElement.Attributes.Count);
Assert.AreEqual("href", innerElement.Attributes[0].AttributeName);
Assert.IsNull(innerElement.Attributes[0].AttributePrefix);
Assert.AreEqual("test of a test", (innerElement.Attributes[0].ValueNode as DothtmlValueTextNode).Text);
}
[TestMethod]
public void DothtmlParser_Valid_SingleQuotedAttribute()
{
var markup = @"this <b>is<a href='test of a test'>test</a></b> a test";
var nodes = ParseMarkup(markup).Content;
var innerElement = (DothtmlElementNode)((DothtmlElementNode)nodes[1]).Content[1];
Assert.AreEqual(1, innerElement.Attributes.Count);
Assert.AreEqual("href", innerElement.Attributes[0].AttributeName);
Assert.IsNull(innerElement.Attributes[0].AttributePrefix);
Assert.AreEqual("test of a test", (innerElement.Attributes[0].ValueNode as DothtmlValueTextNode).Text);
}
[TestMethod]
public void DothtmlParser_Valid_AttributeWithoutValue()
{
var markup = @"this <input type=checkbox checked /> a test";
var nodes = ParseMarkup(markup).Content;
var innerElement = (DothtmlElementNode)nodes[1];
Assert.AreEqual(2, innerElement.Attributes.Count);
Assert.AreEqual("type", innerElement.Attributes[0].AttributeName);
Assert.IsNull(innerElement.Attributes[0].AttributePrefix);
Assert.AreEqual("checked", innerElement.Attributes[1].AttributeName);
Assert.IsNull(innerElement.Attributes[1].AttributePrefix);
Assert.IsNull(innerElement.Attributes[1].ValueNode);
}
[TestMethod]
public void DothtmlParser_Valid_UnquotedAttribute()
{
var markup = @"this <b>is<a href=test>test</a></b> a test";
var nodes = ParseMarkup(markup).Content;
var innerElement = (DothtmlElementNode)((DothtmlElementNode)nodes[1]).Content[1];
Assert.AreEqual(1, innerElement.Attributes.Count);
Assert.AreEqual("href", innerElement.Attributes[0].AttributeName);
Assert.IsNull(innerElement.Attributes[0].AttributePrefix);
Assert.AreEqual("test", (innerElement.Attributes[0].ValueNode as DothtmlValueTextNode).Text);
}
[TestMethod]
public void DothtmlParser_Valid_UnquotedAttributeWithWhitespace()
{
var markup = @"this <b>is<a href = test>test</a></b> a test";
var nodes = ParseMarkup(markup).Content;
var innerElement = (DothtmlElementNode)((DothtmlElementNode)nodes[1]).Content[1];
Assert.AreEqual(1, innerElement.Attributes.Count);
Assert.AreEqual("href", innerElement.Attributes[0].AttributeName);
Assert.IsNull(innerElement.Attributes[0].AttributePrefix);
Assert.AreEqual("test", (innerElement.Attributes[0].ValueNode as DothtmlValueTextNode).Text);
}
[TestMethod]
public void DothtmlParser_Valid_BindingInText()
{
var markup = @"this {{value: test}} <b>is</b>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(4, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("this ", ((DothtmlLiteralNode)nodes[0]).Value);
Assert.IsInstanceOfType(nodes[1], typeof(DothtmlBindingNode));
Assert.AreEqual("value", ((DothtmlBindingNode)nodes[1]).Name);
Assert.AreEqual("test", ((DothtmlBindingNode)nodes[1]).Value);
Assert.IsInstanceOfType(nodes[2], typeof(DothtmlLiteralNode));
Assert.AreEqual(" ", ((DothtmlLiteralNode)nodes[2]).Value);
Assert.IsInstanceOfType(nodes[3], typeof(DothtmlElementNode));
Assert.AreEqual("b", ((DothtmlElementNode)nodes[3]).FullTagName);
Assert.AreEqual(1, ((DothtmlElementNode)nodes[3]).Content.Count);
}
[TestMethod]
public void DothtmlParser_Valid_BindingInAttributeValue()
{
var markup = @"this <a href='{value: test}'/>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(2, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("this ", ((DothtmlLiteralNode)nodes[0]).Value);
Assert.IsInstanceOfType(nodes[1], typeof(DothtmlElementNode));
Assert.AreEqual("a", ((DothtmlElementNode)nodes[1]).FullTagName);
Assert.AreEqual(0, ((DothtmlElementNode)nodes[1]).Content.Count);
Assert.AreEqual("href", (nodes[1] as DothtmlElementNode).Attributes[0].AttributeName);
Assert.AreEqual("value", ((nodes[1] as DothtmlElementNode).Attributes[0].ValueNode as DothtmlValueBindingNode).BindingNode.Name);
Assert.AreEqual("test", ((nodes[1] as DothtmlElementNode).Attributes[0].ValueNode as DothtmlValueBindingNode).BindingNode.Value);
}
[TestMethod]
public void DothtmlParser_Valid_DoubleBraceBindingInAttributeValue()
{
var markup = @"this <a href='{{value: test}}'/>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(2, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("this ", ((DothtmlLiteralNode)nodes[0]).Value);
Assert.IsInstanceOfType(nodes[1], typeof(DothtmlElementNode));
Assert.AreEqual("a", ((DothtmlElementNode)nodes[1]).FullTagName);
Assert.AreEqual(0, ((DothtmlElementNode)nodes[1]).Content.Count);
Assert.AreEqual("href", ((DothtmlElementNode)nodes[1]).Attributes[0].AttributeName);
Assert.AreEqual("value", (((DothtmlElementNode)nodes[1]).Attributes[0].ValueNode as DothtmlValueBindingNode).BindingNode.Name);
Assert.AreEqual("test", (((DothtmlElementNode)nodes[1]).Attributes[0].ValueNode as DothtmlValueBindingNode).BindingNode.Value);
}
[TestMethod]
public void DothtmlParser_Valid_BindingInUnquotedAttributeValue()
{
var markup = @"this <a href={value: test}/>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(2, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("this ", ((DothtmlLiteralNode)nodes[0]).Value);
Assert.IsInstanceOfType(nodes[1], typeof(DothtmlElementNode));
Assert.AreEqual("a", ((DothtmlElementNode)nodes[1]).FullTagName);
Assert.AreEqual(0, ((DothtmlElementNode)nodes[1]).Content.Count);
Assert.AreEqual("href", (nodes[1] as DothtmlElementNode).Attributes[0].AttributeName);
Assert.AreEqual("value", ((nodes[1] as DothtmlElementNode).Attributes[0].ValueNode as DothtmlValueBindingNode).BindingNode.Name);
Assert.AreEqual("test", ((nodes[1] as DothtmlElementNode).Attributes[0].ValueNode as DothtmlValueBindingNode).BindingNode.Value);
}
[TestMethod]
public void DothtmlParser_Valid_Directives()
{
var markup = @"@viewmodel MyNamespace.TestViewModel, MyAssembly
@basetype Test
this is a content";
var result = ParseMarkup(markup);
Assert.AreEqual(2, result.Directives.Count);
Assert.AreEqual("viewmodel", result.Directives[0].Name);
Assert.AreEqual("MyNamespace.TestViewModel, MyAssembly", result.Directives[0].Value);
Assert.AreEqual("basetype", result.Directives[1].Name);
Assert.AreEqual("Test", result.Directives[1].Value);
Assert.AreEqual(1, result.Content.Count);
Assert.IsInstanceOfType(result.Content[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("\nthis is a content", ((DothtmlLiteralNode)result.Content[0]).Value);
}
[TestMethod]
public void DothtmlParser_Valid_Doctype()
{
var markup = @"@viewmodel MyNamespace.TestViewModel, MyAssembly
<!DOCTYPE html>
test";
var result = ParseMarkup(markup);
Assert.AreEqual(1, result.Directives.Count);
Assert.AreEqual("viewmodel", result.Directives[0].Name);
Assert.AreEqual("MyNamespace.TestViewModel, MyAssembly", result.Directives[0].Value);
Assert.AreEqual(1, result.Content.Count);
Assert.IsInstanceOfType(result.Content[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("\n<!DOCTYPE html>\ntest", ((DothtmlLiteralNode)result.Content[0]).Value);
}
[TestMethod]
public void DothtmlParser_Invalid_SpaceInTagName()
{
var markup = @"<dot:ContentPlace Holder DataContext=""sdads"">
</ dot:ContentPlaceHolder > ";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(3, nodes.Count);
Assert.AreEqual("Holder", ((DothtmlElementNode)nodes[0]).Attributes[0].AttributeName);
Assert.AreEqual(null, ((DothtmlElementNode)nodes[0]).Attributes[0].ValueNode);
Assert.AreEqual("DataContext", ((DothtmlElementNode)nodes[0]).Attributes[1].AttributeName);
Assert.AreEqual("sdads", (((DothtmlElementNode)nodes[0]).Attributes[1].ValueNode as DothtmlValueTextNode).Text);
Assert.IsTrue(((DothtmlElementNode)nodes[1]).IsClosingTag);
Assert.AreEqual("", ((DothtmlElementNode)nodes[1]).FullTagName);
Assert.IsTrue(((DothtmlElementNode)nodes[1]).NodeWarnings.Any());
Assert.AreEqual(" dot:ContentPlaceHolder > ", ((DothtmlLiteralNode)nodes[2]).Value);
}
[TestMethod]
public void DothtmlParser_Invalid_ClosingTagOnly()
{
var markup = @"</a>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(1, nodes.Count);
Assert.IsTrue(((DothtmlElementNode)nodes[0]).IsClosingTag);
Assert.AreEqual("a", ((DothtmlElementNode)nodes[0]).FullTagName);
Assert.IsTrue(((DothtmlElementNode)nodes[0]).NodeWarnings.Any());
}
[TestMethod]
public void DothtmlParser_SlashAttributeValue()
{
var markup = "<a href='/'>Test</a>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(1, nodes.Count);
var ael = (DothtmlElementNode)nodes[0];
Assert.AreEqual("a", ael.FullTagName);
Assert.AreEqual(1, ael.Attributes.Count);
Assert.AreEqual("href", ael.Attributes[0].AttributeName);
Assert.AreEqual("/", (ael.Attributes[0].ValueNode as DothtmlValueTextNode).Text);
}
[TestMethod]
public void DothtmlParser_UnquotedSlashAttributeValue()
{
var markup = "<a href=/>Test</a>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(1, nodes.Count);
var ael = (DothtmlElementNode)nodes[0];
Assert.AreEqual("a", ael.FullTagName);
Assert.AreEqual(1, ael.Attributes.Count);
Assert.AreEqual("href", ael.Attributes[0].AttributeName);
Assert.AreEqual("", (ael.Attributes[0].ValueNode as DothtmlValueTextNode).Text);
Assert.IsTrue(ael.Tokens.Any(n => n.Error is object));
}
[TestMethod]
public void DothtmlParser_Invalid_ClosingTags()
{
var markup = @"</a></b>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(2, nodes.Count);
Assert.IsTrue(((DothtmlElementNode)nodes[0]).IsClosingTag);
Assert.AreEqual("a", ((DothtmlElementNode)nodes[0]).FullTagName);
Assert.IsTrue(((DothtmlElementNode)nodes[0]).NodeWarnings.Any());
Assert.IsTrue(((DothtmlElementNode)nodes[1]).IsClosingTag);
Assert.AreEqual("b", ((DothtmlElementNode)nodes[1]).FullTagName);
Assert.IsTrue(((DothtmlElementNode)nodes[1]).NodeWarnings.Any());
}
[TestMethod]
public void DothtmlParser_Invalid_ClosingTagInsideElement()
{
var markup = @"<a></b></a>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(3, nodes.Count);
Assert.IsFalse(((DothtmlElementNode)nodes[0]).IsClosingTag);
Assert.AreEqual("a", ((DothtmlElementNode)nodes[0]).FullTagName);
Assert.IsTrue(((DothtmlElementNode)nodes[0]).NodeWarnings.Any());
Assert.IsTrue(((DothtmlElementNode)nodes[1]).IsClosingTag);
Assert.AreEqual("b", ((DothtmlElementNode)nodes[1]).FullTagName);
Assert.IsTrue(((DothtmlElementNode)nodes[1]).NodeWarnings.Any());
Assert.IsTrue(((DothtmlElementNode)nodes[2]).IsClosingTag);
Assert.AreEqual("a", ((DothtmlElementNode)nodes[2]).FullTagName);
Assert.IsTrue(((DothtmlElementNode)nodes[2]).NodeWarnings.Any());
}
[TestMethod]
public void DothtmlParser_Invalid_UnclosedLinkInHead()
{
var markup = @"<html><head><link></head><body></body></html>";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(1, nodes.Count);
var html = ((DothtmlElementNode)nodes[0]);
Assert.IsFalse(html.IsClosingTag);
Assert.AreEqual("html", html.FullTagName);
Assert.IsFalse(html.HasNodeErrors);
Assert.AreEqual(2, html.Content.Count);
var head = ((DothtmlElementNode)html.Content[0]);
Assert.IsFalse(head.IsClosingTag);
Assert.AreEqual("head", head.FullTagName);
Assert.IsFalse(head.HasNodeErrors);
Assert.AreEqual(1, head.Content.Count);
var link = ((DothtmlElementNode)head.Content[0]);
Assert.IsFalse(link.IsClosingTag);
Assert.AreEqual("link", link.FullTagName);
Assert.IsFalse(link.HasNodeErrors);
Assert.AreEqual(0, link.Content.Count);
var body = ((DothtmlElementNode)html.Content[1]);
Assert.IsFalse(body.IsClosingTag);
Assert.AreEqual("body", body.FullTagName);
Assert.IsFalse(body.HasNodeErrors);
Assert.AreEqual(0, body.Content.Count);
}
[TestMethod]
public void DothtmlParser_Valid_Comment()
{
var markup = @"test <!--<a href=""test1"">test2</a>--> test3 <img />";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(4, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("test ", ((DothtmlLiteralNode)nodes[0]).Value);
Assert.IsInstanceOfType(nodes[1], typeof(DotHtmlCommentNode));
Assert.AreEqual(@"<a href=""test1"">test2</a>", ((DotHtmlCommentNode)nodes[1]).Value);
Assert.IsInstanceOfType(nodes[2], typeof(DothtmlLiteralNode));
Assert.AreEqual(" test3 ", ((DothtmlLiteralNode)nodes[2]).Value);
Assert.IsInstanceOfType(nodes[3], typeof(DothtmlElementNode));
Assert.AreEqual("img", ((DothtmlElementNode)nodes[3]).TagName);
Assert.IsTrue(((DothtmlElementNode)nodes[3]).IsSelfClosingTag);
}
[TestMethod]
public void DothtmlParser_Valid_CData()
{
var markup = @"test <![CDATA[<a href=""test1"">test2</a>]]> test3 <img />";
var nodes = ParseMarkup(markup).Content;
Assert.AreEqual(4, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DothtmlLiteralNode));
Assert.AreEqual("test ", ((DothtmlLiteralNode)nodes[0]).Value);
Assert.IsInstanceOfType(nodes[1], typeof(DothtmlLiteralNode));
Assert.AreEqual(@"<![CDATA[<a href=""test1"">test2</a>]]>", ((DothtmlLiteralNode)nodes[1]).Value);
Assert.IsInstanceOfType(nodes[2], typeof(DothtmlLiteralNode));
Assert.AreEqual(" test3 ", ((DothtmlLiteralNode)nodes[2]).Value);
Assert.IsInstanceOfType(nodes[3], typeof(DothtmlElementNode));
Assert.AreEqual("img", ((DothtmlElementNode)nodes[3]).TagName);
Assert.IsTrue(((DothtmlElementNode)nodes[3]).IsSelfClosingTag);
}
[TestMethod]
public void DothtmlParser_Valid_CommentBeforeDirective()
{
var markup = "<!-- my comment --> @viewModel TestDirective\nTest";
var root = ParseMarkup(markup);
var nodes = root.Content;
Assert.AreEqual(3, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DotHtmlCommentNode));
Assert.AreEqual(" my comment ", ((DotHtmlCommentNode)nodes[0]).Value);
Assert.IsInstanceOfType(nodes[1], typeof(DothtmlLiteralNode));
Assert.AreEqual(@" ", ((DothtmlLiteralNode)nodes[1]).Value);
Assert.IsInstanceOfType(nodes[2], typeof(DothtmlLiteralNode));
Assert.AreEqual(@"Test", ((DothtmlLiteralNode)nodes[2]).Value);
Assert.AreEqual(1, root.Directives.Count);
Assert.AreEqual("viewModel", root.Directives[0].Name);
Assert.AreEqual("TestDirective", root.Directives[0].Value);
}
[TestMethod]
public void DothtmlParser_Valid_CommentInsideDirectives()
{
var markup = "@masterPage hello\n<!-- my comment --> @viewModel TestDirective\nTest";
var root = ParseMarkup(markup);
var nodes = root.Content;
Assert.AreEqual(3, nodes.Count);
Assert.IsInstanceOfType(nodes[0], typeof(DotHtmlCommentNode));
Assert.AreEqual(" my comment ", ((DotHtmlCommentNode)nodes[0]).Value);
Assert.IsInstanceOfType(nodes[1], typeof(DothtmlLiteralNode));
Assert.AreEqual(@" ", ((DothtmlLiteralNode)nodes[1]).Value);
Assert.IsInstanceOfType(nodes[2], typeof(DothtmlLiteralNode));
Assert.AreEqual(@"Test", ((DothtmlLiteralNode)nodes[2]).Value);
Assert.AreEqual(2, root.Directives.Count);
Assert.AreEqual("masterPage", root.Directives[0].Name);
Assert.AreEqual("hello", root.Directives[0].Value);
Assert.AreEqual("viewModel", root.Directives[1].Name);
Assert.AreEqual("TestDirective", root.Directives[1].Value);
}
[TestMethod]
public void BindingParser_TextBinding_Invalid_MissingName()
{
var markup = "<a href='#'>{{Property1}}</a>";
var node = (DothtmlElementNode)ParseMarkup(markup).Content[0];
Assert.AreEqual("a", (node.FullTagName));
Assert.IsInstanceOfType(node.Content[0], typeof(DothtmlBindingNode));
var content = node.Content[0] as DothtmlBindingNode;
}
[TestMethod]
public void DothtmlParser_HierarchyBuildingVisitor_Element_InvalidTag()
{
var markup = "<!-- my comment --> @viewModel TestDirective\n<div><div><ul><li>item</li><ul><a href='lol'>link</a></div></div>";
var root = ParseMarkup(markup);
var visitor = new HierarchyBuildingVisitor {
CursorPosition = 61
};
root.Accept(visitor);
var cursorNode = visitor.LastFoundNode;
var hierarchyList = visitor.GetHierarchy();
Assert.AreEqual(6, hierarchyList.Count);
Assert.IsInstanceOfType(cursorNode, typeof(DothtmlNameNode));
var cursorName = cursorNode as DothtmlNameNode;
var parentNode = cursorNode.ParentNode;
Assert.IsInstanceOfType(parentNode, typeof(DothtmlElementNode));
var parentElement = parentNode as DothtmlElementNode;
Assert.AreEqual(parentElement.TagName, cursorName.Text);
Assert.AreEqual(parentElement.TagName, "li");
}
[TestMethod]
public void DothtmlParser_HierarchyBuildingVisitor_Element_UnclosedTagContent()
{
var markup = "<!-- my comment --> @viewModel TestDirective\n<div><div><ul><li>\n\t\t\t\t<a href='lol'></a></li></ul>\n</div></div>";
var root = ParseMarkup(markup);
var visitor = new HierarchyBuildingVisitor
{
CursorPosition = 81
};
root.Accept(visitor);
var hierarchyList = visitor.GetHierarchy();
var lastElement = hierarchyList.Where( node => node is DothtmlElementNode).First() as DothtmlElementNode;
Assert.AreEqual(6, hierarchyList.Count);
Assert.AreEqual(lastElement.FullTagName, "a");
Assert.IsInstanceOfType(lastElement.ParentNode, typeof(DothtmlElementNode));
var parentLiElement = lastElement.ParentNode as DothtmlElementNode;
Assert.AreEqual(parentLiElement.FullTagName, "li");
Assert.IsInstanceOfType(parentLiElement.ParentNode, typeof(DothtmlElementNode));
var parentUlElement = parentLiElement.ParentNode as DothtmlElementNode;
Assert.AreEqual(parentUlElement.FullTagName, "ul");
Assert.AreEqual((hierarchyList[0] as DothtmlElementNode)?.FullTagName,"a");
Assert.AreEqual((hierarchyList[1] as DothtmlElementNode)?.FullTagName, "li");
Assert.AreEqual((hierarchyList[2] as DothtmlElementNode)?.FullTagName, "ul");
Assert.AreEqual((hierarchyList[3] as DothtmlElementNode)?.FullTagName, "div");
Assert.AreEqual((hierarchyList[4] as DothtmlElementNode)?.FullTagName, "div");
Assert.IsInstanceOfType(hierarchyList[5], typeof(DothtmlRootNode));
}
[TestMethod]
public void DothtmlParser_HierarchyBuildingVisitor_Element_Valid()
{
var markup = "<!-- my comment --> @viewModel TestDirective\n<div><div><ul><li>item</li></ul><a href='lol'>link</a></div></div>";
var root = ParseMarkup(markup);
var visitor = new HierarchyBuildingVisitor
{
CursorPosition = 61
};
root.Accept(visitor);
var cursorNode = visitor.LastFoundNode;
var hierarchyList = visitor.GetHierarchy();
Assert.AreEqual(6, hierarchyList.Count);
Assert.IsInstanceOfType(cursorNode, typeof(DothtmlNameNode));
var cursorName = cursorNode as DothtmlNameNode;
var parentNode = cursorNode.ParentNode;
Assert.IsInstanceOfType(parentNode, typeof(DothtmlElementNode));
var parentElement = parentNode as DothtmlElementNode;
Assert.AreEqual(parentElement.TagName, cursorName.Text);
Assert.AreEqual(parentElement.TagName, "li");
}
[TestMethod]
public void DothtmlParser_HierarchyBuildingVisitor_Attribute_TextValue()
{
var markup = "<!-- my comment --> @viewModel TestDirective\n<div><div><ul><li>item</li></ul><a href='lol'>link</a></div></div>";
var root = ParseMarkup(markup);
var visitor = new HierarchyBuildingVisitor
{
CursorPosition = 87
};
root.Accept(visitor);
var cursorNode = visitor.LastFoundNode;
var hierarchyList = visitor.GetHierarchy();
Assert.AreEqual(6, hierarchyList.Count);
Assert.IsInstanceOfType(cursorNode, typeof(DothtmlValueTextNode));
var cursorValue = cursorNode as DothtmlValueTextNode;
var parentNode = cursorNode.ParentNode;
Assert.IsInstanceOfType(parentNode, typeof(DothtmlAttributeNode));
var parentAttribute = parentNode as DothtmlAttributeNode;
Assert.AreEqual(parentAttribute.AttributeName, "href");
var parentParentNode = parentAttribute.ParentNode;
Assert.IsInstanceOfType(parentParentNode, typeof(DothtmlElementNode));
var parentElement = parentParentNode as DothtmlElementNode;
Assert.AreEqual(parentElement.TagName, "a");
}
[TestMethod]
public void DothtmlParser_HierarchyBuildingVisitor_Attribute_BindingValue()
{
var markup = "<!-- my comment --> @viewModel TestDirective\n<div><div><ul><li>item</li></ul><a href='{value: lol}'>link</a></div></div>";
var root = ParseMarkup(markup);
var visitor = new HierarchyBuildingVisitor
{
CursorPosition = 95
};
root.Accept(visitor);
var cursorNode = visitor.LastFoundNode;
var hierarchyList = visitor.GetHierarchy();
Assert.AreEqual(8, hierarchyList.Count);
Assert.IsInstanceOfType(cursorNode, typeof(DothtmlValueTextNode));
var bindingValue = cursorNode as DothtmlValueTextNode;
Assert.AreEqual(bindingValue.Text, "lol");
Assert.AreEqual(bindingValue.WhitespacesBefore.Count(), 1);
Assert.AreEqual(bindingValue.WhitespacesAfter.Count(), 0);
Assert.IsInstanceOfType(bindingValue.ParentNode, typeof(DothtmlBindingNode));
var binding = bindingValue.ParentNode as DothtmlBindingNode;
Assert.AreEqual(binding.Name, "value");
Assert.AreEqual(binding.Value, bindingValue.Text);
Assert.IsInstanceOfType(binding.ParentNode, typeof(DothtmlValueBindingNode));
var cursorValue = binding.ParentNode as DothtmlValueBindingNode;
Assert.IsInstanceOfType(cursorValue.ParentNode, typeof(DothtmlAttributeNode));
var parentAttribute = cursorValue.ParentNode as DothtmlAttributeNode;
Assert.AreEqual(parentAttribute.AttributeName, "href");
var parentParentNode = parentAttribute.ParentNode;
Assert.IsInstanceOfType(parentParentNode, typeof(DothtmlElementNode));
var parentElement = parentParentNode as DothtmlElementNode;
Assert.AreEqual(parentElement.TagName, "a");
}
[TestMethod]
public void DothtmlParser_EmptyText()
{
var markup = string.Empty;
var root = ParseMarkup(markup);
Assert.IsTrue(root.StartPosition == 0);
Assert.IsTrue(root.Length == 0);
Assert.IsTrue(root.Tokens.Count == 0);
Assert.IsTrue(root.Content.Count == 0);
Assert.IsTrue(root.Directives.Count == 0);
Assert.IsTrue(root.Content.Count == 0);
}
[TestMethod]
public void DothtmlParser_CompletelyUnclosedTag_WarningOnNode()
{
var markup = "<div><p>Something</div>";
var root = ParseMarkup(markup);
var pNode = root
.Content[0].CastTo<DothtmlNodeWithContent>()
.Content[0].CastTo<DothtmlElementNode>();
Assert.AreEqual("p", pNode.TagName, "Tree is differen as expected, second tier should be p.");
Assert.AreEqual(1, pNode.NodeWarnings.Count(), "There should have been a warning about unclosed element.");
Assert.AreEqual(true, pNode.NodeWarnings.Any(w => w.Contains("implicitly closed")));
}
[TestMethod]
public void DothtmlParser_UnclosedTagImplicitlyClosedEndOfFile_WarningOnNode()
{
var markup = "<div><p>";
var root = ParseMarkup(markup);
var pNode = root
.Content[0].CastTo<DothtmlNodeWithContent>()
.Content[0].CastTo<DothtmlElementNode>();
Assert.AreEqual("p", pNode.TagName, "Tree is different as expected, second tier should be p.");
Assert.AreEqual(1, pNode.NodeErrors.Count(), "There should have been an error about file ending");
Assert.AreEqual(true, pNode.NodeErrors.Any(w => w.Contains("not closed")));
}
[TestMethod]
public void DothtmlParser_UnclosedTagImplicitlyClosed_WarningOnNode()
{
var markup = "<div><p>Something<p>Something else</p></div>";
var root = ParseMarkup(markup);
var pNode = root
.Content[0].CastTo<DothtmlNodeWithContent>()
.Content[0].CastTo<DothtmlElementNode>();
Assert.AreEqual("p", pNode.TagName, "Tree is different as expected, second tier should be p.");
Assert.AreEqual(1, pNode.NodeWarnings.Count(), "There should have been a warning about implicitly closing p element.");
Assert.AreEqual(true, pNode.NodeWarnings.Any(w=> w.Contains("implicitly closed")));
}
[TestMethod]
public void DothtmlParser_AngleCharsInsideBinding()
{
var markup = "<div class-active='{value: Activity > 3 && Activity < 100}' />";
var root = ParseMarkup(markup);
var binding = root.EnumerateNodes().OfType<DothtmlBindingNode>().Single();
Assert.AreEqual("Activity > 3 && Activity < 100", binding.Value);
}
[TestMethod]
public void DothtmlParser_HtmlCommentInsideBinding()
{
var markup = "<div class-active='{value: \"<!-- comment -->\"}' />";
var root = ParseMarkup(markup);
var binding = root.EnumerateNodes().OfType<DothtmlBindingNode>().Single();
Assert.AreEqual("\"<!-- comment -->\"", binding.Value);
}
public static DothtmlRootNode ParseMarkup(string markup)
{
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(markup.Replace("\r\n", "\n"));
var parser = new DothtmlParser();
var node = parser.Parse(tokenizer.Tokens);
return node;
}
}
}
| |
// 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 Xunit;
namespace System.Globalization.Tests
{
public abstract class CalendarTestBase
{
public abstract Calendar Calendar { get; }
public virtual DateTime MinSupportedDateTime => DateTime.MinValue;
public virtual DateTime MaxSupportedDateTime => DateTime.MaxValue;
public virtual int[] Eras => new int[] { 1 };
public virtual bool SkipErasTest => false;
public virtual CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar;
public virtual bool IsReadOnly => false;
[Fact]
public void MinSupportedDateTime_Get_ReturnsExpected()
{
Assert.Equal(MinSupportedDateTime, Calendar.MinSupportedDateTime);
}
[Fact]
public void MaxSupportedDateTime_Get_ReturnsExpected()
{
Assert.Equal(MaxSupportedDateTime, Calendar.MaxSupportedDateTime);
}
[Fact]
public void Eras_Get_ReturnsExpected()
{
if (SkipErasTest)
{
return;
}
Assert.Equal(Eras, Calendar.Eras);
}
[Fact]
public void Eras_Get_ReturnsDifferentInstance()
{
Calendar calendar = Calendar;
Assert.NotSame(calendar.Eras, calendar.Eras);
}
[Fact]
public void AlgorithmType_Get_ReturnsExpected()
{
Assert.Equal(AlgorithmType, Calendar.AlgorithmType);
}
[Fact]
public void IsReadOnly_Get_ReturnsExpected()
{
Assert.Equal(IsReadOnly, Calendar.IsReadOnly);
}
public enum DataType
{
Year = 1,
Month = 2,
Day = 8
}
private static int MinEra(Calendar calendar) => calendar.GetEra(calendar.MinSupportedDateTime);
private static int MaxEra(Calendar calendar) => calendar.GetEra(calendar.MaxSupportedDateTime);
private static int MaxCalendarYearInEra(Calendar calendar, int era)
{
int[] eras = calendar.Eras;
Assert.InRange(era, 0, eras[0]);
if (eras.Length == 1 || era == eras[0] || era == 0)
{
return calendar.GetYear(calendar.MaxSupportedDateTime);
}
return calendar.GetYear(calendar.ToDateTime(1, 1, 1, 0, 0, 0, 0, era + 1).AddDays(-1)) + 1;
}
// Get the max year in the passed era plus the sum of the max year for each subsequent era
private static int MaxCalendarYearInEras(Calendar calendar, int era)
{
int[] eras = calendar.Eras;
Assert.InRange(era, 0, eras[0]);
if (eras.Length == 1 || era == eras[0] || era == 0)
{
return MaxCalendarYearInEra(calendar, era);
}
int year = 0;
for (int i = era; i <= calendar.Eras[0]; i++)
{
year += MaxCalendarYearInEra(calendar, i);
}
return year;
}
private static int MaxGregorianYearInEra(Calendar calendar, int era)
{
int[] eras = calendar.Eras;
Assert.InRange(era, 0, eras[0]);
if (eras.Length == 1 || era == eras[0] || era == 0)
{
return calendar.MaxSupportedDateTime.Year;
}
return (calendar.ToDateTime(1, 1, 1, 0, 0, 0, 0, era + 1).AddDays(-1)).Year;
}
private static int MinGregorianYearInEra(Calendar calendar, int era)
{
int[] eras = calendar.Eras;
Assert.InRange(era, 0, eras[0]);
if (eras.Length == 1 || era == eras[eras.Length - 1] || era == 0)
{
return calendar.MinSupportedDateTime.Year;
}
return calendar.ToDateTime(1, 1, 1, 0, 0, 0, 0, era).Year;
}
private static int MinCalendarYearInEra(Calendar calendar, int era)
{
int[] eras = calendar.Eras;
Assert.InRange(era, 0, eras[0]);
if (eras.Length == 1 || era == eras[eras.Length - 1] || era == 0)
{
return calendar.GetYear(calendar.MinSupportedDateTime);
}
return calendar.GetYear(calendar.ToDateTime(1, 1, 1, 0, 0, 0, 0, era));
}
public IEnumerable<(int year, int month, int day, int era, string exceptionParamName)> Year_Month_Day_Era_TestData(Calendar calendar, DataType type)
{
int month = 1;
int day = 1;
if (calendar is JapaneseLunisolarCalendar && PlatformDetection.IsFullFramework)
{
// desktop has a bug in JapaneseLunisolarCalendar which is fixed in .NET Core.
// in case of a new era starts in the middle of a month which means part of the month will belong to one
// era and the rest will belong to the new era. When calculating the calendar year number for dates which
// in the rest of the month and exist in the new started era, we should still use the old era info instead
// of the new era info because the rest of the month still belong to the year of last era.
// https://github.com/dotnet/coreclr/pull/3662
yield break;
}
foreach (int era in calendar.Eras)
{
int year = MaxCalendarYearInEra(calendar, era) - 2;
// Year is invalid
yield return (-1, month, day, era, "year");
yield return (0, month, day, era, "year");
yield return (MaxCalendarYearInEras(calendar, era) + 1, month, day, era, "year");
if ((type & DataType.Month) != 0)
{
// Month is invalid
yield return (year, -1, day, era, "month");
yield return (year, 0, day, era, "month");
yield return (year, calendar.GetMonthsInYear(year, era) + 1, day, era, "month");
}
if ((type & DataType.Day) != 0)
{
// Day is invalid
yield return (year, month, -1, era, "day");
yield return (year, month, 0, era, "day");
yield return (year, month, calendar.GetDaysInMonth(year, month, era) + 1, era, "day");
}
}
// Year is invalid
yield return (MinCalendarYearInEra(calendar, MinEra(calendar)) - 1, month, day, MinEra(calendar), "year");
// Era is invalid
yield return (calendar.GetYear(calendar.MaxSupportedDateTime), month, day, MinEra(calendar) - 2, "era");
yield return (calendar.GetYear(calendar.MaxSupportedDateTime), month, day, MaxEra(calendar) + 1, "era");
}
public static IEnumerable<DateTime> DateTime_TestData(Calendar calendar)
{
DateTime minDate = calendar.MinSupportedDateTime;
if (minDate != DateTime.MinValue)
{
yield return minDate.AddDays(-1);
}
DateTime maxDate = calendar.MaxSupportedDateTime;
if (maxDate != DateTime.MaxValue)
{
yield return maxDate.AddDays(1);
}
}
[Fact]
public void GetDaysInYear_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(Year_Month_Day_Era_TestData(calendar, DataType.Year), test =>
AssertExtensions.Throws<ArgumentOutOfRangeException>(test.exceptionParamName, () => calendar.GetDaysInYear(test.year, test.era))
);
}
[Fact]
public void GetMonthsInYear_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(Year_Month_Day_Era_TestData(calendar, DataType.Year), test =>
AssertExtensions.Throws<ArgumentOutOfRangeException>(test.exceptionParamName, () => calendar.GetMonthsInYear(test.year, test.era))
);
}
[Fact]
public void GetDaysInMonth_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(Year_Month_Day_Era_TestData(calendar, DataType.Year | DataType.Month), test =>
AssertExtensions.Throws<ArgumentOutOfRangeException>(test.exceptionParamName, () => calendar.GetDaysInMonth(test.year, test.month, test.era))
);
}
[Fact]
public void IsLeapDay_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(Year_Month_Day_Era_TestData(calendar, DataType.Year | DataType.Month | DataType.Day), test =>
AssertExtensions.Throws<ArgumentOutOfRangeException>(test.exceptionParamName, () => calendar.IsLeapDay(test.year, test.month, test.day, test.era))
);
}
[Fact]
public void IsLeapMonth_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(Year_Month_Day_Era_TestData(calendar, DataType.Year | DataType.Month), test =>
AssertExtensions.Throws<ArgumentOutOfRangeException>(test.exceptionParamName, () => calendar.IsLeapMonth(test.year, test.month, test.era))
);
}
[Fact]
public void IsLeapYear_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(Year_Month_Day_Era_TestData(calendar, DataType.Year), test =>
AssertExtensions.Throws<ArgumentOutOfRangeException>(test.exceptionParamName, () => calendar.IsLeapYear(test.year, test.era))
);
}
[Fact]
public void GetLeapMonth_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(Year_Month_Day_Era_TestData(calendar, DataType.Year), test =>
AssertExtensions.Throws<ArgumentOutOfRangeException>(test.exceptionParamName, () => calendar.GetLeapMonth(test.year, test.era))
);
}
[Fact]
public void AddYears_Invalid_ThrowsArgumentException()
{
Calendar calendar = Calendar;
Assert.ThrowsAny<ArgumentException>(() => calendar.AddYears(calendar.MaxSupportedDateTime, 1));
Assert.ThrowsAny<ArgumentException>(() => calendar.AddYears(calendar.MinSupportedDateTime, -1));
}
[Fact]
public void AddMonths_Invalid_ThrowsArgumentException()
{
Calendar calendar = Calendar;
Assert.ThrowsAny<ArgumentException>(() => calendar.AddMonths(calendar.MaxSupportedDateTime, 1));
Assert.ThrowsAny<ArgumentException>(() => calendar.AddMonths(calendar.MinSupportedDateTime, -1)); // JapaneseCalendar throws ArgumentException
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => calendar.AddMonths(DateTime.Now, -120001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => calendar.AddMonths(DateTime.Now, 120001));
}
[Fact]
public void AddDays_Invalid_ThrowsArgumentException()
{
Calendar calendar = Calendar;
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddDays(calendar.MaxSupportedDateTime, 1));
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddDays(calendar.MinSupportedDateTime, -1));
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddDays(DateTime.Now, -120001 * 30));
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddDays(DateTime.Now, 120001 * 30));
}
[Fact]
public void AddHours_Invalid_ThrowsArgumentException()
{
Calendar calendar = Calendar;
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddHours(calendar.MaxSupportedDateTime, 1));
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddHours(calendar.MinSupportedDateTime, -1));
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddHours(DateTime.Now, -120001 * 30 * 24));
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddHours(DateTime.Now, 120001 * 30 * 24));
}
[Fact]
public void AddMinutes_Invalid_ThrowsArgumentException()
{
Calendar calendar = Calendar;
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddMinutes(calendar.MaxSupportedDateTime, 1));
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddMinutes(calendar.MinSupportedDateTime, -1));
}
[Fact]
public void AddSeconds_Invalid_ThrowsArgumentException()
{
Calendar calendar = Calendar;
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddSeconds(calendar.MaxSupportedDateTime, 1));
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddSeconds(calendar.MinSupportedDateTime, -1));
}
[Fact]
public void AddMilliseconds_Invalid_ThrowsArgumentException()
{
Calendar calendar = Calendar;
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddMilliseconds(calendar.MaxSupportedDateTime, 1));
AssertExtensions.Throws<ArgumentException>(null, () => calendar.AddMilliseconds(calendar.MinSupportedDateTime, -1));
}
[Fact]
public void GetWeekOfYear_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
// Rule is outside supported range
AssertExtensions.Throws<ArgumentOutOfRangeException>("rule", () => calendar.GetWeekOfYear(calendar.MaxSupportedDateTime, CalendarWeekRule.FirstDay - 1, DayOfWeek.Saturday));
AssertExtensions.Throws<ArgumentOutOfRangeException>("rule", () => calendar.GetWeekOfYear(calendar.MaxSupportedDateTime, CalendarWeekRule.FirstFourDayWeek + 1, DayOfWeek.Saturday));
// FirstDayOfWeek is outside supported range
AssertExtensions.Throws<ArgumentOutOfRangeException>("firstDayOfWeek", () => calendar.GetWeekOfYear(calendar.MaxSupportedDateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday - 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("firstDayOfWeek", () => calendar.GetWeekOfYear(calendar.MaxSupportedDateTime, CalendarWeekRule.FirstDay, DayOfWeek.Saturday + 1));
}
[Fact]
public void ToDateTime_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
if (PlatformDetection.IsFullFramework && calendar is JapaneseLunisolarCalendar)
{
return;
}
int month = 1;
int day = 1;
int hour = 1;
int minute = 1;
int second = 1;
int millisecond = 1;
foreach (int era in calendar.Eras)
{
int year = MaxCalendarYearInEra(calendar, era) - 2;
// Year is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(-1, month, day, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(0, month, day, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(MaxCalendarYearInEras(calendar, era) + 1, month, day, hour, minute, second, millisecond, era));
// Month is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, -1, day, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, 0, day, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, calendar.GetMonthsInYear(year, era) + 1, day, hour, minute, second, millisecond, era));
// Day is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, -1, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, 0, hour, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, calendar.GetDaysInMonth(year, month, era) + 1, hour, minute, second, millisecond, era));
// Hour is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, -1, minute, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, 60, minute, second, millisecond, era));
// Minute is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, -1, second, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, 60, second, millisecond, era));
// Second is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, minute, -1, millisecond, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, minute, 60, millisecond, era));
// Millisecond is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, minute, second, -1, era));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(year, month, day, hour, minute, second, 1000, era));
}
// Year is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(MinCalendarYearInEra(calendar, MinEra(calendar)) - 1, month, day, hour, minute, second, millisecond, MinEra(calendar)));
// Era is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(calendar.GetYear(calendar.MaxSupportedDateTime), month, day, hour, minute, second, millisecond, MinEra(calendar) - 2));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(calendar.GetYear(calendar.MaxSupportedDateTime), month, day, hour, minute, second, millisecond, MaxEra(calendar) + 1));
// New date is out of range
DateTime minDateTime = calendar.MinSupportedDateTime;
int minEra = calendar.GetEra(minDateTime);
int minYear = calendar.GetYear(minDateTime);
DateTime maxDateTime = calendar.MaxSupportedDateTime;
int maxEra = calendar.GetEra(maxDateTime);
int maxYear = calendar.GetYear(maxDateTime);
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(minYear - 1, minDateTime.Month, minDateTime.Day, minDateTime.Hour, minDateTime.Minute, minDateTime.Second, minDateTime.Millisecond, minEra));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.ToDateTime(maxYear + 1, maxDateTime.Month, maxDateTime.Day, maxDateTime.Hour, maxDateTime.Minute, maxDateTime.Second, maxDateTime.Millisecond, maxEra));
}
[Fact]
public void ToFourDigitYear_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => calendar.ToFourDigitYear(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => calendar.ToFourDigitYear(MaxCalendarYearInEra(calendar, MaxEra(calendar)) + 1));
if (!(calendar is JapaneseLunisolarCalendar))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => calendar.ToFourDigitYear(MinCalendarYearInEra(calendar, MinEra(calendar)) - 2));
}
}
[Fact]
public void TwoDigitYearMax_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.TwoDigitYearMax = 98);
int max = Math.Max(MaxGregorianYearInEra(calendar, MaxEra(calendar)), MaxCalendarYearInEra(calendar, MaxEra(calendar)));
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.TwoDigitYearMax = max + 1);
}
[Fact]
public void GetEra_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(DateTime_TestData(calendar), dt =>
{
// JapaneseCalendar throws on Unix (ICU), but not on Windows
if ((calendar is JapaneseCalendar && PlatformDetection.IsWindows) || calendar is HebrewCalendar || calendar is TaiwanLunisolarCalendar || calendar is JapaneseLunisolarCalendar)
{
calendar.GetEra(dt);
}
else
{
Assert.Throws<ArgumentOutOfRangeException>(() => calendar.GetEra(dt));
}
});
}
[Fact]
public void GetYear_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(DateTime_TestData(calendar), dt =>
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetYear(dt))
);
}
[Fact]
public void GetMonth_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(DateTime_TestData(calendar), dt =>
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetMonth(dt))
);
}
[Fact]
public void GetDayOfYear_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(DateTime_TestData(calendar), dt =>
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetDayOfYear(dt))
);
}
[Fact]
public void GetDayOfMonth_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(DateTime_TestData(calendar), dt =>
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetDayOfMonth(dt))
);
}
[Fact]
public void GetDayOfWeek_Invalid_ThrowsArgumentOutOfRangeException()
{
Calendar calendar = Calendar;
Assert.All(DateTime_TestData(calendar), dt =>
{
if (calendar is HijriCalendar || calendar is UmAlQuraCalendar || calendar is PersianCalendar || calendar is HebrewCalendar)
{
calendar.GetDayOfWeek(dt);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("time", () => calendar.GetDayOfWeek(dt));
}
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void TestJapaneseCalendarDateParsing()
{
CultureInfo ciJapanese = new CultureInfo("ja-JP") { DateTimeFormat = { Calendar = new JapaneseCalendar() } };
DateTime dt = new DateTime(1970, 1, 1);
string eraName = dt.ToString("gg", ciJapanese);
Assert.Equal(new DateTime(1995, 1, 1), DateTime.Parse(eraName + " 70/1/1 0:00:00", ciJapanese));
}
}
}
| |
/*
* Copyright (c) 2013 Mario Freitas (imkira@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.IO;
using System.Text;
namespace URLClient
{
public interface IHTTPResponse
{
long StatusCode { get; }
IHTTPHeaderList Headers { get; }
ulong ExpectedReceiveContentLength { get; }
ulong ResumedContentLength { get; }
ulong ReceivedContentLength { get; }
ulong ExpectedAcquiredContentLength { get; }
ulong AcquiredContentLength { get; }
bool SupportsContentStream { get; }
Stream ContentStream { get; }
bool SupportsContentMemoryStream { get; }
MemoryStream ContentMemoryStream { get; }
bool SupportsContentFilePath { get; }
string ContentFilePath { get; }
byte[] ContentToBytes();
string ContentToString(Encoding enc = null);
int RedirectCount { get; }
bool IsProgressAvailable { get; }
float Progress { get; }
float ReceiveProgress { get; }
}
public class HTTPResponse : IHTTPResponse
{
/// <summary>Status code.</summary>
public long statusCode;
public long StatusCode
{
get
{
return statusCode;
}
}
/// <summary>Headers received.</summary>
public HTTPHeaderList headers;
public IHTTPHeaderList Headers
{
get
{
return headers;
}
}
/// <summary>Total expected content length to receive.</summary>
public long expectedReceiveContentLength;
public ulong ExpectedReceiveContentLength
{
get
{
if (expectedReceiveContentLength < (long)0)
{
return (ulong)0;
}
return (ulong)expectedReceiveContentLength;
}
}
/// <summary>Total content length resumed.</summary>
public ulong resumedContentLength;
public ulong ResumedContentLength
{
get
{
return resumedContentLength;
}
}
/// <summary>Total content length received.</summary>
public ulong receivedContentLength;
public ulong ReceivedContentLength
{
get
{
return receivedContentLength;
}
}
/// <summary>Total expected acquire content length.</summary>
public ulong ExpectedAcquiredContentLength
{
get
{
if (expectedReceiveContentLength < (long)0)
{
return (ulong)0;
}
ulong total = (ulong)expectedReceiveContentLength +
resumedContentLength;
if (total < resumedContentLength)
{
return ulong.MaxValue;
}
return total;
}
}
/// <summary>Total content length acquired (resumed + received).</summary>
public ulong AcquiredContentLength
{
get
{
ulong total = receivedContentLength + resumedContentLength;
if (total < resumedContentLength)
{
return ulong.MaxValue;
}
return total;
}
}
/// <summary>Whether ContentStream is supported.</summary>
public bool supportsContentStream;
public bool SupportsContentStream
{
get
{
return supportsContentStream;
}
}
/// <summary>Stream with received content.</summary>
public Stream contentStream;
public Stream ContentStream
{
get
{
return contentStream;
}
}
/// <summary>Whether ContentMemoryStream is supported.</summary>
public bool supportsContentMemoryStream;
public bool SupportsContentMemoryStream
{
get
{
return supportsContentMemoryStream;
}
}
/// <summary>MemoryStream with received content.</summary>
public MemoryStream ContentMemoryStream
{
get
{
if (supportsContentMemoryStream == false)
{
return null;
}
return (MemoryStream)contentStream;
}
}
/// <summary>Whether ContentFilePath is supported.</summary>
public bool supportsContentFilePath;
public bool SupportsContentFilePath
{
get
{
return supportsContentFilePath;
}
}
/// <summary>Path to file with received content.</summary>
public string contentFilePath;
public string ContentFilePath
{
get
{
if (supportsContentFilePath == false)
{
return null;
}
return contentFilePath;
}
}
/// <summary>Number of redirects processed.</summary>
public int redirectCount;
public int RedirectCount
{
get
{
return redirectCount;
}
}
/// <summary>Check whether progress is available.</summary>
public bool IsProgressAvailable
{
get
{
return (expectedReceiveContentLength >= (long)0);
}
}
/// <summary>Estimated total progress (0 to 1).</summary>
public float Progress
{
get
{
if (expectedReceiveContentLength < (long)0)
{
return -1f;
}
ulong expectedLength = ExpectedAcquiredContentLength;
ulong acquiredLength = AcquiredContentLength;
if ((expectedLength == 0) ||
(acquiredLength >= expectedLength))
{
return 1f;
}
return acquiredLength / (float)expectedLength;
}
}
/// <summary>Estimated receive progress (0 to 1).</summary>
public float ReceiveProgress
{
get
{
if (expectedReceiveContentLength < (long)0)
{
return -1f;
}
if ((expectedReceiveContentLength == (long)0) ||
(receivedContentLength >= (ulong)expectedReceiveContentLength))
{
return 1f;
}
return receivedContentLength / (float)expectedReceiveContentLength;
}
}
public HTTPResponse()
{
statusCode = (long)0;
receivedContentLength = (ulong)0;
resumedContentLength = (ulong)0;
expectedReceiveContentLength = (long)-1;
supportsContentStream = false;
contentStream = null;
supportsContentMemoryStream = false;
supportsContentFilePath = false;
contentFilePath = null;
headers = null;
}
public byte[] ContentToBytes()
{
MemoryStream stream = ContentMemoryStream;
if (stream == null)
{
return null;
}
return stream.ToArray();
}
public string ContentToString(Encoding enc = null)
{
byte[] bytes = ContentToBytes();
if (bytes == null)
{
return null;
}
if (enc == null)
{
enc = Encoding.UTF8;
}
return enc.GetString(bytes);
}
public override string ToString()
{
return string.Format("HTTPResponse<StatusCode={0}," +
"ReceivedContentLength={1},ResumedContentLength={2}," +
"ExpectedReceiveContentLength={3}," +
"AcquiredContentLength={4},ExpectedAcquiredContentLength={5}," +
"ContentFilePath={6}," +
"IsProgressAvailable={7},Progress={8:0.##}%," +
"ReceiveProgress={9:0.##}%,RedirectCount={10},Headers={11}>",
statusCode, receivedContentLength, resumedContentLength,
ExpectedReceiveContentLength, AcquiredContentLength,
ExpectedAcquiredContentLength, ContentFilePath,
IsProgressAvailable,
Progress * 100f, ReceiveProgress * 100, redirectCount, headers);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
/*=================================JapaneseCalendar==========================
**
** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as
** Gregorian calendar. However, the year value is an offset to the Gregorian
** year based on the era.
**
** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor,
** and the era begins on the day an emperor ascends the throne and continues until his death.
** The era changes at 12:00AM.
**
** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st.
** 1989/1/8 A.D. is also Heisei 1st 1/8.
**
** Any date in the year during which era is changed can be reckoned in either era. For example,
** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year.
**
** Note:
** The DateTime can be represented by the JapaneseCalendar are limited to two factors:
** 1. The min value and max value of DateTime class.
** 2. The available era information.
**
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1868/09/08 9999/12/31
** Japanese Meiji 01/01 Heisei 8011/12/31
============================================================================*/
[Serializable]
public partial class JapaneseCalendar : Calendar
{
internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8);
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
//
// Using a field initializer rather than a static constructor so that the whole class can be lazy
// init.
internal static volatile EraInfo[] japaneseEraInfo;
//
// Read our era info
//
// m_EraInfo must be listed in reverse chronological order. The most recent era
// should be the first element.
// That is, m_EraInfo[0] contains the most recent era.
//
// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
// we don't read the registry and instead we call WinRT to get the needed informatio
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
//
internal static EraInfo[] GetEraInfo()
{
// See if we need to build it
if (japaneseEraInfo == null)
{
japaneseEraInfo = GetJapaneseEras();
// See if we have to use the built-in eras
if (japaneseEraInfo == null)
{
// We know about some built-in ranges
EraInfo[] defaultEraRanges = new EraInfo[4];
defaultEraRanges[0] = new EraInfo(4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988,
"\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear
defaultEraRanges[1] = new EraInfo(3, 1926, 12, 25, 1925, 1, 1989 - 1925,
"\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear
defaultEraRanges[2] = new EraInfo(2, 1912, 7, 30, 1911, 1, 1926 - 1911,
"\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear
defaultEraRanges[3] = new EraInfo(1, 1868, 1, 1, 1867, 1, 1912 - 1867,
"\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear
// Remember the ranges we built
japaneseEraInfo = defaultEraRanges;
}
}
// return the era we found/made
return japaneseEraInfo;
}
internal static volatile Calendar s_defaultInstance;
internal GregorianCalendarHelper helper;
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
internal static Calendar GetDefaultInstance()
{
if (s_defaultInstance == null)
{
s_defaultInstance = new JapaneseCalendar();
}
return (s_defaultInstance);
}
public JapaneseCalendar()
{
try
{
new CultureInfo("ja-JP");
}
catch (ArgumentException e)
{
throw new TypeInitializationException(this.GetType().ToString(), e);
}
helper = new GregorianCalendarHelper(this, GetEraInfo());
}
internal override CalendarId ID
{
get
{
return CalendarId.JAPAN;
}
}
public override DateTime AddMonths(DateTime time, int months)
{
return (helper.AddMonths(time, months));
}
public override DateTime AddYears(DateTime time, int years)
{
return (helper.AddYears(time, years));
}
/*=================================GetDaysInMonth==========================
**Action: Returns the number of days in the month given by the year and month arguments.
**Returns: The number of days in the given month.
**Arguments:
** year The year in Japanese calendar.
** month The month
** era The Japanese era value.
**Exceptions
** ArgumentException If month is less than 1 or greater * than 12.
============================================================================*/
public override int GetDaysInMonth(int year, int month, int era)
{
return (helper.GetDaysInMonth(year, month, era));
}
public override int GetDaysInYear(int year, int era)
{
return (helper.GetDaysInYear(year, era));
}
public override int GetDayOfMonth(DateTime time)
{
return (helper.GetDayOfMonth(time));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return (helper.GetDayOfWeek(time));
}
public override int GetDayOfYear(DateTime time)
{
return (helper.GetDayOfYear(time));
}
public override int GetMonthsInYear(int year, int era)
{
return (helper.GetMonthsInYear(year, era));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
}
/*=================================GetEra==========================
**Action: Get the era value of the specified time.
**Returns: The era value for the specified time.
**Arguments:
** time the specified date time.
**Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges.
============================================================================*/
public override int GetEra(DateTime time)
{
return (helper.GetEra(time));
}
public override int GetMonth(DateTime time)
{
return (helper.GetMonth(time));
}
public override int GetYear(DateTime time)
{
return (helper.GetYear(time));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return (helper.IsLeapDay(year, month, day, era));
}
public override bool IsLeapYear(int year, int era)
{
return (helper.IsLeapYear(year, era));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
}
public override bool IsLeapMonth(int year, int month, int era)
{
return (helper.IsLeapMonth(year, month, era));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
}
// For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years.
// Therefore, for any two digit number, we just return the original number.
public override int ToFourDigitYear(int year)
{
if (year <= 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedPosNum);
}
Contract.EndContractBlock();
if (year > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
helper.MaxYear));
}
return (year);
}
public override int[] Eras
{
get
{
return (helper.Eras);
}
}
//
// Return the various era strings
// Note: The arrays are backwards of the eras
//
internal static String[] EraNames()
{
EraInfo[] eras = GetEraInfo();
String[] eraNames = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
eraNames[i] = eras[eras.Length - i - 1].eraName;
}
return eraNames;
}
internal static String[] AbbrevEraNames()
{
EraInfo[] eras = GetEraInfo();
String[] erasAbbrev = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName;
}
return erasAbbrev;
}
internal static String[] EnglishEraNames()
{
EraInfo[] eras = GetEraInfo();
String[] erasEnglish = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasEnglish[i] = eras[eras.Length - i - 1].englishEraName;
}
return erasEnglish;
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99;
internal override bool IsValidYear(int year, int era)
{
return helper.IsValidYear(year, era);
}
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
helper.MaxYear));
}
twoDigitYearMax = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Collections.Utilities;
using Orleans.Streams;
using Orleans.Streams.Endpoints;
using Orleans.Streams.Messages;
using Microsoft.PSharp.Actors;
namespace Orleans.Collections
{
/// <summary>
/// Implementation of a containerNode grain.
/// </summary>
public class ContainerNodeGrain<T> : Grain, IContainerNodeGrain<T>
{
protected IList<T> Collection;
protected SingleStreamProvider<ContainerHostedElement<T>> StreamProvider;
private SingleStreamConsumer<T> _streamConsumer;
private const string StreamProviderName = "CollectionStreamProvider";
public async Task<IReadOnlyCollection<ContainerElementReference<T>>> AddRange(IEnumerable<T> items)
{
var newReferences = await InternalAddItems(items);
return newReferences;
}
public async Task EnumerateItems(ICollection<IBatchItemAdder<T>> adders)
{
await adders.BatchAdd(Collection);
}
public Task Clear()
{
Collection.Clear();
return TaskDone.Done;
}
public Task<bool> Contains(T item)
{
return Task.FromResult(Collection.Contains(item));
}
public Task<int> Count()
{
return Task.FromResult(Collection.Count);
}
public async Task<bool> Remove(T item)
{
return await InternalRemove(item);
}
protected virtual Task<bool> InternalRemove(T item)
{
return Task.FromResult(Collection.Remove(item));
}
public async Task<bool> Remove(ContainerElementReference<T> reference)
{
if (!reference.ContainerId.Equals(this.GetPrimaryKey()))
{
throw new ArgumentException();
}
return await InternalRemove(reference);
}
protected virtual Task<bool> InternalRemove(ContainerElementReference<T> reference)
{
if (Collection.Count < reference.Offset)
{
return Task.FromResult(false);
}
Collection.RemoveAt(reference.Offset);
return Task.FromResult(true);
}
public async Task<int> EnumerateToStream(int? transactionId = null)
{
var hostedItems = Collection.Select((value, index) => new ContainerHostedElement<T>(GetReferenceForItem(index), value)).ToList();
return await StreamProvider.SendItems(hostedItems, true, transactionId);
}
public override async Task OnActivateAsync()
{
Collection = new List<T>();
StreamProvider = new SingleStreamProvider<ContainerHostedElement<T>>(GetStreamProvider(StreamProviderName), this.GetPrimaryKey());
_streamConsumer = new SingleStreamConsumer<T>(GetStreamProvider(StreamProviderName), this, TearDown);
await base.OnActivateAsync();
}
protected virtual Task<IReadOnlyCollection<ContainerElementReference<T>>> InternalAddItems(IEnumerable<T> batch)
{
lock (Collection)
{
var oldCount = Collection.Count;
foreach (var item in batch)
{
Collection.Add(item);
}
IReadOnlyCollection<ContainerElementReference<T>> newReferences =
Enumerable.Range(oldCount, Collection.Count - oldCount).Select(i => GetReferenceForItem(i)).ToList();
return Task.FromResult(newReferences);
}
}
protected T GetItemAt(int offset)
{
return Collection[offset];
}
protected ContainerElementReference<T> GetReferenceForItem(int offset, bool exists = true)
{
return new ContainerElementReference<T>(this.GetPrimaryKey(), offset, this,
this.AsReference<IContainerNodeGrain<T>>(), exists);
}
public async Task<StreamIdentity<ContainerHostedElement<T>>> GetStreamIdentity()
{
return await StreamProvider.GetStreamIdentity();
}
public async Task SetInput(StreamIdentity<T> inputStream)
{
await _streamConsumer.SetInput(inputStream);
}
public Task TransactionComplete(int transactionId)
{
return _streamConsumer.TransactionComplete(transactionId);
}
public async Task TearDown()
{
await StreamProvider.TearDown();
}
public async Task<bool> IsTearedDown()
{
var tearDownStates = await ActorModel.WhenAll(_streamConsumer.IsTearedDown(), StreamProvider.IsTearedDown());
return tearDownStates[0] && tearDownStates[1];
}
public Task ExecuteSync(Action<T> action, ContainerElementReference<T> reference = null)
{
return ExecuteSync((x, state) => action(x), null, reference);
}
public Task ExecuteSync(Action<T, object> action, object state, ContainerElementReference<T> reference = null)
{
if (reference != null)
{
if (!reference.ContainerId.Equals(this.GetPrimaryKey()))
{
throw new InvalidOperationException();
}
var curItem = GetItemAt(reference.Offset);
action(curItem, state);
}
else
{
foreach (var item in Collection)
{
action(item, state);
}
}
return TaskDone.Done;
}
public Task<IList<object>> ExecuteSync(Func<T, object> func)
{
return ExecuteSync((x, state) => func(x), null);
}
public Task<object> ExecuteSync(Func<T, object, object> func, object state, ContainerElementReference<T> reference)
{
if (!this.GetPrimaryKey().Equals(reference.ContainerId))
{
throw new InvalidOperationException();
}
var curItem = GetItemAt(reference.Offset);
var result = func(curItem, state);
return Task.FromResult(result);
}
public Task<IList<object>> ExecuteSync(Func<T, object, object> func, object state)
{
IList<object> results = Collection.Select(item => func(item, state)).ToList();
return Task.FromResult(results);
}
public Task<object> ExecuteSync(Func<T, object> func, ContainerElementReference<T> reference = null)
{
return ExecuteSync((x, state) => func(x), null, reference);
}
public Task ExecuteAsync(Func<T, Task> func, ContainerElementReference<T> reference = null)
{
return ExecuteAsync((x, state) => func(x), null, reference);
}
public async Task ExecuteAsync(Func<T, object, Task> func, object state, ContainerElementReference<T> reference = null)
{
if (reference != null)
{
if (!this.GetPrimaryKey().Equals(reference.ContainerId))
{
throw new InvalidOperationException();
}
var curItem = GetItemAt(reference.Offset);
await func(curItem, state);
}
else
{
foreach (var item in Collection)
{
await func(item, state);
}
}
}
public Task<IList<object>> ExecuteAsync(Func<T, Task<object>> func)
{
return ExecuteAsync((x, state) => func(x), null);
}
public async Task<IList<object>> ExecuteAsync(Func<T, object, Task<object>> func, object state)
{
var results = Collection.Select(item => func(item, state)).ToList();
var resultSet = await ActorModel.WhenAll(results);
return new List<object>(resultSet);
}
public Task<object> ExecuteAsync(Func<T, Task<object>> func, ContainerElementReference<T> reference)
{
return ExecuteAsync((x, state) => func(x), null, reference);
}
public async Task<object> ExecuteAsync(Func<T, object, Task<object>> func, object state, ContainerElementReference<T> reference)
{
if (!this.GetPrimaryKey().Equals(reference.ContainerId))
{
throw new InvalidOperationException();
}
var curItem = GetItemAt(reference.Offset);
var result = await func(curItem, state);
return result;
}
public async Task Visit(ItemMessage<T> message)
{
await InternalAddItems(message.Items);
}
public Task Visit(TransactionMessage transactionMessage)
{
return TaskDone.Done;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.ExceptionServices;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.SignalR.Internal;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace Microsoft.AspNetCore.SignalR.Protocol
{
/// <summary>
/// Implements the SignalR Hub Protocol using Newtonsoft.Json.
/// </summary>
public class NewtonsoftJsonHubProtocol : IHubProtocol
{
private const string ResultPropertyName = "result";
private const string ItemPropertyName = "item";
private const string InvocationIdPropertyName = "invocationId";
private const string StreamIdsPropertyName = "streamIds";
private const string TypePropertyName = "type";
private const string ErrorPropertyName = "error";
private const string TargetPropertyName = "target";
private const string ArgumentsPropertyName = "arguments";
private const string HeadersPropertyName = "headers";
private const string AllowReconnectPropertyName = "allowReconnect";
private const string ProtocolName = "json";
private const int ProtocolVersion = 1;
/// <summary>
/// Gets the serializer used to serialize invocation arguments and return values.
/// </summary>
public JsonSerializer PayloadSerializer { get; }
/// <summary>
/// Initializes a new instance of the <see cref="NewtonsoftJsonHubProtocol"/> class.
/// </summary>
public NewtonsoftJsonHubProtocol() : this(Options.Create(new NewtonsoftJsonHubProtocolOptions()))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NewtonsoftJsonHubProtocol"/> class.
/// </summary>
/// <param name="options">The options used to initialize the protocol.</param>
public NewtonsoftJsonHubProtocol(IOptions<NewtonsoftJsonHubProtocolOptions> options)
{
PayloadSerializer = JsonSerializer.Create(options.Value.PayloadSerializerSettings);
}
/// <inheritdoc />
public string Name => ProtocolName;
/// <inheritdoc />
public int Version => ProtocolVersion;
/// <inheritdoc />
public TransferFormat TransferFormat => TransferFormat.Text;
/// <inheritdoc />
public bool IsVersionSupported(int version)
{
return version == Version;
}
/// <inheritdoc />
public bool TryParseMessage(ref ReadOnlySequence<byte> input, IInvocationBinder binder, [NotNullWhen(true)] out HubMessage? message)
{
if (!TextMessageParser.TryParseMessage(ref input, out var payload))
{
message = null;
return false;
}
var textReader = Utf8BufferTextReader.Get(payload);
try
{
message = ParseMessage(textReader, binder);
}
finally
{
Utf8BufferTextReader.Return(textReader);
}
return message != null;
}
/// <inheritdoc />
public void WriteMessage(HubMessage message, IBufferWriter<byte> output)
{
WriteMessageCore(message, output);
TextMessageFormatter.WriteRecordSeparator(output);
}
/// <inheritdoc />
public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message)
{
return HubProtocolExtensions.GetMessageBytes(this, message);
}
private HubMessage? ParseMessage(Utf8BufferTextReader textReader, IInvocationBinder binder)
{
try
{
// We parse using the JsonTextReader directly but this has a problem. Some of our properties are dependent on other properties
// and since reading the json might be unordered, we need to store the parsed content as JToken to re-parse when true types are known.
// if we're lucky and the state we need to directly parse is available, then we'll use it.
int? type = null;
string? invocationId = null;
string? target = null;
string? error = null;
var hasItem = false;
object? item = null;
JToken? itemToken = null;
var hasResult = false;
object? result = null;
JToken? resultToken = null;
var hasArguments = false;
object?[]? arguments = null;
string[]? streamIds = null;
JArray? argumentsToken = null;
ExceptionDispatchInfo? argumentBindingException = null;
Dictionary<string, string>? headers = null;
var completed = false;
var allowReconnect = false;
using (var reader = JsonUtils.CreateJsonTextReader(textReader))
{
reader.DateParseHandling = DateParseHandling.None;
JsonUtils.CheckRead(reader);
// We're always parsing a JSON object
JsonUtils.EnsureObjectStart(reader);
do
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
var memberName = reader.Value?.ToString();
switch (memberName)
{
case TypePropertyName:
var messageType = JsonUtils.ReadAsInt32(reader, TypePropertyName);
if (messageType == null)
{
throw new InvalidDataException($"Missing required property '{TypePropertyName}'.");
}
type = messageType.Value;
break;
case InvocationIdPropertyName:
invocationId = JsonUtils.ReadAsString(reader, InvocationIdPropertyName);
break;
case StreamIdsPropertyName:
JsonUtils.CheckRead(reader);
if (reader.TokenType != JsonToken.StartArray)
{
throw new InvalidDataException($"Expected '{StreamIdsPropertyName}' to be of type {JTokenType.Array}.");
}
var newStreamIds = new List<string>();
reader.Read();
while (reader.TokenType != JsonToken.EndArray)
{
newStreamIds.Add(reader.Value?.ToString() ?? throw new InvalidDataException($"Null value for '{StreamIdsPropertyName}' is not valid."));
reader.Read();
}
streamIds = newStreamIds.ToArray();
break;
case TargetPropertyName:
target = JsonUtils.ReadAsString(reader, TargetPropertyName);
break;
case ErrorPropertyName:
error = JsonUtils.ReadAsString(reader, ErrorPropertyName);
break;
case AllowReconnectPropertyName:
allowReconnect = JsonUtils.ReadAsBoolean(reader, AllowReconnectPropertyName);
break;
case ResultPropertyName:
hasResult = true;
if (string.IsNullOrEmpty(invocationId))
{
JsonUtils.CheckRead(reader);
// If we don't have an invocation id then we need to store it as a JToken so we can parse it later
resultToken = JToken.Load(reader);
}
else
{
// If we have an invocation id already we can parse the end result
var returnType = binder.GetReturnType(invocationId);
if (!JsonUtils.ReadForType(reader, returnType))
{
throw new JsonReaderException("Unexpected end when reading JSON");
}
result = PayloadSerializer.Deserialize(reader, returnType);
}
break;
case ItemPropertyName:
JsonUtils.CheckRead(reader);
hasItem = true;
string? id = null;
if (!string.IsNullOrEmpty(invocationId))
{
id = invocationId;
}
else
{
// If we don't have an id yet then we need to store it as a JToken to parse later
itemToken = JToken.Load(reader);
break;
}
try
{
var itemType = binder.GetStreamItemType(id);
item = PayloadSerializer.Deserialize(reader, itemType);
}
catch (Exception ex)
{
return new StreamBindingFailureMessage(id, ExceptionDispatchInfo.Capture(ex));
}
break;
case ArgumentsPropertyName:
JsonUtils.CheckRead(reader);
int initialDepth = reader.Depth;
if (reader.TokenType != JsonToken.StartArray)
{
throw new InvalidDataException($"Expected '{ArgumentsPropertyName}' to be of type {JTokenType.Array}.");
}
hasArguments = true;
if (string.IsNullOrEmpty(target))
{
// We don't know the method name yet so just parse an array of generic JArray
argumentsToken = JArray.Load(reader);
}
else
{
try
{
var paramTypes = binder.GetParameterTypes(target);
arguments = BindArguments(reader, paramTypes);
}
catch (Exception ex)
{
argumentBindingException = ExceptionDispatchInfo.Capture(ex);
// Could be at any point in argument array JSON when an error is thrown
// Read until the end of the argument JSON array
while (reader.Depth == initialDepth && reader.TokenType == JsonToken.StartArray ||
reader.Depth > initialDepth)
{
JsonUtils.CheckRead(reader);
}
}
}
break;
case HeadersPropertyName:
JsonUtils.CheckRead(reader);
headers = ReadHeaders(reader);
break;
default:
// Skip read the property name
JsonUtils.CheckRead(reader);
// Skip the value for this property
reader.Skip();
break;
}
break;
case JsonToken.EndObject:
completed = true;
break;
}
}
while (!completed && JsonUtils.CheckRead(reader));
}
HubMessage message;
switch (type)
{
case HubProtocolConstants.InvocationMessageType:
{
if (target is null)
{
throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
}
if (argumentsToken != null)
{
// We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything.
try
{
var paramTypes = binder.GetParameterTypes(target);
arguments = BindArguments(argumentsToken, paramTypes);
}
catch (Exception ex)
{
argumentBindingException = ExceptionDispatchInfo.Capture(ex);
}
}
message = argumentBindingException != null
? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException)
: BindInvocationMessage(invocationId, target, arguments, hasArguments, streamIds, binder);
}
break;
case HubProtocolConstants.StreamInvocationMessageType:
{
if (target is null)
{
throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
}
if (argumentsToken != null)
{
// We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything.
try
{
var paramTypes = binder.GetParameterTypes(target);
arguments = BindArguments(argumentsToken, paramTypes);
}
catch (Exception ex)
{
argumentBindingException = ExceptionDispatchInfo.Capture(ex);
}
}
message = argumentBindingException != null
? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException)
: BindStreamInvocationMessage(invocationId, target, arguments, hasArguments, streamIds, binder);
}
break;
case HubProtocolConstants.StreamItemMessageType:
if (invocationId is null)
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (itemToken != null)
{
try
{
var itemType = binder.GetStreamItemType(invocationId);
item = itemToken.ToObject(itemType, PayloadSerializer);
}
catch (Exception ex)
{
message = new StreamBindingFailureMessage(invocationId, ExceptionDispatchInfo.Capture(ex));
break;
};
}
message = BindStreamItemMessage(invocationId, item, hasItem, binder);
break;
case HubProtocolConstants.CompletionMessageType:
if (invocationId is null)
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (resultToken != null)
{
var returnType = binder.GetReturnType(invocationId);
result = resultToken.ToObject(returnType, PayloadSerializer);
}
message = BindCompletionMessage(invocationId, error, result, hasResult, binder);
break;
case HubProtocolConstants.CancelInvocationMessageType:
message = BindCancelInvocationMessage(invocationId);
break;
case HubProtocolConstants.PingMessageType:
return PingMessage.Instance;
case HubProtocolConstants.CloseMessageType:
return BindCloseMessage(error, allowReconnect);
case null:
throw new InvalidDataException($"Missing required property '{TypePropertyName}'.");
default:
// Future protocol changes can add message types, old clients can ignore them
return null;
}
return ApplyHeaders(message, headers);
}
catch (JsonReaderException jrex)
{
throw new InvalidDataException("Error reading JSON.", jrex);
}
}
private static Dictionary<string, string> ReadHeaders(JsonTextReader reader)
{
var headers = new Dictionary<string, string>(StringComparer.Ordinal);
if (reader.TokenType != JsonToken.StartObject)
{
throw new InvalidDataException($"Expected '{HeadersPropertyName}' to be of type {JTokenType.Object}.");
}
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
var propertyName = reader.Value!.ToString()!;
JsonUtils.CheckRead(reader);
if (reader.TokenType != JsonToken.String)
{
throw new InvalidDataException($"Expected header '{propertyName}' to be of type {JTokenType.String}.");
}
headers[propertyName] = reader.Value.ToString()!;
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
return headers;
}
}
throw new JsonReaderException("Unexpected end when reading message headers");
}
private void WriteMessageCore(HubMessage message, IBufferWriter<byte> stream)
{
var textWriter = Utf8BufferTextWriter.Get(stream);
try
{
using (var writer = JsonUtils.CreateJsonTextWriter(textWriter))
{
writer.WriteStartObject();
switch (message)
{
case InvocationMessage m:
WriteMessageType(writer, HubProtocolConstants.InvocationMessageType);
WriteHeaders(writer, m);
WriteInvocationMessage(m, writer);
break;
case StreamInvocationMessage m:
WriteMessageType(writer, HubProtocolConstants.StreamInvocationMessageType);
WriteHeaders(writer, m);
WriteStreamInvocationMessage(m, writer);
break;
case StreamItemMessage m:
WriteMessageType(writer, HubProtocolConstants.StreamItemMessageType);
WriteHeaders(writer, m);
WriteStreamItemMessage(m, writer);
break;
case CompletionMessage m:
WriteMessageType(writer, HubProtocolConstants.CompletionMessageType);
WriteHeaders(writer, m);
WriteCompletionMessage(m, writer);
break;
case CancelInvocationMessage m:
WriteMessageType(writer, HubProtocolConstants.CancelInvocationMessageType);
WriteHeaders(writer, m);
WriteCancelInvocationMessage(m, writer);
break;
case PingMessage _:
WriteMessageType(writer, HubProtocolConstants.PingMessageType);
break;
case CloseMessage m:
WriteMessageType(writer, HubProtocolConstants.CloseMessageType);
WriteCloseMessage(m, writer);
break;
default:
throw new InvalidOperationException($"Unsupported message type: {message.GetType().FullName}");
}
writer.WriteEndObject();
writer.Flush();
}
}
finally
{
Utf8BufferTextWriter.Return(textWriter);
}
}
private static void WriteHeaders(JsonTextWriter writer, HubInvocationMessage message)
{
if (message.Headers != null && message.Headers.Count > 0)
{
writer.WritePropertyName(HeadersPropertyName);
writer.WriteStartObject();
foreach (var value in message.Headers)
{
writer.WritePropertyName(value.Key);
writer.WriteValue(value.Value);
}
writer.WriteEndObject();
}
}
private void WriteCompletionMessage(CompletionMessage message, JsonTextWriter writer)
{
WriteInvocationId(message, writer);
if (!string.IsNullOrEmpty(message.Error))
{
writer.WritePropertyName(ErrorPropertyName);
writer.WriteValue(message.Error);
}
else if (message.HasResult)
{
writer.WritePropertyName(ResultPropertyName);
PayloadSerializer.Serialize(writer, message.Result);
}
}
private static void WriteCancelInvocationMessage(CancelInvocationMessage message, JsonTextWriter writer)
{
WriteInvocationId(message, writer);
}
private void WriteStreamItemMessage(StreamItemMessage message, JsonTextWriter writer)
{
WriteInvocationId(message, writer);
writer.WritePropertyName(ItemPropertyName);
PayloadSerializer.Serialize(writer, message.Item);
}
private void WriteInvocationMessage(InvocationMessage message, JsonTextWriter writer)
{
WriteInvocationId(message, writer);
writer.WritePropertyName(TargetPropertyName);
writer.WriteValue(message.Target);
WriteArguments(message.Arguments, writer);
WriteStreamIds(message.StreamIds, writer);
}
private void WriteStreamInvocationMessage(StreamInvocationMessage message, JsonTextWriter writer)
{
WriteInvocationId(message, writer);
writer.WritePropertyName(TargetPropertyName);
writer.WriteValue(message.Target);
WriteArguments(message.Arguments, writer);
WriteStreamIds(message.StreamIds, writer);
}
private static void WriteCloseMessage(CloseMessage message, JsonTextWriter writer)
{
if (message.Error != null)
{
writer.WritePropertyName(ErrorPropertyName);
writer.WriteValue(message.Error);
}
if (message.AllowReconnect)
{
writer.WritePropertyName(AllowReconnectPropertyName);
writer.WriteValue(true);
}
}
private void WriteArguments(object?[] arguments, JsonTextWriter writer)
{
writer.WritePropertyName(ArgumentsPropertyName);
writer.WriteStartArray();
foreach (var argument in arguments)
{
PayloadSerializer.Serialize(writer, argument);
}
writer.WriteEndArray();
}
private static void WriteStreamIds(string[]? streamIds, JsonTextWriter writer)
{
if (streamIds == null)
{
return;
}
writer.WritePropertyName(StreamIdsPropertyName);
writer.WriteStartArray();
foreach (var streamId in streamIds)
{
writer.WriteValue(streamId);
}
writer.WriteEndArray();
}
private static void WriteInvocationId(HubInvocationMessage message, JsonTextWriter writer)
{
if (!string.IsNullOrEmpty(message.InvocationId))
{
writer.WritePropertyName(InvocationIdPropertyName);
writer.WriteValue(message.InvocationId);
}
}
private static void WriteMessageType(JsonTextWriter writer, int type)
{
writer.WritePropertyName(TypePropertyName);
writer.WriteValue(type);
}
private static HubMessage BindCancelInvocationMessage(string? invocationId)
{
if (string.IsNullOrEmpty(invocationId))
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
return new CancelInvocationMessage(invocationId);
}
private static HubMessage BindCompletionMessage(string invocationId, string? error, object? result, bool hasResult, IInvocationBinder binder)
{
if (string.IsNullOrEmpty(invocationId))
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (error != null && hasResult)
{
throw new InvalidDataException("The 'error' and 'result' properties are mutually exclusive.");
}
if (hasResult)
{
return new CompletionMessage(invocationId, error, result, hasResult: true);
}
return new CompletionMessage(invocationId, error, result: null, hasResult: false);
}
private static HubMessage BindStreamItemMessage(string invocationId, object? item, bool hasItem, IInvocationBinder binder)
{
if (string.IsNullOrEmpty(invocationId))
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (!hasItem)
{
throw new InvalidDataException($"Missing required property '{ItemPropertyName}'.");
}
return new StreamItemMessage(invocationId, item);
}
private static HubMessage BindStreamInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds, IInvocationBinder binder)
{
if (string.IsNullOrEmpty(invocationId))
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (!hasArguments)
{
throw new InvalidDataException($"Missing required property '{ArgumentsPropertyName}'.");
}
if (string.IsNullOrEmpty(target))
{
throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
}
Debug.Assert(arguments != null);
return new StreamInvocationMessage(invocationId, target, arguments, streamIds);
}
private static HubMessage BindInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds, IInvocationBinder binder)
{
if (string.IsNullOrEmpty(target))
{
throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
}
if (!hasArguments)
{
throw new InvalidDataException($"Missing required property '{ArgumentsPropertyName}'.");
}
Debug.Assert(arguments != null);
return new InvocationMessage(invocationId, target, arguments, streamIds);
}
private static bool ReadArgumentAsType(JsonTextReader reader, IReadOnlyList<Type> paramTypes, int paramIndex)
{
if (paramIndex < paramTypes.Count)
{
var paramType = paramTypes[paramIndex];
return JsonUtils.ReadForType(reader, paramType);
}
return reader.Read();
}
private object?[] BindArguments(JsonTextReader reader, IReadOnlyList<Type> paramTypes)
{
object?[]? arguments = null;
var paramIndex = 0;
var argumentsCount = 0;
var paramCount = paramTypes.Count;
while (ReadArgumentAsType(reader, paramTypes, paramIndex))
{
if (reader.TokenType == JsonToken.EndArray)
{
if (argumentsCount != paramCount)
{
throw new InvalidDataException($"Invocation provides {argumentsCount} argument(s) but target expects {paramCount}.");
}
return arguments ?? Array.Empty<object?>();
}
if (arguments == null)
{
arguments = new object?[paramCount];
}
try
{
if (paramIndex < paramCount)
{
arguments[paramIndex] = PayloadSerializer.Deserialize(reader, paramTypes[paramIndex]);
}
else
{
reader.Skip();
}
argumentsCount++;
paramIndex++;
}
catch (Exception ex)
{
throw new InvalidDataException("Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.", ex);
}
}
throw new JsonReaderException("Unexpected end when reading JSON");
}
private static CloseMessage BindCloseMessage(string? error, bool allowReconnect)
{
// An empty string is still an error
if (error == null && !allowReconnect)
{
return CloseMessage.Empty;
}
return new CloseMessage(error, allowReconnect);
}
private object?[] BindArguments(JArray args, IReadOnlyList<Type> paramTypes)
{
var paramCount = paramTypes.Count;
var argCount = args.Count;
if (paramCount != argCount)
{
throw new InvalidDataException($"Invocation provides {argCount} argument(s) but target expects {paramCount}.");
}
if (paramCount == 0)
{
return Array.Empty<object?>();
}
var arguments = new object?[argCount];
try
{
for (var i = 0; i < paramCount; i++)
{
var paramType = paramTypes[i];
arguments[i] = args[i].ToObject(paramType, PayloadSerializer);
}
return arguments;
}
catch (Exception ex)
{
throw new InvalidDataException("Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.", ex);
}
}
private static HubMessage ApplyHeaders(HubMessage message, Dictionary<string, string>? headers)
{
if (headers != null && message is HubInvocationMessage invocationMessage)
{
invocationMessage.Headers = headers;
}
return message;
}
internal static JsonSerializerSettings CreateDefaultSerializerSettings()
{
return new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding;
/** Handles path calls for a single unit.
* \ingroup relevant
* This is a component which is meant to be attached to a single unit (AI, Robot, Player, whatever) to handle it's pathfinding calls.
* It also handles post-processing of paths using modifiers.
* \see \ref calling-pathfinding
*/
[AddComponentMenu("Pathfinding/Seeker")]
[HelpURL("http://arongranberg.com/astar/docs/class_seeker.php")]
public class Seeker : MonoBehaviour, ISerializationCallbackReceiver {
//====== SETTINGS ======
/** Enables drawing of the last calculated path using Gizmos.
* The path will show up in green.
*
* \see OnDrawGizmos
*/
public bool drawGizmos = true;
/** Enables drawing of the non-postprocessed path using Gizmos.
* The path will show up in orange.
*
* Requires that #drawGizmos is true.
*
* This will show the path before any post processing such as smoothing is applied.
*
* \see drawGizmos
* \see OnDrawGizmos
*/
public bool detailedGizmos;
/** Path modifier which tweaks the start and end points of a path */
public StartEndModifier startEndModifier = new StartEndModifier();
/** The tags which the Seeker can traverse.
*
* \note This field is a bitmask.
* \see https://en.wikipedia.org/wiki/Mask_(computing)
*/
[HideInInspector]
public int traversableTags = -1;
/** Required for serialization backwards compatibility.
* \since 3.6.8
*/
[UnityEngine.Serialization.FormerlySerializedAs("traversableTags")]
[SerializeField]
[HideInInspector]
protected TagMask traversableTagsCompatibility = new TagMask(-1, -1);
/** Penalties for each tag.
* Tag 0 which is the default tag, will have added a penalty of tagPenalties[0].
* These should only be positive values since the A* algorithm cannot handle negative penalties.
*
* \note This array should always have a length of 32 otherwise the system will ignore it.
*
* \see Pathfinding.Path.tagPenalties
*/
[HideInInspector]
public int[] tagPenalties = new int[32];
//====== SETTINGS ======
/** Callback for when a path is completed.
* Movement scripts should register to this delegate.\n
* A temporary callback can also be set when calling StartPath, but that delegate will only be called for that path
*/
public OnPathDelegate pathCallback;
/** Called before pathfinding is started */
public OnPathDelegate preProcessPath;
/** Called after a path has been calculated, right before modifiers are executed.
* Can be anything which only modifies the positions (Vector3[]).
*/
public OnPathDelegate postProcessPath;
/** Used for drawing gizmos */
[System.NonSerialized]
List<Vector3> lastCompletedVectorPath;
/** Used for drawing gizmos */
[System.NonSerialized]
List<GraphNode> lastCompletedNodePath;
/** The current path */
[System.NonSerialized]
protected Path path;
/** Previous path. Used to draw gizmos */
[System.NonSerialized]
private Path prevPath;
/** Cached delegate to avoid allocating one every time a path is started */
private readonly OnPathDelegate onPathDelegate;
/** Temporary callback only called for the current path. This value is set by the StartPath functions */
private OnPathDelegate tmpPathCallback;
/** The path ID of the last path queried */
protected uint lastPathID;
/** Internal list of all modifiers */
readonly List<IPathModifier> modifiers = new List<IPathModifier>();
public enum ModifierPass {
PreProcess,
// An obsolete item occupied index 1 previously
PostProcess = 2,
}
public Seeker () {
onPathDelegate = OnPathComplete;
}
/** Initializes a few variables */
void Awake () {
startEndModifier.Awake(this);
}
/** Path that is currently being calculated or was last calculated.
* You should rarely have to use this. Instead get the path when the path callback is called.
*
* \see pathCallback
*/
public Path GetCurrentPath () {
return path;
}
/** Stop calculating the current path request.
* If this Seeker is currently calculating a path it will be canceled.
* The callback (usually to a method named OnPathComplete) will soon be called
* with a path that has the 'error' field set to true.
*
* This does not stop the character from moving, it just aborts
* the path calculation.
*
* \param pool If true then the path will be pooled when the pathfinding system is done with it.
*/
public void CancelCurrentPathRequest (bool pool = true) {
if (!IsDone()) {
path.Error();
if (pool) {
// Make sure the path has had its reference count incremented and decremented once.
// If this is not done the system will think no pooling is used at all and will not pool the path.
// The particular object that is used as the parameter (in this case 'path') doesn't matter at all
// it just has to be *some* object.
path.Claim(path);
path.Release(path);
}
}
}
/** Cleans up some variables.
* Releases any eventually claimed paths.
* Calls OnDestroy on the #startEndModifier.
*
* \see ReleaseClaimedPath
* \see startEndModifier
*/
public void OnDestroy () {
ReleaseClaimedPath();
startEndModifier.OnDestroy(this);
}
/** Releases the path used for gizmos (if any).
* The seeker keeps the latest path claimed so it can draw gizmos.
* In some cases this might not be desireable and you want it released.
* In that case, you can call this method to release it (not that path gizmos will then not be drawn).
*
* If you didn't understand anything from the description above, you probably don't need to use this method.
*
* \see \ref pooling
*/
public void ReleaseClaimedPath () {
if (prevPath != null) {
prevPath.Release(this, true);
prevPath = null;
}
}
/** Called by modifiers to register themselves */
public void RegisterModifier (IPathModifier mod) {
modifiers.Add(mod);
// Sort the modifiers based on their specified order
modifiers.Sort((a, b) => a.Order.CompareTo(b.Order));
}
/** Called by modifiers when they are disabled or destroyed */
public void DeregisterModifier (IPathModifier mod) {
modifiers.Remove(mod);
}
/** Post Processes the path.
* This will run any modifiers attached to this GameObject on the path.
* This is identical to calling RunModifiers(ModifierPass.PostProcess, path)
* \see RunModifiers
* \since Added in 3.2
*/
public void PostProcess (Path p) {
RunModifiers(ModifierPass.PostProcess, p);
}
/** Runs modifiers on path \a p */
public void RunModifiers (ModifierPass pass, Path p) {
// Call delegates if they exist
if (pass == ModifierPass.PreProcess && preProcessPath != null) {
preProcessPath(p);
} else if (pass == ModifierPass.PostProcess && postProcessPath != null) {
postProcessPath(p);
}
// Loop through all modifiers and apply post processing
for (int i = 0; i < modifiers.Count; i++) {
// Cast to MonoModifier, i.e modifiers attached as scripts to the game object
var mMod = modifiers[i] as MonoModifier;
// Ignore modifiers which are not enabled
if (mMod != null && !mMod.enabled) continue;
if (pass == ModifierPass.PreProcess) {
modifiers[i].PreProcess(p);
} else if (pass == ModifierPass.PostProcess) {
modifiers[i].Apply(p);
}
}
}
/** Is the current path done calculating.
* Returns true if the current #path has been returned or if the #path is null.
*
* \note Do not confuse this with Pathfinding.Path.IsDone. They usually return the same value, but not always
* since the path might be completely calculated, but it has not yet been processed by the Seeker.
*
* \since Added in 3.0.8
* \version Behaviour changed in 3.2
*/
public bool IsDone () {
return path == null || path.GetState() >= PathState.Returned;
}
/** Called when a path has completed.
* This should have been implemented as optional parameter values, but that didn't seem to work very well with delegates (the values weren't the default ones)
* \see OnPathComplete(Path,bool,bool)
*/
void OnPathComplete (Path p) {
OnPathComplete(p, true, true);
}
/** Called when a path has completed.
* Will post process it and return it by calling #tmpPathCallback and #pathCallback
*/
void OnPathComplete (Path p, bool runModifiers, bool sendCallbacks) {
if (p != null && p != path && sendCallbacks) {
return;
}
if (this == null || p == null || p != path)
return;
if (!path.error && runModifiers) {
// This will send the path for post processing to modifiers attached to this Seeker
RunModifiers(ModifierPass.PostProcess, path);
}
if (sendCallbacks) {
p.Claim(this);
lastCompletedNodePath = p.path;
lastCompletedVectorPath = p.vectorPath;
// This will send the path to the callback (if any) specified when calling StartPath
if (tmpPathCallback != null) {
tmpPathCallback(p);
}
// This will send the path to any script which has registered to the callback
if (pathCallback != null) {
pathCallback(p);
}
// Recycle the previous path to reduce the load on the GC
if (prevPath != null) {
prevPath.Release(this, true);
}
prevPath = p;
// If not drawing gizmos, then storing prevPath is quite unecessary
// So clear it and set prevPath to null
if (!drawGizmos) ReleaseClaimedPath();
}
}
/** Returns a new path instance.
* The path will be taken from the path pool if path recycling is turned on.\n
* This path can be sent to #StartPath(Path,OnPathDelegate,int) with no change, but if no change is required #StartPath(Vector3,Vector3,OnPathDelegate) does just that.
* \code
* var seeker = GetComponent<Seeker>();
* Path p = seeker.GetNewPath (transform.position, transform.position+transform.forward*100);
* // Disable heuristics on just this path for example
* p.heuristic = Heuristic.None;
* seeker.StartPath (p, OnPathComplete);
* \endcode
*/
public ABPath GetNewPath (Vector3 start, Vector3 end) {
// Construct a path with start and end points
return ABPath.Construct(start, end, null);
}
/** Call this function to start calculating a path.
* \param start The start point of the path
* \param end The end point of the path
*/
public Path StartPath (Vector3 start, Vector3 end) {
return StartPath(start, end, null, -1);
}
/** Call this function to start calculating a path.
*
* \param start The start point of the path
* \param end The end point of the path
* \param callback The function to call when the path has been calculated
*
* \a callback will be called when the path has completed.
* \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */
public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback) {
return StartPath(start, end, callback, -1);
}
/** Call this function to start calculating a path.
*
* \param start The start point of the path
* \param end The end point of the path
* \param callback The function to call when the path has been calculated
* \param graphMask Mask used to specify which graphs should be searched for close nodes. See #Pathfinding.NNConstraint.graphMask.
*
* \a callback will be called when the path has completed.
* \a Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) */
public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback, int graphMask) {
return StartPath(ABPath.Construct(start, end, null), callback, graphMask);
}
/** Call this function to start calculating a path.
*
* \param p The path to start calculating
* \param callback The function to call when the path has been calculated
* \param graphMask Mask used to specify which graphs should be searched for close nodes. See #Pathfinding.NNConstraint.graphMask.
*
* The \a callback will be called when the path has been calculated (which may be several frames into the future).
* The \a callback will not be called if a new path request is started before this path request has been calculated.
*
* \version Since 3.8.3 this method works properly if a MultiTargetPath is used.
* It now behaves identically to the StartMultiTargetPath(MultiTargetPath) method.
*/
public Path StartPath (Path p, OnPathDelegate callback = null, int graphMask = -1) {
p.callback += onPathDelegate;
p.enabledTags = traversableTags;
p.tagPenalties = tagPenalties;
p.nnConstraint.graphMask = graphMask;
StartPathInternal(p, callback);
return p;
}
/** Internal method to start a path and mark it as the currently active path */
void StartPathInternal (Path p, OnPathDelegate callback) {
// Cancel a previously requested path is it has not been processed yet and also make sure that it has not been recycled and used somewhere else
if (path != null && path.GetState() <= PathState.Processing && path.CompleteState != PathCompleteState.Error && lastPathID == path.pathID) {
path.Error();
path.LogError("Canceled path because a new one was requested.\n"+
"This happens when a new path is requested from the seeker when one was already being calculated.\n" +
"For example if a unit got a new order, you might request a new path directly instead of waiting for the now" +
" invalid path to be calculated. Which is probably what you want.\n" +
"If you are getting this a lot, you might want to consider how you are scheduling path requests.");
// No callback will be sent for the canceled path
}
// Set p as the active path
path = p;
tmpPathCallback = callback;
// Save the path id so we can make sure that if we cancel a path (see above) it should not have been recycled yet.
lastPathID = path.pathID;
// Pre process the path
RunModifiers(ModifierPass.PreProcess, path);
// Send the request to the pathfinder
AstarPath.StartPath(path);
}
/** Draws gizmos for the Seeker */
public void OnDrawGizmos () {
if (lastCompletedNodePath == null || !drawGizmos) {
return;
}
if (detailedGizmos) {
Gizmos.color = new Color(0.7F, 0.5F, 0.1F, 0.5F);
if (lastCompletedNodePath != null) {
for (int i = 0; i < lastCompletedNodePath.Count-1; i++) {
Gizmos.DrawLine((Vector3)lastCompletedNodePath[i].position, (Vector3)lastCompletedNodePath[i+1].position);
}
}
}
Gizmos.color = new Color(0, 1F, 0, 1F);
if (lastCompletedVectorPath != null) {
for (int i = 0; i < lastCompletedVectorPath.Count-1; i++) {
Gizmos.DrawLine(lastCompletedVectorPath[i], lastCompletedVectorPath[i+1]);
}
}
}
/** Handle serialization backwards compatibility */
void ISerializationCallbackReceiver.OnBeforeSerialize () {
}
/** Handle serialization backwards compatibility */
void ISerializationCallbackReceiver.OnAfterDeserialize () {
if (traversableTagsCompatibility != null && traversableTagsCompatibility.tagsChange != -1) {
traversableTags = traversableTagsCompatibility.tagsChange;
traversableTagsCompatibility = new TagMask(-1, -1);
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.FileSystem;
using Microsoft.CodeAnalysis.Editor.Implementation.Interactive;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver;
internal abstract class InteractiveEvaluator : IInteractiveEvaluator, ICurrentWorkingDirectoryDiscoveryService
{
// full path or null
private readonly string _responseFilePath;
private readonly InteractiveHost _interactiveHost;
private string _initialWorkingDirectory;
private string _initialScriptFileOpt;
private readonly IContentType _contentType;
private readonly InteractiveWorkspace _workspace;
private IInteractiveWindow _currentWindow;
private ImmutableArray<MetadataReference> _rspReferences;
private ImmutableArray<string> _rspImports;
private MetadataReferenceResolver _metadataReferenceResolver;
private SourceReferenceResolver _sourceReferenceResolver;
private ProjectId _previousSubmissionProjectId;
private ProjectId _currentSubmissionProjectId;
private readonly IViewClassifierAggregatorService _classifierAggregator;
private readonly IInteractiveWindowCommandsFactory _commandsFactory;
private readonly ImmutableArray<IInteractiveWindowCommand> _commands;
private IInteractiveWindowCommands _interactiveCommands;
private ITextView _currentTextView;
private ITextBuffer _currentSubmissionBuffer;
private readonly ISet<ValueTuple<ITextView, ITextBuffer>> _submissionBuffers = new HashSet<ValueTuple<ITextView, ITextBuffer>>();
private int _submissionCount = 0;
private readonly EventHandler<ContentTypeChangedEventArgs> _contentTypeChangedHandler;
public ImmutableArray<string> ReferenceSearchPaths { get; private set; }
public ImmutableArray<string> SourceSearchPaths { get; private set; }
public string WorkingDirectory { get; private set; }
internal InteractiveEvaluator(
IContentType contentType,
HostServices hostServices,
IViewClassifierAggregatorService classifierAggregator,
IInteractiveWindowCommandsFactory commandsFactory,
ImmutableArray<IInteractiveWindowCommand> commands,
string responseFilePath,
string initialWorkingDirectory,
string interactiveHostPath,
Type replType)
{
Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath));
_contentType = contentType;
_responseFilePath = responseFilePath;
_workspace = new InteractiveWorkspace(this, hostServices);
_contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged);
_classifierAggregator = classifierAggregator;
_initialWorkingDirectory = initialWorkingDirectory;
_commandsFactory = commandsFactory;
_commands = commands;
// The following settings will apply when the REPL starts without .rsp file.
// They are discarded once the REPL is reset.
ReferenceSearchPaths = ImmutableArray<string>.Empty;
SourceSearchPaths = ImmutableArray<string>.Empty;
WorkingDirectory = initialWorkingDirectory;
var metadataService = _workspace.CurrentSolution.Services.MetadataService;
_metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory);
_sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory);
_interactiveHost = new InteractiveHost(replType, interactiveHostPath, initialWorkingDirectory);
_interactiveHost.ProcessStarting += ProcessStarting;
}
public IContentType ContentType
{
get
{
return _contentType;
}
}
public IInteractiveWindow CurrentWindow
{
get
{
return _currentWindow;
}
set
{
if (_currentWindow != value)
{
_interactiveHost.Output = value.OutputWriter;
_interactiveHost.ErrorOutput = value.ErrorOutputWriter;
if (_currentWindow != null)
{
_currentWindow.SubmissionBufferAdded -= SubmissionBufferAdded;
}
_currentWindow = value;
}
_currentWindow.SubmissionBufferAdded += SubmissionBufferAdded;
_interactiveCommands = _commandsFactory.CreateInteractiveCommands(_currentWindow, "#", _commands);
}
}
protected IInteractiveWindowCommands InteractiveCommands
{
get
{
return _interactiveCommands;
}
}
protected abstract string LanguageName { get; }
protected abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver, ImmutableArray<string> imports);
protected abstract ParseOptions ParseOptions { get; }
protected abstract CommandLineParser CommandLineParser { get; }
#region Initialization
public string GetConfiguration()
{
return null;
}
private IInteractiveWindow GetInteractiveWindow()
{
var window = CurrentWindow;
if (window == null)
{
throw new InvalidOperationException(EditorFeaturesResources.EngineMustBeAttachedToAnInteractiveWindow);
}
return window;
}
public Task<ExecutionResult> InitializeAsync()
{
var window = GetInteractiveWindow();
_interactiveHost.Output = window.OutputWriter;
_interactiveHost.ErrorOutput = window.ErrorOutputWriter;
return ResetAsyncWorker();
}
public void Dispose()
{
_workspace.Dispose();
_interactiveHost.Dispose();
}
/// <summary>
/// Invoked by <see cref="InteractiveHost"/> when a new process is being started.
/// </summary>
private void ProcessStarting(bool initialize)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(new Action(() => ProcessStarting(initialize)));
return;
}
// Freeze all existing classifications and then clear the list of
// submission buffers we have.
FreezeClassifications();
_submissionBuffers.Clear();
// We always start out empty
_workspace.ClearSolution();
_currentSubmissionProjectId = null;
_previousSubmissionProjectId = null;
var metadataService = _workspace.CurrentSolution.Services.MetadataService;
var mscorlibRef = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly);
var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveScriptGlobals).Assembly.Location, Script.HostAssemblyReferenceProperties);
_rspReferences = ImmutableArray.Create<MetadataReference>(mscorlibRef, interactiveHostObjectRef);
_rspImports = ImmutableArray<string>.Empty;
_initialScriptFileOpt = null;
ReferenceSearchPaths = ImmutableArray<string>.Empty;
SourceSearchPaths = ImmutableArray<string>.Empty;
if (initialize && File.Exists(_responseFilePath))
{
// 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(_responseFilePath);
var args = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null);
if (args.Errors.Length == 0)
{
var metadataResolver = CreateMetadataReferenceResolver(metadataService, args.ReferencePaths, rspDirectory);
var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory);
// ignore unresolved references, they will be reported in the interactive window:
var rspReferences = args.ResolveMetadataReferences(metadataResolver).Where(r => !(r is UnresolvedMetadataReference));
_initialScriptFileOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;
ReferenceSearchPaths = args.ReferencePaths;
SourceSearchPaths = args.SourcePaths;
_rspReferences = _rspReferences.AddRange(rspReferences);
_rspImports = CommandLineHelpers.GetImports(args);
}
}
_metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory);
_sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory);
// create the first submission project in the workspace after reset:
if (_currentSubmissionBuffer != null)
{
AddSubmission(_currentTextView, _currentSubmissionBuffer, this.LanguageName);
}
}
private Dispatcher Dispatcher
{
get { return ((FrameworkElement)GetInteractiveWindow().TextView).Dispatcher; }
}
private static MetadataReferenceResolver CreateMetadataReferenceResolver(IMetadataService metadataService, ImmutableArray<string> searchPaths, string baseDirectory)
{
return new RuntimeMetadataReferenceResolver(
new RelativePathResolver(searchPaths, baseDirectory),
null,
GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null,
(path, properties) => metadataService.GetReference(path, properties));
}
private static SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new SourceFileResolver(searchPaths, baseDirectory);
}
#endregion
#region Workspace
private void SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs args)
{
AddSubmission(_currentWindow.TextView, args.NewBuffer, this.LanguageName);
}
// The REPL window might change content type to host command content type (when a host command is typed at the beginning of the buffer).
private void LanguageBufferContentTypeChanged(object sender, ContentTypeChangedEventArgs e)
{
// It's not clear whether this situation will ever happen, but just in case.
if (e.BeforeContentType == e.AfterContentType)
{
return;
}
var buffer = e.Before.TextBuffer;
var contentTypeName = this.ContentType.TypeName;
var afterIsLanguage = e.AfterContentType.IsOfType(contentTypeName);
var afterIsInteractiveCommand = e.AfterContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
var beforeIsLanguage = e.BeforeContentType.IsOfType(contentTypeName);
var beforeIsInteractiveCommand = e.BeforeContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
Debug.Assert((afterIsLanguage && beforeIsInteractiveCommand)
|| (beforeIsLanguage && afterIsInteractiveCommand));
// We're switching between the target language and the Interactive Command "language".
// First, remove the current submission from the solution.
var oldSolution = _workspace.CurrentSolution;
var newSolution = oldSolution;
foreach (var documentId in _workspace.GetRelatedDocumentIds(buffer.AsTextContainer()))
{
Debug.Assert(documentId != null);
newSolution = newSolution.RemoveDocument(documentId);
// TODO (tomat): Is there a better way to remove mapping between buffer and document in REPL?
// Perhaps TrackingWorkspace should implement RemoveDocumentAsync?
_workspace.ClearOpenDocument(documentId);
}
// Next, remove the previous submission project and update the workspace.
newSolution = newSolution.RemoveProject(_currentSubmissionProjectId);
_workspace.SetCurrentSolution(newSolution);
// Add a new submission with the correct language for the current buffer.
var languageName = afterIsLanguage
? this.LanguageName
: InteractiveLanguageNames.InteractiveCommand;
AddSubmission(_currentTextView, buffer, languageName);
}
private void AddSubmission(ITextView textView, ITextBuffer subjectBuffer, string languageName)
{
var solution = _workspace.CurrentSolution;
Project project;
ImmutableArray<string> imports;
ImmutableArray<MetadataReference> references;
if (_previousSubmissionProjectId != null)
{
// only the first project needs imports and references
imports = ImmutableArray<string>.Empty;
references = ImmutableArray<MetadataReference>.Empty;
}
else if (_initialScriptFileOpt != null)
{
// insert a project for initialization script listed in .rsp:
project = CreateSubmissionProject(solution, languageName, _rspImports, _rspReferences);
var documentId = DocumentId.CreateNewId(project.Id, debugName: _initialScriptFileOpt);
solution = project.Solution.AddDocument(documentId, Path.GetFileName(_initialScriptFileOpt), new FileTextLoader(_initialScriptFileOpt, defaultEncoding: null));
_previousSubmissionProjectId = project.Id;
imports = ImmutableArray<string>.Empty;
references = ImmutableArray<MetadataReference>.Empty;
}
else
{
imports = _rspImports;
references = _rspReferences;
}
// project for the new submission:
project = CreateSubmissionProject(solution, languageName, imports, references);
// Keep track of this buffer so we can freeze the classifications for it in the future.
var viewAndBuffer = ValueTuple.Create(textView, subjectBuffer);
if (!_submissionBuffers.Contains(viewAndBuffer))
{
_submissionBuffers.Add(ValueTuple.Create(textView, subjectBuffer));
}
SetSubmissionDocument(subjectBuffer, project);
_currentSubmissionProjectId = project.Id;
if (_currentSubmissionBuffer != null)
{
_currentSubmissionBuffer.ContentTypeChanged -= _contentTypeChangedHandler;
}
subjectBuffer.ContentTypeChanged += _contentTypeChangedHandler;
subjectBuffer.Properties[typeof(ICurrentWorkingDirectoryDiscoveryService)] = this;
_currentSubmissionBuffer = subjectBuffer;
_currentTextView = textView;
}
private Project CreateSubmissionProject(Solution solution, string languageName, ImmutableArray<string> imports, ImmutableArray<MetadataReference> references)
{
var name = "Submission#" + (_submissionCount++);
// Grab a local copy so we aren't closing over the field that might change. The
// collection itself is an immutable collection.
var localCompilationOptions = GetSubmissionCompilationOptions(name, _metadataReferenceResolver, _sourceReferenceResolver, imports);
var localParseOptions = ParseOptions;
var projectId = ProjectId.CreateNewId(debugName: name);
solution = solution.AddProject(
ProjectInfo.Create(
projectId,
VersionStamp.Create(),
name: name,
assemblyName: name,
language: languageName,
compilationOptions: localCompilationOptions,
parseOptions: localParseOptions,
documents: null,
projectReferences: null,
metadataReferences: references,
hostObjectType: typeof(InteractiveScriptGlobals),
isSubmission: true));
if (_previousSubmissionProjectId != null)
{
solution = solution.AddProjectReference(projectId, new ProjectReference(_previousSubmissionProjectId));
}
return solution.GetProject(projectId);
}
private void SetSubmissionDocument(ITextBuffer buffer, Project project)
{
var documentId = DocumentId.CreateNewId(project.Id, debugName: project.Name);
var solution = project.Solution
.AddDocument(documentId, project.Name, buffer.CurrentSnapshot.AsText());
_workspace.SetCurrentSolution(solution);
// opening document will start workspace listening to changes in this text container
_workspace.OpenDocument(documentId, buffer.AsTextContainer());
}
private void FreezeClassifications()
{
foreach (var textViewAndBuffer in _submissionBuffers)
{
var textView = textViewAndBuffer.Item1;
var textBuffer = textViewAndBuffer.Item2;
if (textBuffer != _currentSubmissionBuffer)
{
InertClassifierProvider.CaptureExistingClassificationSpans(_classifierAggregator, textView, textBuffer);
}
}
}
#endregion
#region IInteractiveEngine
public virtual bool CanExecuteCode(string text)
{
if (_interactiveCommands != null && _interactiveCommands.InCommand)
{
return true;
}
return false;
}
public Task<ExecutionResult> ResetAsync(bool initialize = true)
{
GetInteractiveWindow().AddInput(_interactiveCommands.CommandPrefix + "reset");
GetInteractiveWindow().WriteLine(InteractiveEditorFeaturesResources.ResettingExecutionEngine);
GetInteractiveWindow().FlushOutput();
return ResetAsyncWorker(initialize);
}
private async Task<ExecutionResult> ResetAsyncWorker(bool initialize = true)
{
try
{
var options = new InteractiveHostOptions(
initializationFile: initialize ? _responseFilePath : null,
culture: CultureInfo.CurrentUICulture);
var result = await _interactiveHost.ResetAsync(options).ConfigureAwait(false);
if (result.Success)
{
UpdateResolvers(result);
}
return new ExecutionResult(result.Success);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public async Task<ExecutionResult> ExecuteCodeAsync(string text)
{
try
{
if (InteractiveCommands.InCommand)
{
var cmdResult = InteractiveCommands.TryExecuteCommand();
if (cmdResult != null)
{
return await cmdResult.ConfigureAwait(false);
}
}
var result = await _interactiveHost.ExecuteAsync(text).ConfigureAwait(false);
if (result.Success)
{
// We are not executing a command (the current content type is not "Interactive Command"),
// so the source document should not have been removed.
Debug.Assert(_workspace.CurrentSolution.GetProject(_currentSubmissionProjectId).HasDocuments);
// only remember the submission if we compiled successfully, otherwise we
// ignore it's id so we don't reference it in the next submission.
_previousSubmissionProjectId = _currentSubmissionProjectId;
// update local search paths - remote paths has already been updated
UpdateResolvers(result);
}
return new ExecutionResult(result.Success);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public void AbortExecution()
{
// TODO: abort execution
}
public string FormatClipboard()
{
// keep the clipboard content as is
return null;
}
#endregion
#region Paths, Resolvers
private void UpdateResolvers(RemoteExecutionResult result)
{
UpdateResolvers(result.ChangedReferencePaths.AsImmutableOrNull(), result.ChangedSourcePaths.AsImmutableOrNull(), result.ChangedWorkingDirectory);
}
private void UpdateResolvers(ImmutableArray<string> changedReferenceSearchPaths, ImmutableArray<string> changedSourceSearchPaths, string changedWorkingDirectory)
{
if (changedReferenceSearchPaths.IsDefault && changedSourceSearchPaths.IsDefault && changedWorkingDirectory == null)
{
return;
}
var solution = _workspace.CurrentSolution;
// Maybe called after reset, when no submissions are available.
var optionsOpt = (_currentSubmissionProjectId != null) ? solution.GetProjectState(_currentSubmissionProjectId).CompilationOptions : null;
if (changedWorkingDirectory != null)
{
WorkingDirectory = changedWorkingDirectory;
}
if (!changedReferenceSearchPaths.IsDefault)
{
ReferenceSearchPaths = changedReferenceSearchPaths;
}
if (!changedSourceSearchPaths.IsDefault)
{
SourceSearchPaths = changedSourceSearchPaths;
}
if (!changedReferenceSearchPaths.IsDefault || changedWorkingDirectory != null)
{
_metadataReferenceResolver = CreateMetadataReferenceResolver(_workspace.CurrentSolution.Services.MetadataService, ReferenceSearchPaths, WorkingDirectory);
if (optionsOpt != null)
{
optionsOpt = optionsOpt.WithMetadataReferenceResolver(_metadataReferenceResolver);
}
}
if (!changedSourceSearchPaths.IsDefault || changedWorkingDirectory != null)
{
_sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, WorkingDirectory);
if (optionsOpt != null)
{
optionsOpt = optionsOpt.WithSourceReferenceResolver(_sourceReferenceResolver);
}
}
if (optionsOpt != null)
{
_workspace.SetCurrentSolution(solution.WithProjectCompilationOptions(_currentSubmissionProjectId, optionsOpt));
}
}
public async Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory)
{
try
{
var result = await _interactiveHost.SetPathsAsync(referenceSearchPaths.ToArray(), sourceSearchPaths.ToArray(), workingDirectory).ConfigureAwait(false);
UpdateResolvers(result);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public string GetPrompt()
{
if (CurrentWindow.CurrentLanguageBuffer != null &&
CurrentWindow.CurrentLanguageBuffer.CurrentSnapshot.LineCount > 1)
{
return ". ";
}
return "> ";
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace System.Diagnostics
{
/// <summary>
/// A Performance counter category object.
/// </summary>
public sealed class PerformanceCounterCategory
{
private string _categoryName;
private string _categoryHelp;
private string _machineName;
internal const int MaxCategoryNameLength = 80;
internal const int MaxCounterNameLength = 32767;
internal const int MaxHelpLength = 32767;
private const string PerfMutexName = "netfxperf.1.0";
public PerformanceCounterCategory()
{
_machineName = ".";
}
/// <summary>
/// Creates a PerformanceCounterCategory object for given category.
/// Uses the local machine.
/// </summary>
public PerformanceCounterCategory(string categoryName)
: this(categoryName, ".")
{
}
/// <summary>
/// Creates a PerformanceCounterCategory object for given category.
/// Uses the given machine name.
/// </summary>
public PerformanceCounterCategory(string categoryName, string machineName)
{
if (categoryName == null)
throw new ArgumentNullException(nameof(categoryName));
if (categoryName.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName));
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
permission.Demand();
_categoryName = categoryName;
_machineName = machineName;
}
/// <summary>
/// Gets/sets the Category name
/// </summary>
public string CategoryName
{
get
{
return _categoryName;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(CategoryName), value), nameof(value));
// the lock prevents a race between setting CategoryName and MachineName, since this permission
// checks depend on both pieces of info.
lock (this)
{
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, _machineName, value);
permission.Demand();
_categoryName = value;
}
}
}
/// <summary>
/// Gets/sets the Category help
/// </summary>
public string CategoryHelp
{
get
{
if (_categoryName == null)
throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
if (_categoryHelp == null)
_categoryHelp = PerformanceCounterLib.GetCategoryHelp(_machineName, _categoryName);
return _categoryHelp;
}
}
public PerformanceCounterCategoryType CategoryType
{
get
{
CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName);
// If we get MultiInstance, we can be confident it is correct. If it is single instance, though
// we need to check if is a custom category and if the IsMultiInstance value is set in the registry.
// If not we return Unknown
if (categorySample._isMultiInstance)
return PerformanceCounterCategoryType.MultiInstance;
else
{
if (PerformanceCounterLib.IsCustomCategory(".", _categoryName))
return PerformanceCounterLib.GetCategoryType(".", _categoryName);
else
return PerformanceCounterCategoryType.SingleInstance;
}
}
}
/// <summary>
/// Gets/sets the Machine name
/// </summary>
public string MachineName
{
get
{
return _machineName;
}
set
{
if (!SyntaxCheck.CheckMachineName(value))
throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(MachineName), value), nameof(value));
// the lock prevents a race between setting CategoryName and MachineName, since this permission
// checks depend on both pieces of info.
lock (this)
{
if (_categoryName != null)
{
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, value, _categoryName);
permission.Demand();
}
_machineName = value;
}
}
}
/// <summary>
/// Returns true if the counter is registered for this category
/// </summary>
public bool CounterExists(string counterName)
{
if (counterName == null)
throw new ArgumentNullException(nameof(counterName));
if (_categoryName == null)
throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
return PerformanceCounterLib.CounterExists(_machineName, _categoryName, counterName);
}
/// <summary>
/// Returns true if the counter is registered for this category on the current machine.
/// </summary>
public static bool CounterExists(string counterName, string categoryName)
{
return CounterExists(counterName, categoryName, ".");
}
/// <summary>
/// Returns true if the counter is registered for this category on a particular machine.
/// </summary>
public static bool CounterExists(string counterName, string categoryName, string machineName)
{
if (counterName == null)
throw new ArgumentNullException(nameof(counterName));
if (categoryName == null)
throw new ArgumentNullException(nameof(categoryName));
if (categoryName.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName));
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
permission.Demand();
return PerformanceCounterLib.CounterExists(machineName, categoryName, counterName);
}
/// <summary>
/// Registers one extensible performance category of type NumberOfItems32 with the system
/// </summary>
[Obsolete("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, string counterName, string counterHelp)
{
CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32);
return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, new CounterCreationDataCollection(new CounterCreationData[] { customData }));
}
public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp)
{
CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32);
return Create(categoryName, categoryHelp, categoryType, new CounterCreationDataCollection(new CounterCreationData[] { customData }));
}
/// <summary>
/// Registers the extensible performance category with the system on the local machine
/// </summary>
[Obsolete("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, CounterCreationDataCollection counterData)
{
return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, counterData);
}
public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData)
{
if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance)
throw new ArgumentOutOfRangeException(nameof(categoryType));
if (counterData == null)
throw new ArgumentNullException(nameof(counterData));
CheckValidCategory(categoryName);
if (categoryHelp != null)
{
// null categoryHelp is a valid option - it gets set to "Help Not Available" later on.
CheckValidHelp(categoryHelp);
}
string machineName = ".";
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);
permission.Demand();
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
SharedUtils.EnterMutex(PerfMutexName, ref mutex);
if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName))
throw new InvalidOperationException(SR.Format(SR.PerformanceCategoryExists, categoryName));
CheckValidCounterLayout(counterData);
PerformanceCounterLib.RegisterCategory(categoryName, categoryType, categoryHelp, counterData);
return new PerformanceCounterCategory(categoryName, machineName);
}
finally
{
if (mutex != null)
{
mutex.ReleaseMutex();
mutex.Close();
}
}
}
// there is an idential copy of CheckValidCategory in PerformnaceCounterInstaller
internal static void CheckValidCategory(string categoryName)
{
if (categoryName == null)
throw new ArgumentNullException(nameof(categoryName));
if (!CheckValidId(categoryName, MaxCategoryNameLength))
throw new ArgumentException(SR.Format(SR.PerfInvalidCategoryName, 1, MaxCategoryNameLength));
// 1026 chars is the size of the buffer used in perfcounter.dll to get this name.
// If the categoryname plus prefix is too long, we won't be able to read the category properly.
if (categoryName.Length > (1024 - SharedPerformanceCounter.DefaultFileMappingName.Length))
throw new ArgumentException(SR.Format(SR.CategoryNameTooLong));
}
internal static void CheckValidCounter(string counterName)
{
if (counterName == null)
throw new ArgumentNullException(nameof(counterName));
if (!CheckValidId(counterName, MaxCounterNameLength))
throw new ArgumentException(SR.Format(SR.PerfInvalidCounterName, 1, MaxCounterNameLength));
}
// there is an idential copy of CheckValidId in PerformnaceCounterInstaller
internal static bool CheckValidId(string id, int maxLength)
{
if (id.Length == 0 || id.Length > maxLength)
return false;
for (int index = 0; index < id.Length; ++index)
{
char current = id[index];
if ((index == 0 || index == (id.Length - 1)) && current == ' ')
return false;
if (current == '\"')
return false;
if (char.IsControl(current))
return false;
}
return true;
}
internal static void CheckValidHelp(string help)
{
if (help == null)
throw new ArgumentNullException(nameof(help));
if (help.Length > MaxHelpLength)
throw new ArgumentException(SR.Format(SR.PerfInvalidHelp, 0, MaxHelpLength));
}
internal static void CheckValidCounterLayout(CounterCreationDataCollection counterData)
{
// Ensure that there are no duplicate counter names being created
Hashtable h = new Hashtable();
for (int i = 0; i < counterData.Count; i++)
{
if (counterData[i].CounterName == null || counterData[i].CounterName.Length == 0)
{
throw new ArgumentException(SR.Format(SR.InvalidCounterName));
}
int currentSampleType = (int)counterData[i].CounterType;
if ((currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) ||
(currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) ||
(currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) ||
(currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) ||
(currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) ||
(currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) ||
(currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) ||
(currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER))
{
if (counterData.Count <= (i + 1))
throw new InvalidOperationException(SR.Format(SR.CounterLayout));
else
{
currentSampleType = (int)counterData[i + 1].CounterType;
if (!PerformanceCounterLib.IsBaseCounter(currentSampleType))
throw new InvalidOperationException(SR.Format(SR.CounterLayout));
}
}
else if (PerformanceCounterLib.IsBaseCounter(currentSampleType))
{
if (i == 0)
throw new InvalidOperationException(SR.Format(SR.CounterLayout));
else
{
currentSampleType = (int)counterData[i - 1].CounterType;
if (
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) &&
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) &&
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) &&
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) &&
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) &&
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) &&
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) &&
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER))
throw new InvalidOperationException(SR.Format(SR.CounterLayout));
}
}
if (h.ContainsKey(counterData[i].CounterName))
{
throw new ArgumentException(SR.Format(SR.DuplicateCounterName, counterData[i].CounterName));
}
else
{
h.Add(counterData[i].CounterName, string.Empty);
// Ensure that all counter help strings aren't null or empty
if (counterData[i].CounterHelp == null || counterData[i].CounterHelp.Length == 0)
{
counterData[i].CounterHelp = counterData[i].CounterName;
}
}
}
}
/// <summary>
/// Removes the counter (category) from the system
/// </summary>
public static void Delete(string categoryName)
{
CheckValidCategory(categoryName);
string machineName = ".";
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);
permission.Demand();
categoryName = categoryName.ToLower(CultureInfo.InvariantCulture);
Mutex mutex = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
SharedUtils.EnterMutex(PerfMutexName, ref mutex);
if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
throw new InvalidOperationException(SR.Format(SR.CantDeleteCategory));
SharedPerformanceCounter.RemoveAllInstances(categoryName);
PerformanceCounterLib.UnregisterCategory(categoryName);
PerformanceCounterLib.CloseAllLibraries();
}
finally
{
if (mutex != null)
{
mutex.ReleaseMutex();
mutex.Close();
}
}
}
/// <summary>
/// Returns true if the category is registered on the current machine.
/// </summary>
public static bool Exists(string categoryName)
{
return Exists(categoryName, ".");
}
/// <summary>
/// Returns true if the category is registered in the machine.
/// </summary>
public static bool Exists(string categoryName, string machineName)
{
if (categoryName == null)
throw new ArgumentNullException(nameof(categoryName));
if (categoryName.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName));
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
permission.Demand();
if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
return true;
return PerformanceCounterLib.CategoryExists(machineName, categoryName);
}
/// <summary>
/// Returns the instance names for a given category
/// </summary>
/// <internalonly/>
internal static string[] GetCounterInstances(string categoryName, string machineName)
{
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);
permission.Demand();
CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName);
if (categorySample._instanceNameTable.Count == 0)
return Array.Empty<string>();
string[] instanceNames = new string[categorySample._instanceNameTable.Count];
categorySample._instanceNameTable.Keys.CopyTo(instanceNames, 0);
if (instanceNames.Length == 1 && instanceNames[0] == PerformanceCounterLib.SingleInstanceName)
return Array.Empty<string>();
return instanceNames;
}
/// <summary>
/// Returns an array of counters in this category. The counter must have only one instance.
/// </summary>
public PerformanceCounter[] GetCounters()
{
if (GetInstanceNames().Length != 0)
throw new ArgumentException(SR.Format(SR.InstanceNameRequired));
return GetCounters("");
}
/// <summary>
/// Returns an array of counters in this category for the given instance.
/// </summary>
public PerformanceCounter[] GetCounters(string instanceName)
{
if (instanceName == null)
throw new ArgumentNullException(nameof(instanceName));
if (_categoryName == null)
throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
if (instanceName.Length != 0 && !InstanceExists(instanceName))
throw new InvalidOperationException(SR.Format(SR.MissingInstance, instanceName, _categoryName));
string[] counterNames = PerformanceCounterLib.GetCounters(_machineName, _categoryName);
PerformanceCounter[] counters = new PerformanceCounter[counterNames.Length];
for (int index = 0; index < counters.Length; index++)
counters[index] = new PerformanceCounter(_categoryName, counterNames[index], instanceName, _machineName, true);
return counters;
}
/// <summary>
/// Returns an array of performance counter categories for the current machine.
/// </summary>
public static PerformanceCounterCategory[] GetCategories()
{
return GetCategories(".");
}
/// <summary>
/// Returns an array of performance counter categories for a particular machine.
/// </summary>
public static PerformanceCounterCategory[] GetCategories(string machineName)
{
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, "*");
permission.Demand();
string[] categoryNames = PerformanceCounterLib.GetCategories(machineName);
PerformanceCounterCategory[] categories = new PerformanceCounterCategory[categoryNames.Length];
for (int index = 0; index < categories.Length; index++)
categories[index] = new PerformanceCounterCategory(categoryNames[index], machineName);
return categories;
}
/// <summary>
/// Returns an array of instances for this category
/// </summary>
public string[] GetInstanceNames()
{
if (_categoryName == null)
throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
return GetCounterInstances(_categoryName, _machineName);
}
/// <summary>
/// Returns true if the instance already exists for this category.
/// </summary>
public bool InstanceExists(string instanceName)
{
if (instanceName == null)
throw new ArgumentNullException(nameof(instanceName));
if (_categoryName == null)
throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName);
return categorySample._instanceNameTable.ContainsKey(instanceName);
}
/// <summary>
/// Returns true if the instance already exists for the category specified.
/// </summary>
public static bool InstanceExists(string instanceName, string categoryName)
{
return InstanceExists(instanceName, categoryName, ".");
}
/// <summary>
/// Returns true if the instance already exists for this category and machine specified.
/// </summary>
public static bool InstanceExists(string instanceName, string categoryName, string machineName)
{
if (instanceName == null)
throw new ArgumentNullException(nameof(instanceName));
if (categoryName == null)
throw new ArgumentNullException(nameof(categoryName));
if (categoryName.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName));
if (!SyntaxCheck.CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, machineName);
return category.InstanceExists(instanceName);
}
/// <summary>
/// Reads all the counter and instance data of this performance category. Note that reading the entire category
/// at once can be as efficient as reading a single counter because of the way the system provides the data.
/// </summary>
public InstanceDataCollectionCollection ReadCategory()
{
if (_categoryName == null)
throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName);
return categorySample.ReadCategory();
}
}
[Flags]
internal enum PerformanceCounterCategoryOptions
{
EnableReuse = 0x1,
UseUniqueSharedMemory = 0x2,
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SplitterPanel.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Windows.Forms {
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel"]/*' />
/// <devdoc>
/// TBD.
/// </devdoc>
[
ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
Docking(DockingBehavior.Never),
Designer("System.Windows.Forms.Design.SplitterPanelDesigner, " + AssemblyRef.SystemDesign),
ToolboxItem(false)
]
public sealed class SplitterPanel : Panel {
SplitContainer owner = null;
private bool collapsed = false;
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.SplitterPanel"]/*' />
public SplitterPanel(SplitContainer owner)
: base() {
this.owner = owner;
SetStyle(ControlStyles.ResizeRedraw, true);
}
internal bool Collapsed {
get {
return collapsed;
}
set {
collapsed = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.AutoSize"]/*' />
/// <devdoc>
/// Override AutoSize to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new bool AutoSize {
get {
return base.AutoSize;
}
set {
base.AutoSize = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.AutoSizeChanged"]/*' />
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler AutoSizeChanged {
add {
base.AutoSizeChanged += value;
}
remove {
base.AutoSizeChanged -= value;
}
}
/// <devdoc>
/// Allows the control to optionally shrink when AutoSize is true.
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false),
Localizable(false)
]
public override AutoSizeMode AutoSizeMode {
get {
return AutoSizeMode.GrowOnly;
}
set {
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Anchor"]/*' />
/// <devdoc>
/// Override Anchor to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new AnchorStyles Anchor {
get {
return base.Anchor;
}
set {
base.Anchor = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.BorderStyle"]/*' />
/// <devdoc>
/// Indicates what type of border the Splitter control has. This value
/// comes from the System.Windows.Forms.BorderStyle enumeration.
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new BorderStyle BorderStyle {
get {
return base.BorderStyle;
}
set {
base.BorderStyle = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Dock"]/*' />
/// <devdoc>
/// The dock property. The dock property controls to which edge
/// of the container this control is docked to. For example, when docked to
/// the top of the container, the control will be displayed flush at the
/// top of the container, extending the length of the container.
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new DockStyle Dock {
get {
return base.Dock;
}
set {
base.Dock = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.DockPadding"]/*' />
/// <devdoc>
/// Override DockPadding to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
new public DockPaddingEdges DockPadding {
get {
return base.DockPadding;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Height"]/*' />
/// <devdoc>
/// The height of this SplitterPanel
/// </devdoc>
[
SRCategory(SR.CatLayout),
Browsable(false), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(SR.ControlHeightDescr)
]
public new int Height {
get {
if (Collapsed) {
return 0;
}
return base.Height;
}
set {
throw new NotSupportedException(SR.GetString(SR.SplitContainerPanelHeight));
}
}
internal int HeightInternal {
get {
return ((Panel)this).Height;
}
set {
((Panel)this).Height = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Location"]/*' />
/// <devdoc>
/// Override Location to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new Point Location {
get {
return base.Location;
}
set {
base.Location = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.DefaultMargin"]/*' />
/// <devdoc>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </devdoc>
protected override Padding DefaultMargin {
get {
return new Padding(0, 0, 0, 0);
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.MinimumSize"]/*' />
/// <devdoc>
/// Override AutoSize to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new Size MinimumSize {
get {
return base.MinimumSize;
}
set {
base.MinimumSize = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.MaximumSize"]/*' />
/// <devdoc>
/// Override AutoSize to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new Size MaximumSize {
get {
return base.MaximumSize;
}
set {
base.MaximumSize = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Name"]/*' />
/// <devdoc>
/// Name of this control. The designer will set this to the same
/// as the programatic Id "(name)" of the control. The name can be
/// used as a key into the ControlCollection.
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new string Name {
get {
return base.Name;
}
set {
base.Name = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Parent"]/*' />
/// <devdoc>
/// The parent of this control.
/// </devdoc>
internal SplitContainer Owner {
get {
return owner;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Parent"]/*' />
/// <devdoc>
/// The parent of this control.
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new Control Parent {
get {
return base.Parent;
}
set {
base.Parent = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Size"]/*' />
/// <devdoc>
/// Override Size to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new Size Size {
get {
if (Collapsed) {
return Size.Empty;
}
return base.Size;
}
set {
base.Size = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.TabIndex"]/*' />
/// <devdoc>
/// Override TabIndex to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new int TabIndex {
get {
return base.TabIndex;
}
set {
base.TabIndex = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.TabStop"]/*' />
/// <devdoc>
/// Override TabStop to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new bool TabStop {
get {
return base.TabStop;
}
set {
base.TabStop = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Visible"]/*' />
/// <devdoc>
/// Override Visible to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new bool Visible {
get {
return base.Visible;
}
set {
base.Visible = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.Width"]/*' />
/// <devdoc>
/// The width of this control.
/// </devdoc>
[
SRCategory(SR.CatLayout),
Browsable(false), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(SR.ControlWidthDescr)
]
public new int Width {
get {
if (Collapsed) {
return 0;
}
return base.Width;
}
set {
throw new NotSupportedException(SR.GetString(SR.SplitContainerPanelWidth));
}
}
internal int WidthInternal {
get {
return ((Panel)this).Width;
}
set {
((Panel)this).Width = value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.VisibleChanged"]/*' />
/// <devdoc>
/// Override VisibleChanged to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new event EventHandler VisibleChanged {
add {
base.VisibleChanged += value;
}
remove {
base.VisibleChanged -= value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.DockChanged"]/*' />
/// <devdoc>
/// Override DockChanged to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new event EventHandler DockChanged {
add {
base.DockChanged += value;
}
remove {
base.DockChanged -= value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.LocationChanged"]/*' />
/// <devdoc>
/// Override LocationChanged to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new event EventHandler LocationChanged {
add {
base.LocationChanged += value;
}
remove {
base.LocationChanged -= value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.TabIndexChanged"]/*' />
/// <devdoc>
/// Override TabIndexChanged to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new event EventHandler TabIndexChanged {
add {
base.TabIndexChanged += value;
}
remove {
base.TabIndexChanged -= value;
}
}
/// <include file='doc\SplitterPanel.uex' path='docs/doc[@for="SplitterPanel.TabStopChanged"]/*' />
/// <devdoc>
/// Override TabStopChanged to make it hidden from the user in the designer
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public new event EventHandler TabStopChanged {
add {
base.TabStopChanged += value;
}
remove {
base.TabStopChanged -= value;
}
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Float", "Constants", "Float property", null, KeyCode.Alpha1 )]
public sealed class RangedFloatNode : PropertyNode
{
private const int OriginalFontSize = 11;
private const string MinValueStr = "Min";
private const string MaxValueStr = "Max";
private const float LabelWidth = 8;
[SerializeField]
private float m_defaultValue = 0;
[SerializeField]
private float m_materialValue = 0;
[SerializeField]
private float m_min = 0;
[SerializeField]
private float m_max = 0;
[SerializeField]
private bool m_floatMode = true;
private int m_cachedPropertyId = -1;
public RangedFloatNode() : base() { }
public RangedFloatNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { }
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddOutputPort( WirePortDataType.FLOAT, Constants.EmptyPortValue );
m_insideSize.Set( 50, 0 );
m_showPreview = false;
m_selectedLocation = PreviewLocation.BottomCenter;
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
m_availableAttribs.Add( new PropertyAttributes( "Toggle", "[Toggle]" ) );
m_availableAttribs.Add( new PropertyAttributes( "Int Range", "[IntRange]" ) );
m_previewShaderGUID = "d9ca47581ac157145bff6f72ac5dd73e";
}
public void SetFloatMode( bool value )
{
if ( m_floatMode == value )
return;
m_floatMode = value;
if ( value )
{
m_insideSize.x = 50;// + ( m_showPreview ? 50 : 0 );
//m_firstPreviewDraw = true;
}
else
{
m_insideSize.x = 200;// + ( m_showPreview ? 0 : 0 );
//m_firstPreviewDraw = true;
}
m_sizeIsDirty = true;
}
public override void CopyDefaultsToMaterial()
{
m_materialValue = m_defaultValue;
}
void DrawMinMaxUI()
{
EditorGUI.BeginChangeCheck();
m_min = EditorGUILayoutFloatField( MinValueStr, m_min );
m_max = EditorGUILayoutFloatField( MaxValueStr, m_max );
if ( m_min > m_max )
m_min = m_max;
if ( m_max < m_min )
m_max = m_min;
if ( EditorGUI.EndChangeCheck() )
{
SetFloatMode( m_min == m_max );
}
}
public override void DrawSubProperties()
{
DrawMinMaxUI();
if ( m_floatMode )
{
m_defaultValue = EditorGUILayoutFloatField( Constants.DefaultValueLabel, m_defaultValue );
}
else
{
m_defaultValue = EditorGUILayoutSlider( Constants.DefaultValueLabel, m_defaultValue, m_min, m_max );
}
}
public override void DrawMaterialProperties()
{
DrawMinMaxUI();
EditorGUI.BeginChangeCheck();
if ( m_floatMode )
{
m_materialValue = EditorGUILayoutFloatField( Constants.MaterialValueLabel, m_materialValue );
}
else
{
m_materialValue = EditorGUILayoutSlider( Constants.MaterialValueLabel, m_materialValue, m_min, m_max );
}
if ( EditorGUI.EndChangeCheck() )
{
//MarkForPreviewUpdate();
if ( m_materialMode )
m_requireMaterialUpdate = true;
}
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if ( m_cachedPropertyId == -1 )
m_cachedPropertyId = Shader.PropertyToID( "_InputFloat" );
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
PreviewMaterial.SetFloat( m_cachedPropertyId, m_materialValue );
else
PreviewMaterial.SetFloat( m_cachedPropertyId, m_defaultValue );
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( m_isVisible )
{
if ( m_floatMode )
{
m_propertyDrawPos.x = m_remainingBox.x - LabelWidth * drawInfo.InvertedZoom;
m_propertyDrawPos.y = m_outputPorts[ 0 ].Position.y - 2 * drawInfo.InvertedZoom;
m_propertyDrawPos.width = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_WIDTH_FIELD_SIZE;
m_propertyDrawPos.height = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_HEIGHT_FIELD_SIZE;
}
else
{
m_propertyDrawPos.x = m_remainingBox.x;
m_propertyDrawPos.y = m_outputPorts[ 0 ].Position.y - 2 * drawInfo.InvertedZoom;
m_propertyDrawPos.width = 0.7f * m_globalPosition.width;
m_propertyDrawPos.height = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_HEIGHT_FIELD_SIZE;
}
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
{
EditorGUI.BeginChangeCheck();
if ( m_floatMode )
{
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_materialValue, LabelWidth * drawInfo.InvertedZoom );
}
else
{
DrawSlider( ref m_materialValue, drawInfo );
}
if ( EditorGUI.EndChangeCheck() )
{
m_requireMaterialUpdate = true;
if ( m_currentParameterType != PropertyType.Constant )
{
//MarkForPreviewUpdate();
BeginDelayedDirtyProperty();
}
}
}
else
{
EditorGUI.BeginChangeCheck();
if ( m_floatMode )
{
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_defaultValue, LabelWidth * drawInfo.InvertedZoom );
}
else
{
DrawSlider( ref m_defaultValue, drawInfo );
}
if ( EditorGUI.EndChangeCheck() )
{
//MarkForPreviewUpdate();
BeginDelayedDirtyProperty();
}
}
}
}
void DrawSlider( ref float value, DrawInfo drawInfo )
{
int originalFontSize = EditorStyles.numberField.fontSize;
EditorStyles.numberField.fontSize = ( int ) ( OriginalFontSize * drawInfo.InvertedZoom );
float rangeWidth = 30 * drawInfo.InvertedZoom;
float rangeSpacing = 5 * drawInfo.InvertedZoom;
//Min
m_propertyDrawPos.width = rangeWidth;
m_min = EditorGUIFloatField( m_propertyDrawPos, m_min, UIUtils.MainSkin.textField );
//Value Slider
m_propertyDrawPos.x += m_propertyDrawPos.width + rangeSpacing;
m_propertyDrawPos.width = 0.65f * ( m_globalPosition.width - 3 * m_propertyDrawPos.width );
Rect slider = m_propertyDrawPos;
slider.height = 5 * drawInfo.InvertedZoom;
slider.y += m_propertyDrawPos.height * 0.5f - slider.height * 0.5f;
GUI.Box( slider, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SliderStyle ) );
value = GUI.HorizontalSlider( m_propertyDrawPos, value, m_min, m_max, GUIStyle.none, UIUtils.RangedFloatSliderThumbStyle );
//Value Area
m_propertyDrawPos.x += m_propertyDrawPos.width + rangeSpacing;
m_propertyDrawPos.width = rangeWidth;
value = EditorGUIFloatField( m_propertyDrawPos, value, UIUtils.MainSkin.textField );
//Max
m_propertyDrawPos.x += m_propertyDrawPos.width + rangeSpacing;
m_propertyDrawPos.width = rangeWidth;
m_max = EditorGUIFloatField( m_propertyDrawPos, m_max, UIUtils.MainSkin.textField );
EditorStyles.numberField.fontSize = originalFontSize;
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar );
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
if ( m_currentParameterType != PropertyType.Constant )
return PropertyData;
return IOUtils.Floatify( m_defaultValue );
}
public override string GetPropertyValue()
{
if ( m_floatMode )
{
return PropertyAttributes + m_propertyName + "(\"" + m_propertyInspectorName + "\", Float) = " + m_defaultValue;
}
else
{
return PropertyAttributes + m_propertyName + "(\"" + m_propertyInspectorName + "\", Range( " + m_min + " , " + m_max + ")) = " + m_defaultValue;
}
}
public override void UpdateMaterial( Material mat )
{
base.UpdateMaterial( mat );
if ( UIUtils.IsProperty( m_currentParameterType ) )
{
mat.SetFloat( m_propertyName, m_materialValue );
}
}
public override void SetMaterialMode( Material mat , bool fetchMaterialValues )
{
base.SetMaterialMode( mat , fetchMaterialValues );
if ( fetchMaterialValues && m_materialMode && UIUtils.IsProperty( m_currentParameterType ) && mat.HasProperty( m_propertyName ) )
{
m_materialValue = mat.GetFloat( m_propertyName );
}
}
public override void ForceUpdateFromMaterial( Material material )
{
if ( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( m_propertyName ) )
m_materialValue = material.GetFloat( m_propertyName );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_defaultValue = Convert.ToSingle( GetCurrentParam( ref nodeParams ) );
m_min = Convert.ToSingle( GetCurrentParam( ref nodeParams ) );
m_max = Convert.ToSingle( GetCurrentParam( ref nodeParams ) );
SetFloatMode( m_min == m_max );
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_min );
IOUtils.AddFieldValueToString( ref nodeInfo, m_max );
}
public override void ReadAdditionalClipboardData( ref string[] nodeParams )
{
base.ReadAdditionalClipboardData( ref nodeParams );
m_materialValue = Convert.ToSingle( GetCurrentParam( ref nodeParams ) );
}
public override void WriteAdditionalClipboardData( ref string nodeInfo )
{
base.WriteAdditionalClipboardData( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_materialValue );
}
public override string GetPropertyValStr()
{
return ( m_materialMode && m_currentParameterType != PropertyType.Constant ) ?
m_materialValue.ToString( Mathf.Abs( m_materialValue ) > 1000 ? Constants.PropertyBigFloatFormatLabel : Constants.PropertyFloatFormatLabel ) :
m_defaultValue.ToString( Mathf.Abs( m_defaultValue ) > 1000 ? Constants.PropertyBigFloatFormatLabel : Constants.PropertyFloatFormatLabel );
}
public float Value
{
get { return m_defaultValue; }
set { m_defaultValue = value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Server.HttpSys
{
public class RequestBodyLimitTests
{
[ConditionalFact]
public async Task ContentLengthEqualsLimit_ReadSync_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Features.Get<IHttpBodyControlFeature>().AllowSynchronousIO = true;
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Equal(11, httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = httpContext.Request.Body.Read(input, 0, input.Length);
httpContext.Response.ContentLength = read;
httpContext.Response.Body.Write(input, 0, read);
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 11))
{
var response = await SendRequestAsync(address, "Hello World");
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task ContentLengthEqualsLimit_ReadAsync_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.True(httpContext.Request.CanHaveBody());
Assert.Equal(11, httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
httpContext.Response.ContentLength = read;
await httpContext.Response.Body.WriteAsync(input, 0, read);
}, options => options.MaxRequestBodySize = 11))
{
var response = await SendRequestAsync(address, "Hello World");
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task ContentLengthEqualsLimit_ReadBeginEnd_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Equal(11, httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = httpContext.Request.Body.EndRead(httpContext.Request.Body.BeginRead(input, 0, input.Length, null, null));
httpContext.Response.ContentLength = read;
httpContext.Response.Body.EndWrite(httpContext.Response.Body.BeginWrite(input, 0, read, null, null));
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 11))
{
var response = await SendRequestAsync(address, "Hello World");
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task ChunkedEqualsLimit_ReadSync_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Features.Get<IHttpBodyControlFeature>().AllowSynchronousIO = true;
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Null(httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = httpContext.Request.Body.Read(input, 0, input.Length);
httpContext.Response.ContentLength = read;
httpContext.Response.Body.Write(input, 0, read);
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 11))
{
var response = await SendRequestAsync(address, "Hello World", chunked: true);
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task ChunkedEqualsLimit_ReadAsync_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.True(httpContext.Request.CanHaveBody());
Assert.Null(httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
httpContext.Response.ContentLength = read;
await httpContext.Response.Body.WriteAsync(input, 0, read);
}, options => options.MaxRequestBodySize = 11))
{
var response = await SendRequestAsync(address, "Hello World", chunked: true);
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task ChunkedEqualsLimit_ReadBeginEnd_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Null(httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = httpContext.Request.Body.EndRead(httpContext.Request.Body.BeginRead(input, 0, input.Length, null, null));
httpContext.Response.ContentLength = read;
httpContext.Response.Body.EndWrite(httpContext.Response.Body.BeginWrite(input, 0, read, null, null));
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 11))
{
var response = await SendRequestAsync(address, "Hello World", chunked: true);
Assert.Equal("Hello World", response);
}
}
[ConditionalFact]
public async Task ContentLengthExceedsLimit_ReadSync_ThrowsImmediately()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Features.Get<IHttpBodyControlFeature>().AllowSynchronousIO = true;
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Equal(11, httpContext.Request.ContentLength);
byte[] input = new byte[100];
var ex = Assert.Throws<BadHttpRequestException>(() => httpContext.Request.Body.Read(input, 0, input.Length));
Assert.Equal("The request's Content-Length 11 is larger than the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
ex = Assert.Throws<BadHttpRequestException>(() => httpContext.Request.Body.Read(input, 0, input.Length));
Assert.Equal("The request's Content-Length 11 is larger than the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 10))
{
var response = await SendRequestAsync(address, "Hello World");
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task ContentLengthExceedsLimit_ReadAsync_ThrowsImmediately()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Equal(11, httpContext.Request.ContentLength);
byte[] input = new byte[100];
var ex = Assert.Throws<BadHttpRequestException>(() => { var t = httpContext.Request.Body.ReadAsync(input, 0, input.Length); });
Assert.Equal("The request's Content-Length 11 is larger than the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
ex = Assert.Throws<BadHttpRequestException>(() => { var t = httpContext.Request.Body.ReadAsync(input, 0, input.Length); });
Assert.Equal("The request's Content-Length 11 is larger than the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 10))
{
var response = await SendRequestAsync(address, "Hello World");
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task ContentLengthExceedsLimit_ReadBeginEnd_ThrowsImmediately()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Equal(11, httpContext.Request.ContentLength);
byte[] input = new byte[100];
var ex = Assert.Throws<BadHttpRequestException>(() => httpContext.Request.Body.BeginRead(input, 0, input.Length, null, null));
Assert.Equal("The request's Content-Length 11 is larger than the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
ex = Assert.Throws<BadHttpRequestException>(() => httpContext.Request.Body.BeginRead(input, 0, input.Length, null, null));
Assert.Equal("The request's Content-Length 11 is larger than the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 10))
{
var response = await SendRequestAsync(address, "Hello World");
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task ChunkedExceedsLimit_ReadSync_ThrowsAtLimit()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Features.Get<IHttpBodyControlFeature>().AllowSynchronousIO = true;
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Null(httpContext.Request.ContentLength);
byte[] input = new byte[100];
var ex = Assert.Throws<BadHttpRequestException>(() => httpContext.Request.Body.Read(input, 0, input.Length));
Assert.Equal("The total number of bytes read 11 has exceeded the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
ex = Assert.Throws<BadHttpRequestException>(() => httpContext.Request.Body.Read(input, 0, input.Length));
Assert.Equal("The total number of bytes read 11 has exceeded the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 10))
{
var response = await SendRequestAsync(address, "Hello World", chunked: true);
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task ChunkedExceedsLimit_ReadAsync_ThrowsAtLimit()
{
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Null(httpContext.Request.ContentLength);
byte[] input = new byte[100];
var ex = await Assert.ThrowsAsync<BadHttpRequestException>(() => httpContext.Request.Body.ReadAsync(input, 0, input.Length));
Assert.Equal("The total number of bytes read 11 has exceeded the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
ex = await Assert.ThrowsAsync<BadHttpRequestException>(() => httpContext.Request.Body.ReadAsync(input, 0, input.Length));
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
Assert.Equal("The total number of bytes read 11 has exceeded the request body size limit 10.", ex.Message);
}, options => options.MaxRequestBodySize = 10))
{
var response = await SendRequestAsync(address, "Hello World", chunked: true);
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task ChunkedExceedsLimit_ReadBeginEnd_ThrowsAtLimit()
{
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Null(httpContext.Request.ContentLength);
byte[] input = new byte[100];
var body = httpContext.Request.Body;
var ex = Assert.Throws<BadHttpRequestException>(() => body.EndRead(body.BeginRead(input, 0, input.Length, null, null)));
Assert.Equal("The total number of bytes read 11 has exceeded the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
ex = Assert.Throws<BadHttpRequestException>(() => body.EndRead(body.BeginRead(input, 0, input.Length, null, null)));
Assert.Equal("The total number of bytes read 11 has exceeded the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 10))
{
var response = await SendRequestAsync(address, "Hello World", chunked: true);
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task Chunked_ReadSyncPartialBodyUnderLimit_ThrowsAfterLimit()
{
var content = new StaggardContent();
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Features.Get<IHttpBodyControlFeature>().AllowSynchronousIO = true;
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Null(httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = httpContext.Request.Body.Read(input, 0, input.Length);
Assert.Equal(10, read);
content.Block.Release();
var ex = Assert.Throws<BadHttpRequestException>(() => httpContext.Request.Body.Read(input, 0, input.Length));
Assert.Equal("The total number of bytes read 20 has exceeded the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
return Task.FromResult(0);
}, options => options.MaxRequestBodySize = 10))
{
string response = await SendRequestAsync(address, content, chunked: true);
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task Chunked_ReadAsyncPartialBodyUnderLimit_ThrowsAfterLimit()
{
var content = new StaggardContent();
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Null(httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
Assert.Equal(10, read);
content.Block.Release();
var ex = await Assert.ThrowsAsync<BadHttpRequestException>(() => httpContext.Request.Body.ReadAsync(input, 0, input.Length));
Assert.Equal("The total number of bytes read 20 has exceeded the request body size limit 10.", ex.Message);
Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode);
}, options => options.MaxRequestBodySize = 10))
{
string response = await SendRequestAsync(address, content, chunked: true);
Assert.Equal(string.Empty, response);
}
}
[ConditionalFact]
public async Task AdjustLimitPerRequest_ContentLength_ReadAsync_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Equal(11, feature.MaxRequestBodySize);
feature.MaxRequestBodySize = 12;
Assert.Equal(12, httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
Assert.True(feature.IsReadOnly);
httpContext.Response.ContentLength = read;
await httpContext.Response.Body.WriteAsync(input, 0, read);
}, options => options.MaxRequestBodySize = 11))
{
var response = await SendRequestAsync(address, "Hello World!");
Assert.Equal("Hello World!", response);
}
}
[ConditionalFact]
public async Task AdjustLimitPerRequest_Chunked_ReadAsync_Success()
{
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
Assert.NotNull(feature);
Assert.False(feature.IsReadOnly);
Assert.Equal(11, feature.MaxRequestBodySize);
feature.MaxRequestBodySize = 12;
Assert.Null(httpContext.Request.ContentLength);
byte[] input = new byte[100];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
Assert.True(feature.IsReadOnly);
httpContext.Response.ContentLength = read;
await httpContext.Response.Body.WriteAsync(input, 0, read);
}, options => options.MaxRequestBodySize = 11))
{
var response = await SendRequestAsync(address, "Hello World!", chunked: true);
Assert.Equal("Hello World!", response);
}
}
private Task<string> SendRequestAsync(string uri, string upload, bool chunked = false)
{
return SendRequestAsync(uri, new StringContent(upload), chunked);
}
private async Task<string> SendRequestAsync(string uri, HttpContent content, bool chunked = false)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = chunked;
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
private class StaggardContent : HttpContent
{
public StaggardContent()
{
Block = new SemaphoreSlim(0, 1);
}
public SemaphoreSlim Block { get; private set; }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
await stream.WriteAsync(new byte[10], 0, 10);
await stream.FlushAsync();
Assert.True(await Block.WaitAsync(TimeSpan.FromSeconds(10)));
await stream.WriteAsync(new byte[10], 0, 10);
}
protected override bool TryComputeLength(out long length)
{
length = 10;
return true;
}
}
}
}
| |
#if WINDOWS_UWP
namespace XPlat.Storage
{
using System;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using XPlat.Storage.Extensions;
using XPlat.Storage.FileProperties;
/// <summary>Represents a file. Provides information about the file and its contents, and ways to manipulate them.</summary>
public sealed class StorageFile : IStorageFile
{
/// <summary>
/// Initializes a new instance of the <see cref="StorageFile"/> class.
/// </summary>
/// <param name="file">
/// The associated <see cref="StorageFile"/>.
/// </param>
public StorageFile(Windows.Storage.StorageFile file)
{
this.Originator = file ?? throw new ArgumentNullException(nameof(file));
}
/// <summary>Gets the instance of the <see cref="Windows.Storage.StorageFile"/> object associated with this file.</summary>
public Windows.Storage.StorageFile Originator { get; }
/// <summary>Gets the date and time when the current item was created.</summary>
public DateTime DateCreated => this.Originator.DateCreated.DateTime;
/// <summary>Gets the name of the item including the file name extension if there is one.</summary>
public string Name => this.Originator.Name;
/// <summary>Gets the user-friendly name of the item.</summary>
public string DisplayName => this.Originator.DisplayName;
/// <summary>Gets the full file-system path of the item, if the item has a path.</summary>
public string Path => this.Originator.Path;
/// <summary>Gets a value indicating whether the item exists.</summary>
public bool Exists => this.Originator != null;
/// <summary>Gets the attributes of a storage item.</summary>
public FileAttributes Attributes => this.Originator.Attributes.ToInternalFileAttributes();
/// <summary>Gets the type (file name extension) of the file.</summary>
public string FileType => this.Originator.FileType;
/// <summary>Gets the MIME type of the contents of the file.</summary>
public string ContentType => this.Originator.ContentType;
/// <summary>Gets an object that provides access to the content-related properties of the item.</summary>
public IStorageItemContentProperties Properties => new StorageItemContentProperties(new WeakReference(this));
public static implicit operator StorageFile(Windows.Storage.StorageFile file)
{
return new StorageFile(file);
}
/// <summary>
/// Retrieves a <see cref="IStorageFile"/> by the given <paramref name="path"/>.
/// </summary>
/// <param name="path">The path to the file.</param>
/// <returns>The <see cref="IStorageFile"/>.</returns>
public static async Task<IStorageFile> GetFileFromPathAsync(string path)
{
Windows.Storage.StorageFile pathFile;
try
{
pathFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);
}
catch (Exception)
{
pathFile = null;
}
if (pathFile == null)
{
return null;
}
StorageFile resultFile = new StorageFile(pathFile);
return resultFile;
}
public static async Task<IStorageFile> GetFileFromApplicationUriAsync(Uri uri)
{
Windows.Storage.StorageFile pathFile;
try
{
pathFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
}
catch (Exception)
{
pathFile = null;
}
if (pathFile == null)
{
return null;
}
StorageFile resultFile = new StorageFile(pathFile);
return resultFile;
}
/// <summary>Renames the current item.</summary>
/// <returns>No object or value is returned by this method when it completes.</returns>
/// <param name="desiredName">The desired, new name of the item.</param>
public Task RenameAsync(string desiredName)
{
return this.RenameAsync(desiredName, NameCollisionOption.FailIfExists);
}
/// <summary>Renames the current item. This method also specifies what to do if an existing item in the current item's location has the same name.</summary>
/// <returns>No object or value is returned by this method when it completes.</returns>
/// <param name="desiredName">The desired, new name of the current item. If there is an existing item in the current item's location that already has the specified desiredName, the specified NameCollisionOption determines how Windows responds to the conflict.</param>
/// <param name="option">The enum value that determines how the system responds if the desiredName is the same as the name of an existing item in the current item's location.</param>
public async Task RenameAsync(string desiredName, NameCollisionOption option)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot rename a file that does not exist.");
}
if (string.IsNullOrWhiteSpace(desiredName))
{
throw new ArgumentNullException(nameof(desiredName));
}
await this.Originator.RenameAsync(desiredName, option.ToWindowsNameCollisionOption());
}
/// <summary>Deletes the current item.</summary>
/// <returns>No object or value is returned by this method when it completes.</returns>
public async Task DeleteAsync()
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot delete a file that does not exist.");
}
await this.Originator.DeleteAsync();
}
/// <summary>Determines whether the current IStorageItem matches the specified StorageItemTypes value.</summary>
/// <returns>True if the IStorageItem matches the specified value; otherwise false.</returns>
/// <param name="type">The value to match against.</param>
public bool IsOfType(StorageItemTypes type)
{
return type == StorageItemTypes.File;
}
/// <summary>Gets the basic properties of the current item (like a file or folder).</summary>
/// <returns>When this method completes successfully, it returns the basic properties of the current item as a BasicProperties object.</returns>
public async Task<IBasicProperties> GetBasicPropertiesAsync()
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(
this.Name,
"Cannot get properties for a folder that does not exist.");
}
Windows.Storage.StorageFile storageFolder = this.Originator;
if (storageFolder == null)
{
return null;
}
Windows.Storage.FileProperties.BasicProperties basicProperties = await storageFolder.GetBasicPropertiesAsync();
return new BasicProperties(basicProperties);
}
/// <summary>Gets the parent folder of the current storage item.</summary>
/// <returns>When this method completes, it returns the parent folder as a StorageFolder.</returns>
public async Task<IStorageFolder> GetParentAsync()
{
Windows.Storage.StorageFolder parent = await this.Originator.GetParentAsync();
return parent == null ? null : new StorageFolder(parent);
}
/// <summary>Indicates whether the current item is the same as the specified item.</summary>
/// <returns>Returns true if the current storage item is the same as the specified storage item; otherwise false.</returns>
/// <param name="item">The IStorageItem object that represents a storage item to compare against.</param>
public bool IsEqual(IStorageItem item)
{
if (item is StorageFile file)
{
return file.Originator.IsEqual(this.Originator);
}
return false;
}
/// <summary>
/// Opens a stream over the current file for reading file contents.
/// </summary>
/// <returns>
/// When this method completes, it returns the stream.
/// </returns>
public async Task<Stream> OpenReadAsync()
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot open a file that does not exist.");
}
IRandomAccessStreamWithContentType s = await this.Originator.OpenReadAsync();
return s.AsStream();
}
/// <summary>Opens a stream over the file.</summary>
/// <returns>When this method completes, it returns the stream.</returns>
/// <param name="accessMode">The type of access to allow.</param>
public async Task<Stream> OpenAsync(FileAccessMode accessMode)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot open a file that does not exist.");
}
IRandomAccessStream s = await this.Originator.OpenAsync(accessMode.ToWindowsFileAccessMode());
return s.AsStream();
}
/// <summary>Creates a copy of the file in the specified folder.</summary>
/// <returns>When this method completes, it returns a StorageFile that represents the copy.</returns>
/// <param name="destinationFolder">The destination folder where the copy is created.</param>
public Task<IStorageFile> CopyAsync(IStorageFolder destinationFolder)
{
return this.CopyAsync(destinationFolder, this.Name);
}
/// <summary>Creates a copy of the file in the specified folder, using the desired name.</summary>
/// <returns>When this method completes, it returns a StorageFile that represents the copy.</returns>
/// <param name="destinationFolder">The destination folder where the copy is created.</param>
/// <param name="desiredNewName">The desired name of the copy. If there is an existing file in the destination folder that already has the specified desiredNewName, Windows generates a unique name for the copy.</param>
public Task<IStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName)
{
return this.CopyAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists);
}
/// <summary>Creates a copy of the file in the specified folder, using the desired name. This method also specifies what to do if an existing file in the specified folder has the same name.</summary>
/// <returns>When this method completes, it returns a StorageFile that represents the copy.</returns>
/// <param name="destinationFolder">The destination folder where the copy is created.</param>
/// <param name="desiredNewName">The desired name of the copy. If there is an existing file in the destination folder that already has the specified desiredNewName, the specified NameCollisionOption determines how Windows responds to the conflict.</param>
/// <param name="option">An enum value that determines how Windows responds if the desiredNewName is the same as the name of an existing file in the destination folder.</param>
public async Task<IStorageFile> CopyAsync(
IStorageFolder destinationFolder,
string desiredNewName,
NameCollisionOption option)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot copy a file that does not exist.");
}
if (destinationFolder == null)
{
throw new ArgumentNullException(nameof(destinationFolder));
}
if (!destinationFolder.Exists)
{
throw new StorageItemNotFoundException(
destinationFolder.Name,
"Cannot copy a file to a folder that does not exist.");
}
if (string.IsNullOrWhiteSpace(desiredNewName))
{
throw new ArgumentNullException(nameof(desiredNewName));
}
Windows.Storage.StorageFolder storageFolder =
await Windows.Storage.StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(destinationFolder.Path));
Windows.Storage.StorageFile copiedStorageFile =
await this.Originator.CopyAsync(storageFolder, desiredNewName, option.ToWindowsNameCollisionOption());
StorageFile copiedFile = new StorageFile(copiedStorageFile);
return copiedFile;
}
/// <summary>Replaces the specified file with a copy of the current file.</summary>
/// <returns>No object or value is returned when this method completes.</returns>
/// <param name="fileToReplace">The file to replace.</param>
public async Task CopyAndReplaceAsync(IStorageFile fileToReplace)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot copy a file that does not exist.");
}
if (fileToReplace == null)
{
throw new ArgumentNullException(nameof(fileToReplace));
}
if (!fileToReplace.Exists)
{
throw new StorageItemNotFoundException(
fileToReplace.Name,
"Cannot copy to and replace a file that does not exist.");
}
Windows.Storage.StorageFile storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(fileToReplace.Path);
await this.Originator.CopyAndReplaceAsync(storageFile);
}
/// <summary>Moves the current file to the specified folder.</summary>
/// <returns>No object or value is returned by this method.</returns>
/// <param name="destinationFolder">The destination folder where the file is moved. This destination folder must be a physical location. Otherwise, if the destination folder exists only in memory, like a file group, this method fails and throws an exception.</param>
public Task MoveAsync(IStorageFolder destinationFolder)
{
return this.MoveAsync(destinationFolder, this.Name);
}
/// <summary>Moves the current file to the specified folder and renames the file according to the desired name.</summary>
/// <returns>No object or value is returned by this method.</returns>
/// <param name="destinationFolder">The destination folder where the file is moved. This destination folder must be a physical location. Otherwise, if the destination folder exists only in memory, like a file group, this method fails and throws an exception.</param>
/// <param name="desiredNewName">The desired name of the file after it is moved. If there is an existing file in the destination folder that already has the specified desiredNewName, Windows generates a unique name for the file.</param>
public Task MoveAsync(IStorageFolder destinationFolder, string desiredNewName)
{
return this.MoveAsync(destinationFolder, desiredNewName, NameCollisionOption.ReplaceExisting);
}
/// <summary>Moves the current file to the specified folder and renames the file according to the desired name. This method also specifies what to do if a file with the same name already exists in the specified folder.</summary>
/// <returns>No object or value is returned by this method.</returns>
/// <param name="destinationFolder">The destination folder where the file is moved. This destination folder must be a physical location. Otherwise, if the destination folder exists only in memory, like a file group, this method fails and throws an exception.</param>
/// <param name="desiredNewName">The desired name of the file after it is moved. If there is an existing file in the destination folder that already has the specified desiredNewName, the specified NameCollisionOption determines how Windows responds to the conflict.</param>
/// <param name="option">An enum value that determines how Windows responds if the desiredNewName is the same as the name of an existing file in the destination folder.</param>
public async Task MoveAsync(
IStorageFolder destinationFolder,
string desiredNewName,
NameCollisionOption option)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot move a file that does not exist.");
}
if (destinationFolder == null)
{
throw new ArgumentNullException(nameof(destinationFolder));
}
if (!destinationFolder.Exists)
{
throw new StorageItemNotFoundException(
destinationFolder.Name,
"Cannot move a file to a folder that does not exist.");
}
if (string.IsNullOrWhiteSpace(desiredNewName))
{
throw new ArgumentNullException(nameof(desiredNewName));
}
Windows.Storage.StorageFolder storageFolder =
await Windows.Storage.StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(destinationFolder.Path));
await this.Originator.MoveAsync(storageFolder, desiredNewName, option.ToWindowsNameCollisionOption());
}
/// <summary>Moves the current file to the location of the specified file and replaces the specified file in that location.</summary>
/// <returns>No object or value is returned by this method.</returns>
/// <param name="fileToReplace">The file to replace.</param>
public async Task MoveAndReplaceAsync(IStorageFile fileToReplace)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot move a file that does not exist.");
}
if (fileToReplace == null)
{
throw new ArgumentNullException(nameof(fileToReplace));
}
if (!fileToReplace.Exists)
{
throw new StorageItemNotFoundException(
fileToReplace.Name,
"Cannot move to and replace a file that does not exist.");
}
Windows.Storage.StorageFile storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(fileToReplace.Path);
await this.Originator.MoveAndReplaceAsync(storageFile);
}
/// <summary>
/// Writes a string to the current file.
/// </summary>
/// <param name="text">
/// The text to write out.
/// </param>
/// <returns>
/// An object that is used to manage the asynchronous operation.
/// </returns>
public async Task WriteTextAsync(string text)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot write to a file that does not exist.");
}
await FileIO.WriteTextAsync(this.Originator, text);
}
/// <summary>
/// Reads the current file as a string.
/// </summary>
/// <returns>
/// When this method completes, it returns the file's content as a string.
/// </returns>
public async Task<string> ReadTextAsync()
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot read from a file that does not exist.");
}
string text = await FileIO.ReadTextAsync(this.Originator);
return text;
}
/// <summary>
/// Writes a byte array to the current file.
/// </summary>
/// <param name="bytes">
/// The byte array to write out.
/// </param>
/// <returns>
/// An object that is used to manage the asynchronous operation.
/// </returns>
public async Task WriteBytesAsync(byte[] bytes)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot write to a file that does not exist.");
}
await FileIO.WriteBytesAsync(this.Originator, bytes);
}
/// <summary>
/// Reads the current file as a byte array.
/// </summary>
/// <returns>
/// When this method completes, it returns the file's content as a byte array.
/// </returns>
public async Task<byte[]> ReadBytesAsync()
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot read from a file that does not exist.");
}
IBuffer buffer = await FileIO.ReadBufferAsync(this.Originator);
return buffer.ToArray();
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
using Koans.Utils;
using Xunit;
namespace Koans.Lessons
{
public class Lesson1ObservableStreams
{
/*
* How to Run: Press Ctrl+R,T (go ahead, try it now)
* Step 1: find the 1st method that fails
* Step 2: Fill in the blank ____ to make it pass
* Step 3: run it again
* Note: Do not change anything other than the blank
*/
[Fact]
public void SimpleSubscription()
{
Observable.Return(42).Subscribe(x => Assert.Equal(___, x));
}
[Fact]
public void WhatGoesInComesOut()
{
Observable.Return(___).Subscribe(x => Assert.Equal(101, x));
}
//Q: Which interface Rx apply? (hint: what does "Return()" return)
//A:
[Fact]
public void ThisIsTheSameAsAnEventStream()
{
var events = new Subject<int>();
events.Subscribe(x => Assert.Equal(___, x));
events.OnNext(37);
}
//Q: What is the relationship between "ThisIsTheSameAsAnEventStream()" and "SimpleSubscription()"?
//A:
[Fact]
public void HowEventStreamsRelateToObservables()
{
int observableResult = 1;
Observable.Return(73).Subscribe(i => observableResult = i);
int eventStreamResult = 1;
var events = new Subject<int>();
events.Subscribe(i => eventStreamResult = i);
events.___(73);
Assert.Equal(observableResult, eventStreamResult);
}
//Q: What does Observable.Return() map to for a Subject?
//A:
[Fact]
public void EventStreamsHaveMultipleEvents()
{
int eventStreamResult = 0;
var events = new Subject<int>();
events.Subscribe(i => eventStreamResult += i);
events.OnNext(10);
events.OnNext(7);
Assert.Equal(____, eventStreamResult);
}
//Q: What does Observable.Return() map to for a Subject?
//A:
[Fact]
public void SimpleReturn()
{
var received = "";
Observable.Return("Foo").Subscribe((string s) => received = s);
Assert.Equal(___, received);
}
[Fact]
public void TheLastEvent()
{
var received = "";
var names = new[] { "Foo", "Bar" };
names.ToObservable().Subscribe((s) => received = s);
Assert.Equal(___, received);
}
[Fact]
public void EveryThingCounts()
{
var received = 0;
var numbers = new[] { 3, 4 };
numbers.ToObservable().Subscribe((int x) => received += x);
Assert.Equal(___, received);
}
[Fact]
public void ThisIsStillAnEventStream()
{
var received = 0;
var numbers = new Subject<int>();
numbers.Subscribe((int x) => received += x);
numbers.OnNext(10);
numbers.OnNext(5);
Assert.Equal(___, received);
}
[Fact]
public void AllEventsWillBeRecieved()
{
var received = "Working ";
var numbers = Range.Create(9, 5);
numbers.ToObservable().Subscribe((int x) => received += x);
Assert.Equal(___, received);
}
[Fact]
public void DoingInTheMiddle()
{
var status = new List<String>();
var daysTillTest = Range.Create(4, 1).ToObservable();
daysTillTest.Do(d => status.Add(d + "=" + (d == 1 ? "Study Like Mad" : ___))).Subscribe();
Assert.Equal("[4=Party, 3=Party, 2=Party, 1=Study Like Mad]", status.AsString());
}
[Fact]
public void NothingListensUntilYouSubscribe()
{
var sum = 0;
var numbers = Range.Create(1, 10).ToObservable();
var observable = numbers.Do(n => sum += n);
Assert.Equal(0, sum);
observable.___();
Assert.Equal(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10, sum);
}
[Fact]
public void EventsBeforeYouSubscribedDoNotCount()
{
var sum = 0;
var numbers = new Subject<int>();
var observable = numbers.Do(n => sum += n);
numbers.OnNext(1);
numbers.OnNext(2);
observable.Subscribe();
numbers.OnNext(3);
numbers.OnNext(4);
Assert.Equal(___, sum);
}
[Fact]
public void EventsAfterYouUnsubscribDoNotCount()
{
var sum = 0;
var numbers = new Subject<int>();
var observable = numbers.Do(n => sum += n);
var subscription = observable.Subscribe();
numbers.OnNext(1);
numbers.OnNext(2);
subscription.Dispose();
numbers.OnNext(3);
numbers.OnNext(4);
Assert.Equal(___, sum);
}
[Fact]
public void EventsWhileSubscribing()
{
var recieved = new List<string>();
var words = new Subject<string>();
var observable = words.Do(recieved.Add);
words.OnNext("Peter");
words.OnNext("said");
var subscription = observable.Subscribe();
words.OnNext("you");
words.OnNext("look");
words.OnNext("pretty");
subscription.Dispose();
words.OnNext("ugly");
Assert.Equal(___, String.Join(" ", recieved));
}
[Fact]
public void UnsubscribeAtAnyTime()
{
var received = "";
var numbers = Range.Create(1, 9);
IDisposable un = null;
un = numbers.ToObservable(Scheduler.NewThread).Subscribe((int x) =>
{
received += x;
if (x == 5)
{
un.___();
}
});
Thread.Sleep(100);
Assert.Equal("12345", received);
}
[Fact]
public void TakeUntilFull()
{
var received = "";
var subject = new Subject<int>();
subject.TakeUntil(subject.Where(x => x > ____)).Subscribe(x => received += x);
subject.OnNext(Range.Create(1, 9).ToArray());
Assert.Equal("12345", received);
}
#region Ignore
public object ___ = "Please Fill in the blank";
public int ____ = 100;
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="EnumeratorInterpreter.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Akka.Event;
using Akka.Streams.Stage;
namespace Akka.Streams.Implementation.Fusing
{
/// <summary>
/// TBD
/// </summary>
internal static class EnumeratorInterpreter
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
public sealed class EnumeratorUpstream<TIn> : GraphInterpreter.UpstreamBoundaryStageLogic
{
/// <summary>
/// TBD
/// </summary>
public bool HasNext;
/// <summary>
/// TBD
/// </summary>
/// <param name="input">TBD</param>
public EnumeratorUpstream(IEnumerator<TIn> input)
{
Out = new Outlet<TIn>("IteratorUpstream.out") { Id = 0 };
SetHandler(Out, onPull: () =>
{
if (!HasNext) CompleteStage();
else
{
var element = input.Current;
HasNext = input.MoveNext();
if (!HasNext)
{
Push(Out, element);
Complete(Out);
}
else Push(Out, element);
}
},
onDownstreamFinish: CompleteStage);
}
/// <summary>
/// TBD
/// </summary>
public override Outlet Out { get; }
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TOut">TBD</typeparam>
public sealed class EnumeratorDownstream<TOut> : GraphInterpreter.DownstreamBoundaryStageLogic, IEnumerator<TOut>
{
/// <summary>
/// TBD
/// </summary>
internal bool IsDone;
/// <summary>
/// TBD
/// </summary>
internal TOut NextElement;
/// <summary>
/// TBD
/// </summary>
internal bool NeedsPull = true;
/// <summary>
/// TBD
/// </summary>
internal Exception LastFailure;
/// <summary>
/// TBD
/// </summary>
public EnumeratorDownstream()
{
In = new Inlet<TOut>("IteratorDownstream.in") { Id = 0 };
SetHandler(In, onPush: () =>
{
NextElement = Grab<TOut>(In);
NeedsPull = false;
},
onUpstreamFinish: () =>
{
IsDone = true;
CompleteStage();
},
onUpstreamFailure: cause =>
{
IsDone = true;
LastFailure = cause;
CompleteStage();
});
}
/// <summary>
/// TBD
/// </summary>
public override Inlet In { get; }
/// <summary>
/// TBD
/// </summary>
public void Dispose() { }
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public bool MoveNext()
{
if (LastFailure != null)
{
var e = LastFailure;
LastFailure = null;
throw e;
}
if (!HasNext())
return false;
NeedsPull = true;
return true;
}
/// <summary>
/// TBD
/// </summary>
public void Reset()
{
IsDone = false;
NextElement = default(TOut);
NeedsPull = true;
LastFailure = null;
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public bool HasNext()
{
if(!IsDone)
PullIfNeeded();
return !(IsDone && NeedsPull) || LastFailure != null;
}
/// <summary>
/// TBD
/// </summary>
public TOut Current => NextElement;
object IEnumerator.Current => Current;
private void PullIfNeeded()
{
if (NeedsPull)
{
Pull(In);
Interpreter.Execute(int.MaxValue);
}
}
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
internal sealed class EnumeratorInterpreter<TIn, TOut> : IEnumerable<TOut>
{
private readonly IEnumerable<PushPullStage<TIn, TOut>> _ops;
private readonly EnumeratorInterpreter.EnumeratorUpstream<TIn> _upstream;
private readonly EnumeratorInterpreter.EnumeratorDownstream<TOut> _downstream = new EnumeratorInterpreter.EnumeratorDownstream<TOut>();
/// <summary>
/// TBD
/// </summary>
/// <param name="input">TBD</param>
/// <param name="ops">TBD</param>
public EnumeratorInterpreter(IEnumerator<TIn> input, IEnumerable<PushPullStage<TIn, TOut>> ops)
{
_ops = ops;
_upstream = new EnumeratorInterpreter.EnumeratorUpstream<TIn>(input);
Init();
}
private void Init()
{
var i = 0;
var length = _ops.Count();
var attributes = new Attributes[length];
for (var j = 0; j < length; j++) attributes[j] = Attributes.None;
var ins = new Inlet[length + 1];
var inOwners = new int[length + 1];
var outs = new Outlet[length + 1];
var outOwners = new int[length + 1];
var stages = new IGraphStageWithMaterializedValue<Shape, object>[length];
ins[length] = null;
inOwners[length] = GraphInterpreter.Boundary;
outs[0] = null;
outOwners[0] = GraphInterpreter.Boundary;
var opsEnumerator = _ops.GetEnumerator();
while (opsEnumerator.MoveNext())
{
var op = opsEnumerator.Current;
var stage = new PushPullGraphStage<TIn, TOut>(_ => op, Attributes.None);
stages[i] = stage;
ins[i] = stage.Shape.Inlet;
inOwners[i] = i;
outs[i + 1] = stage.Shape.Outlet;
outOwners[i + 1] = i;
i++;
}
var assembly = new GraphAssembly(stages, attributes, ins, inOwners, outs, outOwners);
var tup = assembly.Materialize(Attributes.None, assembly.Stages.Select(x => x.Module).ToArray(), new Dictionary<IModule, object>(), _ => { });
var connections = tup.Item1;
var logics = tup.Item2;
var interpreter = new GraphInterpreter(
assembly: assembly,
materializer: NoMaterializer.Instance,
log: NoLogger.Instance,
connections: connections,
logics: logics,
onAsyncInput: (_1, _2, _3) => { throw new NotSupportedException("IteratorInterpreter does not support asynchronous events.");},
fuzzingMode: false,
context: null);
interpreter.AttachUpstreamBoundary(0, _upstream);
interpreter.AttachDownstreamBoundary(length, _downstream);
interpreter.Init(null);
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public IEnumerator<TOut> GetEnumerator() => _downstream;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;
using IRTaktiks.Components.Manager;
namespace IRTaktiks.Components.Scenario
{
/// <summary>
/// Representation of the map of the game.
/// </summary>
public class Map : DrawableGameComponent
{
#region Properties
/// <summary>
/// Graphics device of the game.
/// </summary>
private GraphicsDevice DeviceField;
/// <summary>
/// Graphics device of the game.
/// </summary>
public GraphicsDevice Device
{
get { return DeviceField; }
}
/// <summary>
/// The effect of the map
/// </summary>
private Effect EffectField;
/// <summary>
/// The effect of the map
/// </summary>
public Effect Effect
{
get { return EffectField; }
}
/// <summary>
/// List of 3D vertices to be streamed to the graphics device.
/// </summary>
private VertexBuffer VertexBufferField;
/// <summary>
/// List of 3D vertices to be streamed to the graphics device.
/// </summary>
public VertexBuffer VertexBuffer
{
get { return VertexBufferField; }
}
/// <summary>
/// Rendering order of the vertices.
/// </summary>
private IndexBuffer IndexBufferField;
/// <summary>
/// Rendering order of the vertices.
/// </summary>
public IndexBuffer IndexBuffer
{
get { return IndexBufferField; }
}
/// <summary>
/// The vertices of the map.
/// </summary>
private VertexPositionNormalTexture[] VerticesField;
/// <summary>
/// The vertices of the map.
/// </summary>
public VertexPositionNormalTexture[] Vertices
{
get { return VerticesField; }
set { VerticesField = value; }
}
/// <summary>
/// Vertex declaration.
/// </summary>
private VertexDeclaration VertexDeclarationField;
/// <summary>
/// Vertex declaration.
/// </summary>
public VertexDeclaration VertexDeclaration
{
get { return VertexDeclarationField; }
}
/// <summary>
/// The maximum height of the terrain.
/// </summary>
private int MaxHeightField;
/// <summary>
/// The maximum height of the terrain.
/// </summary>
public int MaxHeight
{
get { return MaxHeightField; }
}
/// <summary>
/// Size of the cell of the terrain.
/// </summary>
private int CellSizeField;
/// <summary>
/// Size of the cell of the terrain.
/// </summary>
public int CellSize
{
get { return CellSizeField; }
}
/// <summary>
/// Dimension of the terrain.
/// </summary>
private int DimensionField;
/// <summary>
/// Dimension of the terrain.
/// </summary>
public int Dimension
{
get { return DimensionField; }
}
#endregion
#region Constructor
/// <summary>
/// Constructor of class.
/// </summary>
/// <param name="game">The instance of game that is running.</param>
public Map(Game game)
: base(game)
{
this.MaxHeightField = 2048;
this.CellSizeField = 128;
this.DimensionField = 48;
this.EffectField = EffectManager.Instance.TerrainEffect;
}
#endregion
#region Component Methods
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
int[] indices = new int[this.Dimension * this.Dimension * 6];
this.VerticesField = new VertexPositionNormalTexture[(this.Dimension + 1) * (this.Dimension + 1)];
for (int i = 0; i < this.Dimension + 1; i++)
{
for (int j = 0; j < this.Dimension + 1; j++)
{
VertexPositionNormalTexture vertice = new VertexPositionNormalTexture();
vertice.Position = new Vector3((i - this.Dimension / 2.0f) * this.CellSize, 0, (j - this.Dimension / 2.0f) * this.CellSize);
vertice.Normal = Vector3.Up;
vertice.TextureCoordinate = new Vector2((float)i / this.Dimension, (float)j / this.Dimension);
this.Vertices[i * (this.Dimension + 1) + j] = vertice;
}
}
for (int i = 0; i < this.Dimension; i++)
{
for (int j = 0; j < this.Dimension; j++)
{
indices[6 * (i * this.Dimension + j)] = (i * (this.Dimension + 1) + j);
indices[6 * (i * this.Dimension + j) + 1] = (i * (this.Dimension + 1) + j + 1);
indices[6 * (i * this.Dimension + j) + 2] = ((i + 1) * (this.Dimension + 1) + j + 1);
indices[6 * (i * this.Dimension + j) + 3] = (i * (this.Dimension + 1) + j);
indices[6 * (i * this.Dimension + j) + 4] = ((i + 1) * (this.Dimension + 1) + j + 1);
indices[6 * (i * this.Dimension + j) + 5] = ((i + 1) * (this.Dimension + 1) + j);
}
}
IGraphicsDeviceService service = (IGraphicsDeviceService)this.Game.Services.GetService(typeof(IGraphicsDeviceService));
this.DeviceField = service.GraphicsDevice;
this.VertexBufferField = new VertexBuffer(this.Device, (this.Dimension + 1) * (this.Dimension + 1) * VertexPositionNormalTexture.SizeInBytes, BufferUsage.Points);
this.IndexBufferField = new IndexBuffer(this.Device, 6 * this.Dimension * this.Dimension * sizeof(int), BufferUsage.Points, IndexElementSize.ThirtyTwoBits);
this.VertexBuffer.SetData<VertexPositionNormalTexture>(this.Vertices);
this.IndexBuffer.SetData<int>(indices);
this.VertexDeclarationField = new VertexDeclaration(this.Device, VertexPositionNormalTexture.VertexElements);
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
/// <summary>
/// Called when the DrawableGameComponent needs to be drawn. Override this method
// with component-specific drawing code.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Draw(GameTime gameTime)
{
IGraphicsDeviceService service = (IGraphicsDeviceService)this.Game.Services.GetService(typeof(IGraphicsDeviceService));
this.DeviceField = service.GraphicsDevice;
this.Device.VertexDeclaration = this.VertexDeclaration;
this.Device.Vertices[0].SetSource(this.VertexBuffer, 0, VertexPositionNormalTexture.SizeInBytes);
this.Device.Indices = this.IndexBuffer;
this.Device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, (this.Dimension + 1) * (this.Dimension + 1), 0, 2 * this.Dimension * this.Dimension);
base.Draw(gameTime);
}
#endregion
}
}
| |
using System;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class ILProcessorTests : BaseTestFixture {
[Test]
public void Append ()
{
var method = CreateTestMethod ();
var il = method.GetILProcessor ();
var ret = il.Create (OpCodes.Ret);
il.Append (ret);
AssertOpCodeSequence (new [] { OpCodes.Ret }, method);
}
[Test]
public void InsertBefore ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
var ldloc_2 = method.Instructions.Where (i => i.OpCode == OpCodes.Ldloc_2).First ();
il.InsertBefore (
ldloc_2,
il.Create (OpCodes.Ldloc_1));
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
}
[Test]
public void InsertAfter ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
var ldloc_0 = method.Instructions.First ();
il.InsertAfter (
ldloc_0,
il.Create (OpCodes.Ldloc_1));
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
}
[Test]
public void InsertAfterUsingIndex ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
il.InsertAfter (
0,
il.Create (OpCodes.Ldloc_1));
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
}
[Test]
public void InsertAfterWithLocalScopes ()
{
var method = CreateTestMethodWithLocalScopes ();
var il = method.GetILProcessor ();
il.InsertAfter (
0,
il.Create (OpCodes.Nop));
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Nop, OpCodes.Ldloc_1, OpCodes.Ldloc_2 }, method);
var wholeBodyScope = VerifyWholeBodyScope (method);
AssertLocalScope (wholeBodyScope.Scopes [0], 0, 2);
AssertLocalScope (wholeBodyScope.Scopes [1], 2, 3);
AssertLocalScope (wholeBodyScope.Scopes [2], 3, null);
}
[Test]
public void ReplaceUsingIndex ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
il.Replace (1, il.Create (OpCodes.Nop));
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Nop, OpCodes.Ldloc_3 }, method);
}
[Test]
public void ReplaceWithLocalScopes ()
{
var method = CreateTestMethodWithLocalScopes ();
var il = method.GetILProcessor ();
// Replace with larger instruction
var instruction = il.Create (OpCodes.Ldstr, "test");
instruction.Offset = method.Instructions [1].Offset;
il.Replace (1, instruction);
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldstr, OpCodes.Ldloc_2 }, method);
var wholeBodyScope = VerifyWholeBodyScope (method);
AssertLocalScope (wholeBodyScope.Scopes [0], 0, 1);
AssertLocalScope (wholeBodyScope.Scopes [1], 1, 6); // size of the new instruction is 5 bytes
AssertLocalScope (wholeBodyScope.Scopes [2], 6, null);
}
[Test]
public void Clear ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
il.Clear ();
AssertOpCodeSequence (new OpCode[] { }, method);
}
static void AssertOpCodeSequence (OpCode [] expected, MethodBody body)
{
var opcodes = body.Instructions.Select (i => i.OpCode).ToArray ();
Assert.AreEqual (expected.Length, opcodes.Length);
for (int i = 0; i < opcodes.Length; i++)
Assert.AreEqual (expected [i], opcodes [i]);
}
static MethodBody CreateTestMethod (params OpCode [] opcodes)
{
var method = new MethodDefinition {
Name = "function",
};
var il = method.Body.GetILProcessor ();
foreach (var opcode in opcodes)
il.Emit (opcode);
var instructions = method.Body.Instructions;
int size = 0;
for (int i = 0; i < instructions.Count; i++) {
var instruction = instructions [i];
instruction.Offset = size;
size += instruction.GetSize ();
}
return method.Body;
}
static ScopeDebugInformation VerifyWholeBodyScope (MethodBody body)
{
var debug_info = body.Method.DebugInformation;
Assert.IsNotNull (debug_info);
AssertLocalScope (debug_info.Scope, 0, null);
return debug_info.Scope;
}
static void AssertLocalScope (ScopeDebugInformation scope, int startOffset, int? endOffset)
{
Assert.IsNotNull (scope);
Assert.AreEqual (startOffset, scope.Start.Offset);
if (endOffset.HasValue)
Assert.AreEqual (endOffset.Value, scope.End.Offset);
else
Assert.IsTrue (scope.End.IsEndOfMethod);
}
static MethodBody CreateTestMethodWithLocalScopes ()
{
var methodBody = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2);
var method = methodBody.Method;
var debug_info = method.DebugInformation;
var wholeBodyScope = new ScopeDebugInformation () {
Start = new InstructionOffset (0),
End = new InstructionOffset ()
};
int size = 0;
var instruction = methodBody.Instructions [0];
var innerScopeBegining = new ScopeDebugInformation () {
Start = new InstructionOffset (size),
End = new InstructionOffset (size + instruction.GetSize ())
};
size += instruction.GetSize ();
wholeBodyScope.Scopes.Add (innerScopeBegining);
instruction = methodBody.Instructions [1];
var innerScopeMiddle = new ScopeDebugInformation () {
Start = new InstructionOffset (size),
End = new InstructionOffset (size + instruction.GetSize ())
};
size += instruction.GetSize ();
wholeBodyScope.Scopes.Add (innerScopeMiddle);
var innerScopeEnd = new ScopeDebugInformation () {
Start = new InstructionOffset (size),
End = new InstructionOffset ()
};
wholeBodyScope.Scopes.Add (innerScopeEnd);
debug_info.Scope = wholeBodyScope;
return methodBody;
}
}
}
| |
/*
*
* Copyright (c) 2007-2013 MindTouch. All rights reserved.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* 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.Xml;
using log4net;
using NUnit.Framework;
using Sgml;
namespace SGMLTests {
public class LoggingXmlReader : XmlReader {
//--- Fields ---
private readonly XmlReader _reader;
private readonly TextWriter _logger;
//--- Constructors ---
public LoggingXmlReader(XmlReader reader, TextWriter logger) {
_reader = reader;
_logger = logger;
}
//--- Properties ---
public override XmlNodeType NodeType
{
get
{
var result = _reader.NodeType;
_logger.WriteLine("NodeType = {0}", result);
return result;
}
}
public override string Name
{
get
{
var result = _reader.Name;
_logger.WriteLine("Name = {0}", result);
return result;
}
}
public override string LocalName
{
get
{
var result = _reader.LocalName;
_logger.WriteLine("LocalName = {0}", result);
return result;
}
}
public override string NamespaceURI
{
get
{
var result = _reader.NamespaceURI;
_logger.WriteLine("NamespaceURI = {0}", result);
return result;
}
}
public override string Prefix
{
get
{
var result = _reader.Prefix;
_logger.WriteLine("Prefix = {0}", result);
return result;
}
}
public override bool HasValue
{
get
{
var result = _reader.HasValue;
_logger.WriteLine("HasValue = {0}", result);
return result;
}
}
public override string Value
{
get
{
var result = _reader.Value;
_logger.WriteLine("Value = {0}", result);
return result;
}
}
public override int Depth
{
get
{
var result = _reader.Depth;
_logger.WriteLine("Depth = {0}", result);
return result;
}
}
public override string BaseURI
{
get
{
var result = _reader.BaseURI;
_logger.WriteLine("BaseURI = {0}", result);
return result;
}
}
public override bool IsEmptyElement
{
get
{
var result = _reader.IsEmptyElement;
_logger.WriteLine("IsEmptyElement = {0}", result);
return result;
}
}
public override bool IsDefault
{
get
{
var result = _reader.IsDefault;
_logger.WriteLine("IsDefault = {0}", result);
return result;
}
}
public override char QuoteChar
{
get
{
var result = _reader.QuoteChar;
_logger.WriteLine("QuoteChar = {0}", result);
return result;
}
}
public override XmlSpace XmlSpace
{
get
{
var result = _reader.XmlSpace;
_logger.WriteLine("XmlSpace = {0}", result);
return result;
}
}
public override string XmlLang
{
get
{
var result = _reader.XmlLang;
_logger.WriteLine("XmlLang = {0}", result);
return result;
}
}
public override int AttributeCount
{
get
{
var result = _reader.AttributeCount;
_logger.WriteLine("AttributeCount = {0}", result);
return result;
}
}
public override string this[int i]
{
get
{
var result = _reader[i];
_logger.WriteLine("this[i] = {0}", result);
return result;
}
}
public override string this[string name]
{
get
{
var result = _reader[name];
_logger.WriteLine("this[name] = {0}", result);
return result;
}
}
public override string this[string name, string namespaceURI]
{
get
{
var result = _reader[name, namespaceURI];
_logger.WriteLine("this[name, namespaceURI] = {0}", result);
return result;
}
}
public override XmlNameTable NameTable
{
get
{
var result = _reader.NameTable;
_logger.WriteLine("NameTable = {0}", result);
return result;
}
}
public override bool EOF
{
get
{
var result = _reader.EOF;
_logger.WriteLine("EOF = {0}", result);
return result;
}
}
public override ReadState ReadState
{
get
{
var result = _reader.ReadState;
_logger.WriteLine("ReadState = {0}", result);
return result;
}
}
//--- Methods ---
public override string GetAttribute(string name)
{
var result = _reader.GetAttribute(name);
_logger.WriteLine("GetAttribute('{1}') = {0}", result, name);
return result;
}
public override string GetAttribute(string name, string namespaceURI)
{
var result = _reader.GetAttribute(name, namespaceURI);
_logger.WriteLine("GetAttribute('{1}', '{2}') = {0}", result, name, namespaceURI);
return result;
}
public override string GetAttribute(int i)
{
var result = _reader.GetAttribute(i);
_logger.WriteLine("GetAttribute({1}) = {0}", result, i);
return result;
}
public override bool MoveToAttribute(string name)
{
var result = _reader.MoveToAttribute(name);
_logger.WriteLine("MoveToAttribute('{1}') = {0}", result, name);
return result;
}
public override bool MoveToAttribute(string name, string ns)
{
var result = _reader.MoveToAttribute(name, ns);
_logger.WriteLine("MoveToAttribute('{1}', '{2}') = {0}", result, name, ns);
return result;
}
public override void MoveToAttribute(int i)
{
_reader.MoveToAttribute(i);
_logger.WriteLine("MoveToAttribute({0})", i);
}
public override bool MoveToFirstAttribute()
{
var result = _reader.MoveToFirstAttribute();
_logger.WriteLine("MoveToFirstAttribute() = {0}", result);
return result;
}
public override bool MoveToNextAttribute()
{
var result = _reader.MoveToNextAttribute();
_logger.WriteLine("MoveToNextAttribute() = {0}", result);
return result;
}
public override bool MoveToElement()
{
var result = _reader.MoveToElement();
_logger.WriteLine("MoveToElement() = {0}", result);
return result;
}
public override bool Read()
{
var result = _reader.Read();
_logger.WriteLine("Read() = {0}", result);
return result;
}
public override void Close()
{
_reader.Close();
_logger.WriteLine("Close()");
}
public override string ReadString()
{
var result = _reader.ReadString();
_logger.WriteLine("ReadString() = {0}", result);
return result;
}
public override string ReadInnerXml()
{
var result = _reader.ReadInnerXml();
_logger.WriteLine("ReadInnerXml() = {0}", result);
return result;
}
public override string ReadOuterXml()
{
var result = _reader.ReadOuterXml();
_logger.WriteLine("ReadOuterXml() = {0}", result);
return result;
}
public override string LookupNamespace(string prefix)
{
var result = _reader.LookupNamespace(prefix);
_logger.WriteLine("LookupNamespace('{1}') = {0}", result, prefix);
return result;
}
public override void ResolveEntity()
{
_reader.ResolveEntity();
_logger.WriteLine("ResolveEntity()");
}
public override bool ReadAttributeValue()
{
var result = _reader.ReadAttributeValue();
_logger.WriteLine("ReadAttributeValue() = {0}", result);
return result;
}
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using MetroFramework.Drawing.Html.Adapters;
using MetroFramework.Drawing.Html.Adapters.Entities;
using MetroFramework.Drawing.Html.Core.Dom;
using MetroFramework.Drawing.Html.Core.Utils;
namespace MetroFramework.Drawing.Html.Core.Handlers
{
/// <summary>
/// Contains all the complex paint code to paint different style borders.
/// </summary>
internal static class BordersDrawHandler
{
#region Fields and Consts
/// <summary>
/// used for all border paint to use the same points and not create new array each time.
/// </summary>
private static readonly RPoint[] _borderPts = new RPoint[4];
#endregion
/// <summary>
/// Draws all the border of the box with respect to style, width, etc.
/// </summary>
/// <param name="g">the device to draw into</param>
/// <param name="box">the box to draw borders for</param>
/// <param name="rect">the bounding rectangle to draw in</param>
/// <param name="isFirst">is it the first rectangle of the element</param>
/// <param name="isLast">is it the last rectangle of the element</param>
public static void DrawBoxBorders(RGraphics g, CssBox box, RRect rect, bool isFirst, bool isLast)
{
if (rect.Width > 0 && rect.Height > 0)
{
if (!(string.IsNullOrEmpty(box.BorderTopStyle) || box.BorderTopStyle == CssConstants.None || box.BorderTopStyle == CssConstants.Hidden) && box.ActualBorderTopWidth > 0)
{
DrawBorder(Border.Top, box, g, rect, isFirst, isLast);
}
if (isFirst && !(string.IsNullOrEmpty(box.BorderLeftStyle) || box.BorderLeftStyle == CssConstants.None || box.BorderLeftStyle == CssConstants.Hidden) && box.ActualBorderLeftWidth > 0)
{
DrawBorder(Border.Left, box, g, rect, true, isLast);
}
if (!(string.IsNullOrEmpty(box.BorderBottomStyle) || box.BorderBottomStyle == CssConstants.None || box.BorderBottomStyle == CssConstants.Hidden) && box.ActualBorderBottomWidth > 0)
{
DrawBorder(Border.Bottom, box, g, rect, isFirst, isLast);
}
if (isLast && !(string.IsNullOrEmpty(box.BorderRightStyle) || box.BorderRightStyle == CssConstants.None || box.BorderRightStyle == CssConstants.Hidden) && box.ActualBorderRightWidth > 0)
{
DrawBorder(Border.Right, box, g, rect, isFirst, true);
}
}
}
/// <summary>
/// Draw simple border.
/// </summary>
/// <param name="border">Desired border</param>
/// <param name="g">the device to draw to</param>
/// <param name="box">Box which the border corresponds</param>
/// <param name="brush">the brush to use</param>
/// <param name="rectangle">the bounding rectangle to draw in</param>
/// <returns>Beveled border path, null if there is no rounded corners</returns>
public static void DrawBorder(Border border, RGraphics g, CssBox box, RBrush brush, RRect rectangle)
{
SetInOutsetRectanglePoints(border, box, rectangle, true, true);
g.DrawPolygon(brush, _borderPts);
}
#region Private methods
/// <summary>
/// Draw specific border (top/bottom/left/right) with the box data (style/width/rounded).<br/>
/// </summary>
/// <param name="border">desired border to draw</param>
/// <param name="box">the box to draw its borders, contain the borders data</param>
/// <param name="g">the device to draw into</param>
/// <param name="rect">the rectangle the border is enclosing</param>
/// <param name="isLineStart">Specifies if the border is for a starting line (no bevel on left)</param>
/// <param name="isLineEnd">Specifies if the border is for an ending line (no bevel on right)</param>
private static void DrawBorder(Border border, CssBox box, RGraphics g, RRect rect, bool isLineStart, bool isLineEnd)
{
var style = GetStyle(border, box);
var color = GetColor(border, box, style);
var borderPath = GetRoundedBorderPath(g, border, box, rect);
if (borderPath != null)
{
// rounded border need special path
Object prevMode = null;
if (box.HtmlContainer != null && !box.HtmlContainer.AvoidGeometryAntialias && box.IsRounded)
prevMode = g.SetAntiAliasSmoothingMode();
var pen = GetPen(g, style, color, GetWidth(border, box));
using (borderPath)
g.DrawPath(pen, borderPath);
g.ReturnPreviousSmoothingMode(prevMode);
}
else
{
// non rounded border
if (style == CssConstants.Inset || style == CssConstants.Outset)
{
// inset/outset border needs special rectangle
SetInOutsetRectanglePoints(border, box, rect, isLineStart, isLineEnd);
g.DrawPolygon(g.GetSolidBrush(color), _borderPts);
}
else
{
// solid/dotted/dashed border draw as simple line
var pen = GetPen(g, style, color, GetWidth(border, box));
switch (border)
{
case Border.Top:
g.DrawLine(pen, Math.Ceiling(rect.Left), rect.Top + box.ActualBorderTopWidth / 2, rect.Right - 1, rect.Top + box.ActualBorderTopWidth / 2);
break;
case Border.Left:
g.DrawLine(pen, rect.Left + box.ActualBorderLeftWidth / 2, Math.Ceiling(rect.Top), rect.Left + box.ActualBorderLeftWidth / 2, Math.Floor(rect.Bottom));
break;
case Border.Bottom:
g.DrawLine(pen, Math.Ceiling(rect.Left), rect.Bottom - box.ActualBorderBottomWidth / 2, rect.Right - 1, rect.Bottom - box.ActualBorderBottomWidth / 2);
break;
case Border.Right:
g.DrawLine(pen, rect.Right - box.ActualBorderRightWidth / 2, Math.Ceiling(rect.Top), rect.Right - box.ActualBorderRightWidth / 2, Math.Floor(rect.Bottom));
break;
}
}
}
}
/// <summary>
/// Set rectangle for inset/outset border as it need diagonal connection to other borders.
/// </summary>
/// <param name="border">Desired border</param>
/// <param name="b">Box which the border corresponds</param>
/// <param name="r">the rectangle the border is enclosing</param>
/// <param name="isLineStart">Specifies if the border is for a starting line (no bevel on left)</param>
/// <param name="isLineEnd">Specifies if the border is for an ending line (no bevel on right)</param>
/// <returns>Beveled border path, null if there is no rounded corners</returns>
private static void SetInOutsetRectanglePoints(Border border, CssBox b, RRect r, bool isLineStart, bool isLineEnd)
{
switch (border)
{
case Border.Top:
_borderPts[0] = new RPoint(r.Left, r.Top);
_borderPts[1] = new RPoint(r.Right, r.Top);
_borderPts[2] = new RPoint(r.Right, r.Top + b.ActualBorderTopWidth);
_borderPts[3] = new RPoint(r.Left, r.Top + b.ActualBorderTopWidth);
if (isLineEnd)
_borderPts[2].X -= b.ActualBorderRightWidth;
if (isLineStart)
_borderPts[3].X += b.ActualBorderLeftWidth;
break;
case Border.Right:
_borderPts[0] = new RPoint(r.Right - b.ActualBorderRightWidth, r.Top + b.ActualBorderTopWidth);
_borderPts[1] = new RPoint(r.Right, r.Top);
_borderPts[2] = new RPoint(r.Right, r.Bottom);
_borderPts[3] = new RPoint(r.Right - b.ActualBorderRightWidth, r.Bottom - b.ActualBorderBottomWidth);
break;
case Border.Bottom:
_borderPts[0] = new RPoint(r.Left, r.Bottom - b.ActualBorderBottomWidth);
_borderPts[1] = new RPoint(r.Right, r.Bottom - b.ActualBorderBottomWidth);
_borderPts[2] = new RPoint(r.Right, r.Bottom);
_borderPts[3] = new RPoint(r.Left, r.Bottom);
if (isLineStart)
_borderPts[0].X += b.ActualBorderLeftWidth;
if (isLineEnd)
_borderPts[1].X -= b.ActualBorderRightWidth;
break;
case Border.Left:
_borderPts[0] = new RPoint(r.Left, r.Top);
_borderPts[1] = new RPoint(r.Left + b.ActualBorderLeftWidth, r.Top + b.ActualBorderTopWidth);
_borderPts[2] = new RPoint(r.Left + b.ActualBorderLeftWidth, r.Bottom - b.ActualBorderBottomWidth);
_borderPts[3] = new RPoint(r.Left, r.Bottom);
break;
}
}
/// <summary>
/// Makes a border path for rounded borders.<br/>
/// To support rounded dotted/dashed borders we need to use arc in the border path.<br/>
/// Return null if the border is not rounded.<br/>
/// </summary>
/// <param name="g">the device to draw into</param>
/// <param name="border">Desired border</param>
/// <param name="b">Box which the border corresponds</param>
/// <param name="r">the rectangle the border is enclosing</param>
/// <returns>Beveled border path, null if there is no rounded corners</returns>
private static RGraphicsPath GetRoundedBorderPath(RGraphics g, Border border, CssBox b, RRect r)
{
RGraphicsPath path = null;
switch (border)
{
case Border.Top:
if (b.ActualCornerNw > 0 || b.ActualCornerNe > 0)
{
path = g.GetGraphicsPath();
path.Start(r.Left + b.ActualBorderLeftWidth / 2, r.Top + b.ActualBorderTopWidth / 2 + b.ActualCornerNw);
if (b.ActualCornerNw > 0)
path.ArcTo(r.Left + b.ActualBorderLeftWidth / 2 + b.ActualCornerNw, r.Top + b.ActualBorderTopWidth / 2, b.ActualCornerNw, RGraphicsPath.Corner.TopLeft);
path.LineTo(r.Right - b.ActualBorderRightWidth / 2 - b.ActualCornerNe, r.Top + b.ActualBorderTopWidth / 2);
if (b.ActualCornerNe > 0)
path.ArcTo(r.Right - b.ActualBorderRightWidth / 2, r.Top + b.ActualBorderTopWidth / 2 + b.ActualCornerNe, b.ActualCornerNe, RGraphicsPath.Corner.TopRight);
}
break;
case Border.Bottom:
if (b.ActualCornerSw > 0 || b.ActualCornerSe > 0)
{
path = g.GetGraphicsPath();
path.Start(r.Right - b.ActualBorderRightWidth / 2, r.Bottom - b.ActualBorderBottomWidth / 2 - b.ActualCornerSe);
if (b.ActualCornerSe > 0)
path.ArcTo(r.Right - b.ActualBorderRightWidth / 2 - b.ActualCornerSe, r.Bottom - b.ActualBorderBottomWidth / 2, b.ActualCornerSe, RGraphicsPath.Corner.BottomRight);
path.LineTo(r.Left + b.ActualBorderLeftWidth / 2 + b.ActualCornerSw, r.Bottom - b.ActualBorderBottomWidth / 2);
if (b.ActualCornerSw > 0)
path.ArcTo(r.Left + b.ActualBorderLeftWidth / 2, r.Bottom - b.ActualBorderBottomWidth / 2 - b.ActualCornerSw, b.ActualCornerSw, RGraphicsPath.Corner.BottomLeft);
}
break;
case Border.Right:
if (b.ActualCornerNe > 0 || b.ActualCornerSe > 0)
{
path = g.GetGraphicsPath();
bool noTop = b.BorderTopStyle == CssConstants.None || b.BorderTopStyle == CssConstants.Hidden;
bool noBottom = b.BorderBottomStyle == CssConstants.None || b.BorderBottomStyle == CssConstants.Hidden;
path.Start(r.Right - b.ActualBorderRightWidth / 2 - (noTop ? b.ActualCornerNe : 0), r.Top + b.ActualBorderTopWidth / 2 + (noTop ? 0 : b.ActualCornerNe));
if (b.ActualCornerNe > 0 && noTop)
path.ArcTo(r.Right - b.ActualBorderLeftWidth / 2, r.Top + b.ActualBorderTopWidth / 2 + b.ActualCornerNe, b.ActualCornerNe, RGraphicsPath.Corner.TopRight);
path.LineTo(r.Right - b.ActualBorderRightWidth / 2, r.Bottom - b.ActualBorderBottomWidth / 2 - b.ActualCornerSe);
if (b.ActualCornerSe > 0 && noBottom)
path.ArcTo(r.Right - b.ActualBorderRightWidth / 2 - b.ActualCornerSe, r.Bottom - b.ActualBorderBottomWidth / 2, b.ActualCornerSe, RGraphicsPath.Corner.BottomRight);
}
break;
case Border.Left:
if (b.ActualCornerNw > 0 || b.ActualCornerSw > 0)
{
path = g.GetGraphicsPath();
bool noTop = b.BorderTopStyle == CssConstants.None || b.BorderTopStyle == CssConstants.Hidden;
bool noBottom = b.BorderBottomStyle == CssConstants.None || b.BorderBottomStyle == CssConstants.Hidden;
path.Start(r.Left + b.ActualBorderLeftWidth / 2 + (noBottom ? b.ActualCornerSw : 0), r.Bottom - b.ActualBorderBottomWidth / 2 - (noBottom ? 0 : b.ActualCornerSw));
if (b.ActualCornerSw > 0 && noBottom)
path.ArcTo(r.Left + b.ActualBorderLeftWidth / 2, r.Bottom - b.ActualBorderBottomWidth / 2 - b.ActualCornerSw, b.ActualCornerSw, RGraphicsPath.Corner.BottomLeft);
path.LineTo(r.Left + b.ActualBorderLeftWidth / 2, r.Top + b.ActualBorderTopWidth / 2 + b.ActualCornerNw);
if (b.ActualCornerNw > 0 && noTop)
path.ArcTo(r.Left + b.ActualBorderLeftWidth / 2 + b.ActualCornerNw, r.Top + b.ActualBorderTopWidth / 2, b.ActualCornerNw, RGraphicsPath.Corner.TopLeft);
}
break;
}
return path;
}
/// <summary>
/// Get pen to be used for border draw respecting its style.
/// </summary>
private static RPen GetPen(RGraphics g, string style, RColor color, double width)
{
var p = g.GetPen(color);
p.Width = width;
switch (style)
{
case "solid":
p.DashStyle = RDashStyle.Solid;
break;
case "dotted":
p.DashStyle = RDashStyle.Dot;
break;
case "dashed":
p.DashStyle = RDashStyle.Dash;
break;
}
return p;
}
/// <summary>
/// Get the border color for the given box border.
/// </summary>
private static RColor GetColor(Border border, CssBoxProperties box, string style)
{
switch (border)
{
case Border.Top:
return style == CssConstants.Inset ? Darken(box.ActualBorderTopColor) : box.ActualBorderTopColor;
case Border.Right:
return style == CssConstants.Outset ? Darken(box.ActualBorderRightColor) : box.ActualBorderRightColor;
case Border.Bottom:
return style == CssConstants.Outset ? Darken(box.ActualBorderBottomColor) : box.ActualBorderBottomColor;
case Border.Left:
return style == CssConstants.Inset ? Darken(box.ActualBorderLeftColor) : box.ActualBorderLeftColor;
default:
throw new ArgumentOutOfRangeException("border");
}
}
/// <summary>
/// Get the border width for the given box border.
/// </summary>
private static double GetWidth(Border border, CssBoxProperties box)
{
switch (border)
{
case Border.Top:
return box.ActualBorderTopWidth;
case Border.Right:
return box.ActualBorderRightWidth;
case Border.Bottom:
return box.ActualBorderBottomWidth;
case Border.Left:
return box.ActualBorderLeftWidth;
default:
throw new ArgumentOutOfRangeException("border");
}
}
/// <summary>
/// Get the border style for the given box border.
/// </summary>
private static string GetStyle(Border border, CssBoxProperties box)
{
switch (border)
{
case Border.Top:
return box.BorderTopStyle;
case Border.Right:
return box.BorderRightStyle;
case Border.Bottom:
return box.BorderBottomStyle;
case Border.Left:
return box.BorderLeftStyle;
default:
throw new ArgumentOutOfRangeException("border");
}
}
/// <summary>
/// Makes the specified color darker for inset/outset borders.
/// </summary>
private static RColor Darken(RColor c)
{
return RColor.FromArgb(c.R / 2, c.G / 2, c.B / 2);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataPointer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
#pragma warning disable 618 // ignore obsolete warning about XmlDataDocument
namespace System.Xml {
using System;
using System.Data;
using System.Diagnostics;
internal sealed class DataPointer : IXmlDataVirtualNode {
private XmlDataDocument doc;
private XmlNode node;
private DataColumn column;
private bool fOnValue;
private bool bNeedFoliate = false;
private bool _isInUse;
internal DataPointer( XmlDataDocument doc, XmlNode node ) {
this.doc = doc;
this.node = node;
this.column = null;
this.fOnValue = false;
bNeedFoliate = false;
this._isInUse = true;
AssertValid();
}
internal DataPointer( DataPointer pointer ) {
this.doc = pointer.doc;
this.node = pointer.node;
this.column = pointer.column;
this.fOnValue = pointer.fOnValue;
this.bNeedFoliate = false;
this._isInUse = true;
AssertValid();
}
internal void AddPointer() {
this.doc.AddPointer( (IXmlDataVirtualNode)this );
}
// Returns the row element of the region that the pointer points into
private XmlBoundElement GetRowElement() {
//AssertValid();
XmlBoundElement rowElem;
if ( this.column != null ) {
rowElem = this.node as XmlBoundElement;
Debug.Assert( rowElem != null );
Debug.Assert( rowElem.Row != null );
return rowElem;
}
doc.Mapper.GetRegion( this.node, out rowElem );
return rowElem;
}
private DataRow Row {
get {
//AssertValid();
XmlBoundElement rowElem = GetRowElement();
if ( rowElem == null )
return null;
Debug.Assert( rowElem.Row != null );
return rowElem.Row;
}
}
private static bool IsFoliated( XmlNode node ) {
if (node != null && node is XmlBoundElement)
return((XmlBoundElement)node).IsFoliated;
return true;
}
internal void MoveTo( DataPointer pointer ) {
AssertValid();
// You should not move outside of this document
Debug.Assert( node == this.doc || node.OwnerDocument == this.doc );
this.doc = pointer.doc;
this.node = pointer.node;
this.column = pointer.column;
this.fOnValue = pointer.fOnValue;
AssertValid();
}
private void MoveTo( XmlNode node ) {
//AssertValid();
// You should not move outside of this document
Debug.Assert( node == this.doc || node.OwnerDocument == this.doc );
this.node = node;
this.column = null;
this.fOnValue = false;
AssertValid();
}
private void MoveTo( XmlNode node, DataColumn column, bool fOnValue ) {
//AssertValid();
// You should not move outside of this document
Debug.Assert( node == this.doc || node.OwnerDocument == this.doc );
this.node = node;
this.column = column;
this.fOnValue = fOnValue;
AssertValid();
}
private DataColumn NextColumn( DataRow row, DataColumn col, bool fAttribute, bool fNulls ) {
if (row.RowState == DataRowState.Deleted)
return null;
DataTable table = row.Table;
DataColumnCollection columns = table.Columns;
int iColumn = (col != null) ? col.Ordinal + 1 : 0;
int cColumns = columns.Count;
DataRowVersion rowVersion = ( row.RowState == DataRowState.Detached ) ? DataRowVersion.Proposed : DataRowVersion.Current;
for (; iColumn < cColumns; iColumn++) {
DataColumn c = columns[iColumn];
if (!doc.IsNotMapped( c ) && (c.ColumnMapping == MappingType.Attribute) == fAttribute && (fNulls || ! Convert.IsDBNull( row[c, rowVersion] ) ) )
return c;
}
return null;
}
private DataColumn NthColumn( DataRow row, bool fAttribute, int iColumn, bool fNulls ) {
DataColumn c = null;
while ((c = NextColumn( row, c, fAttribute, fNulls )) != null) {
if (iColumn == 0)
return c;
iColumn = checked((int)iColumn-1);
}
return null;
}
private int ColumnCount( DataRow row, bool fAttribute, bool fNulls ) {
DataColumn c = null;
int count = 0;
while ((c = NextColumn( row, c, fAttribute, fNulls )) != null) {
count++;
}
return count;
}
internal bool MoveToFirstChild() {
RealFoliate();
AssertValid();
if (node == null)
return false;
if (column != null) {
if (fOnValue)
return false;
fOnValue = true;
return true;
}
else if (!IsFoliated( node )) {
// find virtual column elements first
DataColumn c = NextColumn( Row, null, false, false );
if (c != null) {
MoveTo( node, c, doc.IsTextOnly(c) );
return true;
}
}
// look for anything
XmlNode n = doc.SafeFirstChild( node );
if (n != null) {
MoveTo(n);
return true;
}
return false;
}
internal bool MoveToNextSibling() {
RealFoliate();
AssertValid();
if (node != null) {
if (column != null) {
if (fOnValue && !doc.IsTextOnly(column))
return false;
DataColumn c = NextColumn( Row, column, false, false );
if (c != null) {
MoveTo( this.node, c, false );
return true;
}
XmlNode n = doc.SafeFirstChild( node );
if (n != null) {
MoveTo( n );
return true;
}
}
else {
XmlNode n = doc.SafeNextSibling( node );
if (n != null) {
MoveTo(n);
return true;
}
}
}
return false;
}
internal bool MoveToParent() {
RealFoliate();
AssertValid();
if (node != null) {
if (column != null) {
if (fOnValue && !doc.IsTextOnly(column)) {
MoveTo( node, column, false );
return true;
}
if (column.ColumnMapping != MappingType.Attribute) {
MoveTo( node, null, false );
return true;
}
}
else {
XmlNode n = node.ParentNode;
if (n != null) {
MoveTo(n);
return true;
}
}
}
return false;
}
internal bool MoveToOwnerElement() {
RealFoliate();
AssertValid();
if (node != null) {
if (column != null) {
if (fOnValue || doc.IsTextOnly(column) || column.ColumnMapping != MappingType.Attribute)
return false;
MoveTo( node, null, false );
return true;
}
else if (node.NodeType == XmlNodeType.Attribute) {
XmlNode n = ((XmlAttribute)node).OwnerElement;
if (n != null) {
MoveTo( n, null, false );
return true;
}
}
}
return false;
}
internal int AttributeCount {
get {
RealFoliate();
AssertValid();
if (node != null) {
if (column == null && node.NodeType == XmlNodeType.Element) {
if (!IsFoliated( node )) {
return ColumnCount( Row, true, false );
}
else
return node.Attributes.Count;
}
}
return 0;
}
}
internal bool MoveToAttribute( int i ) {
RealFoliate();
AssertValid();
if ( i < 0 )
return false;
if (node != null) {
if ((column == null || column.ColumnMapping == MappingType.Attribute) && node.NodeType == XmlNodeType.Element) {
if (!IsFoliated( node )) {
DataColumn c = NthColumn( Row, true, i, false );
if (c != null) {
MoveTo( node, c, false );
return true;
}
}
else {
XmlNode n = node.Attributes.Item(i);
if (n != null) {
MoveTo( n, null, false );
return true;
}
}
}
}
return false;
}
internal XmlNodeType NodeType {
get {
RealFoliate();
AssertValid();
if (this.node == null) {
return XmlNodeType.None;
}
else if (this.column == null) {
return this.node.NodeType;
}
else if (this.fOnValue) {
return XmlNodeType.Text;
}
else if (this.column.ColumnMapping == MappingType.Attribute) {
return XmlNodeType.Attribute;
}
else {
return XmlNodeType.Element;
}
}
}
internal string LocalName {
get {
RealFoliate();
AssertValid();
if (this.node == null) {
return string.Empty;
}else if (this.column == null) {
String name = node.LocalName;
Debug.Assert( name != null );
if ( IsLocalNameEmpty( this.node.NodeType ) )
return String.Empty;
return name;
}
else if (this.fOnValue) {
return String.Empty;
}
else {
return doc.NameTable.Add(column.EncodedColumnName);
}
}
}
internal string NamespaceURI {
get {
RealFoliate();
AssertValid();
if (this.node == null) {
return string.Empty;
}
else if (this.column == null) {
return node.NamespaceURI;
}
else if (this.fOnValue) {
return string.Empty;
}
else {
return doc.NameTable.Add(column.Namespace);
}
}
}
internal string Name {
get {
RealFoliate();
AssertValid();
if (this.node == null) {
return string.Empty;
}
else if (this.column == null) {
String name = node.Name;
//Again it could be String.Empty at null position
Debug.Assert( name != null );
if ( IsLocalNameEmpty( this.node.NodeType ) )
return String.Empty;
return name;
}
else {
string prefix = Prefix;
string lname = LocalName;
if (prefix != null && prefix.Length > 0) {
if (lname != null && lname.Length > 0) {
return doc.NameTable.Add( prefix + ":" + lname );
}
else {
return prefix;
}
}
else {
return lname;
}
}
}
}
private bool IsLocalNameEmpty ( XmlNodeType nt) {
switch ( nt ) {
case XmlNodeType.None :
case XmlNodeType.Text :
case XmlNodeType.CDATA :
case XmlNodeType.Comment :
case XmlNodeType.Document :
case XmlNodeType.DocumentFragment :
case XmlNodeType.Whitespace :
case XmlNodeType.SignificantWhitespace :
case XmlNodeType.EndElement :
case XmlNodeType.EndEntity :
return true;
case XmlNodeType.Element :
case XmlNodeType.Attribute :
case XmlNodeType.EntityReference :
case XmlNodeType.Entity :
case XmlNodeType.ProcessingInstruction :
case XmlNodeType.DocumentType :
case XmlNodeType.Notation :
case XmlNodeType.XmlDeclaration :
return false;
default :
return true;
}
}
internal string Prefix {
get {
RealFoliate();
AssertValid();
if (this.node == null) {
return string.Empty;
}
else if (this.column == null) {
return node.Prefix;
}
else {
return string.Empty;
}
}
}
internal string Value {
get {
RealFoliate();
AssertValid();
if (this.node == null) {
return null;
}
else if (this.column == null) {
return this.node.Value;
}
else if (this.column.ColumnMapping == MappingType.Attribute || this.fOnValue) {
DataRow row = this.Row;
DataRowVersion rowVersion = ( row.RowState == DataRowState.Detached ) ? DataRowVersion.Proposed : DataRowVersion.Current;
object value = row[ this.column, rowVersion ];
if ( ! Convert.IsDBNull( value ) )
return this.column.ConvertObjectToXml( value );
return null;
}
else {
// column element has no value
return null;
}
}
}
bool IXmlDataVirtualNode.IsOnNode( XmlNode nodeToCheck ) {
RealFoliate();
return nodeToCheck == this.node;
}
bool IXmlDataVirtualNode.IsOnColumn( DataColumn col ) {
RealFoliate();
return col == this.column;
}
internal XmlNode GetNode() {
return this.node;
}
internal bool IsEmptyElement {
get {
RealFoliate();
AssertValid();
if (node != null && column == null) {
//
if (node.NodeType == XmlNodeType.Element) {
return((XmlElement)node).IsEmpty;
}
}
return false;
}
}
internal bool IsDefault {
get {
RealFoliate();
AssertValid();
if (node != null && column == null && node.NodeType == XmlNodeType.Attribute) {
return !((XmlAttribute)node).Specified;
}
return false;
}
}
void IXmlDataVirtualNode.OnFoliated( XmlNode foliatedNode ) {
// update the pointer if the element node has been foliated
if (node == foliatedNode) {
// if already on this node, nothing to do!
if (column == null)
return;
bNeedFoliate = true;
}
}
internal void RealFoliate() {
if ( !bNeedFoliate )
return;
XmlNode n = null;
if (doc.IsTextOnly( column )) {
n = node.FirstChild;
}
else {
if (column.ColumnMapping == MappingType.Attribute) {
n = node.Attributes.GetNamedItem( column.EncodedColumnName, column.Namespace );
}
else {
for (n = node.FirstChild; n != null; n = n.NextSibling) {
if (n.LocalName == column.EncodedColumnName && n.NamespaceURI == column.Namespace)
break;
}
}
if (n != null && fOnValue)
n = n.FirstChild;
}
if (n == null)
throw new InvalidOperationException(Res.GetString(Res.DataDom_Foliation));
// Cannot use MoveTo( n ); b/c the initial state for MoveTo is invalid (region is foliated but this is not)
this.node = n;
this.column = null;
this.fOnValue = false;
AssertValid();
bNeedFoliate = false;
}
//for the 6 properties below, only when the this.column == null that the nodetype could be XmlDeclaration node
internal String PublicId {
get {
XmlNodeType nt = NodeType;
switch ( nt ) {
case XmlNodeType.DocumentType : {
Debug.Assert( this.column == null );
return ( ( XmlDocumentType ) (this.node)).PublicId;
}
case XmlNodeType.Entity : {
Debug.Assert( this.column == null );
return ( ( XmlEntity ) (this.node)).PublicId;
}
case XmlNodeType.Notation : {
Debug.Assert( this.column == null );
return ( ( XmlNotation ) (this.node)).PublicId;
}
}
return null;
}
}
internal String SystemId {
get {
XmlNodeType nt = NodeType;
switch ( nt ) {
case XmlNodeType.DocumentType : {
Debug.Assert( this.column == null );
return ( ( XmlDocumentType ) (this.node)).SystemId;
}
case XmlNodeType.Entity : {
Debug.Assert( this.column == null );
return ( ( XmlEntity ) (this.node)).SystemId;
}
case XmlNodeType.Notation : {
Debug.Assert( this.column == null );
return ( ( XmlNotation ) (this.node)).SystemId;
}
}
return null;
}
}
internal String InternalSubset {
get {
if ( NodeType == XmlNodeType.DocumentType ) {
Debug.Assert( this.column == null );
return ( ( XmlDocumentType ) (this.node)).InternalSubset;
}
return null;
}
}
internal XmlDeclaration Declaration {
get {
XmlNode child = doc.SafeFirstChild(doc);
if ( child != null && child.NodeType == XmlNodeType.XmlDeclaration )
return (XmlDeclaration)child;
return null;
}
}
internal String Encoding {
get {
if ( NodeType == XmlNodeType.XmlDeclaration ) {
Debug.Assert( this.column == null );
return ( ( XmlDeclaration ) (this.node)).Encoding;
} else if ( NodeType == XmlNodeType.Document ) {
XmlDeclaration dec = Declaration;
if ( dec != null )
return dec.Encoding;
}
return null;
}
}
internal String Standalone {
get {
if ( NodeType == XmlNodeType.XmlDeclaration ) {
Debug.Assert( this.column == null );
return ( ( XmlDeclaration ) (this.node)).Standalone;
} else if ( NodeType == XmlNodeType.Document ) {
XmlDeclaration dec = Declaration;
if ( dec != null )
return dec.Standalone;
}
return null;
}
}
internal String Version {
get {
if ( NodeType == XmlNodeType.XmlDeclaration ) {
Debug.Assert( this.column == null );
return ( ( XmlDeclaration ) (this.node)).Version;
} else if ( NodeType == XmlNodeType.Document ) {
XmlDeclaration dec = Declaration;
if ( dec != null )
return dec.Version;
}
return null;
}
}
[System.Diagnostics.Conditional("DEBUG")]
private void AssertValid() {
// This pointer must be int the document list
if ( this.column != null ) {
// We must be on a de-foliated region
XmlBoundElement rowElem = this.node as XmlBoundElement;
Debug.Assert( rowElem != null );
DataRow row = rowElem.Row;
Debug.Assert( row != null );
ElementState state = rowElem.ElementState;
Debug.Assert( state == ElementState.Defoliated, "Region is accessed using column, but it's state is FOLIATED" );
// We cannot be on a column for which the value is DBNull
DataRowVersion rowVersion = ( row.RowState == DataRowState.Detached ) ? DataRowVersion.Proposed : DataRowVersion.Current;
Debug.Assert( ! Convert.IsDBNull( row[ this.column, rowVersion ] ) );
// If we are on the Text column, we should always have fOnValue == true
Debug.Assert( (this.column.ColumnMapping == MappingType.SimpleContent) ? (this.fOnValue == true) : true );
}
}
bool IXmlDataVirtualNode.IsInUse() {
return _isInUse;
}
internal void SetNoLongerUse() {
this.node = null;
this.column = null;
this.fOnValue = false;
this.bNeedFoliate = false;
this._isInUse = false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// TopLevelDomainsOperations operations.
/// </summary>
internal partial class TopLevelDomainsOperations : IServiceOperations<WebSiteManagementClient>, ITopLevelDomainsOperations
{
/// <summary>
/// Initializes a new instance of the TopLevelDomainsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal TopLevelDomainsOperations(WebSiteManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the WebSiteManagementClient
/// </summary>
public WebSiteManagementClient Client { get; private set; }
/// <summary>
/// Get all top-level domains supported for registration.
/// </summary>
/// <remarks>
/// Get all top-level domains supported for registration.
/// </remarks>
/// <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<TopLevelDomain>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-04-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("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}/providers/Microsoft.DomainRegistration/topLevelDomains").ToString();
_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 HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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<TopLevelDomain>>();
_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<TopLevelDomain>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get details of a top-level domain.
/// </summary>
/// <remarks>
/// Get details of a top-level domain.
/// </remarks>
/// <param name='name'>
/// Name of the top-level domain.
/// </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<TopLevelDomain>> GetWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-04-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("name", name);
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}/providers/Microsoft.DomainRegistration/topLevelDomains/{name}").ToString();
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
_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 HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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<TopLevelDomain>();
_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<TopLevelDomain>(_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 legal agreements that user needs to accept before purchasing a
/// domain.
/// </summary>
/// <remarks>
/// Gets all legal agreements that user needs to accept before purchasing a
/// domain.
/// </remarks>
/// <param name='name'>
/// Name of the top-level domain.
/// </param>
/// <param name='agreementOption'>
/// Domain agreement options.
/// </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<TldLegalAgreement>>> ListAgreementsWithHttpMessagesAsync(string name, TopLevelDomainAgreementOption agreementOption, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (agreementOption == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "agreementOption");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-04-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("name", name);
tracingParameters.Add("agreementOption", agreementOption);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAgreements", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.DomainRegistration/topLevelDomains/{name}/listAgreements").ToString();
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
_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 HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(agreementOption != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(agreementOption, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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<TldLegalAgreement>>();
_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<TldLegalAgreement>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get all top-level domains supported for registration.
/// </summary>
/// <remarks>
/// Get all top-level domains supported for registration.
/// </remarks>
/// <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<TopLevelDomain>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
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<TopLevelDomain>>();
_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<TopLevelDomain>>(_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 legal agreements that user needs to accept before purchasing a
/// domain.
/// </summary>
/// <remarks>
/// Gets all legal agreements that user needs to accept before purchasing a
/// domain.
/// </remarks>
/// <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<TldLegalAgreement>>> ListAgreementsNextWithHttpMessagesAsync(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, "ListAgreementsNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// 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<TldLegalAgreement>>();
_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<TldLegalAgreement>>(_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;
}
}
}
| |
// 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.Collections.ObjectModel;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Threading;
using Microsoft.Internal;
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(destination: typeof(System.Lazy<,>))]
namespace System.ComponentModel.Composition.Hosting
{
public partial class CompositionContainer : ExportProvider, ICompositionService, IDisposable
{
private CompositionOptions _compositionOptions;
private ImportEngine _importEngine;
private ComposablePartExportProvider _partExportProvider;
private ExportProvider _rootProvider;
private IDisposable _disposableRootProvider;
private CatalogExportProvider _catalogExportProvider;
private ExportProvider _localExportProvider;
private IDisposable _disposableLocalExportProvider;
private ExportProvider _ancestorExportProvider;
private IDisposable _disposableAncestorExportProvider;
private readonly ReadOnlyCollection<ExportProvider> _providers;
private volatile bool _isDisposed = false;
private object _lock = new object();
private static ReadOnlyCollection<ExportProvider> EmptyProviders = new ReadOnlyCollection<ExportProvider>(new ExportProvider[]{});
/// <summary>
/// Initializes a new instance of the <see cref="CompositionContainer"/> class.
/// </summary>
public CompositionContainer()
: this((ComposablePartCatalog)null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompositionContainer"/> class
/// with the specified export providers.
/// </summary>
/// <param name="providers">
/// A <see cref="Array"/> of <see cref="ExportProvider"/> objects which provide
/// the <see cref="CompositionContainer"/> access to <see cref="Export"/> objects,
/// or <see langword="null"/> to set <see cref="Providers"/> to an empty
/// <see cref="ReadOnlyCollection{T}"/>.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
public CompositionContainer(params ExportProvider[] providers) :
this((ComposablePartCatalog)null, providers)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompositionContainer"/> class
/// with the specified export providers.
/// </summary>
/// <param name="compositionOPtionss">
/// <see cref="CompositionOptions"/> enumeration with flags controlling the composition.
/// </param>
/// <param name="providers">
/// A <see cref="Array"/> of <see cref="ExportProvider"/> objects which provide
/// the <see cref="CompositionContainer"/> access to <see cref="Export"/> objects,
/// or <see langword="null"/> to set <see cref="Providers"/> to an empty
/// <see cref="ReadOnlyCollection{T}"/>.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
public CompositionContainer(CompositionOptions compositionOptions, params ExportProvider[] providers) :
this((ComposablePartCatalog)null, compositionOptions, providers)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompositionContainer"/> class
/// with the specified catalog and export providers.
/// </summary>
/// <param name="providers">
/// A <see cref="Array"/> of <see cref="ExportProvider"/> objects which provide
/// the <see cref="CompositionContainer"/> access to <see cref="Export"/> objects,
/// or <see langword="null"/> to set <see cref="Providers"/> to an empty
/// <see cref="ReadOnlyCollection{T}"/>.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
public CompositionContainer(ComposablePartCatalog catalog, params ExportProvider[] providers):
this(catalog, false, providers)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompositionContainer"/> class
/// with the specified catalog and export providers.
/// </summary>
/// <param name="isThreadSafe">
/// <see cref="bool"/> indicates whether container instances are threadsafe.
/// </param>
/// <param name="providers">
/// A <see cref="Array"/> of <see cref="ExportProvider"/> objects which provide
/// the <see cref="CompositionContainer"/> access to <see cref="Export"/> objects,
/// or <see langword="null"/> to set <see cref="Providers"/> to an empty
/// <see cref="ReadOnlyCollection{T}"/>.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
public CompositionContainer(ComposablePartCatalog catalog, bool isThreadSafe, params ExportProvider[] providers)
: this(catalog, isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default, providers)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CompositionContainer"/> class
/// with the specified catalog and export providers.
/// </summary>
/// <param name="compositionSettings">
/// <see cref="CompositionOptions"/> enumeration with flags controlling the composition.
/// </param>
/// <param name="providers">
/// A <see cref="Array"/> of <see cref="ExportProvider"/> objects which provide
/// the <see cref="CompositionContainer"/> access to <see cref="Export"/> objects,
/// or <see langword="null"/> to set <see cref="Providers"/> to an empty
/// <see cref="ReadOnlyCollection{T}"/>.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
public CompositionContainer(ComposablePartCatalog catalog, CompositionOptions compositionOptions, params ExportProvider[] providers)
{
if (compositionOptions > (CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe | CompositionOptions.ExportCompositionService))
{
throw new ArgumentOutOfRangeException("compositionOptions");
}
_compositionOptions = compositionOptions;
// We always create the mutable provider
_partExportProvider = new ComposablePartExportProvider(compositionOptions);
_partExportProvider.SourceProvider = this;
// Create the catalog export provider, only if necessary
if (catalog != null)
{
_catalogExportProvider = new CatalogExportProvider(catalog, compositionOptions);
_catalogExportProvider.SourceProvider = this;
}
// Set the local export provider
if (_catalogExportProvider != null)
{
_localExportProvider = new AggregateExportProvider(_partExportProvider, _catalogExportProvider);
_disposableLocalExportProvider = _localExportProvider as IDisposable;
}
else
{
_localExportProvider = _partExportProvider;
}
// Set the ancestor export provider, if ancestors are supplied
if ((providers != null) && (providers.Length > 0))
{
// Aggregate ancestors if and only if more than one passed
if (providers.Length > 1)
{
_ancestorExportProvider = new AggregateExportProvider(providers);
_disposableAncestorExportProvider = _ancestorExportProvider as IDisposable;
}
else
{
if (providers[0] == null)
{
throw ExceptionBuilder.CreateContainsNullElement("providers");
}
_ancestorExportProvider = providers[0];
}
}
// finally set the root provider
if (_ancestorExportProvider == null)
{
// if no ancestors are passed, the local and the root are the same
_rootProvider = _localExportProvider;
}
else
{
int exportProviderCount = 1 + ((catalog != null) ? 1 : 0) + ((providers != null) ? providers.Length : 0);
ExportProvider[] rootProviders = new ExportProvider[exportProviderCount];
rootProviders[0] = _partExportProvider;
int customProviderStartIndex = 1;
if (catalog != null)
{
rootProviders[1] = _catalogExportProvider;
customProviderStartIndex = 2;
}
if (providers != null)
{
for (int i = 0; i < providers.Length; i++)
{
rootProviders[customProviderStartIndex + i] = providers[i];
}
}
_rootProvider = new AggregateExportProvider(rootProviders);
_disposableRootProvider = _rootProvider as IDisposable;
}
//Insert Composition Service
if(compositionOptions.HasFlag(CompositionOptions.ExportCompositionService))
{
this.ComposeExportedValue<ICompositionService>(new CompositionServiceShim(this));
}
_rootProvider.ExportsChanged += OnExportsChangedInternal;
_rootProvider.ExportsChanging += OnExportsChangingInternal;
_providers = (providers != null) ? new ReadOnlyCollection<ExportProvider>((ExportProvider[])providers.Clone()) : EmptyProviders;
}
internal CompositionOptions CompositionOptions
{
get
{
ThrowIfDisposed();
return _compositionOptions;
}
}
/// <summary>
/// Gets the catalog which provides the container access to exports produced
/// from composable parts.
/// </summary>
/// <value>
/// The <see cref="ComposablePartCatalog"/> which provides the
/// <see cref="CompositionContainer"/> access to exports produced from
/// <see cref="ComposablePart"/> objects. The default is <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
public ComposablePartCatalog Catalog
{
get
{
ThrowIfDisposed();
return (_catalogExportProvider != null) ? _catalogExportProvider.Catalog : null;
}
}
internal CatalogExportProvider CatalogExportProvider
{
get
{
ThrowIfDisposed();
return _catalogExportProvider;
}
}
/// <summary>
/// Gets the export providers which provide the container access to additional exports.
/// </summary>
/// <value>
/// A <see cref="ReadOnlyCollection{T}"/> of <see cref="ExportProvider"/> objects
/// which provide the <see cref="CompositionContainer"/> access to additional
/// <see cref="Export"/> objects. The default is an empty
/// <see cref="ReadOnlyCollection{T}"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
public ReadOnlyCollection<ExportProvider> Providers
{
get
{
ThrowIfDisposed();
Contract.Ensures(Contract.Result<ReadOnlyCollection<ExportProvider>>() != null);
return _providers;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!_isDisposed)
{
ExportProvider rootProvider = null;
IDisposable disposableAncestorExportProvider = null;
IDisposable disposableLocalExportProvider = null;
IDisposable disposableRootProvider = null;
ComposablePartExportProvider partExportProvider = null;
CatalogExportProvider catalogExportProvider = null;
ImportEngine importEngine = null;
lock(_lock)
{
if (!_isDisposed)
{
rootProvider = _rootProvider;
_rootProvider = null;
disposableRootProvider = _disposableRootProvider;
_disposableRootProvider = null;
disposableLocalExportProvider = _disposableLocalExportProvider ;
_disposableLocalExportProvider = null;
_localExportProvider = null;
disposableAncestorExportProvider = _disposableAncestorExportProvider;
_disposableAncestorExportProvider = null;
_ancestorExportProvider = null;
partExportProvider = _partExportProvider;
_partExportProvider = null;
catalogExportProvider = _catalogExportProvider;
_catalogExportProvider = null;
importEngine = _importEngine;
_importEngine = null;
_isDisposed = true;
}
}
if (rootProvider != null)
{
rootProvider.ExportsChanged -= OnExportsChangedInternal;
rootProvider.ExportsChanging -= OnExportsChangingInternal;
}
if (disposableRootProvider != null)
{
disposableRootProvider.Dispose();
}
if (disposableAncestorExportProvider != null)
{
disposableAncestorExportProvider.Dispose();
}
if (disposableLocalExportProvider != null)
{
disposableLocalExportProvider.Dispose();
}
if (catalogExportProvider != null)
{
catalogExportProvider.Dispose();
}
if (partExportProvider != null)
{
partExportProvider.Dispose();
}
if (importEngine != null)
{
importEngine.Dispose();
}
}
}
}
public void Compose(CompositionBatch batch)
{
Requires.NotNull(batch, nameof(batch));
ThrowIfDisposed();
_partExportProvider.Compose(batch);
}
/// <summary>
/// Releases the <see cref="Export"/> from the <see cref="CompositionContainer"/>. The behavior
/// may vary depending on the implementation of the <see cref="ExportProvider"/> that produced
/// the <see cref="Export"/> instance. As a general rule non shared exports should be early
/// released causing them to be detached from the container.
///
/// For example the <see cref="CatalogExportProvider"/> will only release
/// an <see cref="Export"/> if it comes from a <see cref="ComposablePart"/> that was constructed
/// under a <see cref="CreationPolicy.NonShared" /> context. Release in this context means walking
/// the dependency chain of the <see cref="Export"/>s, detaching references from the container and
/// calling Dispose on the <see cref="ComposablePart"/>s as needed. If the <see cref="Export"/>
/// was constructed under a <see cref="CreationPolicy.Shared" /> context the
/// <see cref="CatalogExportProvider"/> will do nothing as it may be in use by other requestors.
/// Those will only be detached when the container is itself disposed.
/// </summary>
/// <param name="export"><see cref="Export"/> that needs to be released.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="export"/> is <see langword="null"/>.
/// </exception>
[SuppressMessage("Microsoft.Performance", "CA1822")]
public void ReleaseExport(Export export)
{
Requires.NotNull(export, nameof(export));
IDisposable dependency = export as IDisposable;
if (dependency != null)
{
dependency.Dispose();
}
}
/// <summary>
/// Releases the <see cref="Lazy{T}"/> from the <see cref="CompositionContainer"/>. The behavior
/// may vary depending on the implementation of the <see cref="ExportProvider"/> that produced
/// the <see cref="Export"/> instance. As a general rule non shared exports should be early
/// released causing them to be detached from the container.
///
/// For example the <see cref="CatalogExportProvider"/> will only release
/// an <see cref="Lazy{T}"/> if it comes from a <see cref="ComposablePart"/> that was constructed
/// under a <see cref="CreationPolicy.NonShared" /> context. Release in this context means walking
/// the dependency chain of the <see cref="Export"/>s, detaching references from the container and
/// calling Dispose on the <see cref="ComposablePart"/>s as needed. If the <see cref="Export"/>
/// was constructed under a <see cref="CreationPolicy.Shared" /> context the
/// <see cref="CatalogExportProvider"/> will do nothing as it may be in use by other requestors.
/// Those will only be detached when the container is itself disposed.
/// </summary>
/// <param name="export"><see cref="Export"/> that needs to be released.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="export"/> is <see langword="null"/>.
/// </exception>
[SuppressMessage("Microsoft.Performance", "CA1822")]
public void ReleaseExport<T>(Lazy<T> export)
{
Requires.NotNull(export, nameof(export));
IDisposable dependency = export as IDisposable;
if (dependency != null)
{
dependency.Dispose();
}
}
/// <summary>
/// Releases a set of <see cref="Export"/>s from the <see cref="CompositionContainer"/>.
/// See also <see cref="ReleaseExport"/>.
/// </summary>
/// <param name="exports"><see cref="Export"/>s that need to be released.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="exports"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="exports"/> contains an element that is <see langword="null"/>.
/// </exception>
public void ReleaseExports(IEnumerable<Export> exports)
{
Requires.NotNullOrNullElements(exports, "exports");
foreach (Export export in exports)
{
ReleaseExport(export);
}
}
/// <summary>
/// Releases a set of <see cref="Export"/>s from the <see cref="CompositionContainer"/>.
/// See also <see cref="ReleaseExport"/>.
/// </summary>
/// <param name="exports"><see cref="Export"/>s that need to be released.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="exports"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="exports"/> contains an element that is <see langword="null"/>.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public void ReleaseExports<T>(IEnumerable<Lazy<T>> exports)
{
Requires.NotNullOrNullElements(exports, "exports");
foreach (Lazy<T> export in exports)
{
ReleaseExport(export);
}
}
/// <summary>
/// Releases a set of <see cref="Export"/>s from the <see cref="CompositionContainer"/>.
/// See also <see cref="ReleaseExport"/>.
/// </summary>
/// <param name="exports"><see cref="Export"/>s that need to be released.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="exports"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="exports"/> contains an element that is <see langword="null"/>.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public void ReleaseExports<T, TMetadataView>(IEnumerable<Lazy<T, TMetadataView>> exports)
{
Requires.NotNullOrNullElements(exports, "exports");
foreach (Lazy<T, TMetadataView> export in exports)
{
ReleaseExport(export);
}
}
/// <summary>
/// Sets the imports of the specified composable part exactly once and they will not
/// ever be recomposed.
/// </summary>
/// <param name="part">
/// The <see cref="ComposablePart"/> to set the imports.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="part"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="CompositionException">
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="ICompositionService"/> has been disposed of.
/// </exception>
public void SatisfyImportsOnce(ComposablePart part)
{
ThrowIfDisposed();
if (_importEngine == null)
{
ImportEngine importEngine = new ImportEngine(this, _compositionOptions);
lock(_lock)
{
if (_importEngine == null)
{
Thread.MemoryBarrier();
_importEngine = importEngine;
importEngine = null;
}
}
if(importEngine != null)
{
importEngine.Dispose();
}
}
_importEngine.SatisfyImportsOnce(part);
}
internal void OnExportsChangedInternal(object sender, ExportsChangeEventArgs e)
{
OnExportsChanged(e);
}
internal void OnExportsChangingInternal(object sender, ExportsChangeEventArgs e)
{
OnExportsChanging(e);
}
/// <summary>
/// Returns all exports that match the conditions of the specified import.
/// </summary>
/// <param name="definition">The <see cref="ImportDefinition"/> that defines the conditions of the
/// <see cref="Export"/> to get.</param>
/// <returns></returns>
/// <result>
/// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
/// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
/// empty <see cref="IEnumerable{T}"/>.
/// </result>
/// <remarks>
/// <note type="inheritinfo">
/// The implementers should not treat the cardinality-related mismatches as errors, and are not
/// expected to throw exceptions in those cases.
/// For instance, if the import requests exactly one export and the provider has no matching exports or more than one,
/// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
/// </note>
/// </remarks>
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
IEnumerable<Export> exports = null;
object source;
if(!definition.Metadata.TryGetValue(CompositionConstants.ImportSourceMetadataName, out source))
{
source = ImportSource.Any;
}
switch((ImportSource)source)
{
case ImportSource.Any:
Assumes.NotNull(_rootProvider);
_rootProvider.TryGetExports(definition, atomicComposition, out exports);
break;
case ImportSource.Local:
Assumes.NotNull(_localExportProvider);
_localExportProvider.TryGetExports(definition.RemoveImportSource(), atomicComposition, out exports);
break;
case ImportSource.NonLocal:
if(_ancestorExportProvider != null)
{
_ancestorExportProvider.TryGetExports(definition.RemoveImportSource(), atomicComposition, out exports);
}
break;
}
return exports;
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using Gallio.Common.Collections;
namespace Gallio.Common.Reflection.Impl
{
/// <summary>
/// A type substitution specifies how generic parameters are replaced by other types.
/// It is used by implementors of <see cref="StaticReflectionPolicy" /> when returning
/// types that may be represented as generic parameters.
/// </summary>
public struct StaticTypeSubstitution : IEquatable<StaticTypeSubstitution>
{
private readonly IDictionary<StaticGenericParameterWrapper, ITypeInfo> replacements;
/// <summary>
/// Gets the empty type substitution.
/// </summary>
public static readonly StaticTypeSubstitution Empty = new StaticTypeSubstitution(EmptyDictionary<StaticGenericParameterWrapper, ITypeInfo>.Instance);
private StaticTypeSubstitution(IDictionary<StaticGenericParameterWrapper, ITypeInfo> replacements)
{
this.replacements = replacements;
}
/// <summary>
/// Returns true if the type substitution does not contain any replacements.
/// </summary>
public bool IsEmpty
{
get { return replacements.Count == 0; }
}
/// <summary>
/// Applies a type substitution to the specified type.
/// </summary>
/// <param name="type">The type to substitute.</param>
/// <returns>The substituted type.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="type"/> is null.</exception>
public ITypeInfo Apply(StaticTypeWrapper type)
{
if (type == null)
throw new ArgumentNullException("type");
if (IsEmpty)
return type;
return type.ApplySubstitution(this);
}
/// <summary>
/// Applies a type substitution to the specified generic parameter.
/// </summary>
/// <param name="type">The generic parameter to substitute.</param>
/// <returns>The substituted type.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="type"/> is null.</exception>
public ITypeInfo Apply(StaticGenericParameterWrapper type)
{
if (type == null)
throw new ArgumentNullException("type");
ITypeInfo replacement;
if (replacements.TryGetValue(type, out replacement))
return replacement;
return type;
}
/// <summary>
/// Applies a type substitution to the specified list of types.
/// </summary>
/// <param name="types">The types to substitute.</param>
/// <returns>The substituted types.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="types"/> is null.</exception>
public IList<ITypeInfo> ApplyAll<T>(IList<T> types)
where T : StaticTypeWrapper
{
if (types == null)
throw new ArgumentNullException("types");
if (IsEmpty)
return new CovariantList<T, ITypeInfo>(types);
int count = types.Count;
ITypeInfo[] result = new ITypeInfo[count];
for (int i = 0; i < count; i++)
result[i] = types[i].ApplySubstitution(this);
return result;
}
/// <summary>
/// Returns a new substitution with the specified generic parameters replaced by their respective generic arguments.
/// </summary>
/// <remarks>
/// <para>
/// The extended type substitution is normalized so that generic parameters that
/// are idempotently replaced with themselves are excluded from the substitution altogether.
/// </para>
/// </remarks>
/// <param name="genericParameters">The generic parameters.</param>
/// <param name="genericArguments">The generic arguments.</param>
/// <returns>The resulting substitution.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="genericParameters"/> or <paramref name="genericArguments"/> is null
/// or contain nulls.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="genericArguments"/> does not have the same
/// number of elements as <paramref name="genericParameters"/>.</exception>
public StaticTypeSubstitution Extend(IList<StaticGenericParameterWrapper> genericParameters, IList<ITypeInfo> genericArguments)
{
if (genericParameters == null)
throw new ArgumentNullException("genericParameters");
if (genericArguments == null)
throw new ArgumentNullException("genericArguments");
int count = genericParameters.Count;
if (genericArguments.Count != count)
throw new ArgumentException("The generic argument count does not equal the generic parameter count.", "genericArguments");
if (count == 0)
return this;
var newReplacements = new Dictionary<StaticGenericParameterWrapper, ITypeInfo>(replacements);
for (int i = 0; i < count; i++)
{
StaticGenericParameterWrapper genericParameter = genericParameters[i];
if (genericParameter == null)
throw new ArgumentNullException("genericParameters", "The generic parameters list should not contain null values.");
ITypeInfo genericArgument = genericArguments[i];
if (genericArgument == null)
throw new ArgumentNullException("genericArguments", "The generic arguments list should not contain null values.");
if (! genericParameter.Equals(genericArgument))
newReplacements[genericParameter] = genericArgument;
}
return new StaticTypeSubstitution(newReplacements);
}
/// <summary>
/// Returns a new substitution formed by composing this substitution with the specified one.
/// That is to say, each replacement type in this substitution is replaced as described
/// in the specified substitution.
/// </summary>
/// <param name="substitution">The substitution to compose.</param>
/// <returns>The new substitution.</returns>
public StaticTypeSubstitution Compose(StaticTypeSubstitution substitution)
{
if (substitution.IsEmpty)
return this;
Dictionary<StaticGenericParameterWrapper, ITypeInfo> newReplacements = new Dictionary<StaticGenericParameterWrapper, ITypeInfo>(replacements.Count);
foreach (KeyValuePair<StaticGenericParameterWrapper, ITypeInfo> entry in replacements)
{
StaticTypeWrapper replacementType = entry.Value as StaticTypeWrapper;
if (replacementType != null)
newReplacements.Add(entry.Key, substitution.Apply(replacementType));
else
newReplacements.Add(entry.Key, entry.Value);
}
return new StaticTypeSubstitution(newReplacements);
}
/// <summary>
/// Returns true if this substitution does not contain any of the specified generic parameters.
/// </summary>
/// <param name="genericParameters">The generic parameters.</param>
/// <returns>True if none of the generic parameters are in the substitution.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="genericParameters"/> is null.</exception>
public bool DoesNotContainAny(IList<StaticGenericParameterWrapper> genericParameters)
{
if (genericParameters == null)
throw new ArgumentNullException("genericParameters");
foreach (StaticGenericParameterWrapper genericParameter in genericParameters)
if (replacements.ContainsKey(genericParameter))
return false;
return true;
}
/// <summary>
/// Compares two static type substitutions for equality.
/// </summary>
/// <param name="a">The first substitution.</param>
/// <param name="b">The second substitution.</param>
/// <returns>True if the substitutions are equal.</returns>
public static bool operator==(StaticTypeSubstitution a, StaticTypeSubstitution b)
{
return a.Equals(b);
}
/// <summary>
/// Compares two static type substitutions for inequality.
/// </summary>
/// <param name="a">The first substitution.</param>
/// <param name="b">The second substitution.</param>
/// <returns>True if the substitutions are equal.</returns>
public static bool operator !=(StaticTypeSubstitution a, StaticTypeSubstitution b)
{
return ! a.Equals(b);
}
/// <inheritdoc />
public bool Equals(StaticTypeSubstitution other)
{
return replacements == other.replacements || GenericCollectionUtils.KeyValuePairsEqual(replacements, other.replacements);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return obj is StaticTypeSubstitution && Equals((StaticTypeSubstitution)obj);
}
/// <inheritdoc />
public override int GetHashCode()
{
// Note: This operation is not currently used.
return 0;
}
}
}
| |
using NUnit.Framework;
using RefactoringEssentials.CSharp.Diagnostics;
namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
[TestFixture]
[Ignore("TODO: Issue not ported yet")]
public class ReplaceWithStringIsNullOrEmptyTests : CSharpDiagnosticTestBase
{
[Test]
public void TestInspectorCaseNS1()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (str != null && str != """")
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseNS2()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (null != str && str != """")
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorNegatedStringEmpty()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (null != str && str != string.Empty)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorStringEmpty()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (null == str || str == string.Empty)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseNS3()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (null != str && """" != str)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseNS4()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (str != null && str != """")
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseSN1()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (str != """" && str != null)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseSN2()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if ("""" != str && str != null)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseSN3()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if ("""" != str && null != str)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseSN4()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (str != """" && null != str)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseNS5()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (str == null || str == """")
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseNS6()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (null == str || str == """")
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseNS7()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (null == str || """" == str)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseNS8()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (str == null || """" == str)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseSN5()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (str == """" || str == null)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseSN6()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if ("""" == str || str == null)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseSN7()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if ("""" == str || null == str)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestInspectorCaseSN8()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (str == """" || null == str)
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[TestCase("str == null || str.Length == 0")]
[TestCase("str == null || 0 == str.Length")]
[TestCase("null == str || str.Length == 0")]
[TestCase("null == str || 0 == str.Length")]
public void TestInspectorCaseNL(string expression)
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (" + expression + @")
;
}
}", @"class Foo
{
void Bar (string str)
{
if (string.IsNullOrEmpty (str))
;
}
}");
}
[TestCase("str != null && str.Length != 0")]
[TestCase("str != null && 0 != str.Length")]
[TestCase("str != null && str.Length > 0")]
[TestCase("null != str && str.Length != 0")]
[TestCase("null != str && 0 != str.Length")]
[TestCase("null != str && str.Length > 0")]
public void TestInspectorCaseLN(string expression)
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if (" + expression + @")
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
[Test]
public void TestArrays()
{
Analyze<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar ()
{
int[] foo = new int[10];
if (foo == null || foo.Length == 0) {
}
}
}");
}
[Test]
public void TestInspectorCaseNS1WithParentheses()
{
Test<ReplaceWithStringIsNullOrEmptyAnalyzer>(@"class Foo
{
void Bar (string str)
{
if ((str != null) && (str) != """")
;
}
}", @"class Foo
{
void Bar (string str)
{
if (!string.IsNullOrEmpty (str))
;
}
}");
}
}
}
| |
using IrcClientCore;
using IrcClientCore.Commands;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;
using WinIRC.Handlers;
using WinIRC.Views;
namespace WinIRC.Ui
{
public partial class UserRightClickMenu
{
private CommandManager commands;
private string channel;
public string UserSelected { get; set; }
public int UserClickBehaviour { get; private set; }
public UserRightClickMenu()
{
this.InitializeComponent();
if (Config.Contains(Config.UserListClick))
{
UserClickBehaviour = Config.GetInt(Config.UserListClick);
}
}
private void MenuFlyout_Opened(object sender, object e)
{
var flyout = sender as MenuFlyout;
if (flyout.Target is ChannelView)
{
var view = (ChannelView)flyout.Target;
commands = IrcUiHandler.Instance.connectedServers[view.Server].CommandManager;
channel = view.Channel;
}
else
{
commands = MainPage.instance.GetCurrentServer().CommandManager;
channel = MainPage.instance.currentChannel;
}
UsernameItem.Text = UserSelected;
}
private void UsernameItem_Click(object sender, RoutedEventArgs e)
{
var msgEntry = MainPage.instance.GetInputBox();
if (msgEntry == null) return;
if (msgEntry.Text == "")
{
msgEntry.Text = UserSelected + ": ";
}
else
{
msgEntry.Text += UserSelected + " ";
}
}
private string GetUser(RoutedEventArgs e)
{
var user = "";
if (e.OriginalSource is TextBlock)
{
TextBlock selectedItem = (TextBlock)e.OriginalSource;
if (selectedItem.DataContext is User)
{
user = ((User)selectedItem.DataContext).Nick;
}
if (selectedItem.DataContext is Message)
{
var msg = ((Message)selectedItem.DataContext);
user = msg.User;
channel = msg.Channel;
}
}
else if (e.OriginalSource is ListViewItemPresenter)
{
ListViewItemPresenter selectedItem = (ListViewItemPresenter)e.OriginalSource;
user = ((User)selectedItem.DataContext).Nick;
}
return user;
}
public void User_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
UserSelected = GetUser(e).Replace("@", "").Replace("+", "");
ShowContextMenu(null, e.GetPosition(null));
e.Handled = true;
}
private void ShowContextMenu(UIElement target, Point offset)
{
if (UserSelected == "") return;
var RightClick = this["UserContextMenu"] as MenuFlyout;
System.Diagnostics.Debug.WriteLine("MenuFlyout shown '{0}', '{1}'", target, offset);
RightClick.ShowAt(target, offset);
Style s = new Windows.UI.Xaml.Style { TargetType = typeof(MenuFlyoutPresenter) };
s.Setters.Add(new Setter(FrameworkElement.RequestedThemeProperty, Config.GetBoolean(Config.DarkTheme) ? ElementTheme.Dark : ElementTheme.Light));
RightClick.MenuFlyoutPresenterStyle = s;
}
public void User_Tapped(object sender, TappedRoutedEventArgs e)
{
UserSelected = GetUser(e).Replace("@", "").Replace("+", "");
if (Config.Contains(Config.UserListClick))
{
UserClickBehaviour = Config.GetInt(Config.UserListClick);
}
if (UserClickBehaviour == 0)
{
var msgEntry = MainPage.instance.GetInputBox();
if (msgEntry == null) return;
if (msgEntry.Text == "")
{
msgEntry.Text = UserSelected + ": ";
}
else
{
msgEntry.Text += UserSelected + " ";
}
}
else if (UserClickBehaviour == 1)
{
SendPrivateMessage();
}
else if (UserClickBehaviour == 2)
{
ShowContextMenu(null, e.GetPosition(null));
}
}
private void SendMessageItem_Click(object sender, RoutedEventArgs e)
{
SendPrivateMessage();
}
private void SendPrivateMessage()
{
if (commands == null) return;
commands.HandleCommand(channel, "/query " + UserSelected);
}
private void WhoisItem_Click(object sender, RoutedEventArgs e)
{
commands.HandleCommand(channel, "/whois " + UserSelected);
}
private void OpItem_Click(object sender, RoutedEventArgs e)
{
commands.HandleCommand(channel, "/op " + UserSelected);
}
private void DeopItem_Click(object sender, RoutedEventArgs e)
{
commands.HandleCommand(channel, "/deop " + UserSelected);
}
private void VoiceItem_Click(object sender, RoutedEventArgs e)
{
commands.HandleCommand(channel, "/voice " + UserSelected);
}
private void DevoiceItem_Click(object sender, RoutedEventArgs e)
{
commands.HandleCommand(channel, "/devoice " + UserSelected);
}
private void MuteItem_Click(object sender, RoutedEventArgs e)
{
commands.HandleCommand(channel, "/mute " + UserSelected);
}
private void UnmuteItem_Click(object sender, RoutedEventArgs e)
{
commands.HandleCommand(channel, "/unmute " + UserSelected);
}
private void KickItem_Click(object sender, RoutedEventArgs e)
{
commands.HandleCommand(channel, "/kick " + UserSelected);
}
private void BanItem_Click(object sender, RoutedEventArgs e)
{
commands.HandleCommand(channel, "/ban " + UserSelected);
commands.HandleCommand(channel, "/kick " + UserSelected);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="DropShadowEffect.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.Collections;
using MS.Internal.KnownBoxes;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media.Effects
{
sealed partial class DropShadowEffect : Effect
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new DropShadowEffect Clone()
{
return (DropShadowEffect)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new DropShadowEffect CloneCurrentValue()
{
return (DropShadowEffect)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void ShadowDepthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowEffect target = ((DropShadowEffect) d);
target.PropertyChanged(ShadowDepthProperty);
}
private static void ColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowEffect target = ((DropShadowEffect) d);
target.PropertyChanged(ColorProperty);
}
private static void DirectionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowEffect target = ((DropShadowEffect) d);
target.PropertyChanged(DirectionProperty);
}
private static void OpacityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowEffect target = ((DropShadowEffect) d);
target.PropertyChanged(OpacityProperty);
}
private static void BlurRadiusPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowEffect target = ((DropShadowEffect) d);
target.PropertyChanged(BlurRadiusProperty);
}
private static void RenderingBiasPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowEffect target = ((DropShadowEffect) d);
target.PropertyChanged(RenderingBiasProperty);
}
#region Public Properties
/// <summary>
/// ShadowDepth - double. Default value is 5.0.
/// </summary>
public double ShadowDepth
{
get
{
return (double) GetValue(ShadowDepthProperty);
}
set
{
SetValueInternal(ShadowDepthProperty, value);
}
}
/// <summary>
/// Color - Color. Default value is Colors.Black.
/// </summary>
public Color Color
{
get
{
return (Color) GetValue(ColorProperty);
}
set
{
SetValueInternal(ColorProperty, value);
}
}
/// <summary>
/// Direction - double. Default value is 315.0.
/// </summary>
public double Direction
{
get
{
return (double) GetValue(DirectionProperty);
}
set
{
SetValueInternal(DirectionProperty, value);
}
}
/// <summary>
/// Opacity - double. Default value is 1.0.
/// </summary>
public double Opacity
{
get
{
return (double) GetValue(OpacityProperty);
}
set
{
SetValueInternal(OpacityProperty, value);
}
}
/// <summary>
/// BlurRadius - double. Default value is 5.0.
/// </summary>
public double BlurRadius
{
get
{
return (double) GetValue(BlurRadiusProperty);
}
set
{
SetValueInternal(BlurRadiusProperty, value);
}
}
/// <summary>
/// RenderingBias - RenderingBias. Default value is RenderingBias.Performance.
/// </summary>
public RenderingBias RenderingBias
{
get
{
return (RenderingBias) GetValue(RenderingBiasProperty);
}
set
{
SetValueInternal(RenderingBiasProperty, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new DropShadowEffect();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data.It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
// If we're told we can skip the channel check, then we must be on channel
Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));
if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
{
base.UpdateResource(channel, skipOnChannelCheck);
// Obtain handles for animated properties
DUCE.ResourceHandle hShadowDepthAnimations = GetAnimationResourceHandle(ShadowDepthProperty, channel);
DUCE.ResourceHandle hColorAnimations = GetAnimationResourceHandle(ColorProperty, channel);
DUCE.ResourceHandle hDirectionAnimations = GetAnimationResourceHandle(DirectionProperty, channel);
DUCE.ResourceHandle hOpacityAnimations = GetAnimationResourceHandle(OpacityProperty, channel);
DUCE.ResourceHandle hBlurRadiusAnimations = GetAnimationResourceHandle(BlurRadiusProperty, channel);
// Pack & send command packet
DUCE.MILCMD_DROPSHADOWEFFECT data;
unsafe
{
data.Type = MILCMD.MilCmdDropShadowEffect;
data.Handle = _duceResource.GetHandle(channel);
if (hShadowDepthAnimations.IsNull)
{
data.ShadowDepth = ShadowDepth;
}
data.hShadowDepthAnimations = hShadowDepthAnimations;
if (hColorAnimations.IsNull)
{
data.Color = CompositionResourceManager.ColorToMilColorF(Color);
}
data.hColorAnimations = hColorAnimations;
if (hDirectionAnimations.IsNull)
{
data.Direction = Direction;
}
data.hDirectionAnimations = hDirectionAnimations;
if (hOpacityAnimations.IsNull)
{
data.Opacity = Opacity;
}
data.hOpacityAnimations = hOpacityAnimations;
if (hBlurRadiusAnimations.IsNull)
{
data.BlurRadius = BlurRadius;
}
data.hBlurRadiusAnimations = hBlurRadiusAnimations;
data.RenderingBias = RenderingBias;
// Send packed command structure
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_DROPSHADOWEFFECT));
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_DROPSHADOWEFFECT))
{
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
ReleaseOnChannelAnimations(channel);
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the DropShadowEffect.ShadowDepth property.
/// </summary>
public static readonly DependencyProperty ShadowDepthProperty;
/// <summary>
/// The DependencyProperty for the DropShadowEffect.Color property.
/// </summary>
public static readonly DependencyProperty ColorProperty;
/// <summary>
/// The DependencyProperty for the DropShadowEffect.Direction property.
/// </summary>
public static readonly DependencyProperty DirectionProperty;
/// <summary>
/// The DependencyProperty for the DropShadowEffect.Opacity property.
/// </summary>
public static readonly DependencyProperty OpacityProperty;
/// <summary>
/// The DependencyProperty for the DropShadowEffect.BlurRadius property.
/// </summary>
public static readonly DependencyProperty BlurRadiusProperty;
/// <summary>
/// The DependencyProperty for the DropShadowEffect.RenderingBias property.
/// </summary>
public static readonly DependencyProperty RenderingBiasProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
internal const double c_ShadowDepth = 5.0;
internal static Color s_Color = Colors.Black;
internal const double c_Direction = 315.0;
internal const double c_Opacity = 1.0;
internal const double c_BlurRadius = 5.0;
internal const RenderingBias c_RenderingBias = RenderingBias.Performance;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static DropShadowEffect()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
// Initializations
Type typeofThis = typeof(DropShadowEffect);
ShadowDepthProperty =
RegisterProperty("ShadowDepth",
typeof(double),
typeofThis,
5.0,
new PropertyChangedCallback(ShadowDepthPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
ColorProperty =
RegisterProperty("Color",
typeof(Color),
typeofThis,
Colors.Black,
new PropertyChangedCallback(ColorPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
DirectionProperty =
RegisterProperty("Direction",
typeof(double),
typeofThis,
315.0,
new PropertyChangedCallback(DirectionPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
OpacityProperty =
RegisterProperty("Opacity",
typeof(double),
typeofThis,
1.0,
new PropertyChangedCallback(OpacityPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
BlurRadiusProperty =
RegisterProperty("BlurRadius",
typeof(double),
typeofThis,
5.0,
new PropertyChangedCallback(BlurRadiusPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
RenderingBiasProperty =
RegisterProperty("RenderingBias",
typeof(RenderingBias),
typeofThis,
RenderingBias.Performance,
new PropertyChangedCallback(RenderingBiasPropertyChanged),
new ValidateValueCallback(System.Windows.Media.Effects.ValidateEnums.IsRenderingBiasValid),
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using UnityEngine;
namespace Twitter
{
public class RequestTokenResponse
{
public string Token { get; set; }
public string TokenSecret { get; set; }
}
public class AccessTokenResponse
{
public string Token { get; set; }
public string TokenSecret { get; set; }
public string UserId { get; set; }
public string ScreenName { get; set; }
}
public delegate void RequestTokenCallback(bool success, RequestTokenResponse response);
public delegate void AccessTokenCallback(bool success, AccessTokenResponse response);
public delegate void PostTweetCallback(bool success);
public class API
{
#region OAuth Token Methods
// 1. Get Request-Token From Twitter
// 2. Get PIN from User
// 3. Get Access-Token from Twitter
// 4. Use Accss-Token for APIs requriring OAuth
// Accss-Token will be always valid until the user revokes the access to your application.
// Twitter APIs for OAuth process
private static readonly string RequestTokenURL = "https://api.twitter.com/oauth/request_token";
private static readonly string AuthorizationURL = "https://api.twitter.com/oauth/authenticate?oauth_token={0}";
private static readonly string AccessTokenURL = "https://api.twitter.com/oauth/access_token";
public static IEnumerator GetRequestToken(string consumerKey, string consumerSecret, RequestTokenCallback callback)
{
WWW web = WWWRequestToken(consumerKey, consumerSecret);
yield return web;
if (!string.IsNullOrEmpty(web.error))
{
Debug.Log(string.Format("GetRequestToken - failed. error : {0}", web.error));
callback(false, null);
}
else
{
RequestTokenResponse response = new RequestTokenResponse
{
Token = Regex.Match(web.text, @"oauth_token=([^&]+)").Groups[1].Value,
TokenSecret = Regex.Match(web.text, @"oauth_token_secret=([^&]+)").Groups[1].Value,
};
if (!string.IsNullOrEmpty(response.Token) &&
!string.IsNullOrEmpty(response.TokenSecret))
{
callback(true, response);
}
else
{
Debug.Log(string.Format("GetRequestToken - failed. response : {0}", web.text));
callback(false, null);
}
}
}
public static void OpenAuthorizationPage(string requestToken)
{
Application.OpenURL(string.Format(AuthorizationURL, requestToken));
}
public static IEnumerator GetAccessToken(string consumerKey, string consumerSecret, string requestToken, string pin, AccessTokenCallback callback)
{
WWW web = WWWAccessToken(consumerKey, consumerSecret, requestToken, pin);
yield return web;
if (!string.IsNullOrEmpty(web.error))
{
Debug.Log(string.Format("GetAccessToken - failed. error : {0}", web.error));
callback(false, null);
}
else
{
AccessTokenResponse response = new AccessTokenResponse
{
Token = Regex.Match(web.text, @"oauth_token=([^&]+)").Groups[1].Value,
TokenSecret = Regex.Match(web.text, @"oauth_token_secret=([^&]+)").Groups[1].Value,
UserId = Regex.Match(web.text, @"user_id=([^&]+)").Groups[1].Value,
ScreenName = Regex.Match(web.text, @"screen_name=([^&]+)").Groups[1].Value
};
if (!string.IsNullOrEmpty(response.Token) &&
!string.IsNullOrEmpty(response.TokenSecret) &&
!string.IsNullOrEmpty(response.UserId) &&
!string.IsNullOrEmpty(response.ScreenName))
{
callback(true, response);
}
else
{
Debug.Log(string.Format("GetAccessToken - failed. response : {0}", web.text));
callback(false, null);
}
}
}
private static WWW WWWRequestToken(string consumerKey, string consumerSecret)
{
// Add data to the form to post.
WWWForm form = new WWWForm();
form.AddField("oauth_callback", "oob");
// HTTP header
Dictionary<string, string> parameters = new Dictionary<string, string>();
AddDefaultOAuthParams(parameters, consumerKey, consumerSecret);
parameters.Add("oauth_callback", "oob");
var headers = new Dictionary<string, string>();
headers["Authorization"] = GetFinalOAuthHeader("POST", RequestTokenURL, parameters);
return new WWW(RequestTokenURL, form.data, headers);
}
private static WWW WWWAccessToken(string consumerKey, string consumerSecret, string requestToken, string pin)
{
// Need to fill body since Unity doesn't like an empty request body.
byte[] dummmy = new byte[1];
dummmy[0] = 0;
// HTTP header
var headers = new Dictionary<string, string>();
Dictionary<string, string> parameters = new Dictionary<string, string>();
AddDefaultOAuthParams(parameters, consumerKey, consumerSecret);
parameters.Add("oauth_token", requestToken);
parameters.Add("oauth_verifier", pin);
headers["Authorization"] = GetFinalOAuthHeader("POST", AccessTokenURL, parameters);
return new WWW(AccessTokenURL, dummmy, headers);
}
private static string GetHeaderWithAccessToken(string httpRequestType, string apiURL, string consumerKey, string consumerSecret, AccessTokenResponse response, Dictionary<string, string> parameters)
{
AddDefaultOAuthParams(parameters, consumerKey, consumerSecret);
parameters.Add("oauth_token", response.Token);
parameters.Add("oauth_token_secret", response.TokenSecret);
return GetFinalOAuthHeader(httpRequestType, apiURL, parameters);
}
#endregion
#region Twitter API Methods
private const string PostTweetURL = "https://api.twitter.com/1.1/statuses/update.json";
public static IEnumerator PostTweet(string text, string consumerKey, string consumerSecret, AccessTokenResponse response, PostTweetCallback callback)
{
if (string.IsNullOrEmpty(text) || text.Length > 140)
{
Debug.Log(string.Format("PostTweet - text[{0}] is empty or too long.", text));
callback(false);
}
else
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("status", text);
// Add data to the form to post.
WWWForm form = new WWWForm();
form.AddField("status", text);
// HTTP header
var headers = new Dictionary<string, string>();
headers["Authorization"] = GetHeaderWithAccessToken("POST", PostTweetURL, consumerKey, consumerSecret, response, parameters);
WWW web = new WWW(PostTweetURL, form.data, headers);
yield return web;
if (!string.IsNullOrEmpty(web.error))
{
Debug.Log(string.Format("PostTweet - failed. {0}\n{1}", web.error, web.text));
callback(false);
}
else
{
string error = Regex.Match(web.text, @"<error>([^&]+)</error>").Groups[1].Value;
if (!string.IsNullOrEmpty(error))
{
Debug.Log(string.Format("PostTweet - failed. {0}", error));
callback(false);
}
else
{
callback(true);
}
}
}
}
#endregion
#region OAuth Help Methods
// The below help methods are modified from "WebRequestBuilder.cs" in Twitterizer(http://www.twitterizer.net/).
// Here is its license.
//-----------------------------------------------------------------------
// <copyright file="WebRequestBuilder.cs" company="Patrick 'Ricky' Smith">
// This file is part of the Twitterizer library (http://www.twitterizer.net/)
//
// Copyright (c) 2010, Patrick "Ricky" Smith (ricky@digitally-born.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// - 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 Twitterizer 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>
// <author>Ricky Smith</author>
// <summary>Provides the means of preparing and executing Anonymous and OAuth signed web requests.</summary>
//-----------------------------------------------------------------------
private static readonly string[] OAuthParametersToIncludeInHeader = new[]
{
"oauth_version",
"oauth_nonce",
"oauth_timestamp",
"oauth_signature_method",
"oauth_consumer_key",
"oauth_token",
"oauth_verifier"
// Leave signature omitted from the list, it is added manually
// "oauth_signature",
};
private static readonly string[] SecretParameters = new[]
{
"oauth_consumer_secret",
"oauth_token_secret",
"oauth_signature"
};
private static void AddDefaultOAuthParams(Dictionary<string, string> parameters, string consumerKey, string consumerSecret)
{
parameters.Add("oauth_version", "1.0");
parameters.Add("oauth_nonce", GenerateNonce());
parameters.Add("oauth_timestamp", GenerateTimeStamp());
parameters.Add("oauth_signature_method", "HMAC-SHA1");
parameters.Add("oauth_consumer_key", consumerKey);
parameters.Add("oauth_consumer_secret", consumerSecret);
}
private static string GetFinalOAuthHeader(string HTTPRequestType, string URL, Dictionary<string, string> parameters)
{
// Add the signature to the oauth parameters
string signature = GenerateSignature(HTTPRequestType, URL, parameters);
parameters.Add("oauth_signature", signature);
StringBuilder authHeaderBuilder = new StringBuilder();
authHeaderBuilder.AppendFormat("OAuth realm=\"{0}\"", "Twitter API");
var sortedParameters = from p in parameters
where OAuthParametersToIncludeInHeader.Contains(p.Key)
orderby p.Key, UrlEncode(p.Value)
select p;
foreach (var item in sortedParameters)
{
authHeaderBuilder.AppendFormat(",{0}=\"{1}\"", UrlEncode(item.Key), UrlEncode(item.Value));
}
authHeaderBuilder.AppendFormat(",oauth_signature=\"{0}\"", UrlEncode(parameters["oauth_signature"]));
return authHeaderBuilder.ToString();
}
private static string GenerateSignature(string httpMethod, string url, Dictionary<string, string> parameters)
{
var nonSecretParameters = (from p in parameters
where !SecretParameters.Contains(p.Key)
select p);
// Create the base string. This is the string that will be hashed for the signature.
string signatureBaseString = string.Format(CultureInfo.InvariantCulture,
"{0}&{1}&{2}",
httpMethod,
UrlEncode(NormalizeUrl(new Uri(url))),
UrlEncode(nonSecretParameters));
// Create our hash key (you might say this is a password)
string key = string.Format(CultureInfo.InvariantCulture,
"{0}&{1}",
UrlEncode(parameters["oauth_consumer_secret"]),
parameters.ContainsKey("oauth_token_secret") ? UrlEncode(parameters["oauth_token_secret"]) : string.Empty);
// Generate the hash
HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(key));
byte[] signatureBytes = hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString));
return Convert.ToBase64String(signatureBytes);
}
private static string GenerateTimeStamp()
{
// Default implementation of UNIX time of the current UTC time
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds, CultureInfo.CurrentCulture).ToString(CultureInfo.CurrentCulture);
}
private static string GenerateNonce()
{
// Just a simple implementation of a random number between 123400 and 9999999
return new System.Random().Next(123400, int.MaxValue).ToString("X", CultureInfo.InvariantCulture);
}
private static string NormalizeUrl(Uri url)
{
string normalizedUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{
normalizedUrl += ":" + url.Port;
}
normalizedUrl += url.AbsolutePath;
return normalizedUrl;
}
private static string UrlEncode(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
value = Uri.EscapeDataString(value);
// UrlEncode escapes with lowercase characters (e.g. %2f) but oAuth needs %2F
value = Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper());
// these characters are not escaped by UrlEncode() but needed to be escaped
value = value
.Replace("(", "%28")
.Replace(")", "%29")
.Replace("$", "%24")
.Replace("!", "%21")
.Replace("*", "%2A")
.Replace("'", "%27");
// these characters are escaped by UrlEncode() but will fail if unescaped!
value = value.Replace("%7E", "~");
return value;
}
private static string UrlEncode(IEnumerable<KeyValuePair<string, string>> parameters)
{
StringBuilder parameterString = new StringBuilder();
var paramsSorted = from p in parameters
orderby p.Key, p.Value
select p;
foreach (var item in paramsSorted)
{
if (parameterString.Length > 0)
{
parameterString.Append("&");
}
parameterString.Append(
string.Format(
CultureInfo.InvariantCulture,
"{0}={1}",
UrlEncode(item.Key),
UrlEncode(item.Value)));
}
return UrlEncode(parameterString.ToString());
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace Microsoft.Protocols.TestSuites.Rdpbcgr
{
/// <summary>
/// Encode/Decode MS-RDPEFS packets.
/// </summary>
public static class RdpefsUtility
{
/// <summary>
/// Create Server Announce Request packet.
/// </summary>
/// <returns>Server Announce Request packet</returns>
public static DR_CORE_SERVER_ANNOUNCE_REQ CreateServerAnnounceRequest()
{
DR_CORE_SERVER_ANNOUNCE_REQ servreAnounceRequest = new DR_CORE_SERVER_ANNOUNCE_REQ();
servreAnounceRequest.Header = new RDPDR_HEADER();
servreAnounceRequest.Header.Component = Component_Values.RDPDR_CTYP_CORE;
servreAnounceRequest.Header.PacketId = PacketId_Values.PAKID_CORE_SERVER_ANNOUNCE;
servreAnounceRequest.VersionMajor = VersionMajor_Values.V1;
servreAnounceRequest.VersionMinor = VersionMinor_Values.V1;
servreAnounceRequest.ClientId = 1;
return servreAnounceRequest;
}
/// <summary>
/// Encode Server Announce Request packet.
/// </summary>
/// <param name="packet">Server Announce Request packet</param>
/// <returns>Encoded byte array.</returns>
public static byte[] EncodeServerAnnounceRequest(DR_CORE_SERVER_ANNOUNCE_REQ packet)
{
List<byte> buffer = new List<byte>();
EncodeStructure(buffer, (ushort)(packet.Header.Component));
EncodeStructure(buffer, (ushort)(packet.Header.PacketId));
EncodeStructure(buffer, (ushort)(packet.VersionMajor));
EncodeStructure(buffer, (ushort)(packet.VersionMinor));
EncodeStructure(buffer, (uint)packet.ClientId);
return buffer.ToArray();
}
/// <summary>
/// Create Server Core Capability Request packet.
/// </summary>
/// <returns>Server Core Capability Request packet.</returns>
public static DR_CORE_CAPABILITY_REQ CreateServerCoreCapabilityRequest()
{
DR_CORE_CAPABILITY_REQ request = new DR_CORE_CAPABILITY_REQ();
request.Header = new RDPDR_HEADER();
request.Header.Component = Component_Values.RDPDR_CTYP_CORE;
request.Header.PacketId = PacketId_Values.PAKID_CORE_SERVER_CAPABILITY;
request.numCapabilities = 5;
request.Padding = 0;
List<CAPABILITY_SET> capabilitySet = new List<CAPABILITY_SET>();
GENERAL_CAPS_SET generalCapability = new GENERAL_CAPS_SET();
generalCapability.Header = new CAPABILITY_HEADER();
generalCapability.Header.CapabilityType = CapabilityType_Values.CAP_GENERAL_TYPE;
generalCapability.Header.CapabilityLength = 44;
generalCapability.Header.Version = CAPABILITY_VERSION.V1;
generalCapability.osType = osType_Values.OS_TYPE_UNKNOWN;
generalCapability.osVersion = osVersion_Values.V1;
generalCapability.protocolMajorVersion = protocolMajorVersion_Values.V1;
generalCapability.protocolMinorVersion = 0x000C;
generalCapability.ioCode1 = (ioCode1_Values)0x0000FFFF;
generalCapability.ioCode2 = ioCode2_Values.V1;
generalCapability.extendedPDU = extendedPDU_Values.RDPDR_DEVICE_REMOVE_PDUS | extendedPDU_Values.RDPDR_CLIENT_DISPLAY_NAME_PDU;
generalCapability.extraFlags1 = extraFlags1_Values.ENABLE_ASYNCIO;
generalCapability.extraFlags2 = extraFlags2_Values.V1;
generalCapability.SpecialTypeDeviceCap = 2;
capabilitySet.Add(generalCapability);
PRINTER_CAPS_SET printerCapability = new PRINTER_CAPS_SET();
printerCapability.Header = new CAPABILITY_HEADER();
printerCapability.Header.CapabilityType = CapabilityType_Values.CAP_PRINTER_TYPE;
printerCapability.Header.CapabilityLength = 8;
printerCapability.Header.Version = CAPABILITY_VERSION.V1;
capabilitySet.Add(printerCapability);
PORT_CAPS_SET portCapability = new PORT_CAPS_SET();
portCapability.Header = new CAPABILITY_HEADER();
portCapability.Header.CapabilityType = CapabilityType_Values.CAP_PORT_TYPE;
portCapability.Header.CapabilityLength = 8;
portCapability.Header.Version = CAPABILITY_VERSION.V1;
capabilitySet.Add(portCapability);
DRIVE_CAPS_SET driveCapability = new DRIVE_CAPS_SET();
driveCapability.Header = new CAPABILITY_HEADER();
driveCapability.Header.CapabilityType = CapabilityType_Values.CAP_DRIVE_TYPE;
driveCapability.Header.CapabilityLength = 8;
driveCapability.Header.Version = CAPABILITY_VERSION.V2;
capabilitySet.Add(driveCapability);
SMARTCARD_CAPS_SET smartcardCapability = new SMARTCARD_CAPS_SET();
smartcardCapability.Header = new CAPABILITY_HEADER();
smartcardCapability.Header.CapabilityType = CapabilityType_Values.CAP_SMARTCARD_TYPE;
smartcardCapability.Header.CapabilityLength = 8;
smartcardCapability.Header.Version = CAPABILITY_VERSION.V1;
capabilitySet.Add(smartcardCapability);
request.CapabilityMessage = capabilitySet.ToArray();
return request;
}
/// <summary>
/// Encode Server Core Capability Request packet.
/// </summary>
/// <param name="packet">Server Core Capability Request packet.</param>
/// <returns>Encoded byte array.</returns>
public static byte[] EncodeServerCoreCapabilityRequest(DR_CORE_CAPABILITY_REQ packet)
{
List<byte> buffer = new List<byte>();
EncodeStructure(buffer, (ushort)packet.Header.Component);
EncodeStructure(buffer, (ushort)packet.Header.PacketId);
EncodeStructure(buffer, packet.numCapabilities);
EncodeStructure(buffer, packet.Padding);
if (packet.CapabilityMessage != null)
{
foreach (CAPABILITY_SET capability in packet.CapabilityMessage)
{
if (capability is GENERAL_CAPS_SET)
{
GENERAL_CAPS_SET generalCapability = capability as GENERAL_CAPS_SET;
EncodeStructure(buffer, (ushort)generalCapability.Header.CapabilityType);
EncodeStructure(buffer, (ushort)generalCapability.Header.CapabilityLength);
EncodeStructure(buffer, (uint)generalCapability.Header.Version);
EncodeStructure(buffer, (uint)generalCapability.osType);
EncodeStructure(buffer, (uint)generalCapability.osVersion);
EncodeStructure(buffer, (ushort)generalCapability.protocolMajorVersion);
EncodeStructure(buffer, (ushort)generalCapability.protocolMinorVersion);
EncodeStructure(buffer, (uint)generalCapability.ioCode1);
EncodeStructure(buffer, (uint)generalCapability.ioCode2);
EncodeStructure(buffer, (uint)generalCapability.extendedPDU);
EncodeStructure(buffer, (uint)generalCapability.extraFlags1);
EncodeStructure(buffer, (uint)generalCapability.extraFlags2);
EncodeStructure(buffer, (uint)generalCapability.SpecialTypeDeviceCap);
}
else
{
EncodeStructure(buffer, (ushort)capability.Header.CapabilityType);
EncodeStructure(buffer, (ushort)capability.Header.CapabilityLength);
EncodeStructure(buffer, (uint)capability.Header.Version);
}
}
}
return buffer.ToArray();
}
/// <summary>
/// Create Server Client ID Confirm packet.
/// </summary>
/// <param name="clientId">Client Id.</param>
/// <returns>Server Client ID Confirm packet.</returns>
public static DR_CORE_SERVER_CLIENTID_CONFIRM CreateServerClientIDConfirm(uint clientId)
{
DR_CORE_SERVER_CLIENTID_CONFIRM request = new DR_CORE_SERVER_CLIENTID_CONFIRM();
request.Header = new RDPDR_HEADER();
request.Header.Component = Component_Values.RDPDR_CTYP_CORE;
request.Header.PacketId = PacketId_Values.PAKID_CORE_CLIENTID_CONFIRM;
request.VersionMajor = DR_CORE_SERVER_CLIENTID_CONFIRM_VersionMajor_Values.V1;
request.VersionMinor = DR_CORE_SERVER_CLIENTID_CONFIRM_VersionMinor_Values.V1;
request.ClientId = clientId;
return request;
}
/// <summary>
/// Encode Server Client ID Confirm packet.
/// </summary>
/// <param name="packet">Server Client ID Confirm packet.</param>
/// <returns>Encoded byte array.</returns>
public static byte[] EncodeServerClientIDConfirm(DR_CORE_SERVER_CLIENTID_CONFIRM packet)
{
List<byte> buffer = new List<byte>();
EncodeStructure(buffer, (ushort)(packet.Header.Component));
EncodeStructure(buffer, (ushort)(packet.Header.PacketId));
EncodeStructure(buffer, (ushort)(packet.VersionMajor));
EncodeStructure(buffer, (ushort)(packet.VersionMinor));
EncodeStructure(buffer, (uint)(packet.ClientId));
return buffer.ToArray();
}
/// <summary>
/// Create Server User Logged On packet
/// </summary>
/// <returns>DR_CORE_USER_LOGGEDON</returns>
public static DR_CORE_USER_LOGGEDON CreateServerUserLoggedOn()
{
DR_CORE_USER_LOGGEDON logonPDU = new DR_CORE_USER_LOGGEDON();
logonPDU.Header = new RDPDR_HEADER();
logonPDU.Header.Component = Component_Values.RDPDR_CTYP_CORE;
logonPDU.Header.PacketId = PacketId_Values.PAKID_CORE_USER_LOGGEDON;
return logonPDU;
}
/// <summary>
/// Encode a Server User Logged On packet
/// </summary>
/// <param name="packet"></param>
/// <returns></returns>
public static byte[] EncodeServerUserLoggedOn(DR_CORE_USER_LOGGEDON packet)
{
List<byte> buffer = new List<byte>();
EncodeStructure(buffer, (ushort)(packet.Header.Component));
EncodeStructure(buffer, (ushort)(packet.Header.PacketId));
return buffer.ToArray();
}
/// <summary>
/// Decode Client Announce Reply packet.
/// </summary>
/// <param name="data">Packet data.</param>
/// <returns>Client Announce Reply packet.</returns>
public static DR_CORE_SERVER_ANNOUNCE_RSP DecodeClientAnnounceReply(byte[] data)
{
int index = 0;
DR_CORE_SERVER_ANNOUNCE_RSP packet = new DR_CORE_SERVER_ANNOUNCE_RSP();
packet.Header = DecodeRdpdrHeader(data, ref index, false);
packet.VersionMajor = (DR_CORE_SERVER_ANNOUNCE_RSP_VersionMajor_Values)ParseUInt16(data, ref index, false);
packet.VersionMinor = (DR_CORE_SERVER_ANNOUNCE_RSP_VersionMinor_Values)ParseUInt16(data, ref index, false);
packet.ClientId = ParseUInt32(data, ref index, false);
return packet;
}
/// <summary>
/// Decode Client Core Capability Response packet
/// </summary>
/// <param name="data">Packet data</param>
/// <returns>Client Core Capability Response packet</returns>
public static DR_CORE_CAPABILITY_RSP DecodeClientCoreCapabilityRSP(byte[] data)
{
int index = 0;
DR_CORE_CAPABILITY_RSP packet = new DR_CORE_CAPABILITY_RSP();
packet.Header = DecodeRdpdrHeader(data, ref index, false);
packet.numCapabilities = ParseUInt16(data, ref index, false);
packet.Padding = ParseUInt16(data, ref index, false);
List<CAPABILITY_SET> capbilityList = new List<CAPABILITY_SET>();
while (index + 8 <= data.Length)
{
CAPABILITY_HEADER header = DecodeCapabilityHeader(data, ref index, false);
if (header.CapabilityType == CapabilityType_Values.CAP_GENERAL_TYPE)
{
int originalIndex = index;
GENERAL_CAPS_SET capSet = new GENERAL_CAPS_SET();
capSet.Header = header;
capSet.osType = (osType_Values)ParseUInt32(data, ref index, false);
capSet.osVersion = (osVersion_Values)ParseUInt32(data, ref index, false);
capSet.protocolMajorVersion = (protocolMajorVersion_Values)ParseUInt16(data, ref index, false);
capSet.protocolMinorVersion = ParseUInt16(data, ref index, false);
capSet.ioCode1 = (ioCode1_Values)ParseUInt32(data, ref index, false);
capSet.ioCode2 = (ioCode2_Values)ParseUInt32(data, ref index, false);
capSet.extendedPDU = (extendedPDU_Values)ParseUInt32(data, ref index, false);
capSet.extraFlags1 = (extraFlags1_Values)ParseUInt32(data, ref index, false);
capSet.extraFlags2 = (extraFlags2_Values)ParseUInt32(data, ref index, false);
capSet.SpecialTypeDeviceCap = ParseUInt32(data, ref index, false);
index = originalIndex + header.CapabilityLength;
capbilityList.Add(capSet);
}
else if (header.CapabilityType == CapabilityType_Values.CAP_PRINTER_TYPE)
{
PRINTER_CAPS_SET capSet = new PRINTER_CAPS_SET();
capSet.Header = header;
capbilityList.Add(capSet);
}
else if (header.CapabilityType == CapabilityType_Values.CAP_DRIVE_TYPE)
{
DRIVE_CAPS_SET capSet = new DRIVE_CAPS_SET();
capSet.Header = header;
capbilityList.Add(capSet);
}
else if (header.CapabilityType == CapabilityType_Values.CAP_PORT_TYPE)
{
PORT_CAPS_SET capSet = new PORT_CAPS_SET();
capSet.Header = header;
capbilityList.Add(capSet);
}
else if (header.CapabilityType == CapabilityType_Values.CAP_SMARTCARD_TYPE)
{
SMARTCARD_CAPS_SET capSet = new SMARTCARD_CAPS_SET();
capSet.Header = header;
capbilityList.Add(capSet);
}
else
{
return null;
}
}
packet.CapabilityMessage = capbilityList.ToArray();
return packet;
}
#region private methods
/// <summary>
/// Encode a structure to a byte list.
/// </summary>
/// <param name="buffer">The buffer list to contain the structure.
/// This argument cannot be null. It may throw ArgumentNullException if it is null.</param>
/// <param name="structure">The structure to be added to buffer list.
/// This argument cannot be null. It may throw ArgumentNullException if it is null.</param>
private static void EncodeStructure(List<byte> buffer, object structure)
{
byte[] structBuffer = StructToBytes(structure);
buffer.AddRange(structBuffer);
}
/// <summary>
/// Method to covert struct to byte[]
/// </summary>
/// <param name="structp">The struct prepare to covert</param>
/// <returns>The byte array converted from struct</returns>
private static byte[] StructToBytes(object structp)
{
IntPtr ptr = IntPtr.Zero;
byte[] buffer = null;
try
{
int size = Marshal.SizeOf(structp.GetType());
ptr = Marshal.AllocHGlobal(size);
buffer = new byte[size];
Marshal.StructureToPtr(structp, ptr, false);
Marshal.Copy(ptr, buffer, 0, size);
}
finally
{
if (ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(ptr);
}
}
return buffer;
}
private static RDPDR_HEADER DecodeRdpdrHeader(byte[] data, ref int index, bool isBigEndian)
{
RDPDR_HEADER header = new RDPDR_HEADER();
header.Component = (Component_Values)ParseUInt16(data, ref index, isBigEndian);
header.PacketId = (PacketId_Values)ParseUInt16(data, ref index, isBigEndian);
return header;
}
private static CAPABILITY_HEADER DecodeCapabilityHeader(byte[] data, ref int index, bool isBigEndian)
{
CAPABILITY_HEADER header = new CAPABILITY_HEADER();
header.CapabilityType = (CapabilityType_Values)ParseUInt16(data, ref index, isBigEndian);
header.CapabilityLength = ParseUInt16(data, ref index, isBigEndian);
header.Version = (CAPABILITY_VERSION)ParseUInt32(data, ref index, isBigEndian);
return header;
}
/// <summary>
/// Parse UInt16
/// (parser index is updated according to parsed length)
/// </summary>
/// <param name="data">data to be parsed</param>
/// <param name="index">parser index</param>
/// <param name="isBigEndian">big endian format flag</param>
/// <returns>parsed UInt16 number</returns>
private static UInt16 ParseUInt16(byte[] data, ref int index, bool isBigEndian)
{
// Read 2 bytes
byte[] bytes = GetBytes(data, ref index, sizeof(UInt16));
// Big Endian format requires reversed byte order
if (isBigEndian)
{
Array.Reverse(bytes, 0, sizeof(UInt16));
}
// Convert
return BitConverter.ToUInt16(bytes, 0);
}
/// <summary>
/// Parse UInt32
/// (parser index is updated according to parsed length)
/// </summary>
/// <param name="data">data to be parsed</param>
/// <param name="index">parser index</param>
/// <param name="isBigEndian">big endian format flag</param>
/// <returns>parsed UInt32 number</returns>
private static UInt32 ParseUInt32(byte[] data, ref int index, bool isBigEndian)
{
// Read 4 bytes
byte[] bytes = GetBytes(data, ref index, sizeof(UInt32));
// Big Endian format requires reversed byte order
if (isBigEndian)
{
Array.Reverse(bytes, 0, sizeof(UInt32));
}
// Convert
return BitConverter.ToUInt32(bytes, 0);
}
/// <summary>
/// Get specified length of bytes from a byte array
/// (start index is updated according to the specified length)
/// </summary>
/// <param name="data">data in byte array</param>
/// <param name="startIndex">start index</param>
/// <param name="bytesToRead">specified length</param>
/// <returns>bytes of specified length</returns>
private static byte[] GetBytes(byte[] data, ref int startIndex, int bytesToRead)
{
// if input data is null
if (null == data)
{
return null;
}
// if index is out of range
if ((startIndex < 0) || (startIndex + bytesToRead > data.Length))
{
return null;
}
// read bytes of specific length
byte[] dataRead = new byte[bytesToRead];
Array.Copy(data, startIndex, dataRead, 0, bytesToRead);
// update index
startIndex += bytesToRead;
return dataRead;
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: playground_service.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Playground.Common.ServiceDefinition {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class PlaygroundService {
#region Descriptor
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PlaygroundService() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChhwbGF5Z3JvdW5kX3NlcnZpY2UucHJvdG8iIgoGUGVyc29uEgoKAmlkGAEg",
"ASgFEgwKBG5hbWUYAiABKAkiFgoIUGVyc29uSWQSCgoCaWQYASABKAUiEwoR",
"UGVyc29uTGlzdFJlcXVlc3QiLQoSUGVyc29uTGlzdFJlc3BvbnNlEhcKBnBl",
"b3BsZRgBIAMoCzIHLlBlcnNvbiIbChlMaXN0ZW5Gb3JOZXdQZW9wbGVSZXF1",
"ZXN0Mt0BChFQbGF5Z3JvdW5kU2VydmljZRIlCg1HZXRQZXJzb25CeUlkEgku",
"UGVyc29uSWQaBy5QZXJzb24iABIwCg1HZXRQZXJzb25MaXN0EhIuUGVyc29u",
"TGlzdFJlcXVlc3QaBy5QZXJzb24iADABEjAKDENyZWF0ZVBlb3BsZRIHLlBl",
"cnNvbhoTLlBlcnNvbkxpc3RSZXNwb25zZSIAKAESPQoSTGlzdGVuRm9yTmV3",
"UGVvcGxlEhouTGlzdGVuRm9yTmV3UGVvcGxlUmVxdWVzdBoHLlBlcnNvbiIA",
"MAFCJqoCI1BsYXlncm91bmQuQ29tbW9uLlNlcnZpY2VEZWZpbml0aW9uYgZw",
"cm90bzM="));
descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Playground.Common.ServiceDefinition.Person), new[]{ "Id", "Name" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Playground.Common.ServiceDefinition.PersonId), new[]{ "Id" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Playground.Common.ServiceDefinition.PersonListRequest), null, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Playground.Common.ServiceDefinition.PersonListResponse), new[]{ "People" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Playground.Common.ServiceDefinition.ListenForNewPeopleRequest), null, null, null, null)
}));
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Person : pb::IMessage<Person> {
private static readonly pb::MessageParser<Person> _parser = new pb::MessageParser<Person>(() => new Person());
public static pb::MessageParser<Person> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Playground.Common.ServiceDefinition.Proto.PlaygroundService.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Person() {
OnConstruction();
}
partial void OnConstruction();
public Person(Person other) : this() {
id_ = other.id_;
name_ = other.name_;
}
public Person Clone() {
return new Person(this);
}
public const int IdFieldNumber = 1;
private int id_;
public int Id {
get { return id_; }
set {
id_ = value;
}
}
public const int NameFieldNumber = 2;
private string name_ = "";
public string Name {
get { return name_; }
set {
name_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as Person);
}
public bool Equals(Person other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (Name != other.Name) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Id != 0) hash ^= Id.GetHashCode();
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Id != 0) {
output.WriteRawTag(8);
output.WriteInt32(Id);
}
if (Name.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Name);
}
}
public int CalculateSize() {
int size = 0;
if (Id != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Id);
}
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
public void MergeFrom(Person other) {
if (other == null) {
return;
}
if (other.Id != 0) {
Id = other.Id;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Id = input.ReadInt32();
break;
}
case 18: {
Name = input.ReadString();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PersonId : pb::IMessage<PersonId> {
private static readonly pb::MessageParser<PersonId> _parser = new pb::MessageParser<PersonId>(() => new PersonId());
public static pb::MessageParser<PersonId> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Playground.Common.ServiceDefinition.Proto.PlaygroundService.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public PersonId() {
OnConstruction();
}
partial void OnConstruction();
public PersonId(PersonId other) : this() {
id_ = other.id_;
}
public PersonId Clone() {
return new PersonId(this);
}
public const int IdFieldNumber = 1;
private int id_;
public int Id {
get { return id_; }
set {
id_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as PersonId);
}
public bool Equals(PersonId other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Id != 0) hash ^= Id.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Id != 0) {
output.WriteRawTag(8);
output.WriteInt32(Id);
}
}
public int CalculateSize() {
int size = 0;
if (Id != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Id);
}
return size;
}
public void MergeFrom(PersonId other) {
if (other == null) {
return;
}
if (other.Id != 0) {
Id = other.Id;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Id = input.ReadInt32();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PersonListRequest : pb::IMessage<PersonListRequest> {
private static readonly pb::MessageParser<PersonListRequest> _parser = new pb::MessageParser<PersonListRequest>(() => new PersonListRequest());
public static pb::MessageParser<PersonListRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Playground.Common.ServiceDefinition.Proto.PlaygroundService.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public PersonListRequest() {
OnConstruction();
}
partial void OnConstruction();
public PersonListRequest(PersonListRequest other) : this() {
}
public PersonListRequest Clone() {
return new PersonListRequest(this);
}
public override bool Equals(object other) {
return Equals(other as PersonListRequest);
}
public bool Equals(PersonListRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
public override int GetHashCode() {
int hash = 1;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
}
public int CalculateSize() {
int size = 0;
return size;
}
public void MergeFrom(PersonListRequest other) {
if (other == null) {
return;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PersonListResponse : pb::IMessage<PersonListResponse> {
private static readonly pb::MessageParser<PersonListResponse> _parser = new pb::MessageParser<PersonListResponse>(() => new PersonListResponse());
public static pb::MessageParser<PersonListResponse> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Playground.Common.ServiceDefinition.Proto.PlaygroundService.Descriptor.MessageTypes[3]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public PersonListResponse() {
OnConstruction();
}
partial void OnConstruction();
public PersonListResponse(PersonListResponse other) : this() {
people_ = other.people_.Clone();
}
public PersonListResponse Clone() {
return new PersonListResponse(this);
}
public const int PeopleFieldNumber = 1;
private static readonly pb::FieldCodec<global::Playground.Common.ServiceDefinition.Person> _repeated_people_codec
= pb::FieldCodec.ForMessage(10, global::Playground.Common.ServiceDefinition.Person.Parser);
private readonly pbc::RepeatedField<global::Playground.Common.ServiceDefinition.Person> people_ = new pbc::RepeatedField<global::Playground.Common.ServiceDefinition.Person>();
public pbc::RepeatedField<global::Playground.Common.ServiceDefinition.Person> People {
get { return people_; }
}
public override bool Equals(object other) {
return Equals(other as PersonListResponse);
}
public bool Equals(PersonListResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!people_.Equals(other.people_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= people_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
people_.WriteTo(output, _repeated_people_codec);
}
public int CalculateSize() {
int size = 0;
size += people_.CalculateSize(_repeated_people_codec);
return size;
}
public void MergeFrom(PersonListResponse other) {
if (other == null) {
return;
}
people_.Add(other.people_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
people_.AddEntriesFrom(input, _repeated_people_codec);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ListenForNewPeopleRequest : pb::IMessage<ListenForNewPeopleRequest> {
private static readonly pb::MessageParser<ListenForNewPeopleRequest> _parser = new pb::MessageParser<ListenForNewPeopleRequest>(() => new ListenForNewPeopleRequest());
public static pb::MessageParser<ListenForNewPeopleRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Playground.Common.ServiceDefinition.Proto.PlaygroundService.Descriptor.MessageTypes[4]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ListenForNewPeopleRequest() {
OnConstruction();
}
partial void OnConstruction();
public ListenForNewPeopleRequest(ListenForNewPeopleRequest other) : this() {
}
public ListenForNewPeopleRequest Clone() {
return new ListenForNewPeopleRequest(this);
}
public override bool Equals(object other) {
return Equals(other as ListenForNewPeopleRequest);
}
public bool Equals(ListenForNewPeopleRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
public override int GetHashCode() {
int hash = 1;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
}
public int CalculateSize() {
int size = 0;
return size;
}
public void MergeFrom(ListenForNewPeopleRequest other) {
if (other == null) {
return;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Databases.
/// Contains operations to: Create, Retrieve, Update, and Delete
/// databases, and also includes the ability to get the event logs for a
/// database.
/// </summary>
internal partial class DatabaseOperations : IServiceOperations<SqlManagementClient>, Microsoft.WindowsAzure.Management.Sql.IDatabaseOperations
{
/// <summary>
/// Initializes a new instance of the DatabaseOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DatabaseOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates a database in an Azure SQL Database Server.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server where the
/// database will be created.
/// </param>
/// <param name='parameters'>
/// Required. The parameters for the create database operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a create database request from the
/// service.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DatabaseCreateResponse> CreateAsync(string serverName, DatabaseCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/databases";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(serviceResourceElement);
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
serviceResourceElement.Add(nameElement);
if (parameters.Edition != null)
{
XElement editionElement = new XElement(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure"));
editionElement.Value = parameters.Edition;
serviceResourceElement.Add(editionElement);
}
if (parameters.MaximumDatabaseSizeInGB != null)
{
XElement maxSizeGBElement = new XElement(XName.Get("MaxSizeGB", "http://schemas.microsoft.com/windowsazure"));
maxSizeGBElement.Value = parameters.MaximumDatabaseSizeInGB.ToString();
serviceResourceElement.Add(maxSizeGBElement);
}
if (parameters.CollationName != null)
{
XElement collationNameElement = new XElement(XName.Get("CollationName", "http://schemas.microsoft.com/windowsazure"));
collationNameElement.Value = parameters.CollationName;
serviceResourceElement.Add(collationNameElement);
}
if (parameters.MaximumDatabaseSizeInBytes != null)
{
XElement maxSizeBytesElement = new XElement(XName.Get("MaxSizeBytes", "http://schemas.microsoft.com/windowsazure"));
maxSizeBytesElement.Value = parameters.MaximumDatabaseSizeInBytes.ToString();
serviceResourceElement.Add(maxSizeBytesElement);
}
if (parameters.ServiceObjectiveId != null)
{
XElement serviceObjectiveIdElement = new XElement(XName.Get("ServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
serviceObjectiveIdElement.Value = parameters.ServiceObjectiveId;
serviceResourceElement.Add(serviceObjectiveIdElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseCreateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseCreateResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement2 != null)
{
Database serviceResourceInstance = new Database();
result.Database = serviceResourceInstance;
XElement idElement = serviceResourceElement2.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
int idInstance = int.Parse(idElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.Id = idInstance;
}
XElement editionElement2 = serviceResourceElement2.Element(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure"));
if (editionElement2 != null)
{
string editionInstance = editionElement2.Value;
serviceResourceInstance.Edition = editionInstance;
}
XElement maxSizeGBElement2 = serviceResourceElement2.Element(XName.Get("MaxSizeGB", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeGBElement2 != null)
{
int maxSizeGBInstance = int.Parse(maxSizeGBElement2.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInGB = maxSizeGBInstance;
}
XElement maxSizeBytesElement2 = serviceResourceElement2.Element(XName.Get("MaxSizeBytes", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeBytesElement2 != null)
{
long maxSizeBytesInstance = long.Parse(maxSizeBytesElement2.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInBytes = maxSizeBytesInstance;
}
XElement collationNameElement2 = serviceResourceElement2.Element(XName.Get("CollationName", "http://schemas.microsoft.com/windowsazure"));
if (collationNameElement2 != null)
{
string collationNameInstance = collationNameElement2.Value;
serviceResourceInstance.CollationName = collationNameInstance;
}
XElement creationDateElement = serviceResourceElement2.Element(XName.Get("CreationDate", "http://schemas.microsoft.com/windowsazure"));
if (creationDateElement != null)
{
DateTime creationDateInstance = DateTime.Parse(creationDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.CreationDate = creationDateInstance;
}
XElement isFederationRootElement = serviceResourceElement2.Element(XName.Get("IsFederationRoot", "http://schemas.microsoft.com/windowsazure"));
if (isFederationRootElement != null)
{
bool isFederationRootInstance = bool.Parse(isFederationRootElement.Value);
serviceResourceInstance.IsFederationRoot = isFederationRootInstance;
}
XElement isSystemObjectElement = serviceResourceElement2.Element(XName.Get("IsSystemObject", "http://schemas.microsoft.com/windowsazure"));
if (isSystemObjectElement != null)
{
bool isSystemObjectInstance = bool.Parse(isSystemObjectElement.Value);
serviceResourceInstance.IsSystemObject = isSystemObjectInstance;
}
XElement sizeMBElement = serviceResourceElement2.Element(XName.Get("SizeMB", "http://schemas.microsoft.com/windowsazure"));
if (sizeMBElement != null)
{
string sizeMBInstance = sizeMBElement.Value;
serviceResourceInstance.SizeMB = sizeMBInstance;
}
XElement serviceObjectiveAssignmentErrorCodeElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentErrorCode", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentErrorCodeElement != null)
{
string serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentErrorCode = serviceObjectiveAssignmentErrorCodeInstance;
}
XElement serviceObjectiveAssignmentErrorDescriptionElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentErrorDescription", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentErrorDescriptionElement != null)
{
string serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentErrorDescription = serviceObjectiveAssignmentErrorDescriptionInstance;
}
XElement serviceObjectiveAssignmentStateElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentState", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentStateElement != null)
{
string serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentState = serviceObjectiveAssignmentStateInstance;
}
XElement serviceObjectiveAssignmentStateDescriptionElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentStateDescriptionElement != null)
{
string serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentStateDescription = serviceObjectiveAssignmentStateDescriptionInstance;
}
XElement serviceObjectiveAssignmentSuccessDateElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentSuccessDate", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentSuccessDateElement != null)
{
string serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentSuccessDate = serviceObjectiveAssignmentSuccessDateInstance;
}
XElement serviceObjectiveIdElement2 = serviceResourceElement2.Element(XName.Get("ServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveIdElement2 != null)
{
string serviceObjectiveIdInstance = serviceObjectiveIdElement2.Value;
serviceResourceInstance.ServiceObjectiveId = serviceObjectiveIdInstance;
}
XElement assignedServiceObjectiveIdElement = serviceResourceElement2.Element(XName.Get("AssignedServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
if (assignedServiceObjectiveIdElement != null)
{
string assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.Value;
serviceResourceInstance.AssignedServiceObjectiveId = assignedServiceObjectiveIdInstance;
}
XElement recoveryPeriodStartDateElement = serviceResourceElement2.Element(XName.Get("RecoveryPeriodStartDate", "http://schemas.microsoft.com/windowsazure"));
if (recoveryPeriodStartDateElement != null && string.IsNullOrEmpty(recoveryPeriodStartDateElement.Value) == false)
{
DateTime recoveryPeriodStartDateInstance = DateTime.Parse(recoveryPeriodStartDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.RecoveryPeriodStartDate = recoveryPeriodStartDateInstance;
}
XElement nameElement2 = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance = nameElement2.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Drops a database from an Azure SQL Database Server.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> DeleteAsync(string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/databases/" + databaseName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about an Azure SQL Database.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Contains the response to a Get Database request.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DatabaseGetResponse> GetAsync(string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/databases/" + databaseName.Trim();
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-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement != null)
{
Database serviceResourceInstance = new Database();
result.Database = serviceResourceInstance;
XElement idElement = serviceResourceElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
int idInstance = int.Parse(idElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.Id = idInstance;
}
XElement editionElement = serviceResourceElement.Element(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure"));
if (editionElement != null)
{
string editionInstance = editionElement.Value;
serviceResourceInstance.Edition = editionInstance;
}
XElement maxSizeGBElement = serviceResourceElement.Element(XName.Get("MaxSizeGB", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeGBElement != null)
{
int maxSizeGBInstance = int.Parse(maxSizeGBElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInGB = maxSizeGBInstance;
}
XElement maxSizeBytesElement = serviceResourceElement.Element(XName.Get("MaxSizeBytes", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeBytesElement != null)
{
long maxSizeBytesInstance = long.Parse(maxSizeBytesElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInBytes = maxSizeBytesInstance;
}
XElement collationNameElement = serviceResourceElement.Element(XName.Get("CollationName", "http://schemas.microsoft.com/windowsazure"));
if (collationNameElement != null)
{
string collationNameInstance = collationNameElement.Value;
serviceResourceInstance.CollationName = collationNameInstance;
}
XElement creationDateElement = serviceResourceElement.Element(XName.Get("CreationDate", "http://schemas.microsoft.com/windowsazure"));
if (creationDateElement != null)
{
DateTime creationDateInstance = DateTime.Parse(creationDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.CreationDate = creationDateInstance;
}
XElement isFederationRootElement = serviceResourceElement.Element(XName.Get("IsFederationRoot", "http://schemas.microsoft.com/windowsazure"));
if (isFederationRootElement != null)
{
bool isFederationRootInstance = bool.Parse(isFederationRootElement.Value);
serviceResourceInstance.IsFederationRoot = isFederationRootInstance;
}
XElement isSystemObjectElement = serviceResourceElement.Element(XName.Get("IsSystemObject", "http://schemas.microsoft.com/windowsazure"));
if (isSystemObjectElement != null)
{
bool isSystemObjectInstance = bool.Parse(isSystemObjectElement.Value);
serviceResourceInstance.IsSystemObject = isSystemObjectInstance;
}
XElement sizeMBElement = serviceResourceElement.Element(XName.Get("SizeMB", "http://schemas.microsoft.com/windowsazure"));
if (sizeMBElement != null)
{
string sizeMBInstance = sizeMBElement.Value;
serviceResourceInstance.SizeMB = sizeMBInstance;
}
XElement serviceObjectiveAssignmentErrorCodeElement = serviceResourceElement.Element(XName.Get("ServiceObjectiveAssignmentErrorCode", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentErrorCodeElement != null)
{
string serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentErrorCode = serviceObjectiveAssignmentErrorCodeInstance;
}
XElement serviceObjectiveAssignmentErrorDescriptionElement = serviceResourceElement.Element(XName.Get("ServiceObjectiveAssignmentErrorDescription", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentErrorDescriptionElement != null)
{
string serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentErrorDescription = serviceObjectiveAssignmentErrorDescriptionInstance;
}
XElement serviceObjectiveAssignmentStateElement = serviceResourceElement.Element(XName.Get("ServiceObjectiveAssignmentState", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentStateElement != null)
{
string serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentState = serviceObjectiveAssignmentStateInstance;
}
XElement serviceObjectiveAssignmentStateDescriptionElement = serviceResourceElement.Element(XName.Get("ServiceObjectiveAssignmentStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentStateDescriptionElement != null)
{
string serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentStateDescription = serviceObjectiveAssignmentStateDescriptionInstance;
}
XElement serviceObjectiveAssignmentSuccessDateElement = serviceResourceElement.Element(XName.Get("ServiceObjectiveAssignmentSuccessDate", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentSuccessDateElement != null)
{
string serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentSuccessDate = serviceObjectiveAssignmentSuccessDateInstance;
}
XElement serviceObjectiveIdElement = serviceResourceElement.Element(XName.Get("ServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveIdElement != null)
{
string serviceObjectiveIdInstance = serviceObjectiveIdElement.Value;
serviceResourceInstance.ServiceObjectiveId = serviceObjectiveIdInstance;
}
XElement assignedServiceObjectiveIdElement = serviceResourceElement.Element(XName.Get("AssignedServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
if (assignedServiceObjectiveIdElement != null)
{
string assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.Value;
serviceResourceInstance.AssignedServiceObjectiveId = assignedServiceObjectiveIdInstance;
}
XElement recoveryPeriodStartDateElement = serviceResourceElement.Element(XName.Get("RecoveryPeriodStartDate", "http://schemas.microsoft.com/windowsazure"));
if (recoveryPeriodStartDateElement != null && string.IsNullOrEmpty(recoveryPeriodStartDateElement.Value) == false)
{
DateTime recoveryPeriodStartDateInstance = DateTime.Parse(recoveryPeriodStartDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.RecoveryPeriodStartDate = recoveryPeriodStartDateInstance;
}
XElement nameElement = serviceResourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about an Azure SQL Database event logs.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to be retrieved.
/// </param>
/// <param name='parameters'>
/// Required. The parameters for the Get Database Event Logs operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Contains the response to a Get Database Event Logs request.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DatabaseGetEventLogsResponse> GetEventLogsAsync(string serverName, string databaseName, DatabaseGetEventLogsParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.EventTypes == null)
{
throw new ArgumentNullException("parameters.EventTypes");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "GetEventLogsAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/databases/" + databaseName.Trim() + "/events?";
url = url + "startDate=" + Uri.EscapeDataString(parameters.StartDate.ToString());
url = url + "&intervalSizeInMinutes=" + Uri.EscapeDataString(parameters.IntervalSizeInMinutes.ToString());
url = url + "&eventTypes=" + Uri.EscapeDataString(parameters.EventTypes.Trim());
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-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseGetEventLogsResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseGetEventLogsResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourcesSequenceElement != null)
{
foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")))
{
DatabaseEventLog serviceResourceInstance = new DatabaseEventLog();
result.EventLogs.Add(serviceResourceInstance);
XElement databaseNameElement = serviceResourcesElement.Element(XName.Get("DatabaseName", "http://schemas.microsoft.com/windowsazure"));
if (databaseNameElement != null)
{
string databaseNameInstance = databaseNameElement.Value;
serviceResourceInstance.DatabaseName = databaseNameInstance;
}
XElement startTimeUtcElement = serviceResourcesElement.Element(XName.Get("StartTimeUtc", "http://schemas.microsoft.com/windowsazure"));
if (startTimeUtcElement != null)
{
DateTime startTimeUtcInstance = DateTime.Parse(startTimeUtcElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.StartTimeUtc = startTimeUtcInstance;
}
XElement intervalSizeInMinutesElement = serviceResourcesElement.Element(XName.Get("IntervalSizeInMinutes", "http://schemas.microsoft.com/windowsazure"));
if (intervalSizeInMinutesElement != null)
{
int intervalSizeInMinutesInstance = int.Parse(intervalSizeInMinutesElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.IntervalSizeInMinutes = intervalSizeInMinutesInstance;
}
XElement eventCategoryElement = serviceResourcesElement.Element(XName.Get("EventCategory", "http://schemas.microsoft.com/windowsazure"));
if (eventCategoryElement != null)
{
string eventCategoryInstance = eventCategoryElement.Value;
serviceResourceInstance.EventCategory = eventCategoryInstance;
}
XElement eventTypeElement = serviceResourcesElement.Element(XName.Get("EventType", "http://schemas.microsoft.com/windowsazure"));
if (eventTypeElement != null)
{
string eventTypeInstance = eventTypeElement.Value;
serviceResourceInstance.EventType = eventTypeInstance;
}
XElement eventSubtypeElement = serviceResourcesElement.Element(XName.Get("EventSubtype", "http://schemas.microsoft.com/windowsazure"));
if (eventSubtypeElement != null)
{
string eventSubtypeInstance = eventSubtypeElement.Value;
serviceResourceInstance.EventSubtype = eventSubtypeInstance;
}
XElement eventSubtypeDescriptionElement = serviceResourcesElement.Element(XName.Get("EventSubtypeDescription", "http://schemas.microsoft.com/windowsazure"));
if (eventSubtypeDescriptionElement != null)
{
string eventSubtypeDescriptionInstance = eventSubtypeDescriptionElement.Value;
serviceResourceInstance.EventSubtypeDescription = eventSubtypeDescriptionInstance;
}
XElement numberOfEventsElement = serviceResourcesElement.Element(XName.Get("NumberOfEvents", "http://schemas.microsoft.com/windowsazure"));
if (numberOfEventsElement != null)
{
int numberOfEventsInstance = int.Parse(numberOfEventsElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.NumberOfEvents = numberOfEventsInstance;
}
XElement severityElement = serviceResourcesElement.Element(XName.Get("Severity", "http://schemas.microsoft.com/windowsazure"));
if (severityElement != null)
{
int severityInstance = int.Parse(severityElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.Severity = severityInstance;
}
XElement descriptionElement = serviceResourcesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
if (descriptionElement != null)
{
string descriptionInstance = descriptionElement.Value;
serviceResourceInstance.Description = descriptionInstance;
}
XElement additionalDataElement = serviceResourcesElement.Element(XName.Get("AdditionalData", "http://schemas.microsoft.com/windowsazure"));
if (additionalDataElement != null)
{
bool isNil = false;
XAttribute nilAttribute = additionalDataElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute != null)
{
isNil = nilAttribute.Value == "true";
}
if (isNil == false)
{
string additionalDataInstance = additionalDataElement.Value;
serviceResourceInstance.AdditionalData = additionalDataInstance;
}
}
XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns a collection of Azure SQL Databases.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server from which to
/// retrieve the database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Contains a collection of databases for a given Azure SQL Database
/// Server.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DatabaseListResponse> ListAsync(string serverName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/databases?contentview=generic";
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-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourcesSequenceElement != null)
{
foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")))
{
Database serviceResourceInstance = new Database();
result.Databases.Add(serviceResourceInstance);
XElement idElement = serviceResourcesElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
int idInstance = int.Parse(idElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.Id = idInstance;
}
XElement editionElement = serviceResourcesElement.Element(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure"));
if (editionElement != null)
{
string editionInstance = editionElement.Value;
serviceResourceInstance.Edition = editionInstance;
}
XElement maxSizeGBElement = serviceResourcesElement.Element(XName.Get("MaxSizeGB", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeGBElement != null)
{
int maxSizeGBInstance = int.Parse(maxSizeGBElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInGB = maxSizeGBInstance;
}
XElement maxSizeBytesElement = serviceResourcesElement.Element(XName.Get("MaxSizeBytes", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeBytesElement != null)
{
long maxSizeBytesInstance = long.Parse(maxSizeBytesElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInBytes = maxSizeBytesInstance;
}
XElement collationNameElement = serviceResourcesElement.Element(XName.Get("CollationName", "http://schemas.microsoft.com/windowsazure"));
if (collationNameElement != null)
{
string collationNameInstance = collationNameElement.Value;
serviceResourceInstance.CollationName = collationNameInstance;
}
XElement creationDateElement = serviceResourcesElement.Element(XName.Get("CreationDate", "http://schemas.microsoft.com/windowsazure"));
if (creationDateElement != null)
{
DateTime creationDateInstance = DateTime.Parse(creationDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.CreationDate = creationDateInstance;
}
XElement isFederationRootElement = serviceResourcesElement.Element(XName.Get("IsFederationRoot", "http://schemas.microsoft.com/windowsazure"));
if (isFederationRootElement != null)
{
bool isFederationRootInstance = bool.Parse(isFederationRootElement.Value);
serviceResourceInstance.IsFederationRoot = isFederationRootInstance;
}
XElement isSystemObjectElement = serviceResourcesElement.Element(XName.Get("IsSystemObject", "http://schemas.microsoft.com/windowsazure"));
if (isSystemObjectElement != null)
{
bool isSystemObjectInstance = bool.Parse(isSystemObjectElement.Value);
serviceResourceInstance.IsSystemObject = isSystemObjectInstance;
}
XElement sizeMBElement = serviceResourcesElement.Element(XName.Get("SizeMB", "http://schemas.microsoft.com/windowsazure"));
if (sizeMBElement != null)
{
string sizeMBInstance = sizeMBElement.Value;
serviceResourceInstance.SizeMB = sizeMBInstance;
}
XElement serviceObjectiveAssignmentErrorCodeElement = serviceResourcesElement.Element(XName.Get("ServiceObjectiveAssignmentErrorCode", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentErrorCodeElement != null)
{
string serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentErrorCode = serviceObjectiveAssignmentErrorCodeInstance;
}
XElement serviceObjectiveAssignmentErrorDescriptionElement = serviceResourcesElement.Element(XName.Get("ServiceObjectiveAssignmentErrorDescription", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentErrorDescriptionElement != null)
{
string serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentErrorDescription = serviceObjectiveAssignmentErrorDescriptionInstance;
}
XElement serviceObjectiveAssignmentStateElement = serviceResourcesElement.Element(XName.Get("ServiceObjectiveAssignmentState", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentStateElement != null)
{
string serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentState = serviceObjectiveAssignmentStateInstance;
}
XElement serviceObjectiveAssignmentStateDescriptionElement = serviceResourcesElement.Element(XName.Get("ServiceObjectiveAssignmentStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentStateDescriptionElement != null)
{
string serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentStateDescription = serviceObjectiveAssignmentStateDescriptionInstance;
}
XElement serviceObjectiveAssignmentSuccessDateElement = serviceResourcesElement.Element(XName.Get("ServiceObjectiveAssignmentSuccessDate", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentSuccessDateElement != null)
{
string serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentSuccessDate = serviceObjectiveAssignmentSuccessDateInstance;
}
XElement serviceObjectiveIdElement = serviceResourcesElement.Element(XName.Get("ServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveIdElement != null)
{
string serviceObjectiveIdInstance = serviceObjectiveIdElement.Value;
serviceResourceInstance.ServiceObjectiveId = serviceObjectiveIdInstance;
}
XElement assignedServiceObjectiveIdElement = serviceResourcesElement.Element(XName.Get("AssignedServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
if (assignedServiceObjectiveIdElement != null)
{
string assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.Value;
serviceResourceInstance.AssignedServiceObjectiveId = assignedServiceObjectiveIdInstance;
}
XElement recoveryPeriodStartDateElement = serviceResourcesElement.Element(XName.Get("RecoveryPeriodStartDate", "http://schemas.microsoft.com/windowsazure"));
if (recoveryPeriodStartDateElement != null && string.IsNullOrEmpty(recoveryPeriodStartDateElement.Value) == false)
{
DateTime recoveryPeriodStartDateInstance = DateTime.Parse(recoveryPeriodStartDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.RecoveryPeriodStartDate = recoveryPeriodStartDateInstance;
}
XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates the properties of an Azure SQL Database.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server where the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to be updated.
/// </param>
/// <param name='parameters'>
/// Required. The parameters for the Update Database operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Contains the response from a request to Update Database.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.DatabaseUpdateResponse> UpdateAsync(string serverName, string databaseName, DatabaseUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Edition == null)
{
throw new ArgumentNullException("parameters.Edition");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/databases/" + databaseName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(serviceResourceElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
serviceResourceElement.Add(nameElement);
}
XElement editionElement = new XElement(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure"));
editionElement.Value = parameters.Edition;
serviceResourceElement.Add(editionElement);
if (parameters.MaximumDatabaseSizeInGB != null)
{
XElement maxSizeGBElement = new XElement(XName.Get("MaxSizeGB", "http://schemas.microsoft.com/windowsazure"));
maxSizeGBElement.Value = parameters.MaximumDatabaseSizeInGB.ToString();
serviceResourceElement.Add(maxSizeGBElement);
}
if (parameters.MaximumDatabaseSizeInBytes != null)
{
XElement maxSizeBytesElement = new XElement(XName.Get("MaxSizeBytes", "http://schemas.microsoft.com/windowsazure"));
maxSizeBytesElement.Value = parameters.MaximumDatabaseSizeInBytes.ToString();
serviceResourceElement.Add(maxSizeBytesElement);
}
if (parameters.ServiceObjectiveId != null)
{
XElement serviceObjectiveIdElement = new XElement(XName.Get("ServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
serviceObjectiveIdElement.Value = parameters.ServiceObjectiveId;
serviceResourceElement.Add(serviceObjectiveIdElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DatabaseUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseUpdateResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement2 != null)
{
Database serviceResourceInstance = new Database();
result.Database = serviceResourceInstance;
XElement idElement = serviceResourceElement2.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
int idInstance = int.Parse(idElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.Id = idInstance;
}
XElement editionElement2 = serviceResourceElement2.Element(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure"));
if (editionElement2 != null)
{
string editionInstance = editionElement2.Value;
serviceResourceInstance.Edition = editionInstance;
}
XElement maxSizeGBElement2 = serviceResourceElement2.Element(XName.Get("MaxSizeGB", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeGBElement2 != null)
{
int maxSizeGBInstance = int.Parse(maxSizeGBElement2.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInGB = maxSizeGBInstance;
}
XElement maxSizeBytesElement2 = serviceResourceElement2.Element(XName.Get("MaxSizeBytes", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeBytesElement2 != null)
{
long maxSizeBytesInstance = long.Parse(maxSizeBytesElement2.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInBytes = maxSizeBytesInstance;
}
XElement collationNameElement = serviceResourceElement2.Element(XName.Get("CollationName", "http://schemas.microsoft.com/windowsazure"));
if (collationNameElement != null)
{
string collationNameInstance = collationNameElement.Value;
serviceResourceInstance.CollationName = collationNameInstance;
}
XElement creationDateElement = serviceResourceElement2.Element(XName.Get("CreationDate", "http://schemas.microsoft.com/windowsazure"));
if (creationDateElement != null)
{
DateTime creationDateInstance = DateTime.Parse(creationDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.CreationDate = creationDateInstance;
}
XElement isFederationRootElement = serviceResourceElement2.Element(XName.Get("IsFederationRoot", "http://schemas.microsoft.com/windowsazure"));
if (isFederationRootElement != null)
{
bool isFederationRootInstance = bool.Parse(isFederationRootElement.Value);
serviceResourceInstance.IsFederationRoot = isFederationRootInstance;
}
XElement isSystemObjectElement = serviceResourceElement2.Element(XName.Get("IsSystemObject", "http://schemas.microsoft.com/windowsazure"));
if (isSystemObjectElement != null)
{
bool isSystemObjectInstance = bool.Parse(isSystemObjectElement.Value);
serviceResourceInstance.IsSystemObject = isSystemObjectInstance;
}
XElement sizeMBElement = serviceResourceElement2.Element(XName.Get("SizeMB", "http://schemas.microsoft.com/windowsazure"));
if (sizeMBElement != null)
{
string sizeMBInstance = sizeMBElement.Value;
serviceResourceInstance.SizeMB = sizeMBInstance;
}
XElement serviceObjectiveAssignmentErrorCodeElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentErrorCode", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentErrorCodeElement != null)
{
string serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentErrorCode = serviceObjectiveAssignmentErrorCodeInstance;
}
XElement serviceObjectiveAssignmentErrorDescriptionElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentErrorDescription", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentErrorDescriptionElement != null)
{
string serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentErrorDescription = serviceObjectiveAssignmentErrorDescriptionInstance;
}
XElement serviceObjectiveAssignmentStateElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentState", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentStateElement != null)
{
string serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentState = serviceObjectiveAssignmentStateInstance;
}
XElement serviceObjectiveAssignmentStateDescriptionElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentStateDescription", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentStateDescriptionElement != null)
{
string serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentStateDescription = serviceObjectiveAssignmentStateDescriptionInstance;
}
XElement serviceObjectiveAssignmentSuccessDateElement = serviceResourceElement2.Element(XName.Get("ServiceObjectiveAssignmentSuccessDate", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveAssignmentSuccessDateElement != null)
{
string serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement.Value;
serviceResourceInstance.ServiceObjectiveAssignmentSuccessDate = serviceObjectiveAssignmentSuccessDateInstance;
}
XElement serviceObjectiveIdElement2 = serviceResourceElement2.Element(XName.Get("ServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
if (serviceObjectiveIdElement2 != null)
{
string serviceObjectiveIdInstance = serviceObjectiveIdElement2.Value;
serviceResourceInstance.ServiceObjectiveId = serviceObjectiveIdInstance;
}
XElement assignedServiceObjectiveIdElement = serviceResourceElement2.Element(XName.Get("AssignedServiceObjectiveId", "http://schemas.microsoft.com/windowsazure"));
if (assignedServiceObjectiveIdElement != null)
{
string assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.Value;
serviceResourceInstance.AssignedServiceObjectiveId = assignedServiceObjectiveIdInstance;
}
XElement recoveryPeriodStartDateElement = serviceResourceElement2.Element(XName.Get("RecoveryPeriodStartDate", "http://schemas.microsoft.com/windowsazure"));
if (recoveryPeriodStartDateElement != null && string.IsNullOrEmpty(recoveryPeriodStartDateElement.Value) == false)
{
DateTime recoveryPeriodStartDateInstance = DateTime.Parse(recoveryPeriodStartDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.RecoveryPeriodStartDate = recoveryPeriodStartDateInstance;
}
XElement nameElement2 = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement2 != null)
{
string nameInstance = nameElement2.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
** This file exists to contain miscellaneous module-level attributes
** and other miscellaneous stuff.
**
**
**
===========================================================*/
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.StubHelpers;
using System.Threading.Tasks;
#if FEATURE_COMINTEROP
using System.Runtime.InteropServices.WindowsRuntime;
[assembly:Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D")]
// The following attribute are required to ensure COM compatibility.
[assembly:System.Runtime.InteropServices.ComCompatibleVersion(1, 0, 3300, 0)]
[assembly:System.Runtime.InteropServices.TypeLibVersion(2, 4)]
#endif // FEATURE_COMINTEROP
[assembly:DefaultDependencyAttribute(LoadHint.Always)]
// mscorlib would like to have its literal strings frozen if possible
[assembly: System.Runtime.CompilerServices.StringFreezingAttribute()]
namespace System
{
static class Internal
{
// This method is purely an aid for NGen to statically deduce which
// instantiations to save in the ngen image.
// Otherwise, the JIT-compiler gets used, which is bad for working-set.
// Note that IBC can provide this information too.
// However, this helps in keeping the JIT-compiler out even for
// test scenarios which do not use IBC.
// This can be removed after V2, when we implement other schemes
// of keeping the JIT-compiler out for generic instantiations.
// Method marked as NoOptimization as we don't want the JIT to
// inline any methods or take any short-circuit paths since the
// instantiation closure process is driven by "fixup" references
// left in the final code stream.
[MethodImplAttribute(MethodImplOptions.NoOptimization)]
static void CommonlyUsedGenericInstantiations()
{
// Make absolutely sure we include some of the most common
// instantiations here in mscorlib's ngen image.
// Note that reference type instantiations are already included
// automatically for us.
// Need to sort non null, len > 1 array or paths will short-circuit
Array.Sort<double>(new double[1]);
Array.Sort<int>(new int[1]);
Array.Sort<IntPtr>(new IntPtr[1]);
new ArraySegment<byte>(new byte[1], 0, 0);
new Dictionary<Char, Object>();
new Dictionary<Guid, Byte>();
new Dictionary<Guid, Object>();
new Dictionary<Guid, Guid>(); // Added for Visual Studio 2010
new Dictionary<Int16, IntPtr>();
new Dictionary<Int32, Byte>();
new Dictionary<Int32, Int32>();
new Dictionary<Int32, Object>();
new Dictionary<IntPtr, Boolean>();
new Dictionary<IntPtr, Int16>();
new Dictionary<Object, Boolean>();
new Dictionary<Object, Char>();
new Dictionary<Object, Guid>();
new Dictionary<Object, Int32>();
new Dictionary<Object, Int64>(); // Added for Visual Studio 2010
new Dictionary<uint, WeakReference>(); // NCL team needs this
new Dictionary<Object, UInt32>();
new Dictionary<UInt32, Object>();
new Dictionary<Int64, Object>();
// to genereate mdil for Dictionary instantiation when key is user defined value type
new Dictionary<Guid, Int32>();
// Microsoft.Windows.Design
new Dictionary<System.Reflection.MemberTypes, Object>();
new EnumEqualityComparer<System.Reflection.MemberTypes>();
// Microsoft.Expression.DesignModel
new Dictionary<Object, KeyValuePair<Object,Object>>();
new Dictionary<KeyValuePair<Object,Object>, Object>();
NullableHelper<Boolean>();
NullableHelper<Byte>();
NullableHelper<Char>();
NullableHelper<DateTime>();
NullableHelper<Decimal>();
NullableHelper<Double>();
NullableHelper<Guid>();
NullableHelper<Int16>();
NullableHelper<Int32>();
NullableHelper<Int64>();
NullableHelper<Single>();
NullableHelper<TimeSpan>();
NullableHelper<DateTimeOffset>(); // For SQL
new List<Boolean>();
new List<Byte>();
new List<Char>();
new List<DateTime>();
new List<Decimal>();
new List<Double>();
new List<Guid>();
new List<Int16>();
new List<Int32>();
new List<Int64>();
new List<TimeSpan>();
new List<SByte>();
new List<Single>();
new List<UInt16>();
new List<UInt32>();
new List<UInt64>();
new List<IntPtr>();
new List<KeyValuePair<Object, Object>>();
new List<GCHandle>(); // NCL team needs this
new List<DateTimeOffset>();
new KeyValuePair<Char, UInt16>('\0', UInt16.MinValue);
new KeyValuePair<UInt16, Double>(UInt16.MinValue, Double.MinValue);
new KeyValuePair<Object, Int32>(String.Empty, Int32.MinValue);
new KeyValuePair<Int32, Int32>(Int32.MinValue, Int32.MinValue);
SZArrayHelper<Boolean>(null);
SZArrayHelper<Byte>(null);
SZArrayHelper<DateTime>(null);
SZArrayHelper<Decimal>(null);
SZArrayHelper<Double>(null);
SZArrayHelper<Guid>(null);
SZArrayHelper<Int16>(null);
SZArrayHelper<Int32>(null);
SZArrayHelper<Int64>(null);
SZArrayHelper<TimeSpan>(null);
SZArrayHelper<SByte>(null);
SZArrayHelper<Single>(null);
SZArrayHelper<UInt16>(null);
SZArrayHelper<UInt32>(null);
SZArrayHelper<UInt64>(null);
SZArrayHelper<DateTimeOffset>(null);
SZArrayHelper<CustomAttributeTypedArgument>(null);
SZArrayHelper<CustomAttributeNamedArgument>(null);
#pragma warning disable 4014
// This is necessary to generate MDIL for AsyncVoidMethodBuilder
AsyncHelper<int>();
AsyncHelper2<int>();
AsyncHelper3();
#pragma warning restore 4014
}
static T NullableHelper<T>() where T : struct
{
Nullable.Compare<T>(null, null);
Nullable.Equals<T>(null, null);
Nullable<T> nullable = new Nullable<T>();
return nullable.GetValueOrDefault();
}
static void SZArrayHelper<T>(SZArrayHelper oSZArrayHelper)
{
// Instantiate common methods for IList implementation on Array
oSZArrayHelper.get_Count<T>();
oSZArrayHelper.get_Item<T>(0);
oSZArrayHelper.GetEnumerator<T>();
}
// System.Runtime.CompilerServices.AsyncVoidMethodBuilder
// System.Runtime.CompilerServices.TaskAwaiter
static async void AsyncHelper<T>()
{
await Task.Delay(1);
}
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon]
// System.Runtime.CompilerServices.TaskAwaiter'[System.__Canon]
static async Task<String> AsyncHelper2<T>()
{
return await Task.FromResult<string>("");
}
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1[VoidTaskResult]
static async Task AsyncHelper3()
{
await Task.FromResult<string>("");
}
#if FEATURE_COMINTEROP
// Similar to CommonlyUsedGenericInstantiations but for instantiations of marshaling stubs used
// for WinRT redirected interfaces. Note that we do care about reference types here as well because,
// say, IList<string> and IList<object> cannot share marshaling stubs.
// The methods below "call" most commonly used stub methods on redirected interfaces and take arguments
// typed as matching instantiations of mscorlib copies of WinRT interfaces (IIterable<T>, IVector<T>,
// IMap<K, V>, ...) which is necessary to generate all required IL stubs.
static void CommonlyUsedWinRTRedirectedInterfaceStubs()
{
WinRT_IEnumerable<byte>(null, null, null);
WinRT_IEnumerable<char>(null, null, null);
WinRT_IEnumerable<short>(null, null, null);
WinRT_IEnumerable<ushort>(null, null, null);
WinRT_IEnumerable<int>(null, null, null);
WinRT_IEnumerable<uint>(null, null, null);
WinRT_IEnumerable<long>(null, null, null);
WinRT_IEnumerable<ulong>(null, null, null);
WinRT_IEnumerable<float>(null, null, null);
WinRT_IEnumerable<double>(null, null, null);
// The underlying WinRT types for shared instantiations have to be referenced explicitly.
// They are not guaranteeed to be created indirectly because of generic code sharing.
WinRT_IEnumerable<string>(null, null, null); typeof(IIterable<string>).ToString(); typeof(IIterator<string>).ToString();
WinRT_IEnumerable<object>(null, null, null); typeof(IIterable<object>).ToString(); typeof(IIterator<object>).ToString();
WinRT_IList<int>(null, null, null, null);
WinRT_IList<string>(null, null, null, null); typeof(IVector<string>).ToString();
WinRT_IList<object>(null, null, null, null); typeof(IVector<object>).ToString();
WinRT_IReadOnlyList<int>(null, null, null);
WinRT_IReadOnlyList<string>(null, null, null); typeof(IVectorView<string>).ToString();
WinRT_IReadOnlyList<object>(null, null, null); typeof(IVectorView<object>).ToString();
WinRT_IDictionary<string, int>(null, null, null, null); typeof(IMap<string, int>).ToString();
WinRT_IDictionary<string, string>(null, null, null, null); typeof(IMap<string, string>).ToString();
WinRT_IDictionary<string, object>(null, null, null, null); typeof(IMap<string, object>).ToString();
WinRT_IDictionary<object, object>(null, null, null, null); typeof(IMap<object, object>).ToString();
WinRT_IReadOnlyDictionary<string, int>(null, null, null, null); typeof(IMapView<string, int>).ToString();
WinRT_IReadOnlyDictionary<string, string>(null, null, null, null); typeof(IMapView<string, string>).ToString();
WinRT_IReadOnlyDictionary<string, object>(null, null, null, null); typeof(IMapView<string, object>).ToString();
WinRT_IReadOnlyDictionary<object, object>(null, null, null, null); typeof(IMapView<object, object>).ToString();
WinRT_Nullable<bool>();
WinRT_Nullable<byte>();
WinRT_Nullable<int>();
WinRT_Nullable<uint>();
WinRT_Nullable<long>();
WinRT_Nullable<ulong>();
WinRT_Nullable<float>();
WinRT_Nullable<double>();
}
static void WinRT_IEnumerable<T>(IterableToEnumerableAdapter iterableToEnumerableAdapter, EnumerableToIterableAdapter enumerableToIterableAdapter, IIterable<T> iterable)
{
// instantiate stubs for the one method on IEnumerable<T> and the one method on IIterable<T>
iterableToEnumerableAdapter.GetEnumerator_Stub<T>();
enumerableToIterableAdapter.First_Stub<T>();
}
static void WinRT_IList<T>(VectorToListAdapter vectorToListAdapter, VectorToCollectionAdapter vectorToCollectionAdapter, ListToVectorAdapter listToVectorAdapter, IVector<T> vector)
{
WinRT_IEnumerable<T>(null, null, null);
// instantiate stubs for commonly used methods on IList<T> and ICollection<T>
vectorToListAdapter.Indexer_Get<T>(0);
vectorToListAdapter.Indexer_Set<T>(0, default(T));
vectorToListAdapter.Insert<T>(0, default(T));
vectorToListAdapter.RemoveAt<T>(0);
vectorToCollectionAdapter.Count<T>();
vectorToCollectionAdapter.Add<T>(default(T));
vectorToCollectionAdapter.Clear<T>();
// instantiate stubs for commonly used methods on IVector<T>
listToVectorAdapter.GetAt<T>(0);
listToVectorAdapter.Size<T>();
listToVectorAdapter.SetAt<T>(0, default(T));
listToVectorAdapter.InsertAt<T>(0, default(T));
listToVectorAdapter.RemoveAt<T>(0);
listToVectorAdapter.Append<T>(default(T));
listToVectorAdapter.RemoveAtEnd<T>();
listToVectorAdapter.Clear<T>();
}
static void WinRT_IReadOnlyCollection<T>(VectorViewToReadOnlyCollectionAdapter vectorViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<T>(null, null, null);
// instantiate stubs for commonly used methods on IReadOnlyCollection<T>
vectorViewToReadOnlyCollectionAdapter.Count<T>();
}
static void WinRT_IReadOnlyList<T>(IVectorViewToIReadOnlyListAdapter vectorToListAdapter, IReadOnlyListToIVectorViewAdapter listToVectorAdapter, IVectorView<T> vectorView)
{
WinRT_IEnumerable<T>(null, null, null);
WinRT_IReadOnlyCollection<T>(null);
// instantiate stubs for commonly used methods on IReadOnlyList<T>
vectorToListAdapter.Indexer_Get<T>(0);
// instantiate stubs for commonly used methods on IVectorView<T>
listToVectorAdapter.GetAt<T>(0);
listToVectorAdapter.Size<T>();
}
static void WinRT_IDictionary<K, V>(MapToDictionaryAdapter mapToDictionaryAdapter, MapToCollectionAdapter mapToCollectionAdapter, DictionaryToMapAdapter dictionaryToMapAdapter, IMap<K, V> map)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
// instantiate stubs for commonly used methods on IDictionary<K, V> and ICollection<KeyValuePair<K, V>>
V dummy;
mapToDictionaryAdapter.Indexer_Get<K, V>(default(K));
mapToDictionaryAdapter.Indexer_Set<K, V>(default(K), default(V));
mapToDictionaryAdapter.ContainsKey<K, V>(default(K));
mapToDictionaryAdapter.Add<K, V>(default(K), default(V));
mapToDictionaryAdapter.Remove<K, V>(default(K));
mapToDictionaryAdapter.TryGetValue<K, V>(default(K), out dummy);
mapToCollectionAdapter.Count<K, V>();
mapToCollectionAdapter.Add<K, V>(new KeyValuePair<K, V>(default(K), default(V)));
mapToCollectionAdapter.Clear<K, V>();
// instantiate stubs for commonly used methods on IMap<K, V>
dictionaryToMapAdapter.Lookup<K, V>(default(K));
dictionaryToMapAdapter.Size<K, V>();
dictionaryToMapAdapter.HasKey<K, V>(default(K));
dictionaryToMapAdapter.Insert<K, V>(default(K), default(V));
dictionaryToMapAdapter.Remove<K, V>(default(K));
dictionaryToMapAdapter.Clear<K, V>();
}
static void WinRT_IReadOnlyDictionary<K, V>(IMapViewToIReadOnlyDictionaryAdapter mapToDictionaryAdapter, IReadOnlyDictionaryToIMapViewAdapter dictionaryToMapAdapter, IMapView<K, V> mapView, MapViewToReadOnlyCollectionAdapter mapViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
WinRT_IReadOnlyCollection<KeyValuePair<K, V>>(null);
// instantiate stubs for commonly used methods on IReadOnlyDictionary<K, V>
V dummy;
mapToDictionaryAdapter.Indexer_Get<K, V>(default(K));
mapToDictionaryAdapter.ContainsKey<K, V>(default(K));
mapToDictionaryAdapter.TryGetValue<K, V>(default(K), out dummy);
// instantiate stubs for commonly used methods in IReadOnlyCollection<T>
mapViewToReadOnlyCollectionAdapter.Count<K, V>();
// instantiate stubs for commonly used methods on IMapView<K, V>
dictionaryToMapAdapter.Lookup<K, V>(default(K));
dictionaryToMapAdapter.Size<K, V>();
dictionaryToMapAdapter.HasKey<K, V>(default(K));
}
static void WinRT_Nullable<T>() where T : struct
{
Nullable<T> nullable = new Nullable<T>();
NullableMarshaler.ConvertToNative(ref nullable);
NullableMarshaler.ConvertToManagedRetVoid(IntPtr.Zero, ref nullable);
}
#endif // FEATURE_COMINTEROP
}
}
| |
//#define ENABLE_INC_DEC_FIX
using System;
using System.Collections.Generic;
using System.IO;
using ProtoCore.AST;
using ProtoCore.DSASM;
using ProtoCore.Utils;
using DesignScript.Editor.Core;
namespace FunctionCallParser {
// Since the parser is generated, we don't want the
// compiler to make noise about it not being CLS-compliant
#pragma warning disable 3008
public class Parser {
public const int _EOF = 0;
public const int _ident = 1;
public const int _number = 2;
public const int _float = 3;
public const int _textstring = 4;
public const int _char = 5;
public const int _period = 6;
public const int _openbracket = 7;
public const int _closebracket = 8;
public const int _openparen = 9;
public const int _closeparen = 10;
public const int _not = 11;
public const int _neg = 12;
public const int _pipe = 13;
public const int _lessthan = 14;
public const int _greaterthan = 15;
public const int _lessequal = 16;
public const int _greaterequal = 17;
public const int _equal = 18;
public const int _notequal = 19;
public const int _endline = 20;
public const int _rangeop = 21;
public const int _kw_native = 22;
public const int _kw_class = 23;
public const int _kw_constructor = 24;
public const int _kw_def = 25;
public const int _kw_external = 26;
public const int _kw_extend = 27;
public const int _kw_heap = 28;
public const int _kw_if = 29;
public const int _kw_elseif = 30;
public const int _kw_else = 31;
public const int _kw_while = 32;
public const int _kw_for = 33;
public const int _kw_import = 34;
public const int _kw_prefix = 35;
public const int _kw_from = 36;
public const int _kw_break = 37;
public const int _kw_continue = 38;
public const int _kw_static = 39;
public const int _literal_true = 40;
public const int _literal_false = 41;
public const int _literal_null = 42;
public const int maxT = 56;
const bool T = true;
const bool x = false;
const int minErrDist = 2;
public Scanner scanner;
public Errors errors;
public Token t; // last recognized token
public Token la; // lookahead token
int errDist = minErrDist;
FunctionCallPart rootFunctionCallPart = null;
public FunctionCallPart RootFunctionCallPart
{
get { return this.rootFunctionCallPart; }
}
public Parser(Scanner scanner) {
this.scanner = scanner;
errors = new Errors();
}
System.Drawing.Point PointFromToken(Token token, bool includeToken)
{
if (false != includeToken)
return (new System.Drawing.Point(token.col - 1, token.line - 1));
int x = token.col + token.val.Length - 1;
return (new System.Drawing.Point(x, token.line - 1));
}
void SynErr (int n) {
if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n);
errDist = 0;
}
public void SemErr (string msg) {
if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg);
errDist = 0;
}
void Get () {
for (;;) {
t = la;
la = scanner.Scan();
if (la.kind <= maxT) { ++errDist; break; }
la = t;
}
}
void Expect (int n) {
if (la.kind==n) Get(); else { SynErr(n); }
}
bool StartOf (int s) {
return set[s, la.kind];
}
void ExpectWeak (int n, int follow) {
if (la.kind == n) Get();
else {
SynErr(n);
while (!StartOf(follow)) Get();
}
}
bool WeakSeparator(int n, int syFol, int repFol) {
int kind = la.kind;
if (kind == n) {Get(); return true;}
else if (StartOf(repFol)) {return false;}
else {
SynErr(n);
while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) {
Get();
kind = la.kind;
}
return StartOf(syFol);
}
}
void FunctionCallParser() {
rootFunctionCallPart = new FunctionCallPart();
CommonExpression(rootFunctionCallPart);
}
void CommonExpression(FunctionCallPart part) {
if (StartOf(1)) {
CommonLogicalExpression(part);
} else if (la.kind == 51) {
CommonTernaryOperation(part);
} else SynErr(57);
}
void CommonLogicalExpression(FunctionCallPart part) {
CommonComparisonExpression(part);
while (la.kind == 49 || la.kind == 50) {
CommonLogicalOperator(part);
CommonComparisonExpression(part);
}
}
void CommonTernaryOperation(FunctionCallPart part) {
Expect(51);
CommonExpression(part);
Expect(52);
CommonExpression(part);
}
void CommonComparisonExpression(FunctionCallPart part) {
CommonRangeExpression(part);
while (StartOf(2)) {
CommonComparisonOperator(part);
CommonRangeExpression(part);
}
}
void CommonLogicalOperator(FunctionCallPart part) {
if (la.kind == 49) {
Get();
} else if (la.kind == 50) {
Get();
} else SynErr(58);
}
void CommonRangeExpression(FunctionCallPart part) {
CommonArithmeticExpression(part);
if (la.kind == 21) {
Get();
CommonArithmeticExpression(part);
if (la.kind == 21) {
Get();
if (la.kind == 43 || la.kind == 44) {
if (la.kind == 43) {
Get();
} else {
Get();
}
}
CommonArithmeticExpression(part);
}
}
}
void CommonComparisonOperator(FunctionCallPart part) {
switch (la.kind) {
case 15: {
Get();
break;
}
case 17: {
Get();
break;
}
case 14: {
Get();
break;
}
case 16: {
Get();
break;
}
case 18: {
Get();
break;
}
case 19: {
Get();
break;
}
default: SynErr(59); break;
}
}
void CommonArithmeticExpression(FunctionCallPart part) {
CommonTerm(part);
while (StartOf(3)) {
CommonMathOperator(part);
CommonTerm(part);
}
}
void CommonTerm(FunctionCallPart part) {
switch (la.kind) {
case 40: {
Get();
break;
}
case 41: {
Get();
break;
}
case 42: {
Get();
break;
}
case 5: {
CommonCharacter(part);
break;
}
case 4: {
CommonString(part);
break;
}
case 1: case 2: case 3: case 12: case 53: {
CommonNegativeExpression(part);
break;
}
case 11: {
Get();
CommonTerm(part);
break;
}
default: SynErr(60); break;
}
}
void CommonMathOperator(FunctionCallPart part) {
if (la.kind == 45) {
Get();
} else if (la.kind == 12) {
Get();
} else if (la.kind == 46) {
Get();
} else if (la.kind == 47) {
Get();
} else if (la.kind == 48) {
Get();
} else SynErr(61);
}
void CommonCharacter(FunctionCallPart part) {
Expect(5);
}
void CommonString(FunctionCallPart part) {
Expect(4);
}
void CommonNegativeExpression(FunctionCallPart part) {
if (la.kind == 12) {
Get();
part.AppendIdentifier(t);
}
if (la.kind == 2 || la.kind == 3) {
if (la.kind == 2) {
Get();
} else {
Get();
}
part.AppendIdentifier(t);
} else if (la.kind == 1 || la.kind == 53) {
CommonIdentifierList(part);
} else SynErr(62);
}
void CommonIdentifierList(FunctionCallPart part) {
string partName = string.Empty;
CommonNameReference(part);
partName = part.Identifier;
while (la.kind == 6) {
Get();
CommonNameReference(part);
string newPartName = part.Identifier;
part.Identifier = partName + "." + newPartName;
partName = part.Identifier;
}
}
void CommonNameReference(FunctionCallPart part) {
if (la.kind == 1) {
CommonFunctionCall(part);
} else if (la.kind == 53) {
CommonArrayExpression(part);
} else SynErr(63);
if (la.kind == 7) {
Get();
part.AppendIdentifier(t); part.SetEndPoint(t, false);
if (StartOf(4)) {
CommonExpression(part);
part.SetEndPoint(t, false);
}
Expect(8);
part.AppendIdentifier(t); part.SetEndPoint(t, false);
while (la.kind == 7) {
Get();
part.AppendIdentifier(t); part.SetEndPoint(t, false);
if (StartOf(4)) {
CommonExpression(part);
part.SetEndPoint(t, false);
}
Expect(8);
part.AppendIdentifier(t); part.SetEndPoint(t, false);
}
}
}
void CommonFunctionCall(FunctionCallPart part) {
CommonIdentifier(part);
while (la.kind == 9) {
CommonArguments(part);
}
}
void CommonArrayExpression(FunctionCallPart part) {
Expect(53);
part.SetStartPoint(t, false);
if (StartOf(4)) {
FunctionCallPart elementPart = new FunctionCallPart();
CommonExpression(elementPart);
part.AddArgumentPart(elementPart);
while (la.kind == 54) {
Get();
elementPart = new FunctionCallPart();
CommonExpression(elementPart);
part.AddArgumentPart(elementPart);
}
}
Expect(55);
part.SetEndPoint(t, true);
}
void CommonIdentifier(FunctionCallPart part) {
Expect(1);
part.Identifier = t.val;
}
void CommonArguments(FunctionCallPart part) {
Expect(9);
part.SetStartPoint(t, false);
part.SetEndPoint(la, true);
System.Drawing.Point openBracket = PointFromToken(t, false);
if (StartOf(4)) {
FunctionCallPart parentCallPart = part;
part = new FunctionCallPart();
part.SetStartPoint(t, false);
CommonExpression(part);
part.SetEndPoint(t, false);
parentCallPart.AddArgumentPart(part);
part = parentCallPart;
while (WeakSeparator(54,4,5) ) {
parentCallPart = part;
part = new FunctionCallPart();
part.SetStartPoint(t, false);
CommonExpression(part);
part.SetEndPoint(la, true);
parentCallPart.AddArgumentPart(part);
part = parentCallPart;
}
}
if (part.HasArgument == false) {
// See "AddDefaultArgument" for details.
System.Drawing.Point closeBracket = PointFromToken(la, true);
part.AddDefaultArgument(openBracket, closeBracket);
}
Expect(10);
part.SetEndPoint(t, true);
}
public void Parse() {
la = new Token();
la.val = "";
Get();
FunctionCallParser();
Expect(0);
}
static readonly bool[,] set = {
{T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x},
{x,T,T,T, T,T,x,x, x,x,x,T, T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, T,T,T,x, x,x,x,x, x,x,x,x, x,T,x,x, x,x},
{x,x,x,x, x,x,x,x, x,x,x,x, x,x,T,T, T,T,T,T, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x},
{x,x,x,x, x,x,x,x, x,x,x,x, T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,T,T,T, T,x,x,x, x,x,x,x, x,x},
{x,T,T,T, T,T,x,x, x,x,x,T, T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, T,T,T,x, x,x,x,x, x,x,x,T, x,T,x,x, x,x},
{x,x,x,x, x,x,x,x, x,x,T,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x}
};
} // end Parser
public class Errors {
public int count = 0; // number of errors detected
public virtual void SynErr (int line, int col, int n) {
string s;
switch (n) {
case 0: s = "EOF expected"; break;
case 1: s = "ident expected"; break;
case 2: s = "number expected"; break;
case 3: s = "float expected"; break;
case 4: s = "textstring expected"; break;
case 5: s = "char expected"; break;
case 6: s = "period expected"; break;
case 7: s = "openbracket expected"; break;
case 8: s = "closebracket expected"; break;
case 9: s = "openparen expected"; break;
case 10: s = "closeparen expected"; break;
case 11: s = "not expected"; break;
case 12: s = "neg expected"; break;
case 13: s = "pipe expected"; break;
case 14: s = "lessthan expected"; break;
case 15: s = "greaterthan expected"; break;
case 16: s = "lessequal expected"; break;
case 17: s = "greaterequal expected"; break;
case 18: s = "equal expected"; break;
case 19: s = "notequal expected"; break;
case 20: s = "endline expected"; break;
case 21: s = "rangeop expected"; break;
case 22: s = "kw_native expected"; break;
case 23: s = "kw_class expected"; break;
case 24: s = "kw_constructor expected"; break;
case 25: s = "kw_def expected"; break;
case 26: s = "kw_external expected"; break;
case 27: s = "kw_extend expected"; break;
case 28: s = "kw_heap expected"; break;
case 29: s = "kw_if expected"; break;
case 30: s = "kw_elseif expected"; break;
case 31: s = "kw_else expected"; break;
case 32: s = "kw_while expected"; break;
case 33: s = "kw_for expected"; break;
case 34: s = "kw_import expected"; break;
case 35: s = "kw_prefix expected"; break;
case 36: s = "kw_from expected"; break;
case 37: s = "kw_break expected"; break;
case 38: s = "kw_continue expected"; break;
case 39: s = "kw_static expected"; break;
case 40: s = "literal_true expected"; break;
case 41: s = "literal_false expected"; break;
case 42: s = "literal_null expected"; break;
case 43: s = "\"#\" expected"; break;
case 44: s = "\"~\" expected"; break;
case 45: s = "\"+\" expected"; break;
case 46: s = "\"*\" expected"; break;
case 47: s = "\"/\" expected"; break;
case 48: s = "\"%\" expected"; break;
case 49: s = "\"&&\" expected"; break;
case 50: s = "\"||\" expected"; break;
case 51: s = "\"?\" expected"; break;
case 52: s = "\":\" expected"; break;
case 53: s = "\"{\" expected"; break;
case 54: s = "\",\" expected"; break;
case 55: s = "\"}\" expected"; break;
case 56: s = "??? expected"; break;
case 57: s = "invalid CommonExpression"; break;
case 58: s = "invalid CommonLogicalOperator"; break;
case 59: s = "invalid CommonComparisonOperator"; break;
case 60: s = "invalid CommonTerm"; break;
case 61: s = "invalid CommonMathOperator"; break;
case 62: s = "invalid CommonNegativeExpression"; break;
case 63: s = "invalid CommonNameReference"; break;
default: s = "error " + n; break;
}
count++;
}
public virtual void SemErr (int line, int col, string s) {
count++;
}
public virtual void SemErr (string s) {
count++;
}
public virtual void Warning (int line, int col, string s) {
}
public virtual void Warning(string s) {
}
} // Errors
public class FatalError: Exception {
public FatalError(string m): base(m) {}
}
#pragma warning restore 3008
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.