context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// Reserved Instances Offering /// </summary> [XmlRootAttribute(IsNullable = false)] public class ReservedInstancesOffering { private string reservedInstancesOfferingIdField; private string instanceTypeField; private string availabilityZoneField; private Decimal? durationField; private string usagePriceField; private string fixedPriceField; private string productDescriptionField; private string instanceTenancyField; private string currencyCodeField; private string offeringTypeField; private List<RecurringCharges> recurringChargesField; private bool? isMarketplaceField; private List<PricingDetails> pricingDetailsField; /// <summary> /// The ID of the Reserved Instance offering. /// </summary> [XmlElementAttribute(ElementName = "ReservedInstancesOfferingId")] public string ReservedInstancesOfferingId { get { return this.reservedInstancesOfferingIdField; } set { this.reservedInstancesOfferingIdField = value; } } /// <summary> /// Sets the ID of the Reserved Instance offering. /// </summary> /// <param name="reservedInstancesOfferingId">The ID of the Reserved Instance offering.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithReservedInstancesOfferingId(string reservedInstancesOfferingId) { this.reservedInstancesOfferingIdField = reservedInstancesOfferingId; return this; } /// <summary> /// Checks if ReservedInstancesOfferingId property is set /// </summary> /// <returns>true if ReservedInstancesOfferingId property is set</returns> public bool IsSetReservedInstancesOfferingId() { return this.reservedInstancesOfferingIdField != null; } /// <summary> /// The instance type on which the Reserved Instance can be used. /// </summary> [XmlElementAttribute(ElementName = "InstanceType")] public string InstanceType { get { return this.instanceTypeField; } set { this.instanceTypeField = value; } } /// <summary> /// Sets the instance type on which the Reserved Instance can be used. /// </summary> /// <param name="instanceType">The instance type on which the Reserved /// Instance can be used.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithInstanceType(string instanceType) { this.instanceTypeField = instanceType; return this; } /// <summary> /// Checks if InstanceType property is set /// </summary> /// <returns>true if InstanceType property is set</returns> public bool IsSetInstanceType() { return this.instanceTypeField != null; } /// <summary> /// The Availability Zone in which the Reserved Instance can be used. /// </summary> [XmlElementAttribute(ElementName = "AvailabilityZone")] public string AvailabilityZone { get { return this.availabilityZoneField; } set { this.availabilityZoneField = value; } } /// <summary> /// Sets the Availability Zone in which the Reserved Instance can be used. /// </summary> /// <param name="availabilityZone">The Availability Zone in which the Reserved /// Instance can be used.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithAvailabilityZone(string availabilityZone) { this.availabilityZoneField = availabilityZone; return this; } /// <summary> /// Checks if AvailabilityZone property is set /// </summary> /// <returns>true if AvailabilityZone property is set</returns> public bool IsSetAvailabilityZone() { return this.availabilityZoneField != null; } /// <summary> /// The duration of the Reserved Instance, in seconds. /// </summary> [XmlElementAttribute(ElementName = "Duration")] public Decimal Duration { get { return this.durationField.GetValueOrDefault(); } set { this.durationField = value; } } /// <summary> /// Sets the duration of the Reserved Instance, in seconds. /// </summary> /// <param name="duration">The duration of the Reserved Instance, in /// seconds.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithDuration(Decimal duration) { this.durationField = duration; return this; } /// <summary> /// Checks if Duration property is set /// </summary> /// <returns>true if Duration property is set</returns> public bool IsSetDuration() { return this.durationField.HasValue; } /// <summary> /// The usage price of the Reserved Instance, per hour. /// </summary> [XmlElementAttribute(ElementName = "UsagePrice")] public string UsagePrice { get { return this.usagePriceField; } set { this.usagePriceField = value; } } /// <summary> /// Sets the usage price of the Reserved Instance, per hour. /// </summary> /// <param name="usagePrice">The usage price of the Reserved Instance, per /// hour.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithUsagePrice(string usagePrice) { this.usagePriceField = usagePrice; return this; } /// <summary> /// Checks if UsagePrice property is set /// </summary> /// <returns>true if UsagePrice property is set</returns> public bool IsSetUsagePrice() { return this.usagePriceField != null; } /// <summary> /// The purchase price of the Reserved Instance. /// </summary> [XmlElementAttribute(ElementName = "FixedPrice")] public string FixedPrice { get { return this.fixedPriceField; } set { this.fixedPriceField = value; } } /// <summary> /// Sets the purchase price of the Reserved Instance. /// </summary> /// <param name="fixedPrice">The purchase price of the Reserved Instance.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithFixedPrice(string fixedPrice) { this.fixedPriceField = fixedPrice; return this; } /// <summary> /// Checks if FixedPrice property is set /// </summary> /// <returns>true if FixedPrice property is set</returns> public bool IsSetFixedPrice() { return this.fixedPriceField != null; } /// <summary> /// The Reserved Instance description. /// </summary> [XmlElementAttribute(ElementName = "ProductDescription")] public string ProductDescription { get { return this.productDescriptionField; } set { this.productDescriptionField = value; } } /// <summary> /// Sets the Reserved Instance description. /// </summary> /// <param name="productDescription">The Reserved Instance description.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithProductDescription(string productDescription) { this.productDescriptionField = productDescription; return this; } /// <summary> /// Checks if ProductDescription property is set /// </summary> /// <returns>true if ProductDescription property is set</returns> public bool IsSetProductDescription() { return this.productDescriptionField != null; } /// <summary> /// The tenancy of the reserved instance. /// </summary> [XmlElementAttribute(ElementName = "InstanceTenancy")] public string InstanceTenancy { get { return this.instanceTenancyField; } set { this.instanceTenancyField = value; } } /// <summary> /// Checks if InstanceTenancy property is set /// </summary> /// <returns>true if InstanceTenancy property is set</returns> public bool IsSetInstanceTenancy() { return this.instanceTenancyField != null; } /// <summary> /// Sets the tenancy of the reserved instance. /// </summary> /// <param name="instanceTenancy">The tenancy of the reserved instance.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithInstanceTenancy(string instanceTenancy) { this.instanceTenancyField = instanceTenancy; return this; } /// <summary> /// The currency of the Reserved Instance offering you are purchasing. /// It's specified using ISO 4217 standard (e.g., USD, JPY). /// </summary> [XmlElementAttribute(ElementName = "CurrencyCode")] public string CurrencyCode { get { return this.currencyCodeField; } set { this.currencyCodeField = value; } } /// <summary> /// Checks if CurrencyCode property is set /// </summary> /// <returns>true if CurrencyCode property is set</returns> public bool IsSetCurrencyCode() { return this.currencyCodeField != null; } /// <summary> /// Sets the currency of the Reserved Instance offering you are purchasing. /// </summary> /// <param name="currencyCode">The ISO 4217 CurrencyCode (e.g., USD, JPY).</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithCurrencyCode(string currencyCode) { this.currencyCodeField = currencyCode; return this; } /// <summary> /// The Reserved Instance Offering type. /// </summary> [XmlElementAttribute(ElementName = "OfferingType")] public string OfferingType { get { return this.offeringTypeField; } set { this.offeringTypeField = value; } } /// <summary> /// Checks if OfferingType property is set /// </summary> /// <returns>true if OfferingType property is set</returns> public bool IsSetOfferingType() { return this.offeringTypeField != null; } /// <summary> /// Sets the Reserved Instance Offering type. /// </summary> /// <param name="offeringType">The Reserved Instance Offering type</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithOfferingType(string offeringType) { this.offeringTypeField = offeringType; return this; } /// <summary> /// Zero or more recurring charges associated with the Reserved Instance offering. /// </summary> [XmlElementAttribute(ElementName = "RecurringCharges")] public List<RecurringCharges> RecurringCharges { get { if (this.recurringChargesField == null) { this.recurringChargesField = new List<RecurringCharges>(); } return this.recurringChargesField; } set { this.recurringChargesField = value; } } /// <summary> /// Sets recurring charges associated with the Reserved Instance offering. /// </summary> /// <param name="list">Zero or more recurring charges associated with the Reserved Instance offering.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithRecurringCharges(params RecurringCharges[] list) { foreach (RecurringCharges item in list) { this.RecurringCharges.Add(item); } return this; } /// <summary> /// Checks if RecurringCharges property is set /// </summary> /// <returns>true if RecurringCharges property is set</returns> public bool IsSetRecurringCharges() { return (RecurringCharges.Count > 0); } /// <summary> /// Whether the offering is available through the Reserved Instance /// Marketplace (resale) or AWS. True if it is a Marketplace offering. /// </summary> [XmlElementAttribute(ElementName = "IsMarketPlace")] public bool IsMarketPlace { get { return this.isMarketplaceField.GetValueOrDefault(); } set { this.isMarketplaceField = value; } } /// <summary> /// Sets whether the offering is available through the Reserved Instance /// Marketplace (resale) or AWS. /// </summary> /// <param name="isMarketplace">True if it is a Marketplace offering.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithIsMarketplace(bool isMarketplace) { this.isMarketplaceField = isMarketplace; return this; } /// <summary> /// Checks if the IsMarketplace property is set. /// </summary> /// <returns>True if the property is set</returns> public bool IsSetIsMarketplace() { return this.isMarketplaceField != null; } /// <summary> /// The pricing details of the Reserved Instance offering. /// </summary> [XmlElementAttribute(ElementName = "PricingDetails")] public List<PricingDetails> PricingDetails { get { if (this.pricingDetailsField == null) { this.pricingDetailsField = new List<PricingDetails>(); } return this.pricingDetailsField; } set { this.pricingDetailsField = value; } } /// <summary> /// Sets the pricing details of the Reserved Instance offering. /// </summary> /// <param name="list">Pricing details for the offering</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ReservedInstancesOffering WithPricingDetails(params PricingDetails[] list) { foreach (PricingDetails item in list) { this.PricingDetails.Add(item); } return this; } /// <summary> /// Checks if the PricingDetails property is set. /// </summary> /// <returns>True if the property is set</returns> public bool IsSetPricingDetails() { return (this.PricingDetails.Count > 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using Xunit; namespace System { public static partial class PlatformDetection { public static Version OSXVersion => throw new PlatformNotSupportedException(); public static Version OpenSslVersion => throw new PlatformNotSupportedException(); public static bool IsSuperUser => throw new PlatformNotSupportedException(); public static bool IsCentos6 => false; public static bool IsOpenSUSE => false; public static bool IsUbuntu => false; public static bool IsDebian => false; public static bool IsAlpine => false; public static bool IsDebian8 => false; public static bool IsUbuntu1404 => false; public static bool IsUbuntu1604 => false; public static bool IsUbuntu1704 => false; public static bool IsUbuntu1710 => false; public static bool IsUbuntu1710OrHigher => false; public static bool IsUbuntu1804 => false; public static bool IsTizen => false; public static bool IsNotFedoraOrRedHatFamily => true; public static bool IsFedora => false; public static bool IsWindowsNanoServer => (IsNotWindowsIoTCore && GetInstallationType().Equals("Nano Server", StringComparison.OrdinalIgnoreCase)); public static bool IsWindowsServerCore => GetInstallationType().Equals("Server Core", StringComparison.OrdinalIgnoreCase); public static int WindowsVersion => GetWindowsVersion(); public static bool IsMacOsHighSierraOrHigher { get; } = false; public static Version ICUVersion => new Version(0, 0, 0, 0); public static bool IsRedHatFamily => false; public static bool IsNotRedHatFamily => true; public static bool IsRedHatFamily6 => false; public static bool IsRedHatFamily7 => false; public static bool IsNotRedHatFamily6 => true; public static bool IsWindows10Version1607OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393; public static bool IsWindows10Version1703OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063; public static bool IsWindows10Version1709OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16299; public static bool IsWindows10Version1803OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 17134; // Windows OneCoreUAP SKU doesn't have httpapi.dll public static bool IsNotOneCoreUAP => File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "httpapi.dll")); public static bool IsWindowsIoTCore { get { int productType = GetWindowsProductType(); if ((productType == PRODUCT_IOTUAPCOMMERCIAL) || (productType == PRODUCT_IOTUAP)) { return true; } return false; } } public static bool IsWindowsHomeEdition { get { int productType = GetWindowsProductType(); switch (productType) { case PRODUCT_CORE: case PRODUCT_CORE_COUNTRYSPECIFIC: case PRODUCT_CORE_N: case PRODUCT_CORE_SINGLELANGUAGE: case PRODUCT_HOME_BASIC: case PRODUCT_HOME_BASIC_N: case PRODUCT_HOME_PREMIUM: case PRODUCT_HOME_PREMIUM_N: return true; default: return false; } } } public static bool IsWindows => true; public static bool IsWindows7 => GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1; public static bool IsWindows8x => GetWindowsVersion() == 6 && (GetWindowsMinorVersion() == 2 || GetWindowsMinorVersion() == 3); public static string LibcRelease => "glibc_not_found"; public static string LibcVersion => "glibc_not_found"; public static string GetDistroVersionString() { return "WindowsProductType=" + GetWindowsProductType() + " WindowsInstallationType=" + GetInstallationType(); } private static int s_isInAppContainer = -1; public static bool IsInAppContainer { // This actually checks whether code is running in a modern app. // Currently this is the only situation where we run in app container. // If we want to distinguish the two cases in future, // EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token. get { if (s_isInAppContainer != -1) return s_isInAppContainer == 1; if (!IsWindows || IsWindows7) { s_isInAppContainer = 0; return false; } byte[] buffer = Array.Empty<byte>(); uint bufferSize = 0; try { int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer); switch (result) { case 15703: // APPMODEL_ERROR_NO_APPLICATION s_isInAppContainer = 0; break; case 0: // ERROR_SUCCESS case 122: // ERROR_INSUFFICIENT_BUFFER // Success is actually insufficent buffer as we're really only looking for // not NO_APPLICATION and we're not actually giving a buffer here. The // API will always return NO_APPLICATION if we're not running under a // WinRT process, no matter what size the buffer is. s_isInAppContainer = 1; break; default: throw new InvalidOperationException($"Failed to get AppId, result was {result}."); } } catch (Exception e) { // We could catch this here, being friendly with older portable surface area should we // desire to use this method elsewhere. if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal)) { // API doesn't exist, likely pre Win8 s_isInAppContainer = 0; } else { throw; } } return s_isInAppContainer == 1; } } private static int s_isWindowsElevated = -1; public static bool IsWindowsAndElevated { get { if (s_isWindowsElevated != -1) return s_isWindowsElevated == 1; if (!IsWindows || IsInAppContainer) { s_isWindowsElevated = 0; return false; } IntPtr processToken; Assert.True(OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out processToken)); try { uint tokenInfo; uint returnLength; Assert.True(GetTokenInformation( processToken, TokenElevation, out tokenInfo, sizeof(uint), out returnLength)); s_isWindowsElevated = tokenInfo == 0 ? 0 : 1; } finally { CloseHandle(processToken); } return s_isWindowsElevated == 1; } } private static string GetInstallationType() { string key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"; string value = ""; try { value = (string)Registry.GetValue(key, "InstallationType", defaultValue: ""); } catch (Exception e) when (e is SecurityException || e is InvalidCastException || e is PlatformNotSupportedException /* UAP */) { } return value; } private static int GetWindowsProductType() { Assert.True(GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, out int productType)); return productType; } private static unsafe int GetWindowsMinorVersion() { var osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX); Assert.Equal(0, RtlGetVersion(ref osvi)); return (int)osvi.dwMinorVersion; } private static unsafe int GetWindowsBuildNumber() { var osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX); Assert.Equal(0, RtlGetVersion(ref osvi)); return (int)osvi.dwBuildNumber; } private const uint TokenElevation = 20; private const uint STANDARD_RIGHTS_READ = 0x00020000; private const uint TOKEN_QUERY = 0x0008; private const uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY; [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] private static extern bool GetTokenInformation( IntPtr TokenHandle, uint TokenInformationClass, out uint TokenInformation, uint TokenInformationLength, out uint ReturnLength); private const int PRODUCT_IOTUAP = 0x0000007B; private const int PRODUCT_IOTUAPCOMMERCIAL = 0x00000083; private const int PRODUCT_CORE = 0x00000065; private const int PRODUCT_CORE_COUNTRYSPECIFIC = 0x00000063; private const int PRODUCT_CORE_N = 0x00000062; private const int PRODUCT_CORE_SINGLELANGUAGE = 0x00000064; private const int PRODUCT_HOME_BASIC = 0x00000002; private const int PRODUCT_HOME_BASIC_N = 0x00000005; private const int PRODUCT_HOME_PREMIUM = 0x00000003; private const int PRODUCT_HOME_PREMIUM_N = 0x0000001A; [DllImport("kernel32.dll", SetLastError = false)] private static extern bool GetProductInfo( int dwOSMajorVersion, int dwOSMinorVersion, int dwSpMajorVersion, int dwSpMinorVersion, out int pdwReturnedProductType ); [DllImport("ntdll.dll", ExactSpelling=true)] private static extern int RtlGetVersion(ref RTL_OSVERSIONINFOEX lpVersionInformation); [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] private unsafe struct RTL_OSVERSIONINFOEX { internal uint dwOSVersionInfoSize; internal uint dwMajorVersion; internal uint dwMinorVersion; internal uint dwBuildNumber; internal uint dwPlatformId; internal fixed char szCSDVersion[128]; } private static unsafe int GetWindowsVersion() { var osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX); Assert.Equal(0, RtlGetVersion(ref osvi)); return (int)osvi.dwMajorVersion; } [DllImport("kernel32.dll", ExactSpelling = true)] private static extern int GetCurrentApplicationUserModelId(ref uint applicationUserModelIdLength, byte[] applicationUserModelId); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] private static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle); // The process handle does NOT need closing [DllImport("kernel32.dll", ExactSpelling = true)] private static extern IntPtr GetCurrentProcess(); } }
using System; using RockLib.Configuration.ObjectFactory; using RockLib.Configuration; using RockLib.Immutable; using RockLib.Encryption.Async; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; namespace RockLib.Encryption { /// <summary> /// Provides a set of static methods used for encryption and decryption /// operations. /// </summary> public static class Crypto { private static readonly Semimutable<ICrypto> _current = new Semimutable<ICrypto>(GetDefaultCrypto); /// <summary> /// Gets the current instance of <see cref="ICrypto"/>. /// </summary> /// <remarks> /// Each method of the <see cref="Crypto"/> class ultimately uses the value /// of this property and calls one of its methods. /// </remarks> public static ICrypto Current { get { return _current.Value; } } /// <summary> /// Sets the value of the <see cref="Current"/> property. /// </summary> /// <param name="crypto"> /// The new value for the <see cref="Current"/> property, or null to set /// to the default <see cref="ICrypto"/>. /// </param> /// <remarks> /// Each method of the <see cref="Crypto"/> class ultimately uses the value /// of the <see cref="Current"/> property and calls one of its methods. /// </remarks> public static void SetCurrent(ICrypto crypto) { _current.SetValue(() => crypto ?? GetDefaultCrypto()); } /// <summary> /// Encrypts the specified plain text. /// </summary> /// <param name="plainText">The plain text.</param> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <returns>The encrypted value as a string.</returns> public static string Encrypt(string plainText, string credentialName = null) { return Current.Encrypt(plainText, credentialName); } /// <summary> /// Decrypts the specified cipher text. /// </summary> /// <param name="cipherText">The cipher text.</param> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <returns>The decrypted value as a string.</returns> public static string Decrypt(string cipherText, string credentialName = null) { return Current.Decrypt(cipherText, credentialName); } /// <summary> /// Encrypts the specified plain text. /// </summary> /// <param name="plainText">The plain text.</param> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <returns>The encrypted value as a byte array.</returns> public static byte[] Encrypt(byte[] plainText, string credentialName = null) { return Current.Encrypt(plainText, credentialName); } /// <summary> /// Decrypts the specified cipher text. /// </summary> /// <param name="cipherText">The cipher text.</param> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <returns>The decrypted value as a byte array.</returns> public static byte[] Decrypt(byte[] cipherText, string credentialName = null) { return Current.Decrypt(cipherText, credentialName); } /// <summary> /// Gets an instance of <see cref="IEncryptor"/> for the provided key identifier. /// </summary> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <returns>An object that can be used for encryption operations.</returns> public static IEncryptor GetEncryptor(string credentialName = null) { return Current.GetEncryptor(credentialName); } /// <summary> /// Gets an instance of <see cref="IDecryptor"/> for the provided key identifier. /// </summary> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <returns>An object that can be used for decryption operations.</returns> public static IDecryptor GetDecryptor(string credentialName = null) { return Current.GetDecryptor(credentialName); } /// <summary> /// Asynchronously encrypts the specified plain text. /// </summary> /// <param name="plainText">The plain text.</param> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The encrypted value as a string.</returns> public static Task<string> EncryptAsync(string plainText, string credentialName = null, CancellationToken cancellationToken = default(CancellationToken)) { return Current.AsAsync().EncryptAsync(plainText, credentialName, cancellationToken); } /// <summary> /// Asynchronously decrypts the specified cipher text. /// </summary> /// <param name="cipherText">The cipher text.</param> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The decrypted value as a string.</returns> public static Task<string> DecryptAsync(string cipherText, string credentialName = null, CancellationToken cancellationToken = default(CancellationToken)) { return Current.AsAsync().DecryptAsync(cipherText, credentialName, cancellationToken); } /// <summary> /// Asynchronously encrypts the specified plain text. /// </summary> /// <param name="plainText">The plain text.</param> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The encrypted value as a byte array.</returns> public static Task<byte[]> EncryptAsync(byte[] plainText, string credentialName = null, CancellationToken cancellationToken = default(CancellationToken)) { return Current.AsAsync().EncryptAsync(plainText, credentialName, cancellationToken); } /// <summary> /// Asynchronously decrypts the specified cipher text. /// </summary> /// <param name="cipherText">The cipher text.</param> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The decrypted value as a byte array.</returns> public static Task<byte[]> DecryptAsync(byte[] cipherText, string credentialName = null, CancellationToken cancellationToken = default(CancellationToken)) { return Current.AsAsync().DecryptAsync(cipherText, credentialName, cancellationToken); } /// <summary> /// Gets an instance of <see cref="IAsyncEncryptor"/> for the provided key identifier. /// </summary> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <returns>An object that can be used for encryption operations.</returns> public static IAsyncEncryptor GetAsyncEncryptor(string credentialName = null) { return Current.AsAsync().GetAsyncEncryptor(credentialName); } /// <summary> /// Gets an instance of <see cref="IAsyncDecryptor"/> for the provided key identifier. /// </summary> /// <param name="credentialName"> /// The name of the credential to use for this encryption operation, /// or null to use the default credential. /// </param> /// <returns>An object that can be used for decryption operations.</returns> public static IAsyncDecryptor GetAsyncDecryptor(string credentialName = null) { return Current.AsAsync().GetAsyncDecryptor(credentialName); } private static ICrypto GetDefaultCrypto() { var cryptos = Config.Root.GetCompositeSection("rocklib_encryption", "rocklib.encryption").Create<List<ICrypto>>(); if (cryptos == null || cryptos.Count == 0) { throw new InvalidOperationException("No crypto implementations found in config. See the Readme.md file for details on how to setup the configuration."); } if (cryptos.Count == 1) { return cryptos[0]; } return new CompositeCrypto(cryptos); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using log4net; using System.Reflection; namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture { public class DynamicTextureModule : IRegionModule, IDynamicTextureManager { private Dictionary<UUID, Scene> RegisteredScenes = new Dictionary<UUID, Scene>(); private Dictionary<string, IDynamicTextureRender> RenderPlugins = new Dictionary<string, IDynamicTextureRender>(); private Dictionary<UUID, DynamicTextureUpdater> Updaters = new Dictionary<UUID, DynamicTextureUpdater>(); #region IDynamicTextureManager Members public void RegisterRender(string handleType, IDynamicTextureRender render) { if (!RenderPlugins.ContainsKey(handleType)) { RenderPlugins.Add(handleType, render); } } /// <summary> /// Called by code which actually renders the dynamic texture to supply texture data. /// </summary> /// <param name="id"></param> /// <param name="data"></param> public void ReturnData(UUID id, byte[] data) { DynamicTextureUpdater updater = null; lock (Updaters) { if (Updaters.ContainsKey(id)) { updater = Updaters[id]; } } if (updater != null) { if (RegisteredScenes.ContainsKey(updater.SimUUID)) { Scene scene = RegisteredScenes[updater.SimUUID]; updater.DataReceived(data, scene); } } if (updater.UpdateTimer == 0) { lock (Updaters) { if (!Updaters.ContainsKey(updater.UpdaterID)) { Updaters.Remove(updater.UpdaterID); } } } } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer) { return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { if (RenderPlugins.ContainsKey(contentType)) { //m_log.Debug("dynamic texture being created: " + url + " of type " + contentType); DynamicTextureUpdater updater = new DynamicTextureUpdater(); updater.SimUUID = simID; updater.PrimID = primID; updater.ContentType = contentType; updater.Url = url; updater.UpdateTimer = updateTimer; updater.UpdaterID = UUID.Random(); updater.Params = extraParams; updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; lock (Updaters) { if (!Updaters.ContainsKey(updater.UpdaterID)) { Updaters.Add(updater.UpdaterID, updater); } } RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams); return updater.UpdaterID; } return UUID.Zero; } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer) { return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { if (RenderPlugins.ContainsKey(contentType)) { DynamicTextureUpdater updater = new DynamicTextureUpdater(); updater.SimUUID = simID; updater.PrimID = primID; updater.ContentType = contentType; updater.BodyData = data; updater.UpdateTimer = updateTimer; updater.UpdaterID = UUID.Random(); updater.Params = extraParams; updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; lock (Updaters) { if (!Updaters.ContainsKey(updater.UpdaterID)) { Updaters.Add(updater.UpdaterID, updater); } } RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams); return updater.UpdaterID; } return UUID.Zero; } public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize, out double xSize, out double ySize) { xSize = 0; ySize = 0; if (RenderPlugins.ContainsKey(contentType)) { RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize); } } #endregion #region IRegionModule Members public void Initialize(Scene scene, IConfigSource config) { if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) { RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); scene.RegisterModuleInterface<IDynamicTextureManager>(this); } } public void PostInitialize() { } public void Close() { } public string Name { get { return "DynamicTextureModule"; } } public bool IsSharedModule { get { return true; } } #endregion #region Nested type: DynamicTextureUpdater public class DynamicTextureUpdater { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool BlendWithOldTexture = false; public string BodyData; public string ContentType; public byte FrontAlpha = 255; public UUID LastAssetID; public string Params; public UUID PrimID; public bool SetNewFrontAlpha = false; public UUID SimUUID; public UUID UpdaterID; public int UpdateTimer; public string Url; public DynamicTextureUpdater() { LastAssetID = UUID.Zero; UpdateTimer = 0; BodyData = null; } /// <summary> /// Called once new texture data has been received for this updater. /// </summary> public void DataReceived(byte[] data, Scene scene) { SceneObjectPart part = scene.GetSceneObjectPart(PrimID); if (data == null) { string msg = String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url); scene.SimChat(msg, ChatTypeEnum.Say, 0, part); return; } byte[] assetData; AssetBase oldAsset = null; if (BlendWithOldTexture) { UUID lastTextureID = part.Shape.Textures.DefaultTexture.TextureID; oldAsset = scene.CommsManager.AssetCache.GetAsset(lastTextureID, AssetRequestInfo.InternalRequest()); if (oldAsset != null) { assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha); } else { assetData = new byte[data.Length]; Array.Copy(data, assetData, data.Length); } } else { assetData = new byte[data.Length]; Array.Copy(data, assetData, data.Length); } // Create a new asset for user AssetBase asset = new AssetBase(); asset.FullID = UUID.Random(); asset.Data = assetData; asset.Name = "DynamicImage" + Util.RandomClass.Next(1, 10000); asset.Type = 0; asset.Description = "dynamic image"; asset.Local = false; asset.Temporary = true; scene.CommsManager.AssetCache.AddAsset(asset, AssetRequestInfo.InternalRequest()); LastAssetID = asset.FullID; IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>(); if (cacheLayerDecode != null) { cacheLayerDecode.Decode(asset.FullID, asset.Data); } cacheLayerDecode = null; // mostly keep the values from before Primitive.TextureEntry tmptex = part.Shape.Textures; // remove the old asset from the cache UUID oldID = tmptex.DefaultTexture.TextureID; tmptex.DefaultTexture.TextureID = asset.FullID; // I'm pretty sure we always want to force this to true // I'm pretty sure noone whats to set fullbright true if it wasn't true before. // tmptex.DefaultTexture.Fullbright = true; part.Shape.Textures = tmptex; part.ScheduleFullUpdate(PrimUpdateFlags.Textures); } private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha) { ManagedImage managedImage; Image image; if (OpenJPEG.DecodeToImage(frontImage, out managedImage, out image)) { Bitmap image1 = new Bitmap(image); if (OpenJPEG.DecodeToImage(backImage, out managedImage, out image)) { Bitmap image2 = new Bitmap(image); if (setNewAlpha) SetAlpha(ref image1, newAlpha); Bitmap joint = MergeBitMaps(image1, image2); byte[] result = new byte[0]; try { result = OpenJPEG.EncodeFromImage(joint, true); } catch (Exception) { m_log.Error("[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Empty byte data returned!"); } return result; } } return null; } public Bitmap MergeBitMaps(Bitmap front, Bitmap back) { Bitmap joint; Graphics jG; joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb); jG = Graphics.FromImage(joint); jG.DrawImage(back, 0, 0, back.Width, back.Height); jG.DrawImage(front, 0, 0, back.Width, back.Height); return joint; } private void SetAlpha(ref Bitmap b, byte alpha) { for (int w = 0; w < b.Width; w++) { for (int h = 0; h < b.Height; h++) { b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h))); } } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using Microsoft.Practices.ServiceLocation; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Prism.Regions; namespace Prism.Wpf.Tests.Regions { [TestClass] public class RegionNavigationServiceFixture { [TestMethod] public void WhenNavigating_ViewIsActivated() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act bool isNavigationSuccessful = false; target.RequestNavigate(viewUri, nr => isNavigationSuccessful = nr.Result == true); // Verify Assert.IsTrue(isNavigationSuccessful); bool isViewActive = region.ActiveViews.Contains(view); Assert.IsTrue(isViewActive); } [TestMethod] public void WhenNavigatingWithQueryString_ViewIsActivated() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name + "?MyQuery=true", UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act bool isNavigationSuccessful = false; target.RequestNavigate(viewUri, nr => isNavigationSuccessful = nr.Result == true); // Verify Assert.IsTrue(isNavigationSuccessful); bool isViewActive = region.ActiveViews.Contains(view); Assert.IsTrue(isViewActive); } [TestMethod] public void WhenNavigatingAndViewCannotBeAcquired_ThenNavigationResultHasError() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string otherType = "OtherType"; var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; Mock<IRegionNavigationContentLoader> targetHandlerMock = new Mock<IRegionNavigationContentLoader>(); targetHandlerMock.Setup(th => th.LoadContent(It.IsAny<IRegion>(), It.IsAny<NavigationContext>())).Throws<ArgumentException>(); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, targetHandlerMock.Object, journal); target.Region = region; // Act Exception error = null; target.RequestNavigate( new Uri(otherType.GetType().Name, UriKind.Relative), nr => { error = nr.Error; }); // Verify bool isViewActive = region.ActiveViews.Contains(view); Assert.IsFalse(isViewActive); Assert.IsInstanceOfType(error, typeof(ArgumentException)); } [TestMethod] public void WhenNavigatingWithNullUri_Throws() { // Prepare IRegion region = new Region(); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act NavigationResult navigationResult = null; target.RequestNavigate((Uri)null, nr => navigationResult = nr); // Verify Assert.IsFalse(navigationResult.Result.Value); Assert.IsNotNull(navigationResult.Error); Assert.IsInstanceOfType(navigationResult.Error, typeof(ArgumentNullException)); } [TestMethod] public void WhenNavigatingAndViewImplementsINavigationAware_ThenNavigatedIsInvokedOnNavigation() { // Prepare var region = new Region(); var viewMock = new Mock<INavigationAware>(); viewMock.Setup(ina => ina.IsNavigationTarget(It.IsAny<NavigationContext>())).Returns(true); var view = viewMock.Object; region.Add(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify viewMock.Verify(v => v.OnNavigatedTo(It.Is<NavigationContext>(nc => nc.Uri == navigationUri && nc.NavigationService == target))); } [TestMethod] public void WhenNavigatingAndDataContextImplementsINavigationAware_ThenNavigatedIsInvokesOnNavigation() { // Prepare var region = new Region(); Mock<FrameworkElement> mockFrameworkElement = new Mock<FrameworkElement>(); Mock<INavigationAware> mockINavigationAwareDataContext = new Mock<INavigationAware>(); mockINavigationAwareDataContext.Setup(ina => ina.IsNavigationTarget(It.IsAny<NavigationContext>())).Returns(true); mockFrameworkElement.Object.DataContext = mockINavigationAwareDataContext.Object; var view = mockFrameworkElement.Object; region.Add(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify mockINavigationAwareDataContext.Verify(v => v.OnNavigatedTo(It.Is<NavigationContext>(nc => nc.Uri == navigationUri))); } [TestMethod] public void WhenNavigatingAndBothViewAndDataContextImplementINavigationAware_ThenNavigatedIsInvokesOnNavigation() { // Prepare var region = new Region(); Mock<FrameworkElement> mockFrameworkElement = new Mock<FrameworkElement>(); Mock<INavigationAware> mockINavigationAwareView = mockFrameworkElement.As<INavigationAware>(); mockINavigationAwareView.Setup(ina => ina.IsNavigationTarget(It.IsAny<NavigationContext>())).Returns(true); Mock<INavigationAware> mockINavigationAwareDataContext = new Mock<INavigationAware>(); mockINavigationAwareDataContext.Setup(ina => ina.IsNavigationTarget(It.IsAny<NavigationContext>())).Returns(true); mockFrameworkElement.Object.DataContext = mockINavigationAwareDataContext.Object; var view = mockFrameworkElement.Object; region.Add(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify mockINavigationAwareView.Verify(v => v.OnNavigatedTo(It.Is<NavigationContext>(nc => nc.Uri == navigationUri))); mockINavigationAwareDataContext.Verify(v => v.OnNavigatedTo(It.Is<NavigationContext>(nc => nc.Uri == navigationUri))); } [TestMethod] public void WhenNavigating_NavigationIsRecordedInJournal() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); IRegionNavigationJournalEntry journalEntry = new RegionNavigationJournalEntry(); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(journalEntry); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); var journalMock = new Mock<IRegionNavigationJournal>(); journalMock.Setup(x => x.RecordNavigation(journalEntry)).Verifiable(); IRegionNavigationJournal journal = journalMock.Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(viewUri, nr => { }); // Verify Assert.IsNotNull(journalEntry); Assert.AreEqual(viewUri, journalEntry.Uri); journalMock.VerifyAll(); } [TestMethod] public void WhenNavigatingAndCurrentlyActiveViewImplementsINavigateWithVeto_ThenNavigationRequestQueriesForVeto() { // Prepare var region = new Region(); var viewMock = new Mock<IConfirmNavigationRequest>(); viewMock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Verifiable(); var view = viewMock.Object; region.Add(view); region.Activate(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify viewMock.VerifyAll(); } [TestMethod] public void WhenNavigating_ThenNavigationRequestQueriesForVetoOnAllActiveViewsIfAllSucceed() { // Prepare var region = new Region(); var view1Mock = new Mock<IConfirmNavigationRequest>(); view1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(true)) .Verifiable(); var view1 = view1Mock.Object; region.Add(view1); region.Activate(view1); var view2Mock = new Mock<IConfirmNavigationRequest>(); var view2 = view2Mock.Object; region.Add(view2); var view3Mock = new Mock<INavigationAware>(); var view3 = view3Mock.Object; region.Add(view3); region.Activate(view3); var view4Mock = new Mock<IConfirmNavigationRequest>(); view4Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(true)) .Verifiable(); var view4 = view4Mock.Object; region.Add(view4); region.Activate(view4); var navigationUri = new Uri(view1.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify view1Mock.VerifyAll(); view2Mock.Verify(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>()), Times.Never()); view3Mock.VerifyAll(); view4Mock.VerifyAll(); } [TestMethod] public void WhenRequestNavigateAwayAcceptsThroughCallback_ThenNavigationProceeds() { // Prepare var region = new Region(); var view1Mock = new Mock<IConfirmNavigationRequest>(); view1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(true)) .Verifiable(); var view1 = view1Mock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act var navigationSucceeded = false; target.RequestNavigate(navigationUri, nr => { navigationSucceeded = nr.Result == true; }); // Verify view1Mock.VerifyAll(); Assert.IsTrue(navigationSucceeded); CollectionAssert.AreEqual(new object[] { view1, view2 }, region.ActiveViews.ToArray()); } [TestMethod] public void WhenRequestNavigateAwayRejectsThroughCallback_ThenNavigationDoesNotProceed() { // Prepare var region = new Region(); var view1Mock = new Mock<IConfirmNavigationRequest>(); view1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(false)) .Verifiable(); var view1 = view1Mock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act var navigationFailed = false; target.RequestNavigate(navigationUri, nr => { navigationFailed = nr.Result == false; }); // Verify view1Mock.VerifyAll(); Assert.IsTrue(navigationFailed); CollectionAssert.AreEqual(new object[] { view1 }, region.ActiveViews.ToArray()); } [TestMethod] public void WhenNavigatingAndDataContextOnCurrentlyActiveViewImplementsINavigateWithVeto_ThenNavigationRequestQueriesForVeto() { // Prepare var region = new Region(); var viewModelMock = new Mock<IConfirmNavigationRequest>(); viewModelMock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Verifiable(); var viewMock = new Mock<FrameworkElement>(); var view = viewMock.Object; view.DataContext = viewModelMock.Object; region.Add(view); region.Activate(view); var navigationUri = new Uri(view.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify viewModelMock.VerifyAll(); } [TestMethod] public void WhenRequestNavigateAwayOnDataContextAcceptsThroughCallback_ThenNavigationProceeds() { // Prepare var region = new Region(); var view1DataContextMock = new Mock<IConfirmNavigationRequest>(); view1DataContextMock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(true)) .Verifiable(); var view1Mock = new Mock<FrameworkElement>(); var view1 = view1Mock.Object; view1.DataContext = view1DataContextMock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act var navigationSucceeded = false; target.RequestNavigate(navigationUri, nr => { navigationSucceeded = nr.Result == true; }); // Verify view1DataContextMock.VerifyAll(); Assert.IsTrue(navigationSucceeded); CollectionAssert.AreEqual(new object[] { view1, view2 }, region.ActiveViews.ToArray()); } [TestMethod] public void WhenRequestNavigateAwayOnDataContextRejectsThroughCallback_ThenNavigationDoesNotProceed() { // Prepare var region = new Region(); var view1DataContextMock = new Mock<IConfirmNavigationRequest>(); view1DataContextMock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(false)) .Verifiable(); var view1Mock = new Mock<FrameworkElement>(); var view1 = view1Mock.Object; view1.DataContext = view1DataContextMock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act var navigationFailed = false; target.RequestNavigate(navigationUri, nr => { navigationFailed = nr.Result == false; }); // Verify view1DataContextMock.VerifyAll(); Assert.IsTrue(navigationFailed); CollectionAssert.AreEqual(new object[] { view1 }, region.ActiveViews.ToArray()); } [TestMethod] public void WhenViewAcceptsNavigationOutAfterNewIncomingRequestIsReceived_ThenOriginalRequestIsIgnored() { var region = new Region(); var viewMock = new Mock<IConfirmNavigationRequest>(); var view = viewMock.Object; var confirmationRequests = new List<Action<bool>>(); viewMock .Setup(icnr => icnr.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => { confirmationRequests.Add(c); }); region.Add(view); region.Activate(view); var navigationUri = new Uri("", UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Returns(view); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; bool firstNavigation = false; bool secondNavigation = false; target.RequestNavigate(navigationUri, nr => firstNavigation = nr.Result.Value); target.RequestNavigate(navigationUri, nr => secondNavigation = nr.Result.Value); Assert.AreEqual(2, confirmationRequests.Count); confirmationRequests[0](true); confirmationRequests[1](true); Assert.IsFalse(firstNavigation); Assert.IsTrue(secondNavigation); } [TestMethod] public void WhenViewModelAcceptsNavigationOutAfterNewIncomingRequestIsReceived_ThenOriginalRequestIsIgnored() { var region = new Region(); var viewModelMock = new Mock<IConfirmNavigationRequest>(); var viewMock = new Mock<FrameworkElement>(); var view = viewMock.Object; view.DataContext = viewModelMock.Object; var confirmationRequests = new List<Action<bool>>(); viewModelMock .Setup(icnr => icnr.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => { confirmationRequests.Add(c); }); region.Add(view); region.Activate(view); var navigationUri = new Uri("", UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Returns(view); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; bool firstNavigation = false; bool secondNavigation = false; target.RequestNavigate(navigationUri, nr => firstNavigation = nr.Result.Value); target.RequestNavigate(navigationUri, nr => secondNavigation = nr.Result.Value); Assert.AreEqual(2, confirmationRequests.Count); confirmationRequests[0](true); confirmationRequests[1](true); Assert.IsFalse(firstNavigation); Assert.IsTrue(secondNavigation); } [TestMethod] public void BeforeNavigating_NavigatingEventIsRaised() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; bool isNavigatingRaised = false; target.Navigating += delegate(object sender, RegionNavigationEventArgs e) { if (sender == target) { isNavigatingRaised = true; } }; // Act bool isNavigationSuccessful = false; target.RequestNavigate(viewUri, nr => isNavigationSuccessful = nr.Result == true); // Verify Assert.IsTrue(isNavigationSuccessful); Assert.IsTrue(isNavigatingRaised); } [TestMethod] public void WhenNavigationSucceeds_NavigatedIsRaised() { // Prepare object view = new object(); Uri viewUri = new Uri(view.GetType().Name, UriKind.Relative); IRegion region = new Region(); region.Add(view); string regionName = "RegionName"; RegionManager regionManager = new RegionManager(); regionManager.Regions.Add(regionName, region); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new RegionNavigationContentLoader(serviceLocator); IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; bool isNavigatedRaised = false; target.Navigated += delegate(object sender, RegionNavigationEventArgs e) { if (sender == target) { isNavigatedRaised = true; } }; // Act bool isNavigationSuccessful = false; target.RequestNavigate(viewUri, nr => isNavigationSuccessful = nr.Result == true); // Verify Assert.IsTrue(isNavigationSuccessful); Assert.IsTrue(isNavigatedRaised); } [TestMethod] public void WhenTargetViewCreationThrowsWithAsyncConfirmation_ThenExceptionIsProvidedToNavigationCallback() { var serviceLocatorMock = new Mock<IServiceLocator>(); var targetException = new Exception(); var targetHandlerMock = new Mock<IRegionNavigationContentLoader>(); targetHandlerMock .Setup(th => th.LoadContent(It.IsAny<IRegion>(), It.IsAny<NavigationContext>())) .Throws(targetException); var journalMock = new Mock<IRegionNavigationJournal>(); Action<bool> navigationCallback = null; var viewMock = new Mock<IConfirmNavigationRequest>(); viewMock .Setup(v => v.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => { navigationCallback = c; }); var region = new Region(); region.Add(viewMock.Object); region.Activate(viewMock.Object); var target = new RegionNavigationService(serviceLocatorMock.Object, targetHandlerMock.Object, journalMock.Object); target.Region = region; NavigationResult result = null; target.RequestNavigate(new Uri("", UriKind.Relative), nr => result = nr); navigationCallback(true); Assert.IsNotNull(result); Assert.AreSame(targetException, result.Error); } [TestMethod] public void WhenNavigatingFromViewThatIsNavigationAware_ThenNotifiesActiveViewNavigatingFrom() { // Arrange var region = new Region(); var viewMock = new Mock<INavigationAware>(); var view = viewMock.Object; region.Add(view); var view2 = new object(); region.Add(view2); region.Activate(view); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify viewMock.Verify(v => v.OnNavigatedFrom(It.Is<NavigationContext>(ctx => ctx.Uri == navigationUri && ctx.Parameters.Count() == 0))); } [TestMethod] public void WhenNavigationFromViewThatIsNavigationAware_OnlyNotifiesOnNavigateFromForActiveViews() { // Arrange bool navigationFromInvoked = false; var region = new Region(); var viewMock = new Mock<INavigationAware>(); viewMock .Setup(x => x.OnNavigatedFrom(It.IsAny<NavigationContext>())).Callback(() => navigationFromInvoked = true); var view = viewMock.Object; region.Add(view); var targetViewMock = new Mock<INavigationAware>(); region.Add(targetViewMock.Object); var activeViewMock = new Mock<INavigationAware>(); region.Add(activeViewMock.Object); region.Activate(activeViewMock.Object); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); var navigationUri = new Uri(targetViewMock.Object.GetType().Name, UriKind.Relative); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify Assert.IsFalse(navigationFromInvoked); } [TestMethod] public void WhenNavigatingFromActiveViewWithNavigatinAwareDataConext_NotifiesContextOfNavigatingFrom() { // Arrange var region = new Region(); var mockDataContext = new Mock<INavigationAware>(); var view1Mock = new Mock<FrameworkElement>(); var view1 = view1Mock.Object; view1.DataContext = mockDataContext.Object; region.Add(view1); var view2 = new object(); region.Add(view2); region.Activate(view1); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()).Returns(new RegionNavigationJournalEntry()); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); IServiceLocator serviceLocator = serviceLocatorMock.Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; // Act target.RequestNavigate(navigationUri, nr => { }); // Verify mockDataContext.Verify(v => v.OnNavigatedFrom(It.Is<NavigationContext>(ctx => ctx.Uri == navigationUri && ctx.Parameters.Count() == 0))); } [TestMethod] public void WhenNavigatingWithNullCallback_ThenThrows() { var region = new Region(); var navigationUri = new Uri("/", UriKind.Relative); IServiceLocator serviceLocator = new Mock<IServiceLocator>().Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; ExceptionAssert.Throws<ArgumentNullException>( () => { target.RequestNavigate(navigationUri, null); }); } [TestMethod] public void WhenNavigatingWithNoRegionSet_ThenMarshallExceptionToCallback() { var navigationUri = new Uri("/", UriKind.Relative); IServiceLocator serviceLocator = new Mock<IServiceLocator>().Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); Exception error = null; target.RequestNavigate(navigationUri, nr => error = nr.Error); Assert.IsNotNull(error); Assert.IsInstanceOfType(error, typeof(InvalidOperationException)); } [TestMethod] public void WhenNavigatingWithNullUri_ThenMarshallExceptionToCallback() { IServiceLocator serviceLocator = new Mock<IServiceLocator>().Object; RegionNavigationContentLoader contentLoader = new Mock<RegionNavigationContentLoader>(serviceLocator).Object; IRegionNavigationJournal journal = new Mock<IRegionNavigationJournal>().Object; RegionNavigationService target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = new Region(); Exception error = null; target.RequestNavigate(null, nr => error = nr.Error); Assert.IsNotNull(error); Assert.IsInstanceOfType(error, typeof(ArgumentNullException)); } [TestMethod] public void WhenNavigationFailsBecauseTheContentViewCannotBeRetrieved_ThenNavigationFailedIsRaised() { // Prepare var region = new Region { Name = "RegionName" }; var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Throws<InvalidOperationException>(); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; RegionNavigationFailedEventArgs eventArgs = null; target.NavigationFailed += delegate(object sender, RegionNavigationFailedEventArgs e) { if (sender == target) { eventArgs = e; } }; // Act bool? isNavigationSuccessful = null; target.RequestNavigate(new Uri("invalid", UriKind.Relative), nr => isNavigationSuccessful = nr.Result); // Verify Assert.IsFalse(isNavigationSuccessful.Value); Assert.IsNotNull(eventArgs); Assert.IsNotNull(eventArgs.Error); } [TestMethod] public void WhenNavigationFailsBecauseActiveViewRejectsIt_ThenNavigationFailedIsRaised() { // Prepare var region = new Region { Name = "RegionName" }; var view1Mock = new Mock<IConfirmNavigationRequest>(); view1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(false)) .Verifiable(); var view1 = view1Mock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Returns(view2); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; RegionNavigationFailedEventArgs eventArgs = null; target.NavigationFailed += delegate(object sender, RegionNavigationFailedEventArgs e) { if (sender == target) { eventArgs = e; } }; // Act bool? isNavigationSuccessful = null; target.RequestNavigate(navigationUri, nr => isNavigationSuccessful = nr.Result); // Verify view1Mock.VerifyAll(); Assert.IsFalse(isNavigationSuccessful.Value); Assert.IsNotNull(eventArgs); Assert.IsNull(eventArgs.Error); } [TestMethod] public void WhenNavigationFailsBecauseDataContextForActiveViewRejectsIt_ThenNavigationFailedIsRaised() { // Prepare var region = new Region { Name = "RegionName" }; var viewModel1Mock = new Mock<IConfirmNavigationRequest>(); viewModel1Mock .Setup(ina => ina.ConfirmNavigationRequest(It.IsAny<NavigationContext>(), It.IsAny<Action<bool>>())) .Callback<NavigationContext, Action<bool>>((nc, c) => c(false)) .Verifiable(); var view1Mock = new Mock<FrameworkElement>(); var view1 = view1Mock.Object; view1.DataContext = viewModel1Mock.Object; var view2 = new object(); region.Add(view1); region.Add(view2); region.Activate(view1); var navigationUri = new Uri(view2.GetType().Name, UriKind.Relative); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock .Setup(x => x.GetInstance<IRegionNavigationJournalEntry>()) .Returns(new RegionNavigationJournalEntry()); var contentLoaderMock = new Mock<IRegionNavigationContentLoader>(); contentLoaderMock .Setup(cl => cl.LoadContent(region, It.IsAny<NavigationContext>())) .Returns(view2); var serviceLocator = serviceLocatorMock.Object; var contentLoader = contentLoaderMock.Object; var journal = new Mock<IRegionNavigationJournal>().Object; var target = new RegionNavigationService(serviceLocator, contentLoader, journal); target.Region = region; RegionNavigationFailedEventArgs eventArgs = null; target.NavigationFailed += delegate(object sender, RegionNavigationFailedEventArgs e) { if (sender == target) { eventArgs = e; } }; // Act bool? isNavigationSuccessful = null; target.RequestNavigate(navigationUri, nr => isNavigationSuccessful = nr.Result); // Verify viewModel1Mock.VerifyAll(); Assert.IsFalse(isNavigationSuccessful.Value); Assert.IsNotNull(eventArgs); Assert.IsNull(eventArgs.Error); } } }
// 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.Text; using Xunit; namespace System.Net.Primitives.PalTests { public unsafe class IPAddressPalTests { [Fact] public void IPv4StringToAddress_Valid() { const string AddressString = "127.0.64.255"; var bytes = stackalloc byte[IPAddressParserStatics.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv4AddressBytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(127, bytes[0]); Assert.Equal(0, bytes[1]); Assert.Equal(64, bytes[2]); Assert.Equal(255, bytes[3]); Assert.Equal(0, port); } [Fact] public void IPv4StringToAddress_Valid_ClassB() { const string AddressString = "128.64.256"; var bytes = stackalloc byte[IPAddressParserStatics.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv4AddressBytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(128, bytes[0]); Assert.Equal(64, bytes[1]); Assert.Equal(1, bytes[2]); Assert.Equal(0, bytes[3]); Assert.Equal(0, port); } [Fact] public void IPv4StringToAddress_Valid_ClassC() { const string AddressString = "192.65536"; var bytes = stackalloc byte[IPAddressParserStatics.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv4AddressBytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(192, bytes[0]); Assert.Equal(1, bytes[1]); Assert.Equal(0, bytes[2]); Assert.Equal(0, bytes[3]); Assert.Equal(0, port); } [Fact] public void IPv4StringToAddress_Valid_ClassA() { const string AddressString = "2130706433"; var bytes = stackalloc byte[IPAddressParserStatics.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv4AddressBytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(127, bytes[0]); Assert.Equal(0, bytes[1]); Assert.Equal(0, bytes[2]); Assert.Equal(1, bytes[3]); Assert.Equal(0, port); } [Fact] public void IPv4StringToAddress_Invalid_Empty() { const string AddressString = ""; var bytes = stackalloc byte[IPAddressParserStatics.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv4AddressBytes, out port); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv4StringToAddress_Invalid_NotAnAddress() { const string AddressString = "hello, world"; var bytes = stackalloc byte[IPAddressParserStatics.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv4AddressBytes, out port); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv4StringToAddress_Invalid_Port() { const string AddressString = "127.0.64.255:80"; var bytes = stackalloc byte[IPAddressParserStatics.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv4AddressBytes, out port); Assert.True(err != IPAddressPal.SuccessErrorCode || port != 0); } public static object[][] ValidIPv4Addresses = new object[][] { new object[] { new byte[] { 0, 0, 0, 0 }, "0.0.0.0" }, new object[] { new byte[] { 127, 0, 64, 255 }, "127.0.64.255" }, new object[] { new byte[] { 128, 64, 1, 0 }, "128.64.1.0" }, new object[] { new byte[] { 192, 0, 0, 1 }, "192.0.0.1" }, new object[] { new byte[] { 255, 255, 255, 255 }, "255.255.255.255" } }; [Theory, MemberData(nameof(ValidIPv4Addresses))] public void IPv4AddressToString_Valid(byte[] bytes, string addressString) { var buffer = new StringBuilder(IPAddressParser.INET_ADDRSTRLEN); uint err = IPAddressPal.Ipv4AddressToString(bytes, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(addressString, buffer.ToString()); } [Theory, MemberData(nameof(ValidIPv4Addresses))] public void IPv4AddressToString_RoundTrip(byte[] bytes, string addressString) { var buffer = new StringBuilder(IPAddressParser.INET_ADDRSTRLEN); uint err = IPAddressPal.Ipv4AddressToString(bytes, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); var actualAddressString = buffer.ToString(); Assert.Equal(addressString, actualAddressString); var roundTrippedBytes = stackalloc byte[IPAddressParserStatics.IPv4AddressBytes]; ushort port; err = IPAddressPal.Ipv4StringToAddress(actualAddressString, roundTrippedBytes, IPAddressParserStatics.IPv4AddressBytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(bytes[0], roundTrippedBytes[0]); Assert.Equal(bytes[1], roundTrippedBytes[1]); Assert.Equal(bytes[2], roundTrippedBytes[2]); Assert.Equal(bytes[3], roundTrippedBytes[3]); Assert.Equal(0, port); } [Theory, MemberData(nameof(ValidIPv4Addresses))] public void IPv4StringToAddress_RoundTrip(byte[] bytes, string addressString) { var actualBytesArr = new byte[IPAddressParserStatics.IPv4AddressBytes]; fixed (byte* actualBytes = actualBytesArr) { ushort port; uint err = IPAddressPal.Ipv4StringToAddress(addressString, actualBytes, IPAddressParserStatics.IPv4AddressBytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(bytes[0], actualBytes[0]); Assert.Equal(bytes[1], actualBytes[1]); Assert.Equal(bytes[2], actualBytes[2]); Assert.Equal(bytes[3], actualBytes[3]); Assert.Equal(0, port); var buffer = new StringBuilder(IPAddressParser.INET_ADDRSTRLEN); err = IPAddressPal.Ipv4AddressToString(actualBytesArr, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); var roundTrippedAddressString = buffer.ToString(); Assert.Equal(addressString, roundTrippedAddressString); } } [Fact] public void IPv6StringToAddress_Valid_Localhost() { const string AddressString = "::1"; var expectedBytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err; fixed (byte* bytesPtr = bytes) { err = IPAddressPal.Ipv6StringToAddress(AddressString, bytesPtr, bytes.Length, out scope); } Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid() { const string AddressString = "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }; var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err; fixed (byte* bytesPtr = bytes) { err = IPAddressPal.Ipv6StringToAddress(AddressString, bytesPtr, bytes.Length, out scope); } Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_Bracketed() { const string AddressString = "[2001:db8:aaaa:bbbb:cccc:dddd:eeee:1]"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }; var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err; fixed (byte* bytesPtr = bytes) { err = IPAddressPal.Ipv6StringToAddress(AddressString, bytesPtr, bytes.Length, out scope); } Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_Port() { const string AddressString = "[2001:db8:aaaa:bbbb:cccc:dddd:eeee:1]:80"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }; var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err; fixed (byte* bytesPtr = bytes) { err = IPAddressPal.Ipv6StringToAddress(AddressString, bytesPtr, bytes.Length, out scope); } Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_Port_2() { const string AddressString = "[2001:db8:aaaa:bbbb:cccc:dddd:eeee:1]:"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }; var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err; fixed (byte* bytesPtr = bytes) { err = IPAddressPal.Ipv6StringToAddress(AddressString, bytesPtr, bytes.Length, out scope); } Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_Compressed() { const string AddressString = "2001:db8::1"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err; fixed (byte* bytesPtr = bytes) { err = IPAddressPal.Ipv6StringToAddress(AddressString, bytesPtr, bytes.Length, out scope); } Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_IPv4Compatible() { const string AddressString = "::ffff:222.1.41.90"; var expectedBytes = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 222, 1, 41, 90 }; var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err; fixed (byte* bytesPtr = bytes) { err = IPAddressPal.Ipv6StringToAddress(AddressString, bytesPtr, bytes.Length, out scope); } Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Invalid_Empty() { const string AddressString = ""; var bytes = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv6AddressBytes, out scope); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv6StringToAddress_Invalid_NotAnAddress() { const string AddressString = "hello, world"; var bytes = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv6AddressBytes, out scope); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv6StringToAddress_Invalid_Port() { const string AddressString = "[2001:db8::1]:xx"; var bytes = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv6AddressBytes, out scope); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv6StringToAddress_Invalid_Compression() { const string AddressString = "2001::db8::1"; var bytes = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, IPAddressParserStatics.IPv6AddressBytes, out scope); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } public static object[][] ValidIPv6Addresses = new object[][] { new object[] { new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, "::1" }, new object[] { new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }, "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1" }, new object[] { new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }, "2001:db8::1" }, new object[] { new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 222, 1, 41, 90 }, "::ffff:222.1.41.90" } }; [Theory, MemberData(nameof(ValidIPv6Addresses))] public void IPv6AddressToString_Valid(byte[] bytes, string addressString) { var buffer = new StringBuilder(IPAddressParser.INET6_ADDRSTRLEN); uint err = IPAddressPal.Ipv6AddressToString(bytes, 0, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(addressString, buffer.ToString()); } [Theory, MemberData(nameof(ValidIPv6Addresses))] public void IPv6AddressToString_RoundTrip(byte[] bytes, string addressString) { var buffer = new StringBuilder(IPAddressParser.INET6_ADDRSTRLEN); uint err = IPAddressPal.Ipv6AddressToString(bytes, 0, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); var actualAddressString = buffer.ToString(); Assert.Equal(addressString, actualAddressString); var roundTrippedBytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; fixed (byte* roundTrippedBytesPtr = roundTrippedBytes) { err = IPAddressPal.Ipv6StringToAddress(actualAddressString, roundTrippedBytesPtr, IPAddressParserStatics.IPv6AddressBytes, out scope); } Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < bytes.Length; i++) { Assert.Equal(bytes[i], roundTrippedBytes[i]); } Assert.Equal(0, (int)scope); } [Theory, MemberData(nameof(ValidIPv6Addresses))] public void IPv6StringToAddress_RoundTrip(byte[] bytes, string addressString) { var actualBytes = new byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; uint err; fixed (byte* actualBytesPtr = actualBytes) { err = IPAddressPal.Ipv6StringToAddress(addressString, actualBytesPtr, actualBytes.Length, out scope); } Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < bytes.Length; i++) { Assert.Equal(bytes[i], actualBytes[i]); } Assert.Equal(0, (int)scope); var buffer = new StringBuilder(IPAddressParser.INET6_ADDRSTRLEN); err = IPAddressPal.Ipv6AddressToString(actualBytes, 0, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); var roundTrippedAddressString = buffer.ToString(); Assert.Equal(addressString, roundTrippedAddressString); } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class PostFilteringTargetWrapperTests : NLogTestBase { [Fact] public void PostFilteringTargetWrapperUsingDefaultFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule { Exists = "level >= LogLevel.Error", Filter = "true", }, }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all Info events went through Assert.Equal(3, target.Events.Count); Assert.Same(events[1].LogEvent, target.Events[0]); Assert.Same(events[2].LogEvent, target.Events[1]); Assert.Same(events[5].LogEvent, target.Events[2]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Warn, "Logger1", "Hello").WithContinuation(exceptions.Add), }; string result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Running on 7 events") != -1); Assert.True(result.IndexOf("Rule matched: (level >= Warn)") != -1); Assert.True(result.IndexOf("Filter to apply: (level >= Debug)") != -1); Assert.True(result.IndexOf("After filtering: 6 events.") != -1); Assert.True(result.IndexOf("Sending to MyTarget") != -1); // make sure all Debug,Info,Warn events went through Assert.Equal(6, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[5].LogEvent, target.Events[4]); Assert.Same(events[6].LogEvent, target.Events[5]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest2() { // in this case both rules would match, but first one is picked var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; var result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Running on 7 events") != -1); Assert.True(result.IndexOf("Rule matched: (level >= Error)") != -1); Assert.True(result.IndexOf("Filter to apply: True") != -1); Assert.True(result.IndexOf("After filtering: 7 events.") != -1); Assert.True(result.IndexOf("Sending to MyTarget") != -1); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperOnlyDefaultFilter() { var target = new MyTarget() { OptimizeBufferReuse = true }; var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, DefaultFilter = "level >= LogLevel.Info", // by default log info and above }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); wrapper.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add)); Assert.Single(target.Events); wrapper.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add)); Assert.Single(target.Events); } [Fact] public void PostFilteringTargetWrapperNoFiltersDefined() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } public class MyTarget : Target { public MyTarget() { Events = new List<LogEventInfo>(); } public MyTarget(string name) : this() { Name = name; } public List<LogEventInfo> Events { get; set; } protected override void Write(LogEventInfo logEvent) { Events.Add(logEvent); } } } }
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using Antlr4.Runtime.Atn; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime.Atn { /// <summary> /// Used to cache /// <see cref="PredictionContext"/> /// objects. Its used for the shared /// context cash associated with contexts in DFA states. This cache /// can be used for both lexers and parsers. /// </summary> /// <author>Sam Harwell</author> public class PredictionContextCache { public static readonly Antlr4.Runtime.Atn.PredictionContextCache Uncached = new Antlr4.Runtime.Atn.PredictionContextCache(false); private readonly IDictionary<PredictionContext, PredictionContext> contexts = new Dictionary<PredictionContext, PredictionContext>(); private readonly IDictionary<PredictionContextCache.PredictionContextAndInt, PredictionContext> childContexts = new Dictionary<PredictionContextCache.PredictionContextAndInt, PredictionContext>(); private readonly IDictionary<PredictionContextCache.IdentityCommutativePredictionContextOperands, PredictionContext> joinContexts = new Dictionary<PredictionContextCache.IdentityCommutativePredictionContextOperands, PredictionContext>(); private readonly bool enableCache; public PredictionContextCache() : this(true) { } private PredictionContextCache(bool enableCache) { this.enableCache = enableCache; } public virtual PredictionContext GetAsCached(PredictionContext context) { if (!enableCache) { return context; } PredictionContext result; if (!contexts.TryGetValue(context, out result)) { result = context; contexts[context] = context; } return result; } public virtual PredictionContext GetChild(PredictionContext context, int invokingState) { if (!enableCache) { return context.GetChild(invokingState); } PredictionContextCache.PredictionContextAndInt operands = new PredictionContextCache.PredictionContextAndInt(context, invokingState); PredictionContext result; if (!childContexts.TryGetValue(operands, out result)) { result = context.GetChild(invokingState); result = GetAsCached(result); childContexts[operands] = result; } return result; } public virtual PredictionContext Join(PredictionContext x, PredictionContext y) { if (!enableCache) { return PredictionContext.Join(x, y, this); } PredictionContextCache.IdentityCommutativePredictionContextOperands operands = new PredictionContextCache.IdentityCommutativePredictionContextOperands(x, y); PredictionContext result; if (joinContexts.TryGetValue(operands, out result)) { return result; } result = PredictionContext.Join(x, y, this); result = GetAsCached(result); joinContexts[operands] = result; return result; } protected internal sealed class PredictionContextAndInt { private readonly PredictionContext obj; private readonly int value; public PredictionContextAndInt(PredictionContext obj, int value) { this.obj = obj; this.value = value; } public override bool Equals(object obj) { if (!(obj is PredictionContextCache.PredictionContextAndInt)) { return false; } else { if (obj == this) { return true; } } PredictionContextCache.PredictionContextAndInt other = (PredictionContextCache.PredictionContextAndInt)obj; return this.value == other.value && (this.obj == other.obj || (this.obj != null && this.obj.Equals(other.obj))); } public override int GetHashCode() { int hashCode = 5; hashCode = 7 * hashCode + (obj != null ? obj.GetHashCode() : 0); hashCode = 7 * hashCode + value; return hashCode; } } protected internal sealed class IdentityCommutativePredictionContextOperands { private readonly PredictionContext x; private readonly PredictionContext y; public IdentityCommutativePredictionContextOperands(PredictionContext x, PredictionContext y) { this.x = x; this.y = y; } public PredictionContext X { get { return x; } } public PredictionContext Y { get { return y; } } public override bool Equals(object obj) { if (!(obj is PredictionContextCache.IdentityCommutativePredictionContextOperands)) { return false; } else { if (this == obj) { return true; } } PredictionContextCache.IdentityCommutativePredictionContextOperands other = (PredictionContextCache.IdentityCommutativePredictionContextOperands)obj; return (this.x == other.x && this.y == other.y) || (this.x == other.y && this.y == other.x); } public override int GetHashCode() { return x.GetHashCode() ^ y.GetHashCode(); } } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Linq; namespace NLog.Targets { using System; using System.ComponentModel; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml; using NLog.Common; using NLog.Internal; using NLog.Layouts; /// <summary> /// Calls the specified web service on each log message. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/WebService-target">Documentation on NLog Wiki</seealso> /// <remarks> /// The web service must implement a method that accepts a number of string parameters. /// </remarks> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/WebService/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/Example.cs" /> /// <p>The example web service that works with this example is shown below</p> /// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/WebService1/Service1.asmx.cs" /> /// </example> [Target("WebService")] public sealed class WebServiceTarget : MethodCallTargetBase { private const string SoapEnvelopeNamespace = "http://schemas.xmlsoap.org/soap/envelope/"; private const string Soap12EnvelopeNamespace = "http://www.w3.org/2003/05/soap-envelope"; /// <summary> /// Initializes a new instance of the <see cref="WebServiceTarget" /> class. /// </summary> public WebServiceTarget() { this.Protocol = WebServiceProtocol.Soap11; //default NO utf-8 bom const bool writeBOM = false; this.Encoding = new UTF8Encoding(writeBOM); this.IncludeBOM = writeBOM; } /// <summary> /// Gets or sets the web service URL. /// </summary> /// <docgen category='Web Service Options' order='10' /> public Uri Url { get; set; } /// <summary> /// Gets or sets the Web service method name. Only used with Soap. /// </summary> /// <docgen category='Web Service Options' order='10' /> public string MethodName { get; set; } /// <summary> /// Gets or sets the Web service namespace. Only used with Soap. /// </summary> /// <docgen category='Web Service Options' order='10' /> public string Namespace { get; set; } /// <summary> /// Gets or sets the protocol to be used when calling web service. /// </summary> /// <docgen category='Web Service Options' order='10' /> [DefaultValue("Soap11")] public WebServiceProtocol Protocol { get; set; } /// <summary> /// Should we include the BOM (Byte-order-mark) for UTF? Influences the <see cref="Encoding"/> property. /// /// This will only work for UTF-8. /// </summary> public bool? IncludeBOM { get; set; } /// <summary> /// Gets or sets the encoding. /// </summary> /// <docgen category='Web Service Options' order='10' /> public Encoding Encoding { get; set; } /// <summary> /// Calls the target method. Must be implemented in concrete classes. /// </summary> /// <param name="parameters">Method call parameters.</param> protected override void DoInvoke(object[] parameters) { // method is not used, instead asynchronous overload will be used throw new NotImplementedException(); } /// <summary> /// Invokes the web service method. /// </summary> /// <param name="parameters">Parameters to be passed.</param> /// <param name="continuation">The continuation.</param> protected override void DoInvoke(object[] parameters, AsyncContinuation continuation) { var request = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters)); Func<AsyncCallback, IAsyncResult> begin = (r) => request.BeginGetRequestStream(r, null); Func<IAsyncResult, Stream> getStream = request.EndGetRequestStream; DoInvoke(parameters, continuation, request, begin, getStream); } internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func<AsyncCallback, IAsyncResult> beginFunc, Func<IAsyncResult, Stream> getStreamFunc) { Stream postPayload = null; switch (this.Protocol) { case WebServiceProtocol.Soap11: postPayload = this.PrepareSoap11Request(request, parameters); break; case WebServiceProtocol.Soap12: postPayload = this.PrepareSoap12Request(request, parameters); break; case WebServiceProtocol.HttpGet: this.PrepareGetRequest(request); break; case WebServiceProtocol.HttpPost: postPayload = this.PreparePostRequest(request, parameters); break; } AsyncContinuation sendContinuation = ex => { if (ex != null) { continuation(ex); return; } request.BeginGetResponse( r => { try { using (var response = request.EndGetResponse(r)) { } continuation(null); } catch (Exception ex2) { InternalLogger.Error(ex2, "Error when sending to Webservice."); if (ex2.MustBeRethrown()) { throw; } continuation(ex2); } }, null); }; if (postPayload != null && postPayload.Length > 0) { postPayload.Position = 0; beginFunc( result => { try { using (Stream stream = getStreamFunc(result)) { WriteStreamAndFixPreamble(postPayload, stream, this.IncludeBOM, this.Encoding); postPayload.Dispose(); } sendContinuation(null); } catch (Exception ex) { postPayload.Dispose(); InternalLogger.Error(ex, "Error when sending to Webservice."); if (ex.MustBeRethrown()) { throw; } continuation(ex); } }); } else { sendContinuation(null); } } /// <summary> /// Builds the URL to use when calling the web service for a message, depending on the WebServiceProtocol. /// </summary> /// <param name="parameterValues"></param> /// <returns></returns> private Uri BuildWebServiceUrl(object[] parameterValues) { if (this.Protocol != WebServiceProtocol.HttpGet) { return this.Url; } //if the protocol is HttpGet, we need to add the parameters to the query string of the url var queryParameters = new StringBuilder(); string separator = string.Empty; for (int i = 0; i < this.Parameters.Count; i++) { queryParameters.Append(separator); queryParameters.Append(this.Parameters[i].Name); queryParameters.Append("="); queryParameters.Append(UrlHelper.UrlEncode(Convert.ToString(parameterValues[i], CultureInfo.InvariantCulture), false)); separator = "&"; } var builder = new UriBuilder(this.Url); //append our query string to the URL following //the recommendations at https://msdn.microsoft.com/en-us/library/system.uribuilder.query.aspx if (builder.Query != null && builder.Query.Length > 1) { builder.Query = builder.Query.Substring(1) + "&" + queryParameters.ToString(); } else { builder.Query = queryParameters.ToString(); } return builder.Uri; } private MemoryStream PrepareSoap11Request(HttpWebRequest request, object[] parameterValues) { string soapAction; if (this.Namespace.EndsWith("/", StringComparison.Ordinal)) { soapAction = this.Namespace + this.MethodName; } else { soapAction = this.Namespace + "/" + this.MethodName; } request.Headers["SOAPAction"] = soapAction; return PrepareSoapRequestPost(request, parameterValues, SoapEnvelopeNamespace, "soap"); } private MemoryStream PrepareSoap12Request(HttpWebRequest request, object[] parameterValues) { return PrepareSoapRequestPost(request, parameterValues, Soap12EnvelopeNamespace, "soap12"); } /// <summary> /// Helper for creating soap POST-XML request /// </summary> /// <param name="request"></param> /// <param name="parameterValues"></param> /// <param name="soapEnvelopeNamespace"></param> /// <param name="soapname"></param> /// <returns></returns> private MemoryStream PrepareSoapRequestPost(WebRequest request, object[] parameterValues, string soapEnvelopeNamespace, string soapname) { request.Method = "POST"; request.ContentType = "text/xml; charset=" + this.Encoding.WebName; var ms = new MemoryStream(); XmlWriter xtw = XmlWriter.Create(ms, new XmlWriterSettings { Encoding = this.Encoding }); xtw.WriteStartElement(soapname, "Envelope", soapEnvelopeNamespace); xtw.WriteStartElement("Body", soapEnvelopeNamespace); xtw.WriteStartElement(this.MethodName, this.Namespace); int i = 0; foreach (MethodCallParameter par in this.Parameters) { xtw.WriteElementString(par.Name, Convert.ToString(parameterValues[i], CultureInfo.InvariantCulture)); i++; } xtw.WriteEndElement(); // methodname xtw.WriteEndElement(); // Body xtw.WriteEndElement(); // soap:Envelope xtw.Flush(); return ms; } private MemoryStream PreparePostRequest(HttpWebRequest request, object[] parameterValues) { request.Method = "POST"; return PrepareHttpRequest(request, parameterValues); } private void PrepareGetRequest(HttpWebRequest request) { request.Method = "GET"; } private MemoryStream PrepareHttpRequest(HttpWebRequest request, object[] parameterValues) { request.ContentType = "application/x-www-form-urlencoded; charset=" + this.Encoding.WebName; var ms = new MemoryStream(); string separator = string.Empty; var sw = new StreamWriter(ms, this.Encoding); sw.Write(string.Empty); int i = 0; foreach (MethodCallParameter parameter in this.Parameters) { sw.Write(separator); sw.Write(parameter.Name); sw.Write("="); sw.Write(UrlHelper.UrlEncode(Convert.ToString(parameterValues[i], CultureInfo.InvariantCulture), true)); separator = "&"; i++; } sw.Flush(); return ms; } /// <summary> /// Write from input to output. Fix the UTF-8 bom /// </summary> /// <param name="input"></param> /// <param name="output"></param> /// <param name="writeUtf8BOM"></param> /// <param name="encoding"></param> private static void WriteStreamAndFixPreamble(Stream input, Stream output, bool? writeUtf8BOM, Encoding encoding) { //only when utf-8 encoding is used, the Encoding preamble is optional var nothingToDo = writeUtf8BOM == null || !(encoding is UTF8Encoding); const int preambleSize = 3; if (!nothingToDo) { //it's UTF-8 var hasBomInEncoding = encoding.GetPreamble().Length == preambleSize; //BOM already in Encoding. nothingToDo = writeUtf8BOM.Value && hasBomInEncoding; //Bom already not in Encoding nothingToDo = nothingToDo || !writeUtf8BOM.Value && !hasBomInEncoding; } var offset = nothingToDo ? 0 : preambleSize; input.CopyWithOffset(output, offset); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Xunit.NetCore.Extensions; using ThreadState = System.Threading.ThreadState; namespace System.IO.Ports.Tests { public class SerialStream_WriteByte_Generic : PortsTest { // Set bounds fore random timeout values. // If the min is to low write will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; // If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; // If the percentage difference between the expected timeout and the actual timeout // found through Stopwatch is greater then 10% then the timeout value was not correctly // to the write method and the testcase fails. private const double maxPercentageDifference = .15; private const int NUM_TRYS = 5; private const byte DEFAULT_BYTE = 0; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying write method throws exception after a call to Cloes()"); com.Open(); Stream serialStream = com.BaseStream; com.Close(); VerifyWriteException(serialStream, typeof(ObjectDisposedException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterBaseStreamClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying write method throws exception after a call to BaseStream.Close()"); com.Open(); Stream serialStream = com.BaseStream; com.BaseStream.Close(); VerifyWriteException(serialStream, typeof(ObjectDisposedException)); } } [ConditionalFact(nameof(HasNullModem))] public void Timeout() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(-55); com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.XOnXOff; Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout); com1.Open(); com2.Open(); com2.BaseStream.WriteByte(XOnOff.XOFF); Thread.Sleep(250); com2.Close(); VerifyTimeout(com1); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var rndGen = new Random(-55); com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com.Handshake = Handshake.RequestToSendXOnXOff; // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); com.Open(); try { com.BaseStream.WriteByte(DEFAULT_BYTE); } catch (TimeoutException) { } VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeoutWithWriteSucceeding() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var rndGen = new Random(-55); var asyncEnableRts = new AsyncEnableRts(); var t = new Thread(asyncEnableRts.EnableRTS); int waitTime; com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.RequestToSend; com1.Encoding = new UTF8Encoding(); Debug.WriteLine( "Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before it's timeout", com1.WriteTimeout); com1.Open(); // Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed // before the timeout is reached t.Start(); waitTime = 0; while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000) { // Wait for the thread to start Thread.Sleep(50); waitTime += 50; } try { com1.BaseStream.WriteByte(DEFAULT_BYTE); } catch (TimeoutException) { } asyncEnableRts.Stop(); while (t.IsAlive) Thread.Sleep(100); VerifyTimeout(com1); } } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWrite() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying BytesToWrite with one call to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 200; // Write a random byte[] asynchronously so we can verify some things while the write call is blocking Task task = Task.Run(() => WriteRandomDataBlock(com, TCSupport.MinimumBlockingByteCount)); TCSupport.WaitForTaskToStart(task); TCSupport.WaitForWriteBufferToLoad(com, TCSupport.MinimumBlockingByteCount); // Wait for write method to timeout and complete the task TCSupport.WaitForTaskCompletion(task); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWriteSuccessive() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying BytesToWrite with successive calls to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 4000; int blockLength = TCSupport.MinimumBlockingByteCount; // Write a random byte[] asynchronously so we can verify some things while the write call is blocking Task t1 = Task.Run(() => WriteRandomDataBlock(com, blockLength)); TCSupport.WaitForTaskToStart(t1); TCSupport.WaitForWriteBufferToLoad(com, blockLength); // Write a random byte[] asynchronously so we can verify some things while the write call is blocking Task t2 = Task.Run(() => WriteRandomDataBlock(com, blockLength)); TCSupport.WaitForTaskToStart(t2); TCSupport.WaitForWriteBufferToLoad(com, blockLength * 2); // Wait for both write methods to timeout TCSupport.WaitForTaskCompletion(t1); TCSupport.WaitForTaskCompletion(t2); } } [ConditionalFact(nameof(HasOneSerialPort))] public void Handshake_None() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying Handshake=None"); com.Open(); // Write a random byte[] asynchronously so we can verify some things while the write call is blocking Task task = Task.Run(() => WriteRandomDataBlock(com, TCSupport.MinimumBlockingByteCount)); TCSupport.WaitForTaskToStart(task); // Wait for write methods to complete TCSupport.WaitForTaskCompletion(task); Assert.Equal(0, com.BytesToWrite); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSend() { Verify_Handshake(Handshake.RequestToSend); } [ConditionalFact(nameof(HasNullModem))] public void Handshake_XOnXOff() { Verify_Handshake(Handshake.XOnXOff); } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSendXOnXOff() { Verify_Handshake(Handshake.RequestToSendXOnXOff); } private class AsyncEnableRts { private bool _stop; public void EnableRTS() { lock (this) { using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(-55); int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); // Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.RtsEnable = true; while (!_stop) Monitor.Wait(this); com2.RtsEnable = false; } } } public void Stop() { lock (this) { _stop = true; Monitor.Pulse(this); } } } #endregion #region Verification for Test Cases private static void VerifyWriteException(Stream serialStream, Type expectedException) { Assert.Throws(expectedException, () => serialStream.WriteByte(DEFAULT_BYTE)); } private void VerifyTimeout(SerialPort com) { var timer = new Stopwatch(); int expectedTime = com.WriteTimeout; var actualTime = 0; double percentageDifference; try { com.BaseStream.WriteByte(DEFAULT_BYTE); // Warm up write method } catch (TimeoutException) { } Thread.CurrentThread.Priority = ThreadPriority.Highest; for (var i = 0; i < NUM_TRYS; i++) { timer.Start(); try { com.BaseStream.WriteByte(DEFAULT_BYTE); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); // Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The write method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void Verify_Handshake(Handshake handshake) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Debug.WriteLine("Verifying Handshake={0}", handshake); com1.Handshake = handshake; com1.Open(); com2.Open(); // Setup to ensure write will bock with type of handshake method being used if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = false; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.BaseStream.WriteByte(XOnOff.XOFF); Thread.Sleep(250); } // Write a block of random data asynchronously so we can verify some things while the write call is blocking Task task = Task.Run(() => WriteRandomDataBlock(com1, TCSupport.MinimumBlockingByteCount)); TCSupport.WaitForTaskToStart(task); TCSupport.WaitForWriteBufferToLoad(com1, TCSupport.MinimumBlockingByteCount); // Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) { Fail("ERROR!!! Expected CtsHolding={0} actual {1}", false, com1.CtsHolding); } // Setup to ensure write will succeed if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = true; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.BaseStream.WriteByte(XOnOff.XON); } // Wait till write finishes TCSupport.WaitForTaskCompletion(task); // Verify that the correct number of bytes are in the buffer // (There should be nothing because it's all been transmitted after the flow control was released) Assert.Equal(0, com1.BytesToWrite); // Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) { Fail("ERROR!!! Expected CtsHolding={0} actual {1}", true, com1.CtsHolding); } } } private static void WriteRandomDataBlock(SerialPort com, int blockLength) { var rndGen = new Random(-55); byte[] randomData = new byte[blockLength]; rndGen.NextBytes(randomData); try { com.BaseStream.Write(randomData, 0, randomData.Length); } catch (TimeoutException) { } } #endregion } }
#region Header /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (c) 2007-2008 James Nies and NArrange contributors. * All rights reserved. * * This program and the accompanying materials are made available under * the terms of the Common Public License v1.0 which accompanies this * distribution. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * 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. * *<author>James Nies</author> *<contributor>Everton Elvio Koser</contributor> *<contributor>Justin Dearing</contributor> *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #endregion Header namespace NArrange.CSharp { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Text; using System.Threading; using NArrange.Core; using NArrange.Core.CodeElements; using NArrange.Core.Configuration; /// <summary> /// Visits a tree of code elements for writing C# code /// </summary> internal sealed class CSharpWriteVisitor : CodeWriteVisitor { #region Fields /// <summary> /// Closing comment prefix. /// </summary> private const string ClosingCommentPrefix = "// "; #endregion Fields #region Constructors /// <summary> /// Creates a new CSharpWriteVisitor. /// </summary> /// <param name="writer">Text writer to write code elements to.</param> /// <param name="configuration">Code configuration.</param> public CSharpWriteVisitor(TextWriter writer, CodeConfiguration configuration) : base(writer, configuration) { } #endregion Constructors #region Methods /// <summary> /// Processes an attribute element. /// </summary> /// <param name="element">Attribute code element.</param> public override void VisitAttributeElement(AttributeElement element) { this.WriteComments(element.HeaderComments); bool nested = element.Parent is AttributeElement; if (!nested) { WriteIndented(CSharpSymbol.BeginAttribute.ToString()); if (!string.IsNullOrEmpty(element.Target)) { Writer.Write(element.Target); Writer.Write(CSharpSymbol.TypeImplements); Writer.Write(' '); } } Writer.Write(element.Name); if (!string.IsNullOrEmpty(element.BodyText)) { Writer.Write(CSharpSymbol.BeginParameterList); Writer.Write(element.BodyText); Writer.Write(CSharpSymbol.EndParameterList); } // // Nested list of attributes? // foreach (ICodeElement childElement in element.Children) { AttributeElement childAttribute = childElement as AttributeElement; if (childAttribute != null) { Writer.Write(','); Writer.WriteLine(); WriteIndented(string.Empty); childAttribute.Accept(this); } } if (!nested) { Writer.Write(CSharpSymbol.EndAttribute); } if (!nested && element.Parent != null) { Writer.WriteLine(); } } /// <summary> /// Writes a comment line. /// </summary> /// <param name="comment">Comment code element.</param> public override void VisitCommentElement(CommentElement comment) { StringBuilder builder = new StringBuilder(DefaultBlockLength); if (comment.Type == CommentType.Block) { builder.Append("/*"); builder.Append(FormatCommentText(comment)); builder.Append("*/"); WriteTextBlock(builder.ToString()); } else { if (comment.Type == CommentType.XmlLine) { builder.Append("///"); } else { builder.Append("//"); } builder.Append(FormatCommentText(comment)); WriteIndented(builder.ToString()); } } /// <summary> /// Writes a condition directive element. /// </summary> /// <param name="element">Condition directive code element.</param> public override void VisitConditionDirectiveElement(ConditionDirectiveElement element) { const string ConditionFormat = "{0}{1} {2}"; ConditionDirectiveElement conditionDirective = element; this.WriteIndented( string.Format( CultureInfo.InvariantCulture, ConditionFormat, CSharpSymbol.Preprocessor, CSharpKeyword.If, element.ConditionExpression)); Writer.WriteLine(); WriteChildren(element); if (element.Children.Count > 0) { Writer.WriteLine(); } while (conditionDirective.ElseCondition != null) { conditionDirective = conditionDirective.ElseCondition; if (conditionDirective.ElseCondition == null) { this.WriteIndented(CSharpSymbol.Preprocessor + CSharpKeyword.Else); } else { this.WriteIndented( string.Format( CultureInfo.InvariantCulture, ConditionFormat, CSharpSymbol.Preprocessor, CSharpKeyword.Elif, conditionDirective.ConditionExpression)); } Writer.WriteLine(); WriteChildren(conditionDirective); if (element.Children.Count > 0) { Writer.WriteLine(); } } this.WriteIndented(CSharpSymbol.Preprocessor + CSharpKeyword.EndIf); } /// <summary> /// Processes a constructor element. /// </summary> /// <param name="element">Constructor code element.</param> public override void VisitConstructorElement(ConstructorElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes(element.MemberModifiers); Writer.Write(element.Name); WriteParameterList(element.Parameters); Writer.WriteLine(); if (element.Reference != null) { TabCount++; WriteIndentedLine( string.Format( CultureInfo.InvariantCulture, "{0} {1}", CSharpSymbol.TypeImplements, element.Reference)); TabCount--; } WriteBody(element); } /// <summary> /// Processes a delegate element. /// </summary> /// <param name="element">Delegate code element.</param> public override void VisitDelegateElement(DelegateElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes(element.MemberModifiers); Writer.Write(CSharpKeyword.Delegate); Writer.Write(' '); Writer.Write(element.Type); Writer.Write(' '); Writer.Write(element.Name); WriteTypeParameters(element); WriteParameterList(element.Parameters); WriteTypeParameterConstraints(element); Writer.Write(CSharpSymbol.EndOfStatement); } /// <summary> /// Processes an event element. /// </summary> /// <param name="element">Event code element.</param> public override void VisitEventElement(EventElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes(element.MemberModifiers); Writer.Write(CSharpKeyword.Event); Writer.Write(' '); Writer.Write(element.Type); Writer.Write(' '); Writer.Write(element.Name); if (element.BodyText != null && element.BodyText.Length > 0) { Writer.WriteLine(); WriteBody(element); } else { Writer.Write(CSharpSymbol.EndOfStatement); } } /// <summary> /// Processes a field element. /// </summary> /// <param name="element">Field code element.</param> public override void VisitFieldElement(FieldElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes(element.MemberModifiers); if (element.IsVolatile) { Writer.Write(CSharpKeyword.Volatile); Writer.Write(' '); } if (element[CSharpExtendedProperties.Fixed] is bool && (bool)element[CSharpExtendedProperties.Fixed]) { Writer.Write(CSharpKeyword.Fixed); Writer.Write(' '); } Writer.Write(element.Type); Writer.Write(' '); Writer.Write(element.Name); if (!string.IsNullOrEmpty(element.InitialValue)) { Writer.Write(' '); Writer.Write(CSharpSymbol.Assignment); Writer.Write(' '); if (element.InitialValue.IndexOf("\n") >= 0) { string initialValue = element.InitialValue; int lineFeedIndex = initialValue.IndexOf('\n'); if (lineFeedIndex > 0) { string initialValueFirstLine = initialValue.Substring(0, lineFeedIndex + 1); initialValue = initialValue.Substring(lineFeedIndex + 1); Writer.Write(initialValueFirstLine); } WriteTextBlock(initialValue); } else { Writer.Write(element.InitialValue); } } Writer.Write(CSharpSymbol.EndOfStatement); if (element.TrailingComment != null) { Writer.Write(' '); int tabCountTemp = this.TabCount; this.TabCount = 0; element.TrailingComment.Accept(this); this.TabCount = tabCountTemp; } } /// <summary> /// Processes a method element. /// </summary> /// <param name="element">Method code element.</param> public override void VisitMethodElement(MethodElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); if (element.IsPartial) { Writer.Write(CSharpKeyword.Partial); Writer.Write(' '); } WriteAccess(element.Access); WriteMemberAttributes(element.MemberModifiers); if (element.OperatorType == OperatorType.None) { Writer.Write(element.Type); Writer.Write(' '); if (element.IsOperator) { Writer.Write(CSharpKeyword.Operator); Writer.Write(' '); } Writer.Write(element.Name); } else if (element.IsOperator) { if (element.OperatorType == OperatorType.Explicit) { Writer.Write(CSharpKeyword.Explicit); } else if (element.OperatorType == OperatorType.Implicit) { Writer.Write(CSharpKeyword.Implicit); } Writer.Write(' '); Writer.Write(CSharpKeyword.Operator); Writer.Write(' '); Writer.Write(element.Type); } WriteTypeParameters(element); WriteParameterList(element.Parameters); WriteTypeParameterConstraints(element); if (element.BodyText == null) { Writer.Write(CSharpSymbol.EndOfStatement); } else { Writer.WriteLine(); WriteBody(element); } } /// <summary> /// Processes a namespace element. /// </summary> /// <param name="element">Namespace code element.</param> public override void VisitNamespaceElement(NamespaceElement element) { this.WriteComments(element.HeaderComments); StringBuilder builder = new StringBuilder(DefaultBlockLength); builder.Append(CSharpKeyword.Namespace); builder.Append(' '); builder.Append(element.Name); WriteIndentedLine(builder.ToString()); WriteBeginBlock(); // // Process all children // WriteBlockChildren(element); WriteEndBlock(); } /// <summary> /// Processes a property element. /// </summary> /// <param name="element">Property element to process.</param> public override void VisitPropertyElement(PropertyElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); WriteAccess(element.Access); WriteMemberAttributes(element.MemberModifiers); Writer.Write(element.Type); Writer.Write(' '); Writer.Write(element.Name); if (element.IndexParameter != null) { Writer.Write(CSharpSymbol.BeginAttribute); Writer.Write(element.IndexParameter); Writer.Write(CSharpSymbol.EndAttribute); } Writer.WriteLine(); WriteBody(element); } /// <summary> /// Processes a type element. /// </summary> /// <param name="element">Type elemenent to process.</param> public override void VisitTypeElement(TypeElement element) { this.WriteComments(element.HeaderComments); this.WriteAttributes(element); if (element.Access != CodeAccess.None) { WriteAccess(element.Access); } else { WriteIndented(string.Empty); } if (element.IsNew) { Writer.Write(CSharpKeyword.New); Writer.Write(' '); } if (element.IsUnsafe) { Writer.Write(CSharpKeyword.Unsafe); Writer.Write(' '); } if (element.IsStatic) { Writer.Write(CSharpKeyword.Static); Writer.Write(' '); } if (element.IsSealed) { Writer.Write(CSharpKeyword.Sealed); Writer.Write(' '); } if (element.IsAbstract) { Writer.Write(CSharpKeyword.Abstract); Writer.Write(' '); } if (element.IsPartial) { Writer.Write(CSharpKeyword.Partial); Writer.Write(' '); } StringBuilder builder = new StringBuilder(DefaultBlockLength); switch (element.Type) { case TypeElementType.Class: builder.Append(CSharpKeyword.Class); break; case TypeElementType.Enum: builder.Append(CSharpKeyword.Enumeration); break; case TypeElementType.Interface: builder.Append(CSharpKeyword.Interface); break; case TypeElementType.Structure: builder.Append(CSharpKeyword.Structure); break; default: throw new ArgumentOutOfRangeException( string.Format( Thread.CurrentThread.CurrentCulture, "Unhandled type element type {0}", element.Type)); } builder.Append(' '); builder.Append(element.Name); Writer.Write(builder.ToString()); WriteTypeParameters(element); if (element.Interfaces.Count > 0) { builder = new StringBuilder(DefaultBlockLength); builder.Append(' '); builder.Append(CSharpSymbol.TypeImplements); builder.Append(' '); for (int interfaceIndex = 0; interfaceIndex < element.Interfaces.Count; interfaceIndex++) { InterfaceReference interfaceReference = element.Interfaces[interfaceIndex]; builder.Append(interfaceReference.Name); if (interfaceIndex < element.Interfaces.Count - 1) { builder.Append(CSharpSymbol.AliasSeparator); builder.Append(' '); } } Writer.Write(builder.ToString()); } WriteTypeParameterConstraints(element); Writer.WriteLine(); if (element.Type == TypeElementType.Enum) { WriteBody(element); } else { WriteBeginBlock(); WriteBlockChildren(element); WriteEndBlock(); WriteClosingComment(element, ClosingCommentPrefix); } } /// <summary> /// Processes a using element. /// </summary> /// <param name="element">Using element to process.</param> public override void VisitUsingElement(UsingElement element) { this.WriteComments(element.HeaderComments); StringBuilder builder = new StringBuilder(DefaultBlockLength); builder.Append(CSharpKeyword.Using); builder.Append(' '); builder.Append(element.Name); if (!string.IsNullOrEmpty(element.Redefine)) { builder.Append(" " + CSharpSymbol.Assignment.ToString() + " "); builder.Append(element.Redefine); } builder.Append(CSharpSymbol.EndOfStatement); WriteIndented(builder.ToString()); } /// <summary> /// Writes a begin region directive. /// </summary> /// <param name="element">Region element.</param> protected override void WriteRegionBeginDirective(RegionElement element) { StringBuilder builder = new StringBuilder(DefaultBlockLength); builder.Append(CSharpSymbol.Preprocessor); builder.Append(CSharpKeyword.Region); builder.Append(' '); builder.Append(element.Name); WriteIndented(builder.ToString()); } /// <summary> /// Writes an end region directive. /// </summary> /// <param name="element">Region element.</param> protected override void WriteRegionEndDirective(RegionElement element) { StringBuilder builder = new StringBuilder(DefaultBlockLength); builder.Append(CSharpSymbol.Preprocessor); builder.Append(CSharpKeyword.EndRegion); if (Configuration.Formatting.Regions.EndRegionNameEnabled) { builder.Append(' '); builder.Append(element.Name); } WriteIndented(builder.ToString()); } /// <summary> /// Writes the accessibility for a member or type. /// </summary> /// <param name="codeAccess">Code member or type accessibility.</param> [SuppressMessage("Microsoft.Globalization", "CA1308", Justification = "C# keywords are lowercase.")] private void WriteAccess(CodeAccess codeAccess) { string accessString = string.Empty; if (codeAccess != CodeAccess.None) { accessString = EnumUtilities.ToString(codeAccess).ToLowerInvariant().Replace(",", string.Empty) + " "; } WriteIndented(accessString); } /// <summary> /// Writes a collection of element attributes. /// </summary> /// <param name="element">Attributed code element.</param> private void WriteAttributes(AttributedElement element) { foreach (IAttributeElement attribute in element.Attributes) { attribute.Accept(this); } } /// <summary> /// Writes the begin block for a member body. /// </summary> private void WriteBeginBlock() { WriteIndented(CSharpSymbol.BeginBlock.ToString()); TabCount++; } /// <summary> /// Writes a member body. /// </summary> /// <param name="element">The element.</param> private void WriteBody(TextCodeElement element) { WriteBeginBlock(); Writer.WriteLine(); if (element.BodyText != null && element.BodyText.Trim().Length > 0) { WriteTextBlock(element.BodyText); Writer.WriteLine(); WriteEndBlock(); WriteClosingComment(element, ClosingCommentPrefix); } else { TabCount--; WriteIndented(CSharpSymbol.EndBlock.ToString()); } } /// <summary> /// Writes the end block for a member body. /// </summary> private void WriteEndBlock() { TabCount--; WriteIndented(CSharpSymbol.EndBlock.ToString()); } /// <summary> /// Writes the modifiers for a member. /// </summary> /// <param name="memberAttributes">Member modifiers.</param> private void WriteMemberAttributes(MemberModifiers memberAttributes) { if ((memberAttributes & MemberModifiers.Static) == MemberModifiers.Static) { Writer.Write(CSharpKeyword.Static); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Unsafe) == MemberModifiers.Unsafe) { Writer.Write(CSharpKeyword.Unsafe); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.New) == MemberModifiers.New) { Writer.Write(CSharpKeyword.New); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Constant) == MemberModifiers.Constant) { Writer.Write(CSharpKeyword.Constant); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Abstract) == MemberModifiers.Abstract) { Writer.Write(CSharpKeyword.Abstract); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.External) == MemberModifiers.External) { Writer.Write(CSharpKeyword.External); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Override) == MemberModifiers.Override) { Writer.Write(CSharpKeyword.Override); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.ReadOnly) == MemberModifiers.ReadOnly) { Writer.Write(CSharpKeyword.ReadOnly); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Sealed) == MemberModifiers.Sealed) { Writer.Write(CSharpKeyword.Sealed); Writer.Write(' '); } if ((memberAttributes & MemberModifiers.Virtual) == MemberModifiers.Virtual) { Writer.Write(CSharpKeyword.Virtual); Writer.Write(' '); } } /// <summary> /// Writes a parameter list. /// </summary> /// <param name="paramList">String of comma-separated parameters.</param> private void WriteParameterList(string paramList) { // TODO: Treat parameters as code elements. Writer.Write(CSharpSymbol.BeginParameterList); TabCount++; if (paramList != null) { string[] paramLines = paramList.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); for (int paramLineIndex = 0; paramLineIndex < paramLines.Length; paramLineIndex++) { string paramLine = paramLines[paramLineIndex]; if (paramLineIndex > 0) { Writer.WriteLine(); WriteIndented(paramLine.Trim()); } else { Writer.Write(paramLine); } } } Writer.Write(CSharpSymbol.EndParameterList); TabCount--; } /// <summary> /// Writes the type parameter constraints for a generic code element. /// </summary> /// <param name="genericElement">Generic code element.</param> private void WriteTypeParameterConstraints(IGenericElement genericElement) { if (genericElement.TypeParameters.Count > 0) { foreach (TypeParameter typeParameter in genericElement.TypeParameters) { if (typeParameter.Constraints.Count > 0) { Writer.WriteLine(); if (Configuration.Formatting.Tabs.TabStyle == TabStyle.Tabs) { WriteIndented("\t"); } else { WriteIndented(new string(' ', Configuration.Formatting.Tabs.SpacesPerTab)); } Writer.Write(CSharpKeyword.Where); Writer.Write(' '); Writer.Write(typeParameter.Name); Writer.Write(' '); Writer.Write(CSharpSymbol.TypeImplements); Writer.Write(' '); for (int constraintIndex = 0; constraintIndex < typeParameter.Constraints.Count; constraintIndex++) { string constraint = typeParameter.Constraints[constraintIndex]; Writer.Write(constraint); if (constraintIndex < typeParameter.Constraints.Count - 1) { Writer.Write(CSharpSymbol.AliasSeparator); Writer.Write(' '); } } } } } } /// <summary> /// Writes the list of type parameters for a generic code element. /// </summary> /// <param name="genericElement">Generic code element.</param> private void WriteTypeParameters(IGenericElement genericElement) { if (genericElement.TypeParameters.Count > 0) { Writer.Write(CSharpSymbol.BeginGeneric); for (int parameterIndex = 0; parameterIndex < genericElement.TypeParameters.Count; parameterIndex++) { TypeParameter typeParameter = genericElement.TypeParameters[parameterIndex]; Writer.Write(typeParameter.Name); if (parameterIndex < genericElement.TypeParameters.Count - 1) { Writer.Write(CSharpSymbol.AliasSeparator); Writer.Write(' '); } } Writer.Write(CSharpSymbol.EndGeneric); } } #endregion Methods } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing.Printing; using System.Drawing; namespace Factotum { class RsGraphicNotes : ReportSection { private int notesPosition; public RsGraphicNotes(MainReport report, ReportSectionRules rules, int subsections) : base(report, rules, subsections) { notesPosition = 0; } public override bool IsIncluded() { return (rpt.eInspection != null && (rpt.eInspection.InspectionHasGraphic || rpt.eInspection.InspectionHasGrid)); } public override bool CanFitSome(PrintPageEventArgs args, float Y) { // Except for the first page, this section always begins a new page. // This logic is handled in the main report. return true; } public override bool Print(PrintPageEventArgs args, float Y) { Graphics g = args.Graphics; Graphics measure = args.PageSettings.PrinterSettings.CreateMeasurementGraphics(); float curX = args.MarginBounds.X; int leftX = args.MarginBounds.X; int centerX = (int)(curX + args.MarginBounds.Width/2); int rightX = args.MarginBounds.X + args.MarginBounds.Width; string s; int padding = 5; float startY = Y + padding; float curY = startY; float maxY = startY; float notesHeight; bool hasGraphic = rpt.eInspection.InspectionHasGraphic; // Either we are printing this section for the first time or we've already printed // the graphic and are finishing up the text. bool graphicDone = this.notesPosition > 0; bool sectionDone = false; // GRAPHIC IMAGE // If we have a graphic image, and haven't drawn it yet, draw it. if (hasGraphic && !graphicDone) { g.DrawImage(rpt.eGraphic.GraphicImage, leftX, curY,480,360); maxY += 360 + padding; } // NOTES if (rpt.eInspection.InspectionNotes == null) { curY = maxY; sectionDone = true; goto Finish; } // If we have notes, fill the area available with text, beginning at the current // position in the notes string. else { // set the font Font curFont = rpt.regTextFont; bool notesDone = false; int textPosition = 0; int linesFit = 0; Rectangle rec; // get the text string (or what's left of it) s = rpt.eInspection.InspectionNotes.Substring(this.notesPosition); // construct the rectangle to the right of the graphic if (hasGraphic && !graphicDone) { // If we just added a graphic, first fill the area to the right of the graphic, // then fill the area below it until all the text is done or the page is full. rec = new Rectangle(leftX + 480 + padding, (int)startY, args.MarginBounds.Width - 480 - padding, 360); notesDone = DispenseText(g, measure, rec, Brushes.Black, s, curFont, out textPosition, out linesFit, out notesHeight); if (notesDone) { // the notes fit in the rectangle to the right of the graphic curY = maxY; sectionDone = true; goto Finish; } else { // continue the notes below the graphic until all the text is done or the // page is full int remainingHeight = (int)(args.MarginBounds.Height - rpt.footerHeight - (360 + padding)); if (remainingHeight < curFont.Height) { this.notesPosition = textPosition; return false; } curY = maxY; rec = new Rectangle(leftX, (int)curY, args.MarginBounds.Width, (int)(args.MarginBounds.Bottom - curY - rpt.footerHeight)); notesDone = DispenseText(g, measure, rec, Brushes.Black, s.Substring(textPosition), curFont, out textPosition, out linesFit, out notesHeight); if (notesDone) { // we were able to fit the rest of the notes on the page curY += notesHeight; sectionDone = true; goto Finish; } else { // the notes didn't all fit on the page this.notesPosition = textPosition; sectionDone = false; goto Finish; } } } else { // No Graphic or we added the graphic on a prior page, so we can use the whole width. int remainingHeight = (int)(args.MarginBounds.Bottom - startY - rpt.footerHeight); if (remainingHeight < curFont.Height) { // We can't fit even a single line this.notesPosition = textPosition; sectionDone = false; goto Finish; } // We can fit some, so just fill as much as we can on the page. rec = new Rectangle(leftX, (int)startY, args.MarginBounds.Width, remainingHeight); notesDone = DispenseText(g, measure, rec, Brushes.Black, s.Substring(textPosition), curFont, out textPosition, out linesFit, out notesHeight); if (notesDone) { // we were able to fit the rest of the notes on the page curY = startY + notesHeight + padding; sectionDone = true; goto Finish; } else { // the notes didn't all fit on the page this.notesPosition = textPosition; sectionDone = false; goto Finish; } } } Finish: if (sectionDone) { curY += padding; hr(args, curY); this.Y = curY; } return sectionDone; } public bool DispenseText(Graphics target, Graphics measurer, RectangleF r, Brush brsh, string text, Font fnt, out int textPosition, out int linesFit, out float height) { if (r.Height < fnt.Height) throw new ArgumentException( "The rectangle is not tall enough to fit a single line of text inside."); int charsFit = 0; int cut = 0; linesFit = 0; textPosition = 0; string temp = text; //measure how much of the string we can fit into the rectangle StringFormat format = new StringFormat(StringFormatFlags.FitBlackBox | StringFormatFlags.LineLimit); SizeF stringSize = new SizeF(); stringSize = measurer.MeasureString(temp, fnt, r.Size, format, out charsFit, out linesFit); height = stringSize.Height; // Get the portion of the string that will fit cut = BreakText(temp, charsFit); if (cut != charsFit) temp = temp.Substring(0, cut); temp = temp.Trim(' '); // Draw the string target.DrawString(temp, fnt, brsh, r, format); textPosition += cut; if (textPosition == text.Length) { textPosition = 0; //reset the location so we can repeat the document return true; //finished printing } else return false; } private static int BreakText(string text, int approx) { if (approx == 0) throw new ArgumentException(); if (approx < text.Length) { //are we in the middle of a word? if (char.IsLetterOrDigit(text[approx]) && char.IsLetterOrDigit(text[approx - 1])) { int temp = text.LastIndexOf(' ', approx, approx + 1); if (temp >= 0) return temp; } } return approx; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using NuGetSearch.Common; namespace NuGetSearch.Android { /// <summary> /// Search result adapter. /// </summary> public class SearchResultAdapter : BaseAdapter<SearchResultItem> { private const int InitialBatchSize = 50; private const int SubsequentBatchSize = 50; private Activity context; private INuGetGalleryClient nugetGalleryClient; private INetworkChecker networkChecker; private string searchTerm; private string orderBy; private bool includePrerelease; private int totalCount = 0; private List<SearchResultItem> items = new List<SearchResultItem>(InitialBatchSize + SubsequentBatchSize); private RowSelectedDelegate rowSelectedCallback; /// <summary> /// Initializes a new instance of the <see cref="NuGetSearch.Android.SearchResultAdapter"/> class /// </summary> /// <param name="context">The parent context</param> /// <param name="searchTerm">The search term entered by the user</param> /// <param name="orderBy">A string indicating how the results should be sorted</param> /// <param name="includePrerelease">Boolean indicating whether prerelease packages should be included in the result</param> /// <param name="rowSelectedCallback">method to call when a row is selected</param> public SearchResultAdapter( Activity context, string searchTerm, string orderBy, bool includePrerelease, RowSelectedDelegate rowSelectedCallback) : base() { this.context = context; this.searchTerm = searchTerm; this.orderBy = orderBy; this.includePrerelease = includePrerelease; this.rowSelectedCallback = rowSelectedCallback; this.nugetGalleryClient = new NuGetGalleryClient("http://www.nuget.org", new NetworkProvider()); this.networkChecker = new AndroidNetworkChecker(context); this.LoadSearchResultItems(InitialBatchSize); } public delegate void RowSelectedDelegate(string packageId); /// <summary> /// Gets the view type count. There are two view types used by this adapter: /// 0 = Normal list item /// 1 = The "loading More..." list item /// </summary> /// <value>The number of view types used by this adapter</value> public override int ViewTypeCount { get { return 2; } } /// <summary> /// Gets the total count of results reported by the NuGet Gallery server. /// </summary> /// <value>The number of results available to be retrieved</value> public int TotalCount { get { return this.totalCount; } } /// <summary> /// Gets the count of results that have been loaded in the adapter. /// If not all of the results have been loaded, then it adds one, so that /// the "Loading More..." item can be displayed at the end. /// </summary> /// <value>The number of items contained in the adapter</value> public override int Count { get { return this.HasMore ? this.items.Count + 1 : this.totalCount; } } /// <summary> /// Gets a value indicating whether this instance has more results that have not yet been retrieved from the server. /// </summary> /// <value><c>true</c> if this instance has more results; otherwise, <c>false</c>.</value> private bool HasMore { get { return this.items.Count < this.totalCount; } } /// <summary> /// Gets the <see cref="SearchResultItem"/> with the specified position. /// </summary> /// <returns>The SearchResultItem at the specified position</returns> /// <param name="position">The position of the item to return</param> public override SearchResultItem this[int position] { get { return this.IsLoadingMorePosition(position) ? null : this.items[position]; } } /// <summary> /// Gets the item ID at the specified position. This adapter simply returns the position as the ID. /// </summary> /// <returns>The item ID</returns> /// <param name="position">The position of the item to return</param> public override long GetItemId(int position) { return position; } /// <summary> /// Gets the type of item view at the specified position /// </summary> /// <returns>The item view type</returns> /// <param name="position">The position of the item to return</param> public override int GetItemViewType(int position) { return this.IsLoadingMorePosition(position) ? 1 : 0; } /// <summary> /// Gets the view to use to display the item at the specified position /// </summary> /// <returns>A view for displaying the item at the specified position</returns> /// <param name="position">The position of the item to return</param> /// <param name="convertView">The view to convert</param> /// <param name="parent">The parent view group</param> public override View GetView(int position, View convertView, ViewGroup parent) { if (this.IsLoadingMorePosition(position)) { // Check if there is network connectivity, and if so, load more items if (this.networkChecker.HasNetworkConnectivity()) { Task.Run(() => { this.EnsurePositionLoaded(position + SubsequentBatchSize); }); } // Re-use the view that was passed in the convertView argument, or inflate a new view if it was null View view = convertView; if (view == null) { view = this.context.LayoutInflater.Inflate(Resource.Layout.SearchResultLoadingItem, parent, false); } return view; } else { // Get the item at this position var item = this.items[position]; // Re-use the view that was passed in the convertView argument, or inflate a new view if it was null View view = convertView; if (view == null) { view = this.context.LayoutInflater.Inflate(Resource.Layout.SearchResultItem, parent, false); view.Click += this.View_Click; } // If the view was re-used, then check the tag... // If it is different, then we need to set the title, description, and icon to the new values if (view.Tag == null || view.Tag.ToString() != item.Id) { view.Tag = item.Id; view.FindViewById<TextView>(Resource.Id.title).Text = item.DisplayTitle; view.FindViewById<TextView>(Resource.Id.description).Text = item.Description; if (item.UseDefaultIcon) { var iconImageView = view.FindViewById<ImageView>(Resource.Id.icon); SearchResultAdapter.SetDefaultIconImage(iconImageView); } } // If not using the default icon, then set the icon image if (!item.UseDefaultIcon) { var iconImageView = view.FindViewById<ImageView>(Resource.Id.icon); SearchResultAdapter.SetIconImage(iconImageView, item.IconUrl); } return view; } } /// <summary> /// Sets the default icon image for an image view /// </summary> /// <param name="iconImageView">Image view to set the image of</param> private static void SetDefaultIconImage(ImageView iconImageView) { // If the tag is set already and equals "default", then the default image has already been set, so just return if (iconImageView.Tag != null && iconImageView.Tag.ToString() == "default") { return; } // Set the image using the default icon from resources iconImageView.SetImageResource(Resource.Drawable.packageDefaultIconSmall); // Set the tag so we can quickly tell whether this image view has already had the default image set or not iconImageView.Tag = "default"; } /// <summary> /// Sets the image of the specified ImageView using the specified URL /// </summary> /// <param name="iconImageView">Image view to set the image of</param> /// <param name="url">URL of the image to use</param> private static void SetIconImage(ImageView iconImageView, string url) { // If the tag is set already and equals the url, then the image has already been set, so just return if (iconImageView.Tag != null && iconImageView.Tag.ToString() == url) { return; } // Check whether the icon manager has loaded the image yet or not if (AndroidIconManager.Current.IsLoaded(url)) { // If the image has been loaded, then get it from the icon manager and set it on the image view Bitmap icon = AndroidIconManager.Current.GetIcon(url); if (icon == null) { SearchResultAdapter.SetDefaultIconImage(iconImageView); } else { try { iconImageView.SetImageBitmap(icon); } catch { SearchResultAdapter.SetDefaultIconImage(iconImageView); } } // Set the tag so we can quickly tell whether this image view has already had its image set or not iconImageView.Tag = url; } else { // If the image has not yet been loaded, set the default icon for now. // It will be set to the real image later, after it has been loaded. SearchResultAdapter.SetDefaultIconImage(iconImageView); } } /// <summary> /// Ensures the result item at the specified position has been loaded, and if not, loads a new batch of results /// </summary> /// <param name="position">The position to ensure is loaded</param> private void EnsurePositionLoaded(int position) { // If this position is already loaded, then return immediately if (!this.IsLoadingMorePosition(position)) { return; } lock (this.items) { // Since we might have been blocked, check again if the position is already loaded, and if so, return if (!this.IsLoadingMorePosition(position)) { return; } // Load the requested position PLUS a batch of additional results this.LoadSearchResultItems(position + SubsequentBatchSize); } } /// <summary> /// Loads search results into the adapter up to a specified position /// </summary> /// <param name="toPosition">The position to which to load items</param> private void LoadSearchResultItems(int toPosition) { // Determine if this is the first load bool isFirstLoad = this.items.Count == 0; // Figure out how many rows to skip and how many to load int rowsToSkip = isFirstLoad ? 0 : this.items.Count; int rowsToLoad = toPosition - rowsToSkip; // Query the remote NuGet gallery server for results var searchResult = this.nugetGalleryClient .SearchAsync(this.searchTerm, this.orderBy, this.includePrerelease, rowsToSkip, rowsToLoad, isFirstLoad) .Result; this.context.RunOnUiThread(() => { // Only set the total count if this is the first time results are returned (the total count is not there in subsequent requests) if (isFirstLoad) { this.totalCount = searchResult.Count; } // Add the resulting items to the items list this.items.AddRange(searchResult.Items); this.NotifyDataSetChanged(); }); // Tell the icon manager to make sure it has a bitmap for the icons, and if not, to start loading them AndroidIconManager.Current.Load( searchResult.Items.Select(x => x.IconUrl).Distinct(), x => { this.context.RunOnUiThread(() => { this.NotifyDataSetChanged(); }); }); } /// <summary> /// Returns true if the specified position is the "Loading More..." position /// </summary> /// <returns><c>true</c> if the specified position is the "Loading More..." position; otherwise, <c>false</c>.</returns> /// <param name="position">The position to check if it is the loading more message</param> private bool IsLoadingMorePosition(int position) { return position >= this.items.Count; } /// <summary> /// Click event handler for the view /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void View_Click(object sender, EventArgs e) { if (this.rowSelectedCallback != null) { View view = sender as View; this.rowSelectedCallback(view.Tag.ToString()); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using NPOI.Util; /** * Title: COLINFO Record<p/> * Description: Defines with width and formatting for a range of columns<p/> * REFERENCE: PG 293 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)<p/> * @author Andrew C. Oliver (acoliver at apache dot org) * @version 2.0-pre */ public class ColumnInfoRecord : StandardRecord { public const short sid = 0x7d; private int _first_col; private int _last_col; private int _col_width; private int _xf_index; private int _options; private static BitField hidden = BitFieldFactory.GetInstance(0x01); private static BitField outlevel = BitFieldFactory.GetInstance(0x0700); private static BitField collapsed = BitFieldFactory.GetInstance(0x1000); // Excel seems Write values 2, 10, and 260, even though spec says "must be zero" private int field_6_reserved; public ColumnInfoRecord() { this.ColumnWidth = 2275; _options = 2; _xf_index = 0x0f; field_6_reserved = 2; // seems to be the most common value } /** * Constructs a ColumnInfo record and Sets its fields appropriately * @param in the RecordInputstream to Read the record from */ public ColumnInfoRecord(RecordInputStream in1) { _first_col = in1.ReadUShort(); _last_col = in1.ReadUShort(); _col_width = in1.ReadUShort(); _xf_index = in1.ReadUShort(); _options = in1.ReadUShort(); switch (in1.Remaining) { case 2: // usual case field_6_reserved = in1.ReadUShort(); break; case 1: // often COLINFO Gets encoded 1 byte short // shouldn't matter because this field Is Unused field_6_reserved = in1.ReadByte(); break; case 0: // According to bugzilla 48332, // "SoftArtisans OfficeWriter for Excel" totally skips field 6 // Excel seems to be OK with this, and assumes zero. field_6_reserved = 0; break; default: throw new Exception("Unusual record size remaining=(" + in1.Remaining + ")"); } } /** * @return true if the format, options and column width match */ public bool FormatMatches(ColumnInfoRecord other) { if (_xf_index != other._xf_index) { return false; } if (_options != other._options) { return false; } if (_col_width != other._col_width) { return false; } return true; } /** * Get the first column this record defines formatting info for * @return the first column index (0-based) */ public int FirstColumn { get{return _first_col;} set { _first_col = value; } } /** * Get the last column this record defines formatting info for * @return the last column index (0-based) */ public int LastColumn { get { return _last_col; } set { _last_col = value; } } /** * Get the columns' width in 1/256 of a Char width * @return column width */ public int ColumnWidth { get { return _col_width; } set { _col_width = value; } } /** * Get the columns' default format info * @return the extended format index * @see org.apache.poi.hssf.record.ExtendedFormatRecord */ public int XFIndex { get { return _xf_index; } set { _xf_index = value; } } /** * Get the options bitfield - use the bitSetters instead * @return the bitfield raw value */ public int Options { get { return _options; } set { _options = value; } } // start options bitfield /** * Get whether or not these cells are hidden * @return whether the cells are hidden. * @see #SetOptions(short) */ public bool IsHidden { get { return hidden.IsSet(_options); } set { _options = hidden.SetBoolean(_options, value); } } /** * Get the outline level for the cells * @see #SetOptions(short) * @return outline level for the cells */ public int OutlineLevel { get { return outlevel.GetValue(_options); } set { _options = outlevel.SetValue(_options, value); } } /** * Get whether the cells are collapsed * @return wether the cells are collapsed * @see #SetOptions(short) */ public bool IsCollapsed { get { return collapsed.IsSet(_options); } set { _options = collapsed.SetBoolean(_options, value); } } public override short Sid { get { return sid; } } public bool ContainsColumn(int columnIndex) { return _first_col <= columnIndex && columnIndex <= _last_col; } public bool IsAdjacentBefore(ColumnInfoRecord other) { return _last_col == other._first_col - 1; } protected override int DataSize { get { return 12; } } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(FirstColumn); out1.WriteShort(LastColumn); out1.WriteShort(ColumnWidth); out1.WriteShort(XFIndex); out1.WriteShort(_options); out1.WriteShort(field_6_reserved); } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[COLINFO]\n"); buffer.Append("colfirst = ").Append(FirstColumn) .Append("\n"); buffer.Append("collast = ").Append(LastColumn) .Append("\n"); buffer.Append("colwidth = ").Append(ColumnWidth) .Append("\n"); buffer.Append("xFindex = ").Append(XFIndex).Append("\n"); buffer.Append("options = ").Append(Options).Append("\n"); buffer.Append(" hidden = ").Append(IsHidden).Append("\n"); buffer.Append(" olevel = ").Append(OutlineLevel) .Append("\n"); buffer.Append(" collapsed = ").Append(IsCollapsed) .Append("\n"); buffer.Append("[/COLINFO]\n"); return buffer.ToString(); } public override Object Clone() { ColumnInfoRecord rec = new ColumnInfoRecord(); rec._first_col = _first_col; rec._last_col = _last_col; rec._col_width = _col_width; rec._xf_index = _xf_index; rec._options = _options; rec.field_6_reserved = field_6_reserved; return rec; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management; using Microsoft.WindowsAzure.Management.Models; namespace Microsoft.WindowsAzure { /// <summary> /// The Service Management API provides programmatic access to much of the /// functionality available through the Management Portal. The Service /// Management API is a REST API. All API operations are performed over /// SSL and are mutually authenticated using X.509 v3 certificates. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for /// more information) /// </summary> public static partial class SubscriptionOperationsExtensions { /// <summary> /// The Get Subscription operation returns account and resource /// allocation information for the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ISubscriptionOperations. /// </param> /// <returns> /// The Get Subscription operation response. /// </returns> public static SubscriptionGetResponse Get(this ISubscriptionOperations operations) { return Task.Factory.StartNew((object s) => { return ((ISubscriptionOperations)s).GetAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Subscription operation returns account and resource /// allocation information for the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ISubscriptionOperations. /// </param> /// <returns> /// The Get Subscription operation response. /// </returns> public static Task<SubscriptionGetResponse> GetAsync(this ISubscriptionOperations operations) { return operations.GetAsync(CancellationToken.None); } /// <summary> /// The List Subscription Operations operation returns a list of /// create, update, and delete operations that were performed on a /// subscription during the specified timeframe. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ISubscriptionOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the List Subscription Operations /// operation. /// </param> /// <returns> /// The List Subscription Operations operation response. /// </returns> public static SubscriptionListOperationsResponse ListOperations(this ISubscriptionOperations operations, SubscriptionListOperationsParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ISubscriptionOperations)s).ListOperationsAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List Subscription Operations operation returns a list of /// create, update, and delete operations that were performed on a /// subscription during the specified timeframe. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ISubscriptionOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the List Subscription Operations /// operation. /// </param> /// <returns> /// The List Subscription Operations operation response. /// </returns> public static Task<SubscriptionListOperationsResponse> ListOperationsAsync(this ISubscriptionOperations operations, SubscriptionListOperationsParameters parameters) { return operations.ListOperationsAsync(parameters, CancellationToken.None); } /// <summary> /// Register a resource with your subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ISubscriptionOperations. /// </param> /// <param name='resourceName'> /// Required. Name of the resource to register. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse RegisterResource(this ISubscriptionOperations operations, string resourceName) { return Task.Factory.StartNew((object s) => { return ((ISubscriptionOperations)s).RegisterResourceAsync(resourceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Register a resource with your subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ISubscriptionOperations. /// </param> /// <param name='resourceName'> /// Required. Name of the resource to register. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> RegisterResourceAsync(this ISubscriptionOperations operations, string resourceName) { return operations.RegisterResourceAsync(resourceName, CancellationToken.None); } /// <summary> /// Unregister a resource with your subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ISubscriptionOperations. /// </param> /// <param name='resourceName'> /// Required. Name of the resource to unregister. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse UnregisterResource(this ISubscriptionOperations operations, string resourceName) { return Task.Factory.StartNew((object s) => { return ((ISubscriptionOperations)s).UnregisterResourceAsync(resourceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unregister a resource with your subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.ISubscriptionOperations. /// </param> /// <param name='resourceName'> /// Required. Name of the resource to unregister. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> UnregisterResourceAsync(this ISubscriptionOperations operations, string resourceName) { return operations.UnregisterResourceAsync(resourceName, CancellationToken.None); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; #if !UNITY3D_WEB using System.Windows; #endif using System.Xml; using NLog.Common; using NLog.Filters; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using NLog.Time; /// <summary> /// A class for configuring NLog through an XML configuration file /// (App.config style or App.nlog style). /// </summary> public class XmlLoggingConfiguration : LoggingConfiguration { private readonly ConfigurationItemFactory configurationItemFactory = ConfigurationItemFactory.Default; private readonly Dictionary<string, bool> visitedFile = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, string> variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private string originalFileName; /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> public XmlLoggingConfiguration(string fileName) { using (XmlReader reader = XmlReader.Create(fileName)) { this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(string fileName, bool ignoreErrors) { using (XmlReader reader = XmlReader.Create(fileName)) { this.Initialize(reader, fileName, ignoreErrors); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> public XmlLoggingConfiguration(XmlReader reader, string fileName) { this.Initialize(reader, fileName, false); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors) { this.Initialize(reader, fileName, ignoreErrors); } #if !SILVERLIGHT /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> /// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, ignoreErrors); } } #endif #if !SILVERLIGHT /// <summary> /// Gets the default <see cref="LoggingConfiguration" /> object by parsing /// the application configuration file (<c>app.exe.config</c>). /// </summary> public static LoggingConfiguration AppConfig { get { object o = System.Configuration.ConfigurationManager.GetSection("nlog"); return o as LoggingConfiguration; } } #endif /// <summary> /// Gets the variables defined in the configuration. /// </summary> public Dictionary<string, string> Variables { get { return variables; } } /// <summary> /// Gets or sets a value indicating whether the configuration files /// should be watched for changes and reloaded automatically when changed. /// </summary> public bool AutoReload { get; set; } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// This is the list of configuration files processed. /// If the <c>autoReload</c> attribute is not set it returns empty collection. /// </summary> public override IEnumerable<string> FileNamesToWatch { get { if (this.AutoReload) { return this.visitedFile.Keys; } return new string[0]; } } /// <summary> /// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object. /// </summary> /// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns> public override LoggingConfiguration Reload() { return new XmlLoggingConfiguration(this.originalFileName); } private static bool IsTargetElement(string name) { return name.Equals("target", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target", StringComparison.OrdinalIgnoreCase); } private static bool IsTargetRefElement(string name) { return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase); } private static string CleanWhitespace(string s) { s = s.Replace(" ", string.Empty); // get rid of the whitespace return s; } private static string StripOptionalNamespacePrefix(string attributeValue) { if (attributeValue == null) { return null; } int p = attributeValue.IndexOf(':'); if (p < 0) { return attributeValue; } return attributeValue.Substring(p + 1); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")] private static Target WrapWithAsyncTargetWrapper(Target target) { var asyncTargetWrapper = new AsyncTargetWrapper(); asyncTargetWrapper.WrappedTarget = target; asyncTargetWrapper.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name); target = asyncTargetWrapper; return target; } /// <summary> /// Initializes the configuration. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> private void Initialize(XmlReader reader, string fileName, bool ignoreErrors) { try { reader.MoveToContent(); var content = new NLogXmlElement(reader); if (fileName != null) { #if SILVERLIGHT string key = fileName; #else string key = Path.GetFullPath(fileName); #endif this.visitedFile[key] = true; this.originalFileName = fileName; this.ParseTopLevel(content, Path.GetDirectoryName(fileName)); InternalLogger.Info("Configured from an XML element in {0}...", fileName); } else { this.ParseTopLevel(content, null); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception); if (!ignoreErrors) { if (LogManager.ThrowExceptions) { throw ConfigException; } else { InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException); } } else { InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException); } } } private void ConfigureFromFile(string fileName) { #if SILVERLIGHT // file names are relative to XAP string key = fileName; #else string key = Path.GetFullPath(fileName); #endif if (this.visitedFile.ContainsKey(key)) { return; } this.visitedFile[key] = true; this.ParseTopLevel(new NLogXmlElement(fileName), Path.GetDirectoryName(fileName)); } private void ParseTopLevel(NLogXmlElement content, string baseDirectory) { content.AssertName("nlog", "configuration"); switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "CONFIGURATION": this.ParseConfigurationElement(content, baseDirectory); break; case "NLOG": this.ParseNLogElement(content, baseDirectory); break; } } private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory) { InternalLogger.Trace("ParseConfigurationElement"); configurationElement.AssertName("configuration"); foreach (var el in configurationElement.Elements("nlog")) { this.ParseNLogElement(el, baseDirectory); } } private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory) { InternalLogger.Trace("ParseNLogElement"); nlogElement.AssertName("nlog"); if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false)) { this.DefaultCultureInfo = CultureInfo.InvariantCulture; } this.AutoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", false); LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions); InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole); InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError); InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile); InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name)); LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name)); foreach (var el in nlogElement.Children) { switch (el.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "EXTENSIONS": this.ParseExtensionsElement(el, baseDirectory); break; case "INCLUDE": this.ParseIncludeElement(el, baseDirectory); break; case "APPENDERS": case "TARGETS": this.ParseTargetsElement(el); break; case "VARIABLE": this.ParseVariableElement(el); break; case "RULES": this.ParseRulesElement(el, this.LoggingRules); break; case "TIME": this.ParseTimeElement(el); break; default: InternalLogger.Warn("Skipping unknown node: {0}", el.LocalName); break; } } } private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection) { InternalLogger.Trace("ParseRulesElement"); rulesElement.AssertName("rules"); foreach (var loggerElement in rulesElement.Elements("logger")) { this.ParseLoggerElement(loggerElement, rulesCollection); } } private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection) { loggerElement.AssertName("logger"); var namePattern = loggerElement.GetOptionalAttribute("name", "*"); var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true); if (!enabled) { InternalLogger.Debug("The logger named '{0}' are disabled"); return; } var rule = new LoggingRule(); string appendTo = loggerElement.GetOptionalAttribute("appendTo", null); if (appendTo == null) { appendTo = loggerElement.GetOptionalAttribute("writeTo", null); } rule.LoggerNamePattern = namePattern; if (appendTo != null) { foreach (string t in appendTo.Split(',')) { string targetName = t.Trim(); Target target = FindTargetByName(targetName); if (target != null) { rule.Targets.Add(target); } else { throw new NLogConfigurationException("Target " + targetName + " not found."); } } } rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false); string levelString; if (loggerElement.AttributeValues.TryGetValue("level", out levelString)) { LogLevel level = LogLevel.FromString(levelString); rule.EnableLoggingForLevel(level); } else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString)) { levelString = CleanWhitespace(levelString); string[] tokens = levelString.Split(','); foreach (string s in tokens) { if (!string.IsNullOrEmpty(s)) { LogLevel level = LogLevel.FromString(s); rule.EnableLoggingForLevel(level); } } } else { int minLevel = 0; int maxLevel = LogLevel.MaxLevel.Ordinal; string minLevelString; string maxLevelString; if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString)) { minLevel = LogLevel.FromString(minLevelString).Ordinal; } if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString)) { maxLevel = LogLevel.FromString(maxLevelString).Ordinal; } for (int i = minLevel; i <= maxLevel; ++i) { rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i)); } } foreach (var child in loggerElement.Children) { switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "FILTERS": this.ParseFilters(rule, child); break; case "LOGGER": this.ParseLoggerElement(child, rule.ChildRules); break; } } rulesCollection.Add(rule); } private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement) { filtersElement.AssertName("filters"); foreach (var filterElement in filtersElement.Children) { string name = filterElement.LocalName; Filter filter = this.configurationItemFactory.Filters.CreateInstance(name); this.ConfigureObjectFromAttributes(filter, filterElement, false); rule.Filters.Add(filter); } } private void ParseVariableElement(NLogXmlElement variableElement) { variableElement.AssertName("variable"); string name = variableElement.GetRequiredAttribute("name"); string value = this.ExpandVariables(variableElement.GetRequiredAttribute("value")); this.variables[name] = value; } private void ParseTargetsElement(NLogXmlElement targetsElement) { targetsElement.AssertName("targets", "appenders"); bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false); NLogXmlElement defaultWrapperElement = null; var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>(); foreach (var targetElement in targetsElement.Children) { string name = targetElement.LocalName; string type = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null)); switch (name.ToUpper(CultureInfo.InvariantCulture)) { case "DEFAULT-WRAPPER": defaultWrapperElement = targetElement; break; case "DEFAULT-TARGET-PARAMETERS": if (type == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } typeNameToDefaultTargetParameters[type] = targetElement; break; case "TARGET": case "APPENDER": case "WRAPPER": case "WRAPPER-TARGET": case "COMPOUND-TARGET": if (type == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); NLogXmlElement defaults; if (typeNameToDefaultTargetParameters.TryGetValue(type, out defaults)) { this.ParseTargetElement(newTarget, defaults); } this.ParseTargetElement(newTarget, targetElement); if (asyncWrap) { newTarget = WrapWithAsyncTargetWrapper(newTarget); } if (defaultWrapperElement != null) { newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement); } InternalLogger.Info("Adding target {0}", newTarget); AddTarget(newTarget.Name, newTarget); break; } } } private void ParseTargetElement(Target target, NLogXmlElement targetElement) { var compound = target as CompoundTargetBase; var wrapper = target as WrapperTargetBase; this.ConfigureObjectFromAttributes(target, targetElement, true); foreach (var childElement in targetElement.Children) { string name = childElement.LocalName; if (compound != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } compound.Targets.Add(newTarget); continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } compound.Targets.Add(newTarget); } continue; } } if (wrapper != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } wrapper.WrappedTarget = newTarget; continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } if (wrapper.WrappedTarget != null) { throw new NLogConfigurationException("Wrapped target already defined."); } wrapper.WrappedTarget = newTarget; } continue; } } this.SetPropertyFromElement(target, childElement); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")] private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory) { extensionsElement.AssertName("extensions"); foreach (var addElement in extensionsElement.Elements("add")) { string prefix = addElement.GetOptionalAttribute("prefix", null); if (prefix != null) { prefix = prefix + "."; } string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null)); if (type != null) { this.configurationItemFactory.RegisterType(Type.GetType(type, true), prefix); } string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null); if (assemblyFile != null) { try { #if UNITY3D_WEB throw new NotSupportedException(); #else #if SILVERLIGHT var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else string fullFileName = Path.Combine(baseDirectory, assemblyFile); InternalLogger.Info("Loading assembly file: {0}", fullFileName); Assembly asm = Assembly.LoadFrom(fullFileName); #endif this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix); #endif } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception); } } continue; } string assemblyName = addElement.GetOptionalAttribute("assembly", null); if (assemblyName != null) { try { InternalLogger.Info("Loading assembly name: {0}", assemblyName); #if UNITY3D_WEB throw new NotSupportedException(); #else #if SILVERLIGHT var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else Assembly asm = Assembly.Load(assemblyName); #endif this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix); #endif } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception); } } continue; } } } private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory) { includeElement.AssertName("include"); string newFileName = includeElement.GetRequiredAttribute("file"); try { newFileName = this.ExpandVariables(newFileName); newFileName = SimpleLayout.Evaluate(newFileName); if (baseDirectory != null) { newFileName = Path.Combine(baseDirectory, newFileName); } #if UNITY3D_WEB throw new NotSupportedException(); #else #if SILVERLIGHT newFileName = newFileName.Replace("\\", "/"); if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null) #else if (File.Exists(newFileName)) #endif { InternalLogger.Debug("Including file '{0}'", newFileName); this.ConfigureFromFile(newFileName); } else { throw new FileNotFoundException("Included file not found: " + newFileName); } #endif } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error when including '{0}' {1}", newFileName, exception); if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false)) { return; } throw new NLogConfigurationException("Error when including: " + newFileName, exception); } } private void ParseTimeElement(NLogXmlElement timeElement) { timeElement.AssertName("time"); string type = timeElement.GetRequiredAttribute("type"); TimeSource newTimeSource = this.configurationItemFactory.TimeSources.CreateInstance(type); this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true); InternalLogger.Info("Selecting time source {0}", newTimeSource); TimeSource.Current = newTimeSource; } private void SetPropertyFromElement(object o, NLogXmlElement element) { if (this.AddArrayItemFromElement(o, element)) { return; } if (this.SetLayoutFromElement(o, element)) { return; } PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandVariables(element.Value), this.configurationItemFactory); } private bool AddArrayItemFromElement(object o, NLogXmlElement element) { string name = element.LocalName; PropertyInfo propInfo; if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo)) { return false; } Type elementType = PropertyHelper.GetArrayItemType(propInfo); if (elementType != null) { IList propertyValue = (IList)propInfo.GetValue(o, null); object arrayItem = FactoryHelper.CreateInstance(elementType); this.ConfigureObjectFromAttributes(arrayItem, element, true); this.ConfigureObjectFromElement(arrayItem, element); propertyValue.Add(arrayItem); return true; } return false; } private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType) { foreach (var kvp in element.AttributeValues) { string childName = kvp.Key; string childValue = kvp.Value; if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase)) { continue; } PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandVariables(childValue), this.configurationItemFactory); } } private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement) { PropertyInfo targetPropertyInfo; string name = layoutElement.LocalName; // if property exists if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo)) { // and is a Layout if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType)) { string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null)); // and 'type' attribute has been specified if (layoutTypeName != null) { // configure it from current element Layout layout = this.configurationItemFactory.Layouts.CreateInstance(this.ExpandVariables(layoutTypeName)); this.ConfigureObjectFromAttributes(layout, layoutElement, true); this.ConfigureObjectFromElement(layout, layoutElement); targetPropertyInfo.SetValue(o, layout, null); return true; } } } return false; } private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element) { foreach (var child in element.Children) { this.SetPropertyFromElement(targetObject, child); } } private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters) { string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type")); Target wrapperTargetInstance = this.configurationItemFactory.Targets.CreateInstance(wrapperType); WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper."); } this.ParseTargetElement(wrapperTargetInstance, defaultParameters); while (wtb.WrappedTarget != null) { wtb = wtb.WrappedTarget as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper."); } } wtb.WrappedTarget = t; wrapperTargetInstance.Name = t.Name; t.Name = t.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name); return wrapperTargetInstance; } private string ExpandVariables(string input) { string output = input; // TODO - make this case-insensitive, will probably require a different approach foreach (var kvp in this.variables) { output = output.Replace("${" + kvp.Key + "}", kvp.Value); } return output; } } }
using System; using Csla; using Invoices.DataAccess; namespace Invoices.Business { /// <summary> /// ProductInfo (read only object).<br/> /// This is a generated <see cref="ProductInfo"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="ProductList"/> collection. /// </remarks> [Serializable] public partial class ProductInfo : ReadOnlyBase<ProductInfo> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="ProductId"/> property. /// </summary> public static readonly PropertyInfo<Guid> ProductIdProperty = RegisterProperty<Guid>(p => p.ProductId, "Product Id", Guid.NewGuid()); /// <summary> /// Gets the Product Id. /// </summary> /// <value>The Product Id.</value> public Guid ProductId { get { return GetProperty(ProductIdProperty); } } /// <summary> /// Maintains metadata about <see cref="ProductCode"/> property. /// </summary> public static readonly PropertyInfo<string> ProductCodeProperty = RegisterProperty<string>(p => p.ProductCode, "Product Code", null); /// <summary> /// Gets the Product Code. /// </summary> /// <value>The Product Code.</value> public string ProductCode { get { return GetProperty(ProductCodeProperty); } } /// <summary> /// Maintains metadata about <see cref="Name"/> property. /// </summary> public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name"); /// <summary> /// Gets the Name. /// </summary> /// <value>The Name.</value> public string Name { get { return GetProperty(NameProperty); } } /// <summary> /// Maintains metadata about <see cref="ProductTypeId"/> property. /// </summary> public static readonly PropertyInfo<int> ProductTypeIdProperty = RegisterProperty<int>(p => p.ProductTypeId, "Product Type Id"); /// <summary> /// Gets the Product Type Id. /// </summary> /// <value>The Product Type Id.</value> public int ProductTypeId { get { return GetProperty(ProductTypeIdProperty); } } /// <summary> /// Maintains metadata about <see cref="UnitCost"/> property. /// </summary> public static readonly PropertyInfo<string> UnitCostProperty = RegisterProperty<string>(p => p.UnitCost, "Unit Cost"); /// <summary> /// Gets the Unit Cost. /// </summary> /// <value>The Unit Cost.</value> public string UnitCost { get { return GetProperty(UnitCostProperty); } } /// <summary> /// Maintains metadata about <see cref="StockByteNull"/> property. /// </summary> public static readonly PropertyInfo<byte?> StockByteNullProperty = RegisterProperty<byte?>(p => p.StockByteNull, "Stock Byte Null", null); /// <summary> /// Gets the Stock Byte Null. /// </summary> /// <value>The Stock Byte Null.</value> public byte? StockByteNull { get { return GetProperty(StockByteNullProperty); } } /// <summary> /// Maintains metadata about <see cref="StockByte"/> property. /// </summary> public static readonly PropertyInfo<byte> StockByteProperty = RegisterProperty<byte>(p => p.StockByte, "Stock Byte"); /// <summary> /// Gets the Stock Byte. /// </summary> /// <value>The Stock Byte.</value> public byte StockByte { get { return GetProperty(StockByteProperty); } } /// <summary> /// Maintains metadata about <see cref="StockShortNull"/> property. /// </summary> public static readonly PropertyInfo<short?> StockShortNullProperty = RegisterProperty<short?>(p => p.StockShortNull, "Stock Short Null", null); /// <summary> /// Gets the Stock Short Null. /// </summary> /// <value>The Stock Short Null.</value> public short? StockShortNull { get { return GetProperty(StockShortNullProperty); } } /// <summary> /// Maintains metadata about <see cref="StockShort"/> property. /// </summary> public static readonly PropertyInfo<short> StockShortProperty = RegisterProperty<short>(p => p.StockShort, "Stock Short"); /// <summary> /// Gets the Stock Short. /// </summary> /// <value>The Stock Short.</value> public short StockShort { get { return GetProperty(StockShortProperty); } } /// <summary> /// Maintains metadata about <see cref="StockIntNull"/> property. /// </summary> public static readonly PropertyInfo<int?> StockIntNullProperty = RegisterProperty<int?>(p => p.StockIntNull, "Stock Int Null", null); /// <summary> /// Gets the Stock Int Null. /// </summary> /// <value>The Stock Int Null.</value> public int? StockIntNull { get { return GetProperty(StockIntNullProperty); } } /// <summary> /// Maintains metadata about <see cref="StockInt"/> property. /// </summary> public static readonly PropertyInfo<int> StockIntProperty = RegisterProperty<int>(p => p.StockInt, "Stock Int"); /// <summary> /// Gets the Stock Int. /// </summary> /// <value>The Stock Int.</value> public int StockInt { get { return GetProperty(StockIntProperty); } } /// <summary> /// Maintains metadata about <see cref="StockLongNull"/> property. /// </summary> public static readonly PropertyInfo<long?> StockLongNullProperty = RegisterProperty<long?>(p => p.StockLongNull, "Stock Long Null", null); /// <summary> /// Gets the Stock Long Null. /// </summary> /// <value>The Stock Long Null.</value> public long? StockLongNull { get { return GetProperty(StockLongNullProperty); } } /// <summary> /// Maintains metadata about <see cref="StockLong"/> property. /// </summary> public static readonly PropertyInfo<long> StockLongProperty = RegisterProperty<long>(p => p.StockLong, "Stock Long"); /// <summary> /// Gets the Stock Long. /// </summary> /// <value>The Stock Long.</value> public long StockLong { get { return GetProperty(StockLongProperty); } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductInfo"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductInfo() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="ProductInfo"/> object from the given <see cref="ProductInfoDto"/>. /// </summary> /// <param name="data">The ProductInfoDto to use.</param> private void Child_Fetch(ProductInfoDto data) { // Value properties LoadProperty(ProductIdProperty, data.ProductId); LoadProperty(ProductCodeProperty, data.ProductCode); LoadProperty(NameProperty, data.Name); LoadProperty(ProductTypeIdProperty, data.ProductTypeId); LoadProperty(UnitCostProperty, data.UnitCost); LoadProperty(StockByteNullProperty, data.StockByteNull); LoadProperty(StockByteProperty, data.StockByte); LoadProperty(StockShortNullProperty, data.StockShortNull); LoadProperty(StockShortProperty, data.StockShort); LoadProperty(StockIntNullProperty, data.StockIntNull); LoadProperty(StockIntProperty, data.StockInt); LoadProperty(StockLongNullProperty, data.StockLongNull); LoadProperty(StockLongProperty, data.StockLong); var args = new DataPortalHookArgs(data); OnFetchRead(args); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
using System; using System.Windows.Forms; using System.Collections; using PrimerProForms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// Word Count Search /// </summary> public class WordCountSearch : Search { //Search parameters private bool m_AlphaSortOrder; private bool m_NumerSortOrder; private bool m_AscendingOrder; private bool m_DescendingOrder; private bool m_IgnoreTone; private string m_Title; private Settings m_Settings; //Search definition tags private const string kAlpha = "sortalpha"; private const string kNumer = "sortnumer"; private const string kAscend = "sortascend"; private const string kDescend = "sortdescend"; private const string kIgnoreTone = "ignoretone"; //private const string kTitle = "Word Count Search from Text Data"; public WordCountSearch(int number, Settings s) : base(number, SearchDefinition.kSyllCount) { m_AlphaSortOrder = true; m_NumerSortOrder = false; m_AscendingOrder = true; m_DescendingOrder = false; m_IgnoreTone = false; m_Settings = s; //m_Title = WordCountSearch.kTitle; m_Title = m_Settings.LocalizationTable.GetMessage("WordCountSearchT"); if (m_Title == "") m_Title = "Word Count Search from Text Data"; } public bool AlphaSortOrder { get { return m_AlphaSortOrder; } set { m_AlphaSortOrder = value; } } public bool NumerSortOrder { get { return m_NumerSortOrder; } set { m_NumerSortOrder = value; } } public bool AscendingOrder { get { return m_AscendingOrder; } set { m_AscendingOrder = value; } } public bool DescendingOrder { get { return m_DescendingOrder; } set { m_DescendingOrder = value; } } public bool IgnoreTone { get { return m_IgnoreTone; } set { m_IgnoreTone = value; } } public string Title { get { return m_Title; } } public bool SetupSearch() { bool flag = false; //FormWordCount fpb = new FormWordCount(); FormWordCount form = new FormWordCount(m_Settings.LocalizationTable); DialogResult dr = form.ShowDialog(); if (dr == DialogResult.OK) { this.AlphaSortOrder = form.AlphaOrder; this.NumerSortOrder = form.NumerOrder; this.AscendingOrder = form.AscendingOrder; this.DescendingOrder = form.DescendingOrder; this.IgnoreTone = form.IgnoreTone;; SearchDefinition sd = new SearchDefinition(SearchDefinition.kCount); SearchDefinitionParm sdp = null; if (this.NumerSortOrder) { sdp = new SearchDefinitionParm(WordCountSearch.kNumer); sd.AddSearchParm(sdp); } else { sdp = new SearchDefinitionParm(WordCountSearch.kAlpha); sd.AddSearchParm(sdp); } if (this.AscendingOrder) { sdp = new SearchDefinitionParm(WordCountSearch.kAscend); sd.AddSearchParm(sdp); } else { sdp = new SearchDefinitionParm(WordCountSearch.kDescend); sd.AddSearchParm(sdp); } if (form.IgnoreTone) { sdp = new SearchDefinitionParm(WordCountSearch.kIgnoreTone); sd.AddSearchParm(sdp); } this.SearchDefinition = sd; flag = true; } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = false; string strTag = ""; for (int i = 0; i < sd.SearchParmsCount(); i++) { strTag = sd.GetSearchParmAt(i).GetTag(); if (strTag == WordCountSearch.kAlpha) { this.AlphaSortOrder = true; this.NumerSortOrder = false; flag = true; } if (strTag == WordCountSearch.kNumer) { this.AlphaSortOrder = false; this.NumerSortOrder = true; flag = true; } if (strTag == WordCountSearch.kAscend) { this.AscendingOrder = true; this.DescendingOrder = false; } if (strTag == WordCountSearch.kDescend) { this.AscendingOrder = false; this.DescendingOrder = true; } if (strTag == WordCountSearch.kIgnoreTone) { this.IgnoreTone = true; flag = true; } } this.SearchDefinition = sd; return flag; } public string BuildResults() { string strText = ""; string str = ""; string strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; strText += this.Title + Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Environment.NewLine; //strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine; str = m_Settings.LocalizationTable.GetMessage("Search2"); if (str == "") str = "entries found"; strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine; strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser; return strText; } public WordCountSearch ExecuteWordCountSearch(TextData td) { SortedList sl = null; char chSortOrder = 'A'; if (this.NumerSortOrder) chSortOrder = 'N'; string strLine = ""; string strRslt = ""; sl = td.GetWordCounts(chSortOrder, this.IgnoreTone); if (this.DescendingOrder) { for (int i = sl.Count - 1; 0 < i; i--) { if (chSortOrder == 'N') strLine = sl.GetByIndex(i).ToString() + Constants.Tab + sl.GetKey(i).ToString().Substring(0, 5) + Environment.NewLine; else strLine = sl.GetKey(i).ToString() + Constants.Tab + sl.GetByIndex(i).ToString().PadLeft(5) + Environment.NewLine; strRslt += strLine; } } else { for (int i = 0; i < sl.Count; i++) { if (chSortOrder == 'N') strLine = sl.GetByIndex(i).ToString() + Constants.Tab + sl.GetKey(i).ToString().Substring(0, 5) + Environment.NewLine; else strLine = sl.GetKey(i).ToString() + Constants.Tab + sl.GetByIndex(i).ToString().PadLeft(5) + Environment.NewLine; strRslt += strLine; } } this.SearchResults = strRslt; this.SearchCount = sl.Count; return this; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; namespace Hydra.Framework.Geometric { public class LineObject : IMapviewObject, IPersist, ICloneable { #region Private Members of Line Object public event GraphicEvents GraphicSelected; public float x1; public float y1; public float x2; public float y2; private bool isselected = false; private bool isfilled = false; private bool visible = true; private bool showtooptip = false; private bool iscurrent = true; private bool islocked = false; private bool isdisabled = false; private bool showhandle = false; private int handlesize = 6; private Color fillcolor = Color.Cyan; private Color normalcolor = Color.Yellow; private Color selectcolor = Color.Red; private Color disabledcolor = Color.Gray; private int linewidth = 2; private string xml = ""; public PointF[] points = new PointF[0]; #endregion #region Properties of Line Object public PointF[] Vertices { get { return points; } set { points = value; } } [Category("Colors"), Description("The disabled graphic object will be drawn using this pen")] public Color DisabledColor { get { return disabledcolor; } set { disabledcolor = value; } } [Category("Colors"), Description("The selected graphic object willbe drawn using this pen")] public Color SelectColor { get { return selectcolor; } set { selectcolor = value; } } [Category("Colors"), Description("The graphic object willbe drawn using this pen")] public Color NormalColor { get { return normalcolor; } set { normalcolor = value; } } [DefaultValue(2), Category("AbstractStyle"), Description("The gives the line thickness of the graphic object")] public int LineWidth { get { return linewidth; } set { linewidth = value; } } [Category("Appearance"), Description("The graphic object will be filled with a given color or pattern")] public bool IsFilled { get { return isfilled; } set { isfilled = value; } } [Category("Appearance"), Description("Determines whether the object is visible or hidden")] public bool Visible { get { return visible; } set { visible = value; } } [Category("Appearance"), Description("Determines whether the tooltip information to be shown or not")] public bool ShowToopTip { get { return showtooptip; } set { showtooptip = value; } } [Category("Appearance"), Description("Determines whether the object is in current selected legend or not")] public bool IsCurrent { get { return iscurrent; } set { iscurrent = value; } } [Category("Appearance"), Description("Determines whether the object is locked from the current user or not")] public bool IsLocked { get { return islocked; } set { islocked = value; } } [Category("Appearance"), Description("Determines whether the object is disabled from editing")] public bool IsDisabled { get { return isdisabled; } set { isdisabled = value; } } [Category("Appearance"), Description("Determines whether the object is in edit mode")] public bool IsEdit { get { return showhandle; } set { isselected = true; showhandle = value; } } #endregion #region Constructors of Line Object public LineObject(float x_1, float y_1, float x_2, float y_2) { x1 = x_1; y1 = y_1; x2 = x_2; y2 = y_2; PointF pt0 = new PointF(x1, y1); PointF pt1 = new PointF(x2, y2); PointF[] points = { pt0, pt1 }; } public LineObject(LineObject lo) { PointF pt0 = new PointF(lo.x1, lo.y1); PointF pt1 = new PointF(lo.x2, lo.y2); PointF[] points = { pt0, pt1 }; } #endregion #region Methods of ICloneable public object Clone() { return new LineObject(this); } #endregion #region Methods of Line Object public bool IsSelected() { return isselected; } public void Select(bool m) { isselected = m; } public bool IsObjectAt(PointF pnt, float dist) { double curr_dist = GeoUtil.DistanceBetweenPointToSegment(new PointF(x1, y1), new PointF(x2, y2), pnt); return Math.Sqrt(curr_dist) < dist; } public Rectangle BoundingBox() { return new Rectangle((int)x1, (int)y1, (int)x2 - (int)x1, (int)y2 - (int)y1); } public float X() { return x1; } public float Y() { return y1; } public void Move(PointF p) { float dx = p.X - x1; float dy = p.Y - y1; x1 += dx; y1 += dy; x2 += dx; y2 += dy; } public void MoveBy(float xs, float ys) { x1 += xs; y1 += ys; x2 += xs; y2 += ys; } public void Scale(int scale) { x1 *= scale; y1 *= scale; } public void Rotate(float radians) { // } public void RotateAt(PointF pt) { // } public void RoateAt(Point pt) { // } public void Draw(Graphics graph, System.Drawing.Drawing2D.Matrix trans) { if (visible) { // create 0,0 and width,height points PointF[] points = { new PointF(x1, y1), new PointF(x2, y2) }; trans.TransformPoints(points); if (isselected) { graph.DrawLine(new Pen(selectcolor, linewidth), (int)points[0].X, (int)points[0].Y, (int)points[1].X, (int)points[1].Y); if (showhandle) { for (int i = 0; i < 2; i++) { graph.FillRectangle(new SolidBrush(fillcolor), points[i].X - handlesize / 2, points[i].Y - handlesize / 2, handlesize, handlesize); graph.DrawRectangle(new Pen(Color.Black, 1), points[i].X - handlesize / 2, points[i].Y - handlesize / 2, handlesize, handlesize); } } } else if (isdisabled || islocked) { graph.DrawLine(new Pen(disabledcolor, linewidth), (int)points[0].X, (int)points[0].Y, (int)points[1].X, (int)points[1].Y); } else { graph.DrawLine(new Pen(normalcolor, linewidth), (int)points[0].X, (int)points[0].Y, (int)points[1].X, (int)points[1].Y); } } } #endregion #region IPersist Methods public string ToXML { get { return xml; } set { xml = value; } } public string ToGML { get { return xml; } set { xml = value; } } public string ToVML { get { return "<line from=" + x1 + " " + y1 + " to=" + x2 + " " + y2 + " id=null href=null target=null class=null title=null alt='null' style='visibility:visible' opacity='1.0' chromakey='null' stroke='true' strokecolor=" + normalcolor + " strokeweight=" + linewidth + " fill='true' fillcolor=" + selectcolor + " print='true' coordsize='1000,1000' coordorigin='0 0' />"; } set { xml = value; } } public string ToSVG { get { return "<g stroke=" + normalcolor + "><line x1=" + x1 + " y1=" + y1 + " x2=" + x2 + " y2=" + y2 + " stroke-width=" + linewidth + " /></g>"; } set { xml = value; } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="CompilationLock.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ //#define MUTEXINSTRUMENTATION namespace System.Web.Compilation { using System; using System.Threading; using System.Globalization; using System.Security.Principal; using System.Web.Util; using System.Web.Configuration; using System.Runtime.InteropServices; using System.Web.Management; using System.Runtime.Versioning; using System.Diagnostics; using Debug = System.Web.Util.Debug; internal sealed class CompilationMutex : IDisposable { private String _name; private String _comment; #if MUTEXINSTRUMENTATION // Used to keep track of the stack when the mutex is obtained private string _stackTrace; #endif // ROTORTODO: replace unmanaged aspnet_isapi mutex with managed implementation #if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis private HandleRef _mutexHandle; // Lock Status is used to drain out all worker threads out of Mutex ownership on // app domain shutdown: -1 locked for good, 0 unlocked, N locked by a worker thread(s) private int _lockStatus; private bool _draining = false; #endif // !FEATURE_PAL internal CompilationMutex(String name, String comment) { #if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis // Attempt to get the mutex string from the registry (VSWhidbey 415795) string mutexRandomName = (string) Misc.GetAspNetRegValue("CompilationMutexName", null /*valueName*/, null /*defaultValue*/); if (mutexRandomName != null) { // If we were able to use the registry value, use it. Also, we need to prepend "Global\" // to the mutex name, to make sure it can be shared between a terminal server session // and IIS (VSWhidbey 307523). _name += @"Global\" + name + "-" + mutexRandomName; } else { // If we couldn't get the reg value, don't use it, and prepend "Local\" to the mutex // name to make it local to the session (and hence prevent hijacking) _name += @"Local\" + name; } _comment = comment; Debug.Trace("Mutex", "Creating Mutex " + MutexDebugName); _mutexHandle = new HandleRef(this, UnsafeNativeMethods.InstrumentedMutexCreate(_name)); if (_mutexHandle.Handle == IntPtr.Zero) { Debug.Trace("Mutex", "Failed to create Mutex " + MutexDebugName); throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Create)); } Debug.Trace("Mutex", "Successfully created Mutex " + MutexDebugName); #endif // !FEATURE_PAL } ~CompilationMutex() { Close(); } void IDisposable.Dispose() { Close(); System.GC.SuppressFinalize(this); } internal /*public*/ void Close() { #if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis if (_mutexHandle.Handle != IntPtr.Zero) { UnsafeNativeMethods.InstrumentedMutexDelete(_mutexHandle); _mutexHandle = new HandleRef(this, IntPtr.Zero); } #endif // !FEATURE_PAL } [ResourceExposure(ResourceScope.None)] internal /*public*/ void WaitOne() { #if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis if (_mutexHandle.Handle == IntPtr.Zero) throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Null)); // check the lock status for (;;) { int lockStatus = _lockStatus; if (lockStatus == -1 || _draining) throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Drained)); if (Interlocked.CompareExchange(ref _lockStatus, lockStatus+1, lockStatus) == lockStatus) break; // got the lock } Debug.Trace("Mutex", "Waiting for mutex " + MutexDebugName); if (UnsafeNativeMethods.InstrumentedMutexGetLock(_mutexHandle, -1) == -1) { // failed to get the lock Interlocked.Decrement(ref _lockStatus); throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Failed)); } #if MUTEXINSTRUMENTATION // Remember the stack trace for debugging purpose _stackTrace = (new StackTrace()).ToString(); #endif Debug.Trace("Mutex", "Got mutex " + MutexDebugName); #endif // !FEATURE_PAL } internal /*public*/ void ReleaseMutex() { #if !FEATURE_PAL // No unmanaged aspnet_isapi mutex in Coriolis if (_mutexHandle.Handle == IntPtr.Zero) throw new InvalidOperationException(SR.GetString(SR.CompilationMutex_Null)); Debug.Trace("Mutex", "Releasing mutex " + MutexDebugName); #if MUTEXINSTRUMENTATION // Clear out the stack trace _stackTrace = null; #endif if (UnsafeNativeMethods.InstrumentedMutexReleaseLock(_mutexHandle) != 0) Interlocked.Decrement(ref _lockStatus); #endif // !FEATURE_PAL } private String MutexDebugName { get { #if DBG return (_comment != null) ? _name + " (" + _comment + ")" : _name; #else return _name; #endif } } } internal static class CompilationLock { private static CompilationMutex _mutex; static CompilationLock() { // Create the mutex (or just get it if another process created it). // Make the mutex unique per application int hashCode = StringUtil.GetNonRandomizedHashCode("CompilationLock" + HttpRuntime.AppDomainAppId.ToLower(CultureInfo.InvariantCulture)); _mutex = new CompilationMutex( "CL" + hashCode.ToString("x", CultureInfo.InvariantCulture), "CompilationLock for " + HttpRuntime.AppDomainAppVirtualPath); } internal static void GetLock(ref bool gotLock) { // The idea of this try/finally is to make sure that the statements are always // executed together (VSWhidbey 319154) // This code should be using a constrained execution region. try { } finally { // Always take the BuildManager lock *before* taking the mutex, to avoid possible // deadlock situations (VSWhidbey 530732) #pragma warning disable 0618 //@TODO: This overload of Monitor.Enter is obsolete. Please change this to use Monitor.Enter(ref bool), and remove the pragmas -- [....] Monitor.Enter(BuildManager.TheBuildManager); #pragma warning restore 0618 _mutex.WaitOne(); gotLock = true; } } internal static void ReleaseLock() { _mutex.ReleaseMutex(); Monitor.Exit(BuildManager.TheBuildManager); } } }
using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using System.Runtime.InteropServices; using ImplemenationCTestTestAdapter.Events; namespace ImplemenationCTestTestAdapter { [ExtensionUri(ExecutorUriString)] public class CTestExecutor : ITestExecutor { public const string ExecutorUriString = "executor://CTestExecutor/v1"; private const string RegexFieldOutput = "output"; private const string RegexFieldDuration = "duration"; private static Regex RegexOutput = new Regex($@"Output:\r\n-+\r\n(?<{RegexFieldOutput}>.*)\r\n<end of output>\r\n", RegexOptions.Singleline); private static Regex RegexDuration = new Regex($@"<end of output>\r\nTest time =\s+(?<{RegexFieldDuration}>[\d\.]+) sec\r\n", RegexOptions.Singleline); public static readonly Uri ExecutorUri = new Uri(ExecutorUriString); public bool EnableLogging { get; set; } = false; private bool _childWatcherEnabled = false; private ChildProcessWatcher _childWatcher; private bool _cancelled; private readonly CMakeCache _cmakeCache; private readonly BuildConfiguration _buildConfiguration; private readonly CTestInfo _ctestInfo; public CTestExecutor() { _buildConfiguration = new BuildConfiguration(); _cmakeCache = new CMakeCache { CMakeCacheDir = _buildConfiguration.SolutionDir }; _ctestInfo = new CTestInfo(); _childWatcher = new ChildProcessWatcher(); } public void Cancel() { _cancelled = true; } public void RunTests(IEnumerable<string> sources, IRunContext runContext, IFrameworkHandle frameworkHandle) { frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests(src)"); var testInfoFilename = Path.Combine(_buildConfiguration.SolutionDir, CTestInfo.CTestInfoFileName); if (!File.Exists(testInfoFilename)) { frameworkHandle.SendMessage(TestMessageLevel.Warning, $"CTestExecutor.RunTests: didn't find info file:{testInfoFilename}"); } _ctestInfo.ReadTestInfoFile(testInfoFilename); foreach (var s in sources) { if (EnableLogging) { frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests(src) => CTestDiscoverer.ParseTestContainerFile({s})"); } var cases = CTestDiscoverer.ParseTestContainerFile(s, frameworkHandle, EnableLogging, _ctestInfo); RunTests(cases.Values, runContext, frameworkHandle); } } public void RunTests(IEnumerable<TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle) { if (!_buildConfiguration.HasDte) { frameworkHandle.SendMessage(TestMessageLevel.Error, "CTestExecutor.RunTests: DTE object not found, cannot run tests."); return; } if (!File.Exists(_cmakeCache.CTestExecutable)) { frameworkHandle.SendMessage(TestMessageLevel.Error, $"CTestExecutor.RunTests: ctest not found: \"{_cmakeCache.CTestExecutable}\""); return; } if (!Directory.Exists(_cmakeCache.CMakeCacheDir)) { frameworkHandle.SendMessage(TestMessageLevel.Error, $"CTestExecutor.RunTests: working directory not found: \"{_cmakeCache.CMakeCacheDir}\""); return; } if (EnableLogging) { frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests: working directory is \"{_cmakeCache.CMakeCacheDir}\""); } // run test cases foreach (var test in tests) { if (_cancelled) { break; } // verify we have a run directory and a ctest executable var args = $"-R \"^{test.FullyQualifiedName}$\""; args += $" -C \"{_buildConfiguration.ConfigurationName}\""; var startInfo = new ProcessStartInfo() { Arguments = args, FileName = _cmakeCache.CTestExecutable, WorkingDirectory = _cmakeCache.CMakeCacheDir, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden }; var process = new System.Diagnostics.Process { StartInfo = startInfo }; frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests: {_cmakeCache.CTestExecutable} {args}"); if (runContext.IsBeingDebugged) { if (_childWatcherEnabled) { _childWatcher.Parent = process; _childWatcher.Dte = _buildConfiguration.Dte; _childWatcher.Framework = frameworkHandle; _childWatcher.Start(); } process.Start(); frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests: ctest process id ({process.Id}) at ({process.StartTime.ToString()})"); #if true var tryCount = 0; int processId = 0; while (tryCount++ < 10) { frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests: try attaching to process ({tryCount} run)"); try { var ctestChildren = ProcessExtensions.GetChildProcesses(process); if(ctestChildren.Count == 0) { continue; } var dteChildren = _buildConfiguration.Dte.Debugger.LocalProcesses; foreach (EnvDTE.Process dteChild in dteChildren) { foreach (var ctestChild in ctestChildren) { if (dteChild.ProcessID == ctestChild.Id) { frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests: attaching to process ({ctestChild.Id}) ..."); try { dteChild.Attach(); frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests: ... done"); processId = ctestChild.Id; } catch (COMException e) { frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests: ... failed:{e.Message}"); } break; } } if(processId != 0) { break; } } if (processId != 0) { break; } } catch (COMException e) { frameworkHandle.SendMessage(TestMessageLevel.Informational, $"CTestExecutor.RunTests: other error:{e.Message}"); System.Threading.Thread.Sleep(1000); } } #endif } else { process.Start(); } process.WaitForExit(); if (_childWatcherEnabled) { _childWatcher.Stop(); } var output = process.StandardOutput.ReadToEnd(); var logFileName = _cmakeCache.CMakeCacheDir + "/Testing/Temporary/LastTest.log"; var content = File.ReadAllText(logFileName); var matchesDuration = RegexDuration.Match(content); var timeSpan = TimeSpan.FromSeconds( double.Parse(matchesDuration.Groups[RegexFieldDuration].Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat)); var testResult = new TestResult(test) { ComputerName = Environment.MachineName, Duration = timeSpan, Outcome = process.ExitCode == 0 ? TestOutcome.Passed : TestOutcome.Failed }; if (process.ExitCode != 0) { var matchesOutput = RegexOutput.Match(content); testResult.ErrorMessage = matchesOutput.Groups[RegexFieldOutput].Value; frameworkHandle.SendMessage(TestMessageLevel.Error, $"CTestExecutor.RunTests: ERROR IN TEST {test.FullyQualifiedName}:"); frameworkHandle.SendMessage(TestMessageLevel.Error, $"{output}"); frameworkHandle.SendMessage(TestMessageLevel.Error, $"CTestExecutor.RunTests: END OF TEST OUTPUT FROM {test.FullyQualifiedName}"); } frameworkHandle.RecordResult(testResult); } } } }
// // Copyright (c) 2013 Tony Mackay <toneuk@viewmodel.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using MonoDS.Utilities; using MonoDS.Exceptions; using MonoDS.Serialization; namespace MonoDS.Storage { public class StorageProcessor : IDisposable { // paths to the data path and indexes. private string _dataFilePath; private string _dataIndexFilePath; private string _deletedDataIndexFilePath; // the document store entity type for checking document is valid. private string _entityName; // the data index processor is used for saving/loading documents in the datastore. private DataIndexProcessor _dataIndexProcessor; // the data index processor is used for saving/loading pointers to deleted documents in the data file. private DataIndexProcessor _deletedDataIndexProcessor; // the filestream and binary reader for querying documents from the data file. private FileStream _fileStreamReader; private BinaryReader _binaryReader; // the filestream and binary writer for saving documents to the data file. private FileStream _fileStreamWriter; private BinaryWriter _binaryWriter; // the serilizer for converting to and from BSON/Document private readonly ISerializer _serializer; /// <summary> /// Gets the size of the document data file in Bytes. /// </summary> /// <value>The size of the file in Bytes.</value> public Int64 FileSize {get; private set;} /// <summary> /// Gets or sets the padding factor for each document stored. /// This is how much extra space is assigned to each document for allowing the document to expand. /// </summary> /// <value>The padding factor percentage.</value> public int PaddingFactor {get; set;} // return the data header from the start of the data file/ private DataHeader GetDataHeader() { // if the data file is empty create a new header if (this.FileSize == 0){ var header = new DataHeader(); UpdateDataHeader(header); this.FileSize = 64; return header; } _binaryReader.BaseStream.Position = 0; var headerBytes = _binaryReader.ReadBytes(64); var dataHeader = DataHeader.Parse(headerBytes); return dataHeader; } /// <summary> /// Initializes a new instance of the StorageProcessor class. /// Stores document /// </summary> /// <param name="dataDirectory">Data directory.</param> /// <param name="entityName">Entity name.</param> public StorageProcessor (string dataDirectory, string entityName, ISerializer serializer) { // create directory if (!Directory.Exists(dataDirectory)){ Directory.CreateDirectory(dataDirectory); } // assign file paths _dataFilePath = Path.Combine(dataDirectory, String.Format(@"{0}.mds", entityName)); _dataIndexFilePath = Path.Combine(dataDirectory, String.Format(@"{0}-DataIndex.idx", entityName)); _deletedDataIndexFilePath = Path.Combine(dataDirectory, String.Format(@"{0}-DeletedDataIndex.idx", entityName)); // assign the type of entities that are to be stores in this document store; _entityName = entityName; // assign serializer _serializer = serializer; // call function to initialise document store Initialise(); } /// <summary> /// Initialise this instance. /// </summary> public void Initialise() { Dispose(); // load a file stream for reading _fileStreamReader = new FileStream(_dataFilePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write, (int)DiskBufferSize.Default, FileOptions.SequentialScan); // load a file stream for writing _fileStreamWriter = new FileStream(_dataFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, (int)DiskBufferSize.Default, FileOptions.SequentialScan); // load the binary reader _binaryReader = new BinaryReader(_fileStreamReader); // load the binary writer _binaryWriter = new BinaryWriter(_fileStreamWriter); // create the data index processor for storing document key indexes that reference to document records. _dataIndexProcessor = new DataIndexProcessor(_dataIndexFilePath, DiskBufferSize.Larger, DiskBufferSize.Default); // create the deleted data index processor for storing data indexes to deleted or moved document records. _deletedDataIndexProcessor = new DataIndexProcessor(_deletedDataIndexFilePath, DiskBufferSize.Larger, DiskBufferSize.Default); // set if the datastore is empty or not. if (!File.Exists (_dataFilePath)) { DestroyExistingData (); } // assign file size this.FileSize = _binaryReader.BaseStream.Length; } /// <summary> /// Destroys all document data and indexes for the entity belonging to the current instance. /// </summary> public void DestroyExistingData() { // remove document store and indexes. if (File.Exists (_dataFilePath)) File.Delete (_dataFilePath); if (File.Exists (_dataIndexFilePath)) File.Delete (_dataIndexFilePath); if (File.Exists (_deletedDataIndexFilePath)) File.Delete (_deletedDataIndexFilePath); // load the total size of the index file this.FileSize = _binaryWriter.BaseStream.Length; _dataIndexProcessor.DestroyExistingData(); } /// <summary> /// Store the specified entity into the document store. /// </summary> /// <param name="entity">The new Entity (Document to store).</param> /// <typeparam name="T">The 1st type parameter.</typeparam> /// <exception cref="ConcurrencyException">When an entity with the same Id is found.</exception> public void Store<T>(T entity) { if (entity == null) throw new ArgumentNullException("Entity argument can't be null"); // make sure the entity name matches the document store type. string requiredEntityName = entity.GetType().Name; if (_entityName != requiredEntityName) throw new ArgumentException("Entity type is not valid for this data store."); // make sure entity has key field if (!Reflection.PropertyExists (entity, "Id")) throw new InvalidEntityException ("Entity must have an Id property and be of type short, integer or long." + "This is used as the primary key for the entity being stored."); // load the document key from the entity as its needed for adding to the index. var documentKey = Reflection.GetPropertyValueInt64(entity, "Id"); // get the data store header so we can generate keys and store record counts. var header = GetDataHeader(); // boolean so we know to check for duplicate or not on insert. // duplicates only need checked when the user has specified the document key. bool checkForDuplicate = true; if (documentKey == 0) checkForDuplicate = false; // get the next document key from the data file header record. documentKey = header.GenerateNextRecord(documentKey); // update the entity value so that the callers entity gets the saved document key. Reflection.SetPropertyValue(entity, "Id", documentKey); // parse the document into a binary json document for storing in the data file. byte[] binaryJson = _serializer.Serialize<T>(entity); // create the data index with the data pointer at the end of the document. // check to see if there is a deleted slot that can be used to store the data. var dataIndex = _deletedDataIndexProcessor.GetDataIndexWithEnoughSpace(binaryJson.Length); if (dataIndex != null){ // assign this document key to the deleted index. dataIndex.ChangeDocumentKey(documentKey); dataIndex.UpdateRecordLength(binaryJson.Length); } else{ // create a new data index. dataIndex = new DataIndex(documentKey, this.FileSize, binaryJson.Length, this.PaddingFactor); // update the size of the datafile this.FileSize = this.FileSize + dataIndex.RecordLength + dataIndex.PaddingLength; } // create the data index (AddIndex throws ConcurrencyException so no data will save) if (checkForDuplicate) _dataIndexProcessor.AddIndexCheckForDuplicate (dataIndex); else _dataIndexProcessor.AddIndex (dataIndex); // remove the index from the deleted index file if it exists _deletedDataIndexProcessor.RemoveIndex(dataIndex.DocumentKey); // add the data record to the data file _binaryWriter.BaseStream.Position = dataIndex.Pointer; // write the record _binaryWriter.Write(binaryJson); // write the padding. if (dataIndex.PaddingLength > 0){ _binaryWriter.Write(new Byte[dataIndex.PaddingLength]); } // save the data _binaryWriter.Flush(); // update the header record UpdateDataHeader(header); } public T Load<T>(long searchKey) { var dataIndex = _dataIndexProcessor.FindIndex(searchKey); if (dataIndex == null) return default(T); // locate the data in the data store file. _binaryReader.BaseStream.Position = dataIndex.Pointer; var dataBytes = _binaryReader.ReadBytes(dataIndex.RecordLength); // parse bytes into an entity and then return var entity = _serializer.Deserialize<T>(dataBytes); return entity; } public IEnumerable<T> Load<T>() { // create a list to hold the documents. var documentList = new List<T>(); long count = 1; var dataIndex = _dataIndexProcessor.GetDataIndex(count); while (dataIndex != null){ // load the data from the pointer specified in the data index. // locate the data in the data store file. _binaryReader.BaseStream.Position = dataIndex.Pointer; var dataBytes = _binaryReader.ReadBytes(dataIndex.RecordLength); // parse bytes into an entity and then return var entity = _serializer.Deserialize<T>(dataBytes); documentList.Add(entity); count++; dataIndex = _dataIndexProcessor.GetDataIndex(count); } return documentList; } public void Delete(long searchKey) { var dataIndex = _dataIndexProcessor.FindIndex(searchKey); if (dataIndex == null) return; // create a new deleted data index in deleted file pointing to deleted data. _deletedDataIndexProcessor.AddIndexOverwriteDeleted(dataIndex); // no need to delete the data just mark the index entry as deleted _dataIndexProcessor.RemoveIndex(searchKey); // update the record count. var header = GetDataHeader(); header.RemoveRecord(); UpdateDataHeader(header); } public void Update<T>(T entity) { if (entity == null) throw new ArgumentNullException("Entity argument can't be null"); // make sure the entity name matches the document store type. string requiredEntityName = entity.GetType().Name; if (_entityName != requiredEntityName) throw new ArgumentException("Entity type is not valid for this data store."); // make sure entity has key field if (!Reflection.PropertyExists (entity, "Id")) throw new InvalidEntityException ("Entity must have an Id property and be of type short, integer or long." + "This is used as the primary key for the entity being stored."); // load the document key from the entity as its needed for adding to the index. var documentKey = Reflection.GetPropertyValueInt64(entity, "Id"); // search the data store for the document. var dataIndex = _dataIndexProcessor.FindIndex(documentKey); if (dataIndex == null) throw new InvalidEntityException("Could not find an existing entity to update."); // either overwrite entity in existing data slot or append to the the end of the file. // parse the document into a binary json document byte[] binaryJson = _serializer.Serialize<T>(entity); // write the data record to the data file // update the record index to the documents data size. dataIndex.UpdateRecordLength(binaryJson.Length); // check to see if the record needs relocated. // if it does then set the position to the end of the file. if (dataIndex.RequiresRelocation == true){ // create a deleted record pointer to the data file. _deletedDataIndexProcessor.AddIndexOverwriteDeleted(dataIndex); // set position of the document to the end of the file _binaryWriter.BaseStream.Position = this.FileSize; // update the record pointer in the data index dataIndex.UpdateRecordPointer(_binaryWriter.BaseStream.Position, this.PaddingFactor); // update the file size. this.FileSize = this.FileSize + dataIndex.RecordLength + dataIndex.PaddingLength; } else{ // set the position of where the document is in the datafile. _binaryWriter.BaseStream.Position = dataIndex.Pointer; } // make changes to the data _binaryWriter.Write(binaryJson); // write the padding bytes if (dataIndex.PaddingLength > 0){ _binaryWriter.Write(new Byte[dataIndex.PaddingLength]); } // update data index pointer to point to new location. _dataIndexProcessor.UpdateIndex(dataIndex); // save the data _binaryWriter.Flush(); } /// <summary> /// Return the Total Record Count for this Document Collection. /// </summary> public long Count() { var header = GetDataHeader(); return header.RecordCount; } /// <summary> /// Releases all resource used by the StorageProcessor object. /// Closed all pointers to data files and emptys read cache. /// </summary> public void Dispose () { // close the index processor if (_dataIndexProcessor != null) _dataIndexProcessor.Dispose(); // close the deleted index processor if (_deletedDataIndexProcessor != null) _deletedDataIndexProcessor.Dispose(); // dispose of the reader and writer if (_binaryReader != null) _binaryReader.Dispose(); // close writer if(_binaryWriter != null) _binaryWriter.Dispose(); } // update the data header located at the start of the data file. private void UpdateDataHeader(DataHeader dataHeader) { var headerBytes = dataHeader.GetBytes(); _binaryWriter.BaseStream.Position = 0; _binaryWriter.Write(headerBytes); _binaryWriter.Flush(); } } }
#if UNITY_IOS #region References using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using UnityEngine; using UnityEditor.iOS.Xcode.Extensions; using UnityEditor.iOS.Xcode; using System; using System.IO; using System.Linq; using System.Diagnostics; #endregion public class TeakXcodeProjectMutator : IPostprocessBuildWithReport { public int callbackOrder { get { return 100; } } public void OnPostprocessBuild(BuildReport report) { if (TeakSettings.JustShutUpIKnowWhatImDoing) { return; } if (report.summary.platformGroup != BuildTargetGroup.iOS) { return; } string projectPath = PBXProject.GetPBXProjectPath(report.summary.outputPath); PBXProject project = new PBXProject(); project.ReadFromFile(projectPath); #if UNITY_2019_3_OR_NEWER string unityTarget = project.GetUnityMainTargetGuid(); #else string unityTarget = project.TargetGuidByName(PBXProject.GetUnityTargetName()); #endif ///// // Add Frameworks to Unity target string[] teakRequiredFrameworks = new string[] { "AdSupport", "AVFoundation", "CoreServices", "StoreKit", "UserNotifications", "ImageIO" }; project.AddFrameworksToTarget(unityTarget, teakRequiredFrameworks); ///// // Modify plist string plistPath = report.summary.outputPath + "/Info.plist"; File.WriteAllText(plistPath, AddTeakEntriesToPlist(File.ReadAllText(plistPath))); ///// // Add Teak app extensions string[] teakExtensionCommonFrameworks = new string[] {"AdSupport", "AVFoundation", "CoreGraphics", "ImageIO", "CoreServices", "StoreKit", "SystemConfiguration", "UIKit", "UserNotifications"}; AddTeakExtensionToProjectTarget("TeakNotificationService", "TeakNotificationService", teakExtensionCommonFrameworks, project, unityTarget); AddTeakExtensionToProjectTarget("TeakNotificationContent", "TeakNotificationContent", new string[] {"UserNotificationsUI"}.Concat(teakExtensionCommonFrameworks).ToArray(), project, unityTarget); ///// // Write out modified project project.WriteToFile(projectPath); ///// // Add/modify entitlements string unityTargetName = "Unity-iPhone"; string entitlementsFileName = unityTargetName + ".entitlements"; ProjectCapabilityManager capabilityManager = new ProjectCapabilityManager(projectPath, entitlementsFileName, unityTargetName); capabilityManager.AddPushNotifications(UnityEngine.Debug.isDebugBuild); capabilityManager.AddAssociatedDomains(new string[] {"applinks:" + TeakSettings.ShortlinkDomain}); capabilityManager.WriteToFile(); } private static string AddTeakEntriesToPlist(string inputPlist) { PlistDocument plist = new PlistDocument(); plist.ReadFromString(inputPlist); // Teak credentials plist.root.SetString("TeakAppId", TeakSettings.AppId); plist.root.SetString("TeakApiKey", TeakSettings.APIKey); // Teak URL Scheme AddURLSchemeToPlist(plist, "teak" + TeakSettings.AppId); // Add remote notifications background mode AddElementToArrayIfMissing(plist, "UIBackgroundModes", "remote-notification"); return plist.WriteToString(); } public static void AddURLSchemeToPlist(PlistDocument plist, string urlSchemeToAdd) { // Get/create array of URL types PlistElementArray urlTypesArray = null; if (!plist.root.values.ContainsKey("CFBundleURLTypes")) { urlTypesArray = plist.root.CreateArray("CFBundleURLTypes"); } else { urlTypesArray = plist.root.values["CFBundleURLTypes"].AsArray(); } if (urlTypesArray == null) { urlTypesArray = plist.root.CreateArray("CFBundleURLTypes"); } // Get/create an entry in the array PlistElementDict urlTypesItems = null; if (urlTypesArray.values.Count == 0) { urlTypesItems = urlTypesArray.AddDict(); } else { urlTypesItems = urlTypesArray.values[0].AsDict(); if (urlTypesItems == null) { urlTypesItems = urlTypesArray.AddDict(); } } // Get/create array of URL schemes PlistElementArray urlSchemesArray = null; if (!urlTypesItems.values.ContainsKey("CFBundleURLSchemes")) { urlSchemesArray = urlTypesItems.CreateArray("CFBundleURLSchemes"); } else { urlSchemesArray = urlTypesItems.values["CFBundleURLSchemes"].AsArray(); if (urlSchemesArray == null) { urlSchemesArray = urlTypesItems.CreateArray("CFBundleURLSchemes"); } } // Add URL scheme if (!urlSchemesArray.ContainsElement(urlSchemeToAdd)) { urlSchemesArray.Add(urlSchemeToAdd); } } private static PlistElementArray AddElementToArrayIfMissing(PlistDocument plist, string key, object element) { PlistElementArray plistArray = null; if (!plist.root.values.ContainsKey(key)) { plistArray = plist.root.CreateArray(key); } else { plistArray = plist.root.values[key].AsArray(); } if (!plistArray.ContainsElement(element)) { plistArray.Add(element); } return plistArray; } private static string AddTeakExtensionToProjectTarget(string name, string displayName, string[] frameworks, PBXProject project, string target) { string __FILE__ = new StackTrace(new StackFrame(true)).GetFrame(0).GetFileName(); string teakEditorIosPath = Path.GetDirectoryName(__FILE__) + "/iOS"; string extensionSrcPath = teakEditorIosPath + "/" + name; ///// // Create app extension target string extensionTarget = project.AddAppExtension(target, name, PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS) + "." + displayName, extensionSrcPath + "/Info.plist"); string buildPhaseId = project.AddSourcesBuildPhase(extensionTarget); ///// // Set TeamId project.SetTeamId(extensionTarget, PlayerSettings.iOS.appleDeveloperTeamID); ///// // Add source files string[] extensionsIncluded = new string[] {".h", ".m", ".mm"}; string[] fileEntries = Directory.GetFiles(extensionSrcPath); foreach (string fileName in fileEntries) { if (!extensionsIncluded.Contains(Path.GetExtension(fileName))) { continue; } project.AddFileToBuildSection(extensionTarget, buildPhaseId, project.AddFile(fileName, name + "/" + Path.GetFileName(fileName))); } ///// // Add Frameworks project.AddFrameworksToTarget(extensionTarget, frameworks); ///// // Add libTeak.a // If the 'Runtime' directory exists, this is coming from a UPM package string relativeTeakPath = GetRelativeAssetPath(Path.GetDirectoryName(Path.GetDirectoryName(__FILE__))); if (Directory.Exists(relativeTeakPath + "/Runtime")) { relativeTeakPath = "io.teak.unity.sdk/Runtime"; } project.AddFileToBuild(extensionTarget, project.AddFile("libTeak.a", name + "/libTeak.a")); project.AddBuildProperty(extensionTarget, "LIBRARY_SEARCH_PATHS", "$(SRCROOT)/Libraries/" + relativeTeakPath + "/Plugins/iOS"); project.AddBuildProperty(extensionTarget, "ALWAYS_SEARCH_USER_PATHS", "NO"); ///// // Build properties project.SetBuildProperty(extensionTarget, "IPHONEOS_DEPLOYMENT_TARGET", "10.0"); project.AddBuildProperty(extensionTarget, "TARGETED_DEVICE_FAMILY", "1,2"); // armv7 and armv7s do not support Notification Content Extensions project.AddBuildProperty(extensionTarget, "ARCHS", "arm64"); return extensionTarget; } private static string GetRelativeAssetPath(string path) { Uri pathUri = new Uri(path); Uri projectUri = new Uri(Application.dataPath); string relativePath = projectUri.MakeRelativeUri(pathUri).ToString(); string assets = "Assets"; int index = relativePath.IndexOf(assets, StringComparison.Ordinal); return (index < 0) ? relativePath : relativePath.Remove(index, assets.Length + 1); } } #endif // UNITY_IOS
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using MSAst = System.Linq.Expressions; #else using MSAst = Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Compiler; using IronPython.Compiler.Ast; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime { using Ast = MSAst.Expression; using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; /// <summary> /// Created for a user-defined function. /// </summary> [PythonType("function"), DontMapGetMemberNamesToDir, DebuggerDisplay("function {__name__} in {__module__}")] public sealed partial class PythonFunction : PythonTypeSlot, IWeakReferenceable, IPythonMembersList, IDynamicMetaObjectProvider, ICodeFormattable, Binding.IFastInvokable { private readonly CodeContext/*!*/ _context; // the creating code context of the function [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] [PythonHidden] public readonly MutableTuple Closure; private object[]/*!*/ _defaults; // the default parameters of the method internal PythonDictionary _dict; // a dictionary to story arbitrary members on the function object private object _module; // the module name internal int _id, _compat; // ID/Compat flags used for testing in rules private FunctionCode _code; // the Python function code object. Not currently used for much by us... private string _name; // the name of the method private object _doc; // the current documentation string private static int[] _depth_fast = new int[20]; // hi-perf thread static data to avoid hitting a real thread static [ThreadStatic] private static int DepthSlow; // current depth stored in a real thread static with fast depth runs out [MultiRuntimeAware] private static int _CurrentId = 1; // The current ID for functions which are called in complex ways. public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals) : this(context, code, globals, code.PythonCode.Name, null, null) { } public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name) : this(context, code, globals, name, null, null) { } public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name, PythonTuple defaults) : this(context, code, globals, name, defaults, null) { } /// <summary> /// Python ctor - maps to function.__new__ /// /// y = func(x.__code__, globals(), 'foo', None, (a, )) /// </summary> public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name, PythonTuple defaults, PythonTuple closure) { if (closure != null && closure.__len__() != 0) { throw new NotImplementedException("non empty closure argument is not supported"); } if (globals == context.GlobalDict) { _module = context.Module.GetName(); _context = context; } else { _module = null; _context = new CodeContext(new PythonDictionary(), new ModuleContext(globals, DefaultContext.DefaultPythonContext)); } _defaults = defaults == null ? ArrayUtils.EmptyObjects : defaults.ToArray(); _code = code; _name = name; _doc = code._initialDoc; Closure = null; var scopeStatement = _code.PythonCode; if (scopeStatement.IsClosure) { throw new NotImplementedException("code containing closures is not supported"); } scopeStatement.RewriteBody(FunctionDefinition.ArbitraryGlobalsVisitorInstance); _compat = CalculatedCachedCompat(); } internal PythonFunction(CodeContext/*!*/ context, FunctionCode funcInfo, object modName, object[] defaults, MutableTuple closure) { Assert.NotNull(context, funcInfo); _context = context; _defaults = defaults ?? ArrayUtils.EmptyObjects; _code = funcInfo; _doc = funcInfo._initialDoc; _name = funcInfo.co_name; Debug.Assert(_defaults.Length <= _code.co_argcount); if (modName != Uninitialized.Instance) { _module = modName; } Closure = closure; _compat = CalculatedCachedCompat(); } #region Public APIs public object __globals__ { get { return _context.GlobalDict; } set { throw PythonOps.AttributeError("readonly attribute"); } } [PropertyMethod, SpecialName, System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public void Delete__globals__() { throw PythonOps.AttributeError("readonly attribute"); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PythonTuple __defaults__ { get { if (_defaults.Length == 0) return null; return new PythonTuple(_defaults); } set { if (value == null) { _defaults = ArrayUtils.EmptyObjects; } else { _defaults = value.ToArray(); } _compat = CalculatedCachedCompat(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PythonDictionary __kwdefaults__ { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PythonTuple __closure__ { get { var storage = (Context.Dict._storage as RuntimeVariablesDictionaryStorage); if (storage != null) { object[] res = new object[storage.Names.Length]; for (int i = 0; i < res.Length; i++) { res[i] = storage.GetCell(i); } return PythonTuple.MakeTuple(res); } return null; } set { throw PythonOps.AttributeError("readonly attribute"); } } [PropertyMethod, SpecialName, System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public void Delete__closure__() { throw PythonOps.AttributeError("readonly attribute"); } public string __name__ { get { return _name; } set { if (value == null) { throw PythonOps.TypeError("__name__ must be set to a string object"); } _name = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PythonDictionary/*!*/ __dict__ { get { return EnsureDict(); } set { if (value == null) throw PythonOps.TypeError("__dict__ must be set to a dictionary, not a '{0}'", PythonTypeOps.GetName(value)); _dict = value; } } public object __doc__ { get { return _doc; } set { _doc = value; } } public object __module__ { get { return _module; } set { _module = value; } } public FunctionCode __code__ { get { return _code; } set { if (value == null) { throw PythonOps.TypeError("__code__ must be set to a code object"); } _code = value; _compat = CalculatedCachedCompat(); } } public object __call__(CodeContext/*!*/ context, params object[] args) { return PythonCalls.Call(context, this, args); } public object __call__(CodeContext/*!*/ context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) { return PythonCalls.CallWithKeywordArgs(context, this, args, dict); } #endregion #region Internal APIs internal SourceSpan Span { get { return __code__.Span; } } internal string[] ArgNames { get { return __code__.ArgNames; } } /// <summary> /// The parent CodeContext in which this function was declared. /// </summary> internal CodeContext Context { get { return _context; } } internal string GetSignatureString() { StringBuilder sb = new StringBuilder(__name__); sb.Append('('); for (int i = 0; i < _code.ArgNames.Length; i++) { if (i != 0) sb.Append(", "); if (i == ExpandDictPosition) { sb.Append("**"); } else if (i == ExpandListPosition) { sb.Append("*"); } sb.Append(ArgNames[i]); if (i < NormalArgumentCount) { int noDefaults = NormalArgumentCount - Defaults.Length; // number of args w/o defaults if (i - noDefaults >= 0) { sb.Append('='); sb.Append(PythonOps.Repr(Context, Defaults[i - noDefaults])); } } } sb.Append(')'); return sb.ToString(); } /// <summary> /// Captures the # of args and whether we have kw / arg lists. This /// enables us to share sites for simple calls (calls that don't directly /// provide named arguments or the list/dict params). /// </summary> internal int FunctionCompatibility { get { return _compat; } } /// <summary> /// Calculates the _compat value which is used for call-compatibility checks /// for simple calls. Whenver any of the dependent values are updated this /// must be called again. /// /// The dependent values include: /// _nparams - this is readonly, and never requies an update /// _defaults - the user can mutate this (__defaults__) and that forces /// an update /// expand dict/list - based on nparams and flags, both read-only /// /// Bits are allocated as: /// 00003fff - Normal argument count /// 0fffb000 - Default count /// 10000000 - unused /// 20000000 - expand list /// 40000000 - expand dict /// 80000000 - unused /// /// Enforce recursion is added at runtime. /// </summary> private int CalculatedCachedCompat() { return NormalArgumentCount | Defaults.Length << 14 | ((ExpandDictPosition != -1) ? 0x40000000 : 0) | ((ExpandListPosition != -1) ? 0x20000000 : 0); } /// <summary> /// Generators w/ exception handling need to have some data stored /// on them so that we appropriately set/restore the exception state. /// </summary> internal bool IsGeneratorWithExceptionHandling { get { return ((_code.Flags & (FunctionAttributes.CanSetSysExcInfo | FunctionAttributes.Generator)) == (FunctionAttributes.CanSetSysExcInfo | FunctionAttributes.Generator)); } } /// <summary> /// Returns an ID for the function if one has been assigned, or zero if the /// function has not yet required the use of an ID. /// </summary> internal int FunctionID { get { return _id; } } /// <summary> /// Gets the position for the expand list argument or -1 if the function doesn't have an expand list parameter. /// </summary> internal int ExpandListPosition { get { if ((_code.Flags & FunctionAttributes.ArgumentList) != 0) { return _code.co_argcount; } return -1; } } /// <summary> /// Gets the position for the expand dictionary argument or -1 if the function doesn't have an expand dictionary parameter. /// </summary> internal int ExpandDictPosition { get { if ((_code.Flags & FunctionAttributes.KeywordDictionary) != 0) { if ((_code.Flags & FunctionAttributes.ArgumentList) != 0) { return _code.co_argcount + 1; } return _code.co_argcount; } return -1; } } /// <summary> /// Gets the number of normal (not params or kw-params) parameters. /// </summary> internal int NormalArgumentCount { get { return _code.co_argcount; } } /// <summary> /// Gets the number of extra arguments (params or kw-params) /// </summary> internal int ExtraArguments { get { if ((_code.Flags & FunctionAttributes.ArgumentList) != 0) { if ((_code.Flags & FunctionAttributes.KeywordDictionary) != 0) { return 2; } return 1; } else if ((_code.Flags & FunctionAttributes.KeywordDictionary) != 0) { return 1; } return 0; } } internal FunctionAttributes Flags { get { return _code.Flags; } } internal object[] Defaults { get { return _defaults; } } internal Exception BadArgumentError(int count) { return BinderOps.TypeErrorForIncorrectArgumentCount(__name__, NormalArgumentCount, Defaults.Length, count, ExpandListPosition != -1, false); } internal Exception BadKeywordArgumentError(int count) { return BinderOps.TypeErrorForIncorrectArgumentCount(__name__, NormalArgumentCount, Defaults.Length, count, ExpandListPosition != -1, true); } #endregion #region Custom member lookup operators IList<string> IMembersList.GetMemberNames() { return PythonOps.GetStringMemberList(this); } IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { List list; if (_dict == null) { list = PythonOps.MakeList(); } else { list = PythonOps.MakeListFromSequence(_dict); } list.AddNoLock("__module__"); list.extend(TypeCache.Function.GetMemberNames(context, this)); return list; } #endregion #region IWeakReferenceable Members WeakRefTracker IWeakReferenceable.GetWeakRef() { if (_dict != null) { object weakRef; if (_dict.TryGetValue("__weakref__", out weakRef)) { return weakRef as WeakRefTracker; } } return null; } bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) { EnsureDict(); _dict["__weakref__"] = value; return true; } void IWeakReferenceable.SetFinalizer(WeakRefTracker value) { ((IWeakReferenceable)this).SetWeakRef(value); } #endregion #region Private APIs internal PythonDictionary EnsureDict() { if (_dict == null) { Interlocked.CompareExchange(ref _dict, PythonDictionary.MakeSymbolDictionary(), null); } return _dict; } internal static int AddRecursionDepth(int change) { // ManagedThreadId starts at 1 and increases as we get more threads. // Therefore we keep track of a limited number of threads in an array // that only gets created once, and we access each of the elements // from only a single thread. uint tid = (uint)Thread.CurrentThread.ManagedThreadId; if (tid < _depth_fast.Length) { return _depth_fast[tid] += change; } else { return DepthSlow += change; } } internal void EnsureID() { if (_id == 0) { Interlocked.CompareExchange(ref _id, Interlocked.Increment(ref _CurrentId), 0); } } #endregion #region PythonTypeSlot Overrides internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { value = new Method(this, instance, owner); return true; } internal override bool GetAlwaysSucceeds { get { return true; } } #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { return string.Format("<function {0} at {1}>", __name__, PythonOps.HexId(this)); } #endregion #region IDynamicMetaObjectProvider Members DynamicMetaObject/*!*/ IDynamicMetaObjectProvider.GetMetaObject(Ast/*!*/ parameter) { return new Binding.MetaPythonFunction(parameter, BindingRestrictions.Empty, this); } #endregion } [PythonType("cell")] public sealed class ClosureCell : ICodeFormattable #if CLR2 , IValueEquality #endif { [PythonHidden] public object Value; internal ClosureCell(object value) { Value = value; } public object cell_contents { get { if (Value == Uninitialized.Instance) { throw PythonOps.ValueError("cell is empty"); } return Value; } } #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { return String.Format("<cell at {0}: {1}>", IdDispenser.GetId(this), GetContentsRepr() ); } private string GetContentsRepr() { if (Value == Uninitialized.Instance) { return "empty"; } return String.Format("{0} object at {1}", PythonTypeOps.GetName(Value), IdDispenser.GetId(Value)); } #endregion #region IValueEquality Members public const object __hash__ = null; #if CLR2 int IValueEquality.GetValueHashCode() { throw PythonOps.TypeError("unhashable type: cell"); } bool IValueEquality.ValueEquals(object other) { return __cmp__(other) == 0; } #endif #endregion [Python3Warning("cell comparisons not supported in 3.x")] public int __cmp__(object other) { ClosureCell cc = other as ClosureCell; if (cc == null) throw PythonOps.TypeError("cell.__cmp__(x,y) expected cell, got {0}", PythonTypeOps.GetName(other)); return PythonOps.Compare(Value, cc.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. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableDictionaryTest : ImmutableDictionaryTestBase { [Fact] public void AddExistingKeySameValueTest() { AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft"); AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void AddExistingKeyDifferentValueTest() { AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void UnorderedChangeTest() { var map = Empty<string, string>(StringComparer.Ordinal) .Add("Johnny", "Appleseed") .Add("JOHNNY", "Appleseed"); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("Johnny")); Assert.False(map.ContainsKey("johnny")); var newMap = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Equal(1, newMap.Count); Assert.True(newMap.ContainsKey("Johnny")); Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive } [Fact] public void ToSortedTest() { var map = Empty<string, string>(StringComparer.Ordinal) .Add("Johnny", "Appleseed") .Add("JOHNNY", "Appleseed"); var sortedMap = map.ToImmutableSortedDictionary(StringComparer.Ordinal); Assert.Equal(sortedMap.Count, map.Count); CollectionAssertAreEquivalent<KeyValuePair<string, string>>(sortedMap.ToList(), map.ToList()); } [Fact] public void SetItemUpdateEqualKeyTest() { var map = Empty<string, int>().WithComparers(StringComparer.OrdinalIgnoreCase) .SetItem("A", 1); map = map.SetItem("a", 2); Assert.Equal("a", map.Keys.Single()); } /// <summary> /// Verifies that the specified value comparer is applied when /// checking for equality. /// </summary> [Fact] public void SetItemUpdateEqualKeyWithValueEqualityByComparer() { var map = Empty<string, CaseInsensitiveString>().WithComparers(StringComparer.OrdinalIgnoreCase, new MyStringOrdinalComparer()); string key = "key"; var value1 = "Hello"; var value2 = "hello"; map = map.SetItem(key, new CaseInsensitiveString(value1)); map = map.SetItem(key, new CaseInsensitiveString(value2)); Assert.Equal(value2, map[key].Value); Assert.Same(map, map.SetItem(key, new CaseInsensitiveString(value2))); } [Fact] public override void EmptyTest() { base.EmptyTest(); this.EmptyTestHelperHash(Empty<int, bool>(), 5); } [Fact] public void ContainsValueTest() { this.ContainsValueTestHelper(ImmutableDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper()); } [Fact] public void ContainsValue_NoSuchValue_ReturnsFalse() { ImmutableDictionary<int, string> dictionary = new Dictionary<int, string> { { 1, "a" }, { 2, "b" } }.ToImmutableDictionary(); Assert.False(dictionary.ContainsValue("c")); Assert.False(dictionary.ContainsValue(null)); } [Fact] public void EnumeratorWithHashCollisionsTest() { var emptyMap = Empty<int, GenericParameterHelper>(new BadHasher<int>()); this.EnumeratorTestHelper(emptyMap); } [Fact] public void Create() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; var dictionary = ImmutableDictionary.Create<string, string>(); Assert.Equal(0, dictionary.Count); Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableDictionary.Create<string, string>(keyComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableDictionary.Create(keyComparer, valueComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = ImmutableDictionary.CreateRange(pairs); Assert.Equal(1, dictionary.Count); Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableDictionary.CreateRange(keyComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableDictionary.CreateRange(keyComparer, valueComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); } [Fact] public void ToImmutableDictionary() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; ImmutableDictionary<string, string> dictionary = pairs.ToImmutableDictionary(); Assert.Equal(1, dictionary.Count); Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(keyComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant()); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); var list = new int[] { 1, 2 }; var intDictionary = list.ToImmutableDictionary(n => (double)n); Assert.Equal(1, intDictionary[1.0]); Assert.Equal(2, intDictionary[2.0]); Assert.Equal(2, intDictionary.Count); var stringIntDictionary = list.ToImmutableDictionary(n => n.ToString(), StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, stringIntDictionary.KeyComparer); Assert.Equal(1, stringIntDictionary["1"]); Assert.Equal(2, stringIntDictionary["2"]); Assert.Equal(2, intDictionary.Count); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => list.ToImmutableDictionary<int, int>(null)); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => list.ToImmutableDictionary<int, int, int>(null, v => v)); AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => list.ToImmutableDictionary<int, int, int>(k => k, null)); list.ToDictionary(k => k, v => v, null); // verifies BCL behavior is to not throw. list.ToImmutableDictionary(k => k, v => v, null, null); } [Fact] public void ToImmutableDictionaryOptimized() { var dictionary = ImmutableDictionary.Create<string, string>(); var result = dictionary.ToImmutableDictionary(); Assert.Same(dictionary, result); var cultureComparer = StringComparer.CurrentCulture; result = dictionary.WithComparers(cultureComparer, StringComparer.OrdinalIgnoreCase); Assert.Same(cultureComparer, result.KeyComparer); Assert.Same(StringComparer.OrdinalIgnoreCase, result.ValueComparer); } [Fact] public void WithComparers() { var map = ImmutableDictionary.Create<string, string>().Add("a", "1").Add("B", "1"); Assert.Same(EqualityComparer<string>.Default, map.KeyComparer); Assert.True(map.ContainsKey("a")); Assert.False(map.ContainsKey("A")); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); var cultureComparer = StringComparer.CurrentCulture; map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(cultureComparer, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); } [Fact] public void WithComparersCollisions() { // First check where collisions have matching values. var map = ImmutableDictionary.Create<string, string>() .Add("a", "1").Add("A", "1"); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(1, map.Count); Assert.True(map.ContainsKey("a")); Assert.Equal("1", map["a"]); // Now check where collisions have conflicting values. map = ImmutableDictionary.Create<string, string>() .Add("a", "1").Add("A", "2").Add("b", "3"); AssertExtensions.Throws<ArgumentException>(null, () => map.WithComparers(StringComparer.OrdinalIgnoreCase)); // Force all values to be considered equal. map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(EverythingEqual<string>.Default, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("b")); } [Fact] public void CollisionExceptionMessageContainsKey() { var map = ImmutableDictionary.Create<string, string>() .Add("firstKey", "1").Add("secondKey", "2"); var exception = AssertExtensions.Throws<ArgumentException>(null, () => map.Add("firstKey", "3")); if (!PlatformDetection.IsNetNative) //.Net Native toolchain removes exception messages. { Assert.Contains("firstKey", exception.Message); } } [Fact] public void WithComparersEmptyCollection() { var map = ImmutableDictionary.Create<string, string>(); Assert.Same(EqualityComparer<string>.Default, map.KeyComparer); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); } [Fact] public void GetValueOrDefaultOfIImmutableDictionary() { IImmutableDictionary<string, int> empty = ImmutableDictionary.Create<string, int>(); IImmutableDictionary<string, int> populated = ImmutableDictionary.Create<string, int>().Add("a", 5); Assert.Equal(0, empty.GetValueOrDefault("a")); Assert.Equal(1, empty.GetValueOrDefault("a", 1)); Assert.Equal(5, populated.GetValueOrDefault("a")); Assert.Equal(5, populated.GetValueOrDefault("a", 1)); } [Fact] public void GetValueOrDefaultOfConcreteType() { var empty = ImmutableDictionary.Create<string, int>(); var populated = ImmutableDictionary.Create<string, int>().Add("a", 5); Assert.Equal(0, empty.GetValueOrDefault("a")); Assert.Equal(1, empty.GetValueOrDefault("a", 1)); Assert.Equal(5, populated.GetValueOrDefault("a")); Assert.Equal(5, populated.GetValueOrDefault("a", 1)); } [Fact] public void EnumeratorRecyclingMisuse() { var collection = ImmutableDictionary.Create<int, int>().Add(5, 3); var enumerator = collection.GetEnumerator(); var enumeratorCopy = enumerator; Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current); enumerator.Dispose(); // double-disposal should not throw enumeratorCopy.Dispose(); // We expect that acquiring a new enumerator will use the same underlying Stack<T> object, // but that it will not throw exceptions for the new enumerator. enumerator = collection.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableDictionary.Create<int, int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableDictionary.Create<string, int>()); object rootNode = DebuggerAttributes.GetFieldValue(ImmutableDictionary.Create<string, string>(), "_root"); DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode); } [Fact] public void Clear_NoComparer_ReturnsEmptyWithoutComparer() { ImmutableDictionary<string, int> dictionary = new Dictionary<string, int> { { "a", 1 } }.ToImmutableDictionary(); Assert.Same(ImmutableDictionary<string, int>.Empty, dictionary.Clear()); Assert.NotEmpty(dictionary); } [Fact] public void Clear_HasComparer_ReturnsEmptyWithOriginalComparer() { ImmutableDictionary<string, int> dictionary = new Dictionary<string, int> { { "a", 1 } }.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase); ImmutableDictionary<string, int> clearedDictionary = dictionary.Clear(); Assert.NotSame(ImmutableDictionary<string, int>.Empty, clearedDictionary.Clear()); Assert.NotEmpty(dictionary); clearedDictionary = clearedDictionary.Add("a", 1); Assert.True(clearedDictionary.ContainsKey("A")); } protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>() { return ImmutableDictionaryTest.Empty<TKey, TValue>(); } protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer) { return ImmutableDictionary.Create<string, TValue>(comparer); } protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableDictionary<TKey, TValue>)dictionary).ValueComparer; } internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableDictionary<TKey, TValue>)dictionary).Root; } protected void ContainsValueTestHelper<TKey, TValue>(ImmutableDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.ContainsValue(value)); Assert.True(map.Add(key, value).ContainsValue(value)); } private static ImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IEqualityComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null) { return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer); } private void EmptyTestHelperHash<TKey, TValue>(IImmutableDictionary<TKey, TValue> empty, TKey someKey) { Assert.Same(EqualityComparer<TKey>.Default, ((IHashKeyCollection<TKey>)empty).KeyComparer); } /// <summary> /// An ordinal comparer for case-insensitive strings. /// </summary> private class MyStringOrdinalComparer : EqualityComparer<CaseInsensitiveString> { public override bool Equals(CaseInsensitiveString x, CaseInsensitiveString y) { return StringComparer.Ordinal.Equals(x.Value, y.Value); } public override int GetHashCode(CaseInsensitiveString obj) { return StringComparer.Ordinal.GetHashCode(obj.Value); } } /// <summary> /// A string-wrapper that considers equality based on case insensitivity. /// </summary> private class CaseInsensitiveString { public CaseInsensitiveString(string value) { Value = value; } public string Value { get; private set; } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(this.Value); } public override bool Equals(object obj) { return StringComparer.OrdinalIgnoreCase.Equals(this.Value, ((CaseInsensitiveString)obj).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. using System; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.CustomAttributes; using System.Reflection.Runtime.BindingFlagSupport; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; namespace System.Reflection.Runtime.FieldInfos { // // The Runtime's implementation of fields. // [DebuggerDisplay("{_debugName}")] internal abstract partial class RuntimeFieldInfo : FieldInfo, ITraceableTypeMember { // // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // protected RuntimeFieldInfo(RuntimeTypeInfo contextTypeInfo, RuntimeTypeInfo reflectedType) { _contextTypeInfo = contextTypeInfo; _reflectedType = reflectedType; } public sealed override Type DeclaringType { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_DeclaringType(this); #endif return _contextTypeInfo; } } public sealed override Type FieldType { get { return this.FieldRuntimeType; } } public abstract override Type[] GetOptionalCustomModifiers(); public abstract override Type[] GetRequiredCustomModifiers(); public sealed override Object GetValue(Object obj) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_GetValue(this, obj); #endif FieldAccessor fieldAccessor = this.FieldAccessor; return fieldAccessor.GetField(obj); } public sealed override object GetValueDirect(TypedReference obj) { if (obj.IsNull) throw new ArgumentException(SR.Arg_TypedReference_Null); FieldAccessor fieldAccessor = this.FieldAccessor; return fieldAccessor.GetFieldDirect(obj); } public abstract override bool HasSameMetadataDefinitionAs(MemberInfo other); public sealed override Module Module { get { return DefiningType.Module; } } public sealed override Type ReflectedType { get { return _reflectedType; } } public sealed override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_SetValue(this, obj, value); #endif FieldAccessor fieldAccessor = this.FieldAccessor; BinderBundle binderBundle = binder.ToBinderBundle(invokeAttr, culture); fieldAccessor.SetField(obj, value, binderBundle); } public sealed override void SetValueDirect(TypedReference obj, object value) { if (obj.IsNull) throw new ArgumentException(SR.Arg_TypedReference_Null); FieldAccessor fieldAccessor = this.FieldAccessor; fieldAccessor.SetFieldDirect(obj, value); } Type ITraceableTypeMember.ContainingType { get { return _contextTypeInfo; } } /// <summary> /// Override to provide the metadata based name of a field. (Different from the Name /// property in that it does not go into the reflection trace logic.) /// </summary> protected abstract string MetadataName { get; } public sealed override String Name { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_Name(this); #endif return MetadataName; } } String ITraceableTypeMember.MemberName { get { return MetadataName; } } public sealed override object GetRawConstantValue() { if (!IsLiteral) throw new InvalidOperationException(); object defaultValue; if (!GetDefaultValueIfAvailable(raw: true, defaultValue: out defaultValue)) throw new BadImageFormatException(); // Field marked literal but has no default value. return defaultValue; } // Types that derive from RuntimeFieldInfo must implement the following public surface area members public abstract override IEnumerable<CustomAttributeData> CustomAttributes { get; } public abstract override FieldAttributes Attributes { get; } public abstract override int MetadataToken { get; } public abstract override String ToString(); public abstract override bool Equals(Object obj); public abstract override int GetHashCode(); public abstract override RuntimeFieldHandle FieldHandle { get; } /// <summary> /// Get the default value if exists for a field by parsing metadata. Return false if there is no default value. /// </summary> protected abstract bool GetDefaultValueIfAvailable(bool raw, out object defaultValue); /// <summary> /// Return a FieldAccessor object for accessing the value of a non-literal field. May rely on metadata to create correct accessor. /// </summary> protected abstract FieldAccessor TryGetFieldAccessor(); private FieldAccessor FieldAccessor { get { FieldAccessor fieldAccessor = _lazyFieldAccessor; if (fieldAccessor == null) { if (this.IsLiteral) { // Legacy: ECMA335 does not require that the metadata literal match the type of the field that declares it. // For desktop compat, we return the metadata literal as is and do not attempt to convert or validate against the Field type. Object defaultValue; if (!GetDefaultValueIfAvailable(raw: false, defaultValue: out defaultValue)) { throw new BadImageFormatException(); // Field marked literal but has no default value. } _lazyFieldAccessor = fieldAccessor = ReflectionCoreExecution.ExecutionEnvironment.CreateLiteralFieldAccessor(defaultValue, FieldType.TypeHandle); } else { _lazyFieldAccessor = fieldAccessor = TryGetFieldAccessor(); if (fieldAccessor == null) throw ReflectionCoreExecution.ExecutionDomain.CreateNonInvokabilityException(this); } } return fieldAccessor; } } /// <summary> /// Return the type of the field by parsing metadata. /// </summary> protected abstract RuntimeTypeInfo FieldRuntimeType { get; } protected RuntimeFieldInfo WithDebugName() { bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled; #if DEBUG populateDebugNames = true; #endif if (!populateDebugNames) return this; if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. _debugName = ((ITraceableTypeMember)this).MemberName; } return this; } /// <summary> /// Return the DefiningTypeInfo as a RuntimeTypeInfo (instead of as a format specific type info) /// </summary> protected abstract RuntimeTypeInfo DefiningType { get; } /// <summary> /// Returns the field offset (asserts and throws if not an instance field). Does not include the size of the object header. /// </summary> internal int Offset => FieldAccessor.Offset; protected readonly RuntimeTypeInfo _contextTypeInfo; protected readonly RuntimeTypeInfo _reflectedType; private volatile FieldAccessor _lazyFieldAccessor = null; private String _debugName; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Win32; using System.IO; using System.Threading; using System.Diagnostics; using YASAT.Properties; using YASATEngine; namespace YASAT { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { List<Rule> rules = new List<Rule>(); ProjectInfo projectInfo = new ProjectInfo(); public MainWindow() { InitializeComponent(); rules = RuleManager.GetAllRules(); if (rules.Count == 0) MessageBox.Show("No rules files were found. Please make sure the rules directory exists and valid rules are present in that directory. Alternately, select \"Open Rule Files\" from the File Menu.", "No Rules Found", MessageBoxButton.OK, MessageBoxImage.Information); RefreshUI(); } private void RefreshUI() { RuleCountMessage.Text = GetEnabledRuleCount(rules) + " / " + rules.Count + " rules currently checked."; if (!string.IsNullOrEmpty(ScanDirectory.Text) && Directory.Exists(ScanDirectory.Text)) { FileCountMessage.Text = CountFiles(ScanDirectory.Text, 0) + " files discovered that match rules."; Scan.IsEnabled = true; } } private int GetEnabledRuleCount(List<Rule> rules) { int enabledRules = 0; foreach (Rule r in rules) if (r.Selected) enabledRules++; return enabledRules; } private void Browse_Click(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.CheckPathExists = true; ofd.RestoreDirectory = true; if (ofd.ShowDialog().Value) { string dirPath = System.IO.Path.GetDirectoryName(ofd.FileName); if (Directory.Exists(dirPath)) { projectInfo.files.Clear(); ScanDirectory.Text = dirPath; FileCountMessage.Text = CountFiles(dirPath, 0) + " files discovered that match rules."; Scan.IsEnabled = true; RefreshUI(); } } } private int CountFiles(string directory, int currentFileCount) { List<string> filetypeList = new List<string>(); foreach (Rule rule in rules) { foreach (string filetype in rule.ExtensionList()) { if (!filetypeList.Contains(filetype)) filetypeList.Add(filetype); } } foreach (string file in Directory.GetFiles(directory)) { if (filetypeList.Contains("*")) currentFileCount++; else if (disregardFiletypes.IsChecked.Value || filetypeList.Contains(System.IO.Path.GetExtension(file))) currentFileCount++; } foreach (string dir in Directory.GetDirectories(directory)) currentFileCount = CountFiles(dir, currentFileCount); return currentFileCount; } private void PerformScan(string directory) { ReportSummary.Text = "Now Scanning: " + directory; this.UpdateLayout(); foreach (string file in Directory.GetFiles(directory)) { ScanFile(file); } foreach (string dir in Directory.GetDirectories(directory)) { PerformScan(dir); } } private void ScanFile(string file) { SourceFile sourceFile = new SourceFile(file); foreach (Rule rule in rules) { if (rule.ExtensionList().Contains("*")) sourceFile.issues.AddRange(rule.FindIssues(file)); else if (disregardFiletypes.IsChecked.Value || rule.ExtensionList().Contains(System.IO.Path.GetExtension(file))) sourceFile.issues.AddRange(rule.FindIssues(file)); } projectInfo.files.Add(sourceFile); } private void Scan_Click(object sender, RoutedEventArgs e) { string dirPath = ScanDirectory.Text; if (Directory.Exists(dirPath)) { PerformScan(dirPath); } ReportSummary.Visibility = System.Windows.Visibility.Visible; ReportSummary.Text = "Scan Completed, " + projectInfo.GetIssuesCount() + " issues discovered." + "Click Generate Report to create a new report"; GenReport.IsEnabled = true; } private void GenReport_Click(object sender, RoutedEventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.AddExtension = true; sfd.FileName = "YASAT_Report"; sfd.Filter = "HTML Report (*.htm)|*.htm|Condensed HTML Report (*.html)|*.html|CSV Report (*.csv)|*.csv|Text Report (*.txt)|*.txt"; sfd.FilterIndex = 0; if (sfd.ShowDialog().Value) { StreamWriter sw = new StreamWriter(sfd.FileName); switch (System.IO.Path.GetExtension(sfd.FileName)) { case ".htm": SaveAsHTML(sw); break; case ".html": SaveAsSmallHTML(sw); break; case ".txt": SaveAsTxt(sw); break; case ".csv": SaveAsCsv(sw); break; default: break; } sw.Close(); //displays the file in the default viewer Process.Start(sfd.FileName); } } private void SaveAsSmallHTML(StreamWriter sw) { sw.WriteLine(@"<html><head> <style> body{font-family: arial, san-serif;font-size:small;} .IssueDescription{padding: 5px;background-color: #eee;color: #333;font-size: small;} .offendingLine{color: #D22;font-weight: bold;} </style><body>"); sw.WriteLine("<h1>YASAT Report</h1>"); sw.WriteLine("<h2>Statistics</h2>"); sw.WriteLine("{0} files scanned</br>", projectInfo.files.Count); bool haswildCard = false; foreach (Rule r in rules) { if (r.ExtensionList().Contains("*")) haswildCard = true; } if (haswildCard) sw.WriteLine("<em>Warning:</em> One or more of the rules included in the scan has a wildcard (*) in the extension list" + " this will cause YASAT to scan all files (including .gif, .zip, .foo, .bar, etc.). This will likely" + " not give you the Lines of Code measurements and time to code review estimates you were looking for."); sw.WriteLine("{0} lines of code scanned</br>", projectInfo.getTotalLinesOfCode()); WriteLinesPerExtension("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{0} - {1} <br/>", sw, projectInfo); sw.WriteLine("{0} estimated hours to code review</br>", projectInfo.EstimateCodeReviewTime()); sw.WriteLine("{0} total issues disovered</br>", projectInfo.GetIssuesCount()); foreach (SourceFile file in projectInfo.files) { if (file.issues.Count > 0) { sw.WriteLine("<br/><strong>{0}</strong>", file.path); foreach (SourceCodeIssue issue in file.issues) { sw.WriteLine(issue.GenerateSmallHTMLSnippet()); } } } sw.WriteLine("</body></html>"); } private void SaveAsCsv(StreamWriter sw) { foreach (SourceFile file in projectInfo.files) { foreach (SourceCodeIssue issue in file.issues) { sw.WriteLine(issue.GenerateCsv()); } } } private void SaveAsTxt(StreamWriter sw) { foreach (SourceFile file in projectInfo.files) { foreach (SourceCodeIssue issue in file.issues) { sw.WriteLine(issue.GenerateText()); } } } private void SaveAsHTML(StreamWriter sw) { sw.WriteLine(@"<html><head> <style> body{font-family: arial, san-serif;} .IssueDescription{padding: 5px;background-color: #eee;color: #333;font-size: small;} .offendingLine{color: #D22;font-weight: bold;} </style><body>"); sw.WriteLine("<h1>YASAT Report</h1>"); sw.WriteLine("<h2>Statistics</h2>"); sw.WriteLine("{0} files scanned</br>", projectInfo.files.Count); bool haswildCard = false; foreach (Rule r in rules) { if (r.ExtensionList().Contains("*")) haswildCard = true; } if (haswildCard) sw.WriteLine("<em>Warning:</em> One or more of the rules included in the scan has a wildcard (*) in the extension list" + " this will cause YASAT to scan all files (including .gif, .zip, .foo, .bar, etc.). This will likely" + " not give you the Lines of Code measurements and time to code review estimates you were looking for."); sw.WriteLine("{0} lines of code scanned</br>", projectInfo.getTotalLinesOfCode()); WriteLinesPerExtension("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{0} - {1} <br/>", sw, projectInfo); sw.WriteLine("{0} estimated hours to code review</br>", projectInfo.EstimateCodeReviewTime()); sw.WriteLine("{0} total issues disovered</br>", projectInfo.GetIssuesCount()); foreach (SourceFile file in projectInfo.files) { if (file.issues.Count > 0) { sw.WriteLine("<h2>{0}</h2><h5>{1}", System.IO.Path.GetFileName(file.path), file.path); foreach (SourceCodeIssue issue in file.issues) { sw.WriteLine(issue.GenerateHTMLSnippet()); } } } sw.WriteLine("</body></html>"); } private void WriteLinesPerExtension(string format, StreamWriter sw, ProjectInfo projectInfo) { List<KeyValuePair<string, int>> ExtensionLineCount = new List<KeyValuePair<string, int>>(); foreach (SourceFile file in projectInfo.files) { bool found = false; foreach (KeyValuePair<string, int> extLinePair in ExtensionLineCount) { if (extLinePair.Key == System.IO.Path.GetExtension(file.path)) { int newTotal = extLinePair.Value + file.lines; ExtensionLineCount.Remove(extLinePair); ExtensionLineCount.Add(new KeyValuePair<string, int>(System.IO.Path.GetExtension(file.path), newTotal)); found = true; break; } } if (!found && file.issues.Count > 0) { ExtensionLineCount.Add(new KeyValuePair<string, int>(System.IO.Path.GetExtension(file.path), file.lines)); } } foreach (KeyValuePair<string, int> extLinePair in ExtensionLineCount) { sw.WriteLine(format, extLinePair.Key, extLinePair.Value); } } private void CreateRule_Click(object sender, RoutedEventArgs e) { NewRule nr = new NewRule(); nr.ShowDialog(); if (null != nr.newRule) rules.Add(nr.newRule); MessageBox.Show("New rule successfully added, be sure to save the rule set to a rules file, if you are happy with the results", "New Rule Created", MessageBoxButton.OK, MessageBoxImage.Information); RefreshUI(); } private void scanForNotes_Click(object sender, RoutedEventArgs e) { } private void Exit_Click(object sender, RoutedEventArgs e) { this.Close(); } private void OpenRuleFile_Click(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "YASAT Rules File (*.xml)|*.xml"; ofd.Multiselect = true; ofd.FilterIndex = 0; if (ofd.ShowDialog().Value) { ResetState(); List<string> realFiles = new List<string>(); foreach (string file in ofd.FileNames) { if (File.Exists(file)) realFiles.Add(file); } if (realFiles.Count > 0) rules = RuleManager.GetRulesFromFiles(realFiles); } RefreshUI(); } private void ClearRules_Click(object sender, RoutedEventArgs e) { rules.Clear(); RefreshUI(); } private void ResetState() { rules.Clear(); projectInfo.files.Clear(); } private void SelectRules_Click(object sender, RoutedEventArgs e) { SelectRules sr = new SelectRules(rules); sr.ShowDialog(); } } }
// Copyright 2017 (c) [Denis Da Silva]. All rights reserved. // See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Prolix.Extensions.Expressions; namespace Prolix.Logic { /// <summary> /// Base Field descriptor /// </summary> /// <typeparam name="T">Model type</typeparam> public abstract class ModelDescriptorField<T> where T : class { #region Constructors /// <summary> /// Creates a new <see cref="ModelDescriptor{T}" /> based on a expression /// </summary> /// <param name="propertyExpression">The property expression</param> public ModelDescriptorField(LambdaExpression propertyExpression) { if (propertyExpression == null) throw new ArgumentNullException(nameof(propertyExpression)); // Hack EF object expressions Property = propertyExpression.Normalize(); } #endregion #region Private Properties LambdaExpression Property { get; } /// <summary> /// Refleced property info /// </summary> PropertyInfo Info => Property?.GetInfo(); /// <summary> /// Field type /// </summary> Type Type => Info?.PropertyType; #endregion #region Public Properties public IList<ModelDescriptorRule<T>> Rules { get; } = new List<ModelDescriptorRule<T>>(); /// <summary> /// Property name /// </summary> public string Name => Info?.Name ?? string.Empty; /// <summary> /// Property description /// </summary> public string Text { get; set; } #endregion #region Public Methods /// <summary> /// Gets the property value /// </summary> /// <param name="entity">The model</param> /// <returns>The property value</returns> public object GetValue(T entity) { var get = Property.Compile(); return get.DynamicInvoke(entity); } #endregion } /// <summary> /// Field descriptor /// </summary> /// <typeparam name="TM">Model type</typeparam> /// <typeparam name="TP">The property type</typeparam> public sealed class ModelDescriptorField<TM, TP> : ModelDescriptorField<TM> where TM : class { #region Constructors /// <summary> /// Creates a new <see cref="ModelDescriptor{T}" /> based on a expression /// </summary> /// <param name="propertyExpression">The property expression</param> public ModelDescriptorField(LambdaExpression propertyExpression) : base(propertyExpression) { } #endregion #region Public Methods /// <summary> /// Sets the field description /// </summary> /// <param name="caption">The field description</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> Caption(string caption) { Text = caption; return this; } /// <summary> /// Sets the required rule validation /// </summary> /// <param name="message">The error message when the condition is not met.</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> Required(string message = "") { if (string.IsNullOrWhiteSpace(message)) message = string.Format("{0} is required", Text); message = message.Replace(" ", " "); Validate(i => !IsEmpty(i), message); return this; } /// <summary> /// Sets the maximum length rule validation /// </summary> /// <param name="maxLength">The maximum length</param> /// <param name="message">The error message when the condition is not met.</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> MaxLength(int maxLength, string message = "") { if (string.IsNullOrWhiteSpace(message)) message = string.Format("{0} maximum length is {1} characters", Text, maxLength); message = message.Replace(" ", " "); Validate(i => IsLengthLessThan(i, maxLength), message); return this; } /// <summary> /// Sets the minimum length rule validation /// </summary> /// <param name="minLength">The minimum length</param> /// <param name="message">The error message when the condition is not met.</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> MinLength(int minLength, string message = "") { if (string.IsNullOrWhiteSpace(message)) message = string.Format("{0} minimum length is {1} characters", Text, minLength); message = message.Replace(" ", " "); Validate(i => IsLengthGreaterThan(i, minLength), message); return this; } /// <summary> /// Sets the allowed values for the field /// </summary> /// <param name="values">The value list</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> Contains(TP[] values, string message = "") { if (string.IsNullOrWhiteSpace(message)) { var list = string.Join(", ", values); message = string.Format("The allowed values are: {0}", list); } message = message.Replace(" ", " "); Validate(i => SearchArray(i, values), message); return this; } /// <summary> /// Sets the exact value for the field /// </summary> /// <param name="value">The allowed value</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> Exact(TP value, string message = "") { if (string.IsNullOrWhiteSpace(message)) message = string.Format("The allowed value is: {0}", value); message = message.Replace(" ", " "); Validate(i => IsEqual(i, value), message); return this; } /// <summary> /// Sets the minimum value for the field /// </summary> /// <param name="value">The minimum value</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> Minimum(TP value, string message = "", params string[] args) { if (string.IsNullOrWhiteSpace(message)) message = string.Format("The minimum value is {0}", value); message = message.Replace(" ", " "); Validate(i => IsGreater(i, value) || IsEqual(i, value), message); return this; } /// <summary> /// Sets the maximum value for the field /// </summary> /// <param name="value">The maximum value</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> Maximum(TP value, string message = "") { if (string.IsNullOrWhiteSpace(message)) message = string.Format("The maximum value is {0}", value); message = message.Replace(" ", " "); Validate(i => IsLess(i, value) || IsEqual(i, value), message); return this; } /// <summary> /// Sets the maximum limit for the field /// </summary> /// <param name="value">The specified value</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> GreaterThan(TP value, string message = "") { if (string.IsNullOrWhiteSpace(message)) message = string.Format("The value must be greater than {0}", value); message = message.Replace(" ", " "); Validate(i => IsGreater(i, value), message); return this; } /// <summary> /// Sets the minimum limit for the field /// </summary> /// <param name="value">The specified value</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> LessThan(TP value, string message = "") { if (string.IsNullOrWhiteSpace(message)) message = string.Format("The value must be less than {0}", value); message = message.Replace(" ", " "); Validate(i => IsLess(i, value), message); return this; } /// <summary> /// Sets the allowed range for the field /// </summary> /// <param name="min">Minimun value</param> /// <param name="max">Maximun value</param> /// <returns>The descriptor</returns> public ModelDescriptorField<TM, TP> Range(TP min, TP max, string message = "") { if (string.IsNullOrWhiteSpace(message)) message = string.Format("The allowed range is between {0} and {1}", min, max); message = message.Replace(" ", " "); Validate(i => IsLessOrEqual(i, max) && IsLessOrEqual(i, max), message); return this; } /// <summary> /// Adds a custom validation rule /// </summary> /// <param name="condition">The validation expression</param> /// <param name="message">The error message</param> /// <returns>The descriptor</returns> public void Validate(Expression<Func<TM, bool>> condition, string message = "") { var item = new ModelDescriptorRule<TM>(condition, message); Rules.Add(item); } #endregion #region Private Methods TP TryGetValue(TM entity) { if (entity == null) return default(TP); var obj = GetValue(entity); if (obj is TP) return (TP)obj; return default(TP); } bool SearchArray(TM entity, TP[] values) { if (values == null || !values.Any()) return false; var value = TryGetValue(entity); var found = values.Contains(value); return found; } int? Compare(TM entity, TP value) { var current = GetValue(entity); var compare = current as IComparable; if (current == null || compare == null) return null; var result = compare.CompareTo(value); return result; } bool IsEqual(TM entity, TP value) { var compare = Compare(entity, value); return compare != null && compare == 0; } bool IsLess(TM entity, TP value) { var compare = Compare(entity, value); return compare != null && compare < 0; } bool IsGreater(TM entity, TP value) { var compare = Compare(entity, value); return compare != null && compare > 0; } bool IsLessOrEqual(TM entity, TP value) { var compare = Compare(entity, value); return compare != null && (compare < 0 || compare == 0); } bool IsGreaterOrEqual(TM entity, TP value) { var compare = Compare(entity, value); return compare != null && (compare > 0 || compare == 0); } bool IsEmpty(TM entity) { var value = GetValue(entity); if (value == null) return true; if (value is string) { string parsed = string.Format("{0}", value); return string.IsNullOrWhiteSpace(parsed); } else if (value is DateTime || value is DateTime?) { DateTime parsed = (DateTime)value; return parsed == DateTime.MinValue; } return false; } bool IsLengthGreaterThan(TM entity, int minLength) { var value = GetValue(entity); if (value == null || !(value is string)) return true; string parsed = string.Format("{0}", value); return parsed.Length >= minLength; } bool IsLengthLessThan(TM entity, int maxLength) { var value = GetValue(entity); if (value == null || !(value is string)) return true; string parsed = string.Format("{0}", value); return parsed.Length <= maxLength; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Dataphoria.Web.Areas.HelpPage.ModelDescriptions; using Dataphoria.Web.Areas.HelpPage.Models; namespace Dataphoria.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type bool with 3 columns and 3 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct bmat3 : IReadOnlyList<bool>, IEquatable<bmat3> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public bool m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public bool m01; /// <summary> /// Column 0, Rows 2 /// </summary> [DataMember] public bool m02; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public bool m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public bool m11; /// <summary> /// Column 1, Rows 2 /// </summary> [DataMember] public bool m12; /// <summary> /// Column 2, Rows 0 /// </summary> [DataMember] public bool m20; /// <summary> /// Column 2, Rows 1 /// </summary> [DataMember] public bool m21; /// <summary> /// Column 2, Rows 2 /// </summary> [DataMember] public bool m22; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public bmat3(bool m00, bool m01, bool m02, bool m10, bool m11, bool m12, bool m20, bool m21, bool m22) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m20 = m20; this.m21 = m21; this.m22 = m22; } /// <summary> /// Constructs this matrix from a bmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = false; this.m10 = m.m10; this.m11 = m.m11; this.m12 = false; this.m20 = false; this.m21 = false; this.m22 = true; } /// <summary> /// Constructs this matrix from a bmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = false; this.m10 = m.m10; this.m11 = m.m11; this.m12 = false; this.m20 = m.m20; this.m21 = m.m21; this.m22 = true; } /// <summary> /// Constructs this matrix from a bmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = false; this.m10 = m.m10; this.m11 = m.m11; this.m12 = false; this.m20 = m.m20; this.m21 = m.m21; this.m22 = true; } /// <summary> /// Constructs this matrix from a bmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = false; this.m21 = false; this.m22 = true; } /// <summary> /// Constructs this matrix from a bmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a bmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a bmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = false; this.m21 = false; this.m22 = true; } /// <summary> /// Constructs this matrix from a bmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a bmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bvec2 c0, bvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = false; this.m10 = c1.x; this.m11 = c1.y; this.m12 = false; this.m20 = false; this.m21 = false; this.m22 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bvec2 c0, bvec2 c1, bvec2 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = false; this.m10 = c1.x; this.m11 = c1.y; this.m12 = false; this.m20 = c2.x; this.m21 = c2.y; this.m22 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bvec3 c0, bvec3 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m20 = false; this.m21 = false; this.m22 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat3(bvec3 c0, bvec3 c1, bvec3 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m20 = c2.x; this.m21 = c2.y; this.m22 = c2.z; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public bool[,] Values => new[,] { { m00, m01, m02 }, { m10, m11, m12 }, { m20, m21, m22 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public bool[] Values1D => new[] { m00, m01, m02, m10, m11, m12, m20, m21, m22 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public bvec3 Column0 { get { return new bvec3(m00, m01, m02); } set { m00 = value.x; m01 = value.y; m02 = value.z; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public bvec3 Column1 { get { return new bvec3(m10, m11, m12); } set { m10 = value.x; m11 = value.y; m12 = value.z; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public bvec3 Column2 { get { return new bvec3(m20, m21, m22); } set { m20 = value.x; m21 = value.y; m22 = value.z; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public bvec3 Row0 { get { return new bvec3(m00, m10, m20); } set { m00 = value.x; m10 = value.y; m20 = value.z; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public bvec3 Row1 { get { return new bvec3(m01, m11, m21); } set { m01 = value.x; m11 = value.y; m21 = value.z; } } /// <summary> /// Gets or sets the row nr 2 /// </summary> public bvec3 Row2 { get { return new bvec3(m02, m12, m22); } set { m02 = value.x; m12 = value.y; m22 = value.z; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static bmat3 Zero { get; } = new bmat3(false, false, false, false, false, false, false, false, false); /// <summary> /// Predefined all-ones matrix /// </summary> public static bmat3 Ones { get; } = new bmat3(true, true, true, true, true, true, true, true, true); /// <summary> /// Predefined identity matrix /// </summary> public static bmat3 Identity { get; } = new bmat3(true, false, false, false, true, false, false, false, true); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<bool> GetEnumerator() { yield return m00; yield return m01; yield return m02; yield return m10; yield return m11; yield return m12; yield return m20; yield return m21; yield return m22; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (3 x 3 = 9). /// </summary> public int Count => 9; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public bool this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m02; case 3: return m10; case 4: return m11; case 5: return m12; case 6: return m20; case 7: return m21; case 8: return m22; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m02 = value; break; case 3: this.m10 = value; break; case 4: this.m11 = value; break; case 5: this.m12 = value; break; case 6: this.m20 = value; break; case 7: this.m21 = value; break; case 8: this.m22 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public bool this[int col, int row] { get { return this[col * 3 + row]; } set { this[col * 3 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(bmat3 rhs) => ((((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m02.Equals(rhs.m02)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m12.Equals(rhs.m12) && m20.Equals(rhs.m20)) && (m21.Equals(rhs.m21) && m22.Equals(rhs.m22)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is bmat3 && Equals((bmat3) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(bmat3 lhs, bmat3 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(bmat3 lhs, bmat3 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((((m00.GetHashCode()) * 2) ^ m01.GetHashCode()) * 2) ^ m02.GetHashCode()) * 2) ^ m10.GetHashCode()) * 2) ^ m11.GetHashCode()) * 2) ^ m12.GetHashCode()) * 2) ^ m20.GetHashCode()) * 2) ^ m21.GetHashCode()) * 2) ^ m22.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public bmat3 Transposed => new bmat3(m00, m10, m20, m01, m11, m21, m02, m12, m22); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public bool MinElement => ((((m00 && m01) && m02) && (m10 && m11)) && ((m12 && m20) && (m21 && m22))); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public bool MaxElement => ((((m00 || m01) || m02) || (m10 || m11)) || ((m12 || m20) || (m21 || m22))); /// <summary> /// Returns true if all component are true. /// </summary> public bool All => ((((m00 && m01) && m02) && (m10 && m11)) && ((m12 && m20) && (m21 && m22))); /// <summary> /// Returns true if any component is true. /// </summary> public bool Any => ((((m00 || m01) || m02) || (m10 || m11)) || ((m12 || m20) || (m21 || m22))); /// <summary> /// Executes a component-wise &amp;&amp;. (sorry for different overload but &amp;&amp; cannot be overloaded directly) /// </summary> public static bmat3 operator&(bmat3 lhs, bmat3 rhs) => new bmat3(lhs.m00 && rhs.m00, lhs.m01 && rhs.m01, lhs.m02 && rhs.m02, lhs.m10 && rhs.m10, lhs.m11 && rhs.m11, lhs.m12 && rhs.m12, lhs.m20 && rhs.m20, lhs.m21 && rhs.m21, lhs.m22 && rhs.m22); /// <summary> /// Executes a component-wise ||. (sorry for different overload but || cannot be overloaded directly) /// </summary> public static bmat3 operator|(bmat3 lhs, bmat3 rhs) => new bmat3(lhs.m00 || rhs.m00, lhs.m01 || rhs.m01, lhs.m02 || rhs.m02, lhs.m10 || rhs.m10, lhs.m11 || rhs.m11, lhs.m12 || rhs.m12, lhs.m20 || rhs.m20, lhs.m21 || rhs.m21, lhs.m22 || rhs.m22); } }
using NUnit.Framework; using Rhino.Mocks; namespace Spextensions.Specifications.RhinoMocks.Signaling { [TestFixture] public class StringSignalingSpecs { [TestFixture] public class SignalingSpecs { private ISomeInterface _mock1; private ISomeOtherInterface _mock2; private SignalState _signals; private ISomeInterface _stub1; [SetUp] public void SetUp() { _mock1 = MockRepository.GenerateMock<ISomeInterface>(); _stub1 = MockRepository.GenerateStub<ISomeInterface>(); _mock2 = MockRepository.GenerateMock<ISomeOtherInterface>(); _signals = new SignalState(); } [Fact] public void No_exception_when_signal_is_given_before_matched_expectation() { _mock1.Expect(x => x.Method1()) .Signal("given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _mock1.Method1(); _mock2.Method2(); } [Fact] [ExpectedException(typeof(SignalAssertionException))] public void Throws_SignalAssertionException_when_no_signal_is_given_before_matched_expectation() { _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _mock2.Method2(); } [Fact] [ExpectedException(typeof(SignalAssertionException))] public void Throws_SignalAssertionException_when_only_some_other_signal_is_given_before_matched_expectation() { _mock1.Expect(x => x.Method1()) .Signal("other signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("expected signal", _signals); _mock1.Method1(); _mock2.Method2(); } [Fact] [ExpectedException(typeof(SignalAssertionException))] public void Throws_SignalAssertionException_when_expected_signal_is_setup_but_signaling_call_is_never_executed() { _mock1.Expect(x => x.Method1()) .Signal("given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _mock2.Method2(); } [Fact] [ExpectedException(typeof(SignalAssertionException))] public void Throws_SignalAssertionException_when_expected_signal_is_setup_but_signaling_call_is_made_with_wrong_argument() { _mock1.Expect(x => x.Method1("expected argument")) .Signal("given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _mock1.Method1("wrong argument"); _mock2.Method2(); } [Fact] public void No_exception_is_thrown_when_stub_signals_expected_signal_before_matched_call() { _stub1.Stub(x => x.Method1()) .Signal("given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _stub1.Method1(); _mock2.Method2(); } [Fact] [ExpectedException(typeof(SignalAssertionException))] public void Throws_SignalAssertionException_when_stub_signal_is_set_up_but_signaling_call_is_never_made() { _stub1.Stub(x => x.Method1()) .Signal("given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _mock2.Method2(); } [Fact] [ExpectedException(typeof(SignalAssertionException))] public void Throws_SignalAssertionException_when_stub_signal_is_set_up_but_signaling_call_is_made_after_matching_call() { _stub1.Stub(x => x.Method1()) .Signal("given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _mock2.Method2(); _stub1.Method1(); } [Fact] [ExpectedException(typeof(SignalAssertionException))] public void Throws_SignalAssertionException_when_stub_signal_is_set_up_but_signaling_call_is_made_with_wrong_argument() { _stub1.Stub(x => x.Method1("expected argument")) .Signal("given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _stub1.Method1("wrong argument"); _mock2.Method2(); } [Fact] [ExpectedException(typeof(SignalAssertionException))] public void Throws_SignalAssertionException_when_two_signals_are_expected_but_only_one_is_signaled() { _stub1.Stub(x => x.Method1()) .Signal("given signal", _signals); _mock1.Stub(x => x.Method1()) .Signal("other given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals) .AssertSignal("other given signal", _signals); _mock1.Method1(); _mock2.Method2(); } [Fact] public void No_exception_when_two_signals_are_expected_and_both_are_signaled_before_matching_call() { _stub1.Stub(x => x.Method1()) .Signal("given signal", _signals); _mock1.Stub(x => x.Method1()) .Signal("other given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals) .AssertSignal("other given signal", _signals); _stub1.Method1(); _mock1.Method1(); _mock2.Method2(); } [Fact] public void No_expectation_when_signal_set_for_property_setter_is_signaled_before_matching_call() { _mock1.Expect(x => x.Property) .SetPropertyWithArgument("expected value") .Signal("given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _mock1.Property = "expected value"; _mock2.Method2(); } [Fact] [ExpectedException(typeof(SignalAssertionException))] public void Throws_SignalAssertionException_when_signal_is_set_for_property_setter_but_is_called_with_wrong_argument() { _mock1.Expect(x => x.Property) .SetPropertyWithArgument("expected value") .Signal("given signal", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("given signal", _signals); _mock1.Property = "wrong value"; _mock2.Method2(); } [Fact] [ExpectedException(typeof(SignalAssertionException), ExpectedMessage = "test signal name", MatchType = MessageMatch.Contains)] public void SignalAssertionException_message_includes_signal_name() { _mock1.Expect(x => x.Property) .SetPropertyWithArgument("expected value") .Signal("test signal name", _signals); _mock2.Expect(x => x.Method2()) .AssertSignal("test signal name", _signals); _mock1.Property = "wrong value"; _mock2.Method2(); } public interface ISomeInterface { string Property { get; set; } void Method1(); void Method1(string argument); } public interface ISomeOtherInterface { void Method2(); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Linq; namespace NLog.Config { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Xml; using NLog.Common; using NLog.Filters; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using NLog.Time; #if SILVERLIGHT // ReSharper disable once RedundantUsingDirective using System.Windows; #endif /// <summary> /// A class for configuring NLog through an XML configuration file /// (App.config style or App.nlog style). /// </summary> public class XmlLoggingConfiguration : LoggingConfiguration { #region private fields private readonly ConfigurationItemFactory configurationItemFactory = ConfigurationItemFactory.Default; private readonly Dictionary<string, bool> visitedFile = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, string> variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private string originalFileName; #endregion #region contructors /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> public XmlLoggingConfiguration(string fileName) { using (XmlReader reader = XmlReader.Create(fileName)) { this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(string fileName, bool ignoreErrors) { using (XmlReader reader = XmlReader.Create(fileName)) { this.Initialize(reader, fileName, ignoreErrors); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> public XmlLoggingConfiguration(XmlReader reader, string fileName) { this.Initialize(reader, fileName, false); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors) { this.Initialize(reader, fileName, ignoreErrors); } #if !SILVERLIGHT /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> /// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, ignoreErrors); } } #endif #endregion #region public properties #if !SILVERLIGHT /// <summary> /// Gets the default <see cref="LoggingConfiguration" /> object by parsing /// the application configuration file (<c>app.exe.config</c>). /// </summary> public static LoggingConfiguration AppConfig { get { object o = System.Configuration.ConfigurationManager.GetSection("nlog"); return o as LoggingConfiguration; } } #endif /// <summary> /// Did the <see cref="Initialize"/> Succeeded? <c>true</c>= success, <c>false</c>= error, <c>null</c> = initialize not started yet. /// </summary> public bool? InitializeSucceeded { get; private set; } /// <summary> /// Gets the variables defined in the configuration. /// </summary> public override Dictionary<string, string> Variables { get { return variables; } } /// <summary> /// Gets or sets a value indicating whether the configuration files /// should be watched for changes and reloaded automatically when changed. /// </summary> public bool AutoReload { get; set; } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// This is the list of configuration files processed. /// If the <c>autoReload</c> attribute is not set it returns empty collection. /// </summary> public override IEnumerable<string> FileNamesToWatch { get { if (this.AutoReload) { return this.visitedFile.Keys; } return new string[0]; } } #endregion #region public methods /// <summary> /// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object. /// </summary> /// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns> public override LoggingConfiguration Reload() { return new XmlLoggingConfiguration(this.originalFileName); } #endregion private static bool IsTargetElement(string name) { return name.Equals("target", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target", StringComparison.OrdinalIgnoreCase); } private static bool IsTargetRefElement(string name) { return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase); } /// <summary> /// Remove all spaces, also in between text. /// </summary> /// <param name="s">text</param> /// <returns>text without spaces</returns> /// <remarks>Tabs and other whitespace is not removed!</remarks> private static string CleanSpaces(string s) { s = s.Replace(" ", string.Empty); // get rid of the whitespace return s; } /// <summary> /// Remove the namespace (before :) /// </summary> /// <example> /// x:a, will be a /// </example> /// <param name="attributeValue"></param> /// <returns></returns> private static string StripOptionalNamespacePrefix(string attributeValue) { if (attributeValue == null) { return null; } int p = attributeValue.IndexOf(':'); if (p < 0) { return attributeValue; } return attributeValue.Substring(p + 1); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")] private static Target WrapWithAsyncTargetWrapper(Target target) { var asyncTargetWrapper = new AsyncTargetWrapper(); asyncTargetWrapper.WrappedTarget = target; asyncTargetWrapper.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name); target = asyncTargetWrapper; return target; } /// <summary> /// Initializes the configuration. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> private void Initialize(XmlReader reader, string fileName, bool ignoreErrors) { try { InitializeSucceeded = null; reader.MoveToContent(); var content = new NLogXmlElement(reader); if (fileName != null) { #if SILVERLIGHT string key = fileName; #else string key = Path.GetFullPath(fileName); #endif this.visitedFile[key] = true; this.originalFileName = fileName; this.ParseTopLevel(content, Path.GetDirectoryName(fileName)); InternalLogger.Info("Configured from an XML element in {0}...", fileName); } else { this.ParseTopLevel(content, null); } InitializeSucceeded = true; } catch (Exception exception) { InitializeSucceeded = false; if (exception.MustBeRethrown()) { throw; } NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception); if (!ignoreErrors) { if (LogManager.ThrowExceptions) { throw ConfigException; } else { InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException); } } else { InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException); } } } private void ConfigureFromFile(string fileName) { #if SILVERLIGHT // file names are relative to XAP string key = fileName; #else string key = Path.GetFullPath(fileName); #endif if (this.visitedFile.ContainsKey(key)) { return; } this.visitedFile[key] = true; this.ParseTopLevel(new NLogXmlElement(fileName), Path.GetDirectoryName(fileName)); } #region parse methods /// <summary> /// Parse the root /// </summary> /// <param name="content"></param> /// <param name="baseDirectory">path to directory of config file.</param> private void ParseTopLevel(NLogXmlElement content, string baseDirectory) { content.AssertName("nlog", "configuration"); switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "CONFIGURATION": this.ParseConfigurationElement(content, baseDirectory); break; case "NLOG": this.ParseNLogElement(content, baseDirectory); break; } } /// <summary> /// Parse {configuration} xml element. /// </summary> /// <param name="configurationElement"></param> /// <param name="baseDirectory">path to directory of config file.</param> private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory) { InternalLogger.Trace("ParseConfigurationElement"); configurationElement.AssertName("configuration"); foreach (var el in configurationElement.Elements("nlog")) { this.ParseNLogElement(el, baseDirectory); } } /// <summary> /// Parse {NLog} xml element. /// </summary> /// <param name="nlogElement"></param> /// <param name="baseDirectory">path to directory of config file.</param> private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory) { InternalLogger.Trace("ParseNLogElement"); nlogElement.AssertName("nlog"); if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false)) { this.DefaultCultureInfo = CultureInfo.InvariantCulture; } this.AutoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", false); LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions); InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole); InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError); InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile); InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name)); LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name)); var children = nlogElement.Children; //first load the extensions, as the can be used in other elements (targets etc) var extensionsChilds = children.Where(child => child.LocalName.Equals("EXTENSIONS", StringComparison.InvariantCultureIgnoreCase)); foreach (var extensionsChild in extensionsChilds) { this.ParseExtensionsElement(extensionsChild, baseDirectory); } //parse all other direct elements foreach (var child in children) { switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "EXTENSIONS": //already parsed break; case "INCLUDE": this.ParseIncludeElement(child, baseDirectory); break; case "APPENDERS": case "TARGETS": this.ParseTargetsElement(child); break; case "VARIABLE": this.ParseVariableElement(child); break; case "RULES": this.ParseRulesElement(child, this.LoggingRules); break; case "TIME": this.ParseTimeElement(child); break; default: InternalLogger.Warn("Skipping unknown node: {0}", child.LocalName); break; } } } /// <summary> /// Parse {Rules} xml element /// </summary> /// <param name="rulesElement"></param> /// <param name="rulesCollection">Rules are added to this parameter.</param> private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection) { InternalLogger.Trace("ParseRulesElement"); rulesElement.AssertName("rules"); foreach (var loggerElement in rulesElement.Elements("logger")) { this.ParseLoggerElement(loggerElement, rulesCollection); } } /// <summary> /// Parse {Logger} xml element /// </summary> /// <param name="loggerElement"></param> /// <param name="rulesCollection">Rules are added to this parameter.</param> private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection) { loggerElement.AssertName("logger"); var namePattern = loggerElement.GetOptionalAttribute("name", "*"); var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true); if (!enabled) { InternalLogger.Debug("The logger named '{0}' are disabled"); return; } var rule = new LoggingRule(); string appendTo = loggerElement.GetOptionalAttribute("appendTo", null); if (appendTo == null) { appendTo = loggerElement.GetOptionalAttribute("writeTo", null); } rule.LoggerNamePattern = namePattern; if (appendTo != null) { foreach (string t in appendTo.Split(',')) { string targetName = t.Trim(); Target target = FindTargetByName(targetName); if (target != null) { rule.Targets.Add(target); } else { throw new NLogConfigurationException("Target " + targetName + " not found."); } } } rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false); string levelString; if (loggerElement.AttributeValues.TryGetValue("level", out levelString)) { LogLevel level = LogLevel.FromString(levelString); rule.EnableLoggingForLevel(level); } else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString)) { levelString = CleanSpaces(levelString); string[] tokens = levelString.Split(','); foreach (string s in tokens) { if (!string.IsNullOrEmpty(s)) { LogLevel level = LogLevel.FromString(s); rule.EnableLoggingForLevel(level); } } } else { int minLevel = 0; int maxLevel = LogLevel.MaxLevel.Ordinal; string minLevelString; string maxLevelString; if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString)) { minLevel = LogLevel.FromString(minLevelString).Ordinal; } if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString)) { maxLevel = LogLevel.FromString(maxLevelString).Ordinal; } for (int i = minLevel; i <= maxLevel; ++i) { rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i)); } } foreach (var child in loggerElement.Children) { switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "FILTERS": this.ParseFilters(rule, child); break; case "LOGGER": this.ParseLoggerElement(child, rule.ChildRules); break; } } rulesCollection.Add(rule); } private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement) { filtersElement.AssertName("filters"); foreach (var filterElement in filtersElement.Children) { string name = filterElement.LocalName; Filter filter = this.configurationItemFactory.Filters.CreateInstance(name); this.ConfigureObjectFromAttributes(filter, filterElement, false); rule.Filters.Add(filter); } } private void ParseVariableElement(NLogXmlElement variableElement) { variableElement.AssertName("variable"); string name = variableElement.GetRequiredAttribute("name"); string value = this.ExpandVariables(variableElement.GetRequiredAttribute("value")); this.variables[name] = value; } private void ParseTargetsElement(NLogXmlElement targetsElement) { targetsElement.AssertName("targets", "appenders"); bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false); NLogXmlElement defaultWrapperElement = null; var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>(); foreach (var targetElement in targetsElement.Children) { string name = targetElement.LocalName; string type = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null)); switch (name.ToUpper(CultureInfo.InvariantCulture)) { case "DEFAULT-WRAPPER": defaultWrapperElement = targetElement; break; case "DEFAULT-TARGET-PARAMETERS": if (type == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } typeNameToDefaultTargetParameters[type] = targetElement; break; case "TARGET": case "APPENDER": case "WRAPPER": case "WRAPPER-TARGET": case "COMPOUND-TARGET": if (type == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); NLogXmlElement defaults; if (typeNameToDefaultTargetParameters.TryGetValue(type, out defaults)) { this.ParseTargetElement(newTarget, defaults); } this.ParseTargetElement(newTarget, targetElement); if (asyncWrap) { newTarget = WrapWithAsyncTargetWrapper(newTarget); } if (defaultWrapperElement != null) { newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement); } InternalLogger.Info("Adding target {0}", newTarget); AddTarget(newTarget.Name, newTarget); break; } } } private void ParseTargetElement(Target target, NLogXmlElement targetElement) { var compound = target as CompoundTargetBase; var wrapper = target as WrapperTargetBase; this.ConfigureObjectFromAttributes(target, targetElement, true); foreach (var childElement in targetElement.Children) { string name = childElement.LocalName; if (compound != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } compound.Targets.Add(newTarget); continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } compound.Targets.Add(newTarget); } continue; } } if (wrapper != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } wrapper.WrappedTarget = newTarget; continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } if (wrapper.WrappedTarget != null) { throw new NLogConfigurationException("Wrapped target already defined."); } wrapper.WrappedTarget = newTarget; } continue; } } this.SetPropertyFromElement(target, childElement); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")] private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory) { extensionsElement.AssertName("extensions"); foreach (var addElement in extensionsElement.Elements("add")) { string prefix = addElement.GetOptionalAttribute("prefix", null); if (prefix != null) { prefix = prefix + "."; } string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null)); if (type != null) { this.configurationItemFactory.RegisterType(Type.GetType(type, true), prefix); } string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null); if (assemblyFile != null) { try { #if SILVERLIGHT var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else string fullFileName = Path.Combine(baseDirectory, assemblyFile); InternalLogger.Info("Loading assembly file: {0}", fullFileName); Assembly asm = Assembly.LoadFrom(fullFileName); #endif this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception); } } continue; } string assemblyName = addElement.GetOptionalAttribute("assembly", null); if (assemblyName != null) { try { InternalLogger.Info("Loading assembly name: {0}", assemblyName); #if SILVERLIGHT var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else Assembly asm = Assembly.Load(assemblyName); #endif this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception); } } continue; } } } private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory) { includeElement.AssertName("include"); string newFileName = includeElement.GetRequiredAttribute("file"); try { newFileName = this.ExpandVariables(newFileName); newFileName = SimpleLayout.Evaluate(newFileName); if (baseDirectory != null) { newFileName = Path.Combine(baseDirectory, newFileName); } #if SILVERLIGHT newFileName = newFileName.Replace("\\", "/"); if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null) #else if (File.Exists(newFileName)) #endif { InternalLogger.Debug("Including file '{0}'", newFileName); this.ConfigureFromFile(newFileName); } else { throw new FileNotFoundException("Included file not found: " + newFileName); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error when including '{0}' {1}", newFileName, exception); if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false)) { return; } throw new NLogConfigurationException("Error when including: " + newFileName, exception); } } private void ParseTimeElement(NLogXmlElement timeElement) { timeElement.AssertName("time"); string type = timeElement.GetRequiredAttribute("type"); TimeSource newTimeSource = this.configurationItemFactory.TimeSources.CreateInstance(type); this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true); InternalLogger.Info("Selecting time source {0}", newTimeSource); TimeSource.Current = newTimeSource; } #endregion private void SetPropertyFromElement(object o, NLogXmlElement element) { if (this.AddArrayItemFromElement(o, element)) { return; } if (this.SetLayoutFromElement(o, element)) { return; } PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandVariables(element.Value), this.configurationItemFactory); } private bool AddArrayItemFromElement(object o, NLogXmlElement element) { string name = element.LocalName; PropertyInfo propInfo; if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo)) { return false; } Type elementType = PropertyHelper.GetArrayItemType(propInfo); if (elementType != null) { IList propertyValue = (IList)propInfo.GetValue(o, null); object arrayItem = FactoryHelper.CreateInstance(elementType); this.ConfigureObjectFromAttributes(arrayItem, element, true); this.ConfigureObjectFromElement(arrayItem, element); propertyValue.Add(arrayItem); return true; } return false; } private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType) { foreach (var kvp in element.AttributeValues) { string childName = kvp.Key; string childValue = kvp.Value; if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase)) { continue; } PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandVariables(childValue), this.configurationItemFactory); } } private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement) { PropertyInfo targetPropertyInfo; string name = layoutElement.LocalName; // if property exists if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo)) { // and is a Layout if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType)) { string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null)); // and 'type' attribute has been specified if (layoutTypeName != null) { // configure it from current element Layout layout = this.configurationItemFactory.Layouts.CreateInstance(this.ExpandVariables(layoutTypeName)); this.ConfigureObjectFromAttributes(layout, layoutElement, true); this.ConfigureObjectFromElement(layout, layoutElement); targetPropertyInfo.SetValue(o, layout, null); return true; } } } return false; } private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element) { foreach (var child in element.Children) { this.SetPropertyFromElement(targetObject, child); } } private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters) { string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type")); Target wrapperTargetInstance = this.configurationItemFactory.Targets.CreateInstance(wrapperType); WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper."); } this.ParseTargetElement(wrapperTargetInstance, defaultParameters); while (wtb.WrappedTarget != null) { wtb = wtb.WrappedTarget as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper."); } } wtb.WrappedTarget = t; wrapperTargetInstance.Name = t.Name; t.Name = t.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name); return wrapperTargetInstance; } private string ExpandVariables(string input) { string output = input; // TODO - make this case-insensitive, will probably require a different approach foreach (var kvp in this.variables) { output = output.Replace("${" + kvp.Key + "}", kvp.Value); } return output; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Requests/Messages/FortDeployPokemonMessage.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 POGOProtos.Networking.Requests.Messages { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Requests/Messages/FortDeployPokemonMessage.proto</summary> public static partial class FortDeployPokemonMessageReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Requests/Messages/FortDeployPokemonMessage.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FortDeployPokemonMessageReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkZQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVxdWVzdHMvTWVzc2FnZXMvRm9y", "dERlcGxveVBva2Vtb25NZXNzYWdlLnByb3RvEidQT0dPUHJvdG9zLk5ldHdv", "cmtpbmcuUmVxdWVzdHMuTWVzc2FnZXMicgoYRm9ydERlcGxveVBva2Vtb25N", "ZXNzYWdlEg8KB2ZvcnRfaWQYASABKAkSEgoKcG9rZW1vbl9pZBgCIAEoBhIX", "Cg9wbGF5ZXJfbGF0aXR1ZGUYAyABKAESGAoQcGxheWVyX2xvbmdpdHVkZRgE", "IAEoAWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Requests.Messages.FortDeployPokemonMessage), global::POGOProtos.Networking.Requests.Messages.FortDeployPokemonMessage.Parser, new[]{ "FortId", "PokemonId", "PlayerLatitude", "PlayerLongitude" }, null, null, null) })); } #endregion } #region Messages public sealed partial class FortDeployPokemonMessage : pb::IMessage<FortDeployPokemonMessage> { private static readonly pb::MessageParser<FortDeployPokemonMessage> _parser = new pb::MessageParser<FortDeployPokemonMessage>(() => new FortDeployPokemonMessage()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FortDeployPokemonMessage> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Requests.Messages.FortDeployPokemonMessageReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FortDeployPokemonMessage() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FortDeployPokemonMessage(FortDeployPokemonMessage other) : this() { fortId_ = other.fortId_; pokemonId_ = other.pokemonId_; playerLatitude_ = other.playerLatitude_; playerLongitude_ = other.playerLongitude_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FortDeployPokemonMessage Clone() { return new FortDeployPokemonMessage(this); } /// <summary>Field number for the "fort_id" field.</summary> public const int FortIdFieldNumber = 1; private string fortId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string FortId { get { return fortId_; } set { fortId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "pokemon_id" field.</summary> public const int PokemonIdFieldNumber = 2; private ulong pokemonId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong PokemonId { get { return pokemonId_; } set { pokemonId_ = value; } } /// <summary>Field number for the "player_latitude" field.</summary> public const int PlayerLatitudeFieldNumber = 3; private double playerLatitude_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double PlayerLatitude { get { return playerLatitude_; } set { playerLatitude_ = value; } } /// <summary>Field number for the "player_longitude" field.</summary> public const int PlayerLongitudeFieldNumber = 4; private double playerLongitude_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double PlayerLongitude { get { return playerLongitude_; } set { playerLongitude_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FortDeployPokemonMessage); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FortDeployPokemonMessage other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (FortId != other.FortId) return false; if (PokemonId != other.PokemonId) return false; if (PlayerLatitude != other.PlayerLatitude) return false; if (PlayerLongitude != other.PlayerLongitude) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (FortId.Length != 0) hash ^= FortId.GetHashCode(); if (PokemonId != 0UL) hash ^= PokemonId.GetHashCode(); if (PlayerLatitude != 0D) hash ^= PlayerLatitude.GetHashCode(); if (PlayerLongitude != 0D) hash ^= PlayerLongitude.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (FortId.Length != 0) { output.WriteRawTag(10); output.WriteString(FortId); } if (PokemonId != 0UL) { output.WriteRawTag(17); output.WriteFixed64(PokemonId); } if (PlayerLatitude != 0D) { output.WriteRawTag(25); output.WriteDouble(PlayerLatitude); } if (PlayerLongitude != 0D) { output.WriteRawTag(33); output.WriteDouble(PlayerLongitude); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (FortId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(FortId); } if (PokemonId != 0UL) { size += 1 + 8; } if (PlayerLatitude != 0D) { size += 1 + 8; } if (PlayerLongitude != 0D) { size += 1 + 8; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FortDeployPokemonMessage other) { if (other == null) { return; } if (other.FortId.Length != 0) { FortId = other.FortId; } if (other.PokemonId != 0UL) { PokemonId = other.PokemonId; } if (other.PlayerLatitude != 0D) { PlayerLatitude = other.PlayerLatitude; } if (other.PlayerLongitude != 0D) { PlayerLongitude = other.PlayerLongitude; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { FortId = input.ReadString(); break; } case 17: { PokemonId = input.ReadFixed64(); break; } case 25: { PlayerLatitude = input.ReadDouble(); break; } case 33: { PlayerLongitude = input.ReadDouble(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Text.RegularExpressions; using System.Web; using Umbraco.Core.Auditing; using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Services { /// <summary> /// Represents the File Service, which is an easy access to operations involving <see cref="IFile"/> objects like Scripts, Stylesheets and Templates /// </summary> public class FileService : IFileService { private readonly RepositoryFactory _repositoryFactory; private readonly IUnitOfWorkProvider _fileUowProvider; private readonly IDatabaseUnitOfWorkProvider _dataUowProvider; private const string PartialViewHeader = "@inherits Umbraco.Web.Mvc.UmbracoTemplatePage"; private const string PartialViewMacroHeader = "@inherits Umbraco.Web.Macros.PartialViewMacroPage"; public FileService() : this(new RepositoryFactory()) { } public FileService(RepositoryFactory repositoryFactory) : this(new FileUnitOfWorkProvider(), new PetaPocoUnitOfWorkProvider(), repositoryFactory) { } public FileService(IUnitOfWorkProvider fileProvider, IDatabaseUnitOfWorkProvider dataProvider, RepositoryFactory repositoryFactory) { _repositoryFactory = repositoryFactory; _fileUowProvider = fileProvider; _dataUowProvider = dataProvider; } #region Stylesheets /// <summary> /// Gets a list of all <see cref="Stylesheet"/> objects /// </summary> /// <returns>An enumerable list of <see cref="Stylesheet"/> objects</returns> public IEnumerable<Stylesheet> GetStylesheets(params string[] names) { using (var repository = _repositoryFactory.CreateStylesheetRepository(_fileUowProvider.GetUnitOfWork(), _dataUowProvider.GetUnitOfWork())) { return repository.GetAll(names); } } /// <summary> /// Gets a <see cref="Stylesheet"/> object by its name /// </summary> /// <param name="name">Name of the stylesheet incl. extension</param> /// <returns>A <see cref="Stylesheet"/> object</returns> public Stylesheet GetStylesheetByName(string name) { using (var repository = _repositoryFactory.CreateStylesheetRepository(_fileUowProvider.GetUnitOfWork(), _dataUowProvider.GetUnitOfWork())) { return repository.Get(name); } } /// <summary> /// Saves a <see cref="Stylesheet"/> /// </summary> /// <param name="stylesheet"><see cref="Stylesheet"/> to save</param> /// <param name="userId"></param> public void SaveStylesheet(Stylesheet stylesheet, int userId = 0) { if (SavingStylesheet.IsRaisedEventCancelled(new SaveEventArgs<Stylesheet>(stylesheet), this)) return; var uow = _fileUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateStylesheetRepository(uow, _dataUowProvider.GetUnitOfWork())) { repository.AddOrUpdate(stylesheet); uow.Commit(); SavedStylesheet.RaiseEvent(new SaveEventArgs<Stylesheet>(stylesheet, false), this); } Audit.Add(AuditTypes.Save, string.Format("Save Stylesheet performed by user"), userId, -1); } /// <summary> /// Deletes a stylesheet by its name /// </summary> /// <param name="path">Name incl. extension of the Stylesheet to delete</param> /// <param name="userId"></param> public void DeleteStylesheet(string path, int userId = 0) { var uow = _fileUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateStylesheetRepository(uow, _dataUowProvider.GetUnitOfWork())) { var stylesheet = repository.Get(path); if (stylesheet == null) return; if (DeletingStylesheet.IsRaisedEventCancelled(new DeleteEventArgs<Stylesheet>(stylesheet), this)) return; repository.Delete(stylesheet); uow.Commit(); DeletedStylesheet.RaiseEvent(new DeleteEventArgs<Stylesheet>(stylesheet, false), this); Audit.Add(AuditTypes.Delete, string.Format("Delete Stylesheet performed by user"), userId, -1); } } /// <summary> /// Validates a <see cref="Stylesheet"/> /// </summary> /// <param name="stylesheet"><see cref="Stylesheet"/> to validate</param> /// <returns>True if Stylesheet is valid, otherwise false</returns> public bool ValidateStylesheet(Stylesheet stylesheet) { return stylesheet.IsValid() && stylesheet.IsFileValidCss(); } #endregion #region Scripts /// <summary> /// Gets a list of all <see cref="Script"/> objects /// </summary> /// <returns>An enumerable list of <see cref="Script"/> objects</returns> public IEnumerable<Script> GetScripts(params string[] names) { using (var repository = _repositoryFactory.CreateScriptRepository(_fileUowProvider.GetUnitOfWork())) { return repository.GetAll(names); } } /// <summary> /// Gets a <see cref="Script"/> object by its name /// </summary> /// <param name="name">Name of the script incl. extension</param> /// <returns>A <see cref="Script"/> object</returns> public Script GetScriptByName(string name) { using (var repository = _repositoryFactory.CreateScriptRepository(_fileUowProvider.GetUnitOfWork())) { return repository.Get(name); } } /// <summary> /// Saves a <see cref="Script"/> /// </summary> /// <param name="script"><see cref="Script"/> to save</param> /// <param name="userId"></param> public void SaveScript(Script script, int userId = 0) { if (SavingScript.IsRaisedEventCancelled(new SaveEventArgs<Script>(script), this)) return; var uow = _fileUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateScriptRepository(uow)) { repository.AddOrUpdate(script); uow.Commit(); SavedScript.RaiseEvent(new SaveEventArgs<Script>(script, false), this); } Audit.Add(AuditTypes.Save, string.Format("Save Script performed by user"), userId, -1); } /// <summary> /// Deletes a script by its name /// </summary> /// <param name="path">Name incl. extension of the Script to delete</param> /// <param name="userId"></param> public void DeleteScript(string path, int userId = 0) { var uow = _fileUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateScriptRepository(uow)) { var script = repository.Get(path); if (script == null) return; if (DeletingScript.IsRaisedEventCancelled(new DeleteEventArgs<Script>(script), this)) return; ; repository.Delete(script); uow.Commit(); DeletedScript.RaiseEvent(new DeleteEventArgs<Script>(script, false), this); Audit.Add(AuditTypes.Delete, string.Format("Delete Script performed by user"), userId, -1); } } /// <summary> /// Validates a <see cref="Script"/> /// </summary> /// <param name="script"><see cref="Script"/> to validate</param> /// <returns>True if Script is valid, otherwise false</returns> public bool ValidateScript(Script script) { return script.IsValid(); } public void CreateScriptFolder(string folderPath) { var uow = _fileUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateScriptRepository(uow)) { ((ScriptRepository)repository).AddFolder(folderPath); uow.Commit(); } } public void DeleteScriptFolder(string folderPath) { var uow = _fileUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateScriptRepository(uow)) { ((ScriptRepository)repository).DeleteFolder(folderPath); uow.Commit(); } } #endregion #region Templates /// <summary> /// Gets a list of all <see cref="ITemplate"/> objects /// </summary> /// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns> public IEnumerable<ITemplate> GetTemplates(params string[] aliases) { using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork())) { return repository.GetAll(aliases); } } /// <summary> /// Gets a <see cref="ITemplate"/> object by its alias /// </summary> /// <param name="alias">Alias of the template</param> /// <returns>A <see cref="Template"/> object</returns> public ITemplate GetTemplate(string alias) { using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork())) { return repository.Get(alias); } } /// <summary> /// Gets a <see cref="ITemplate"/> object by its alias /// </summary> /// <param name="id">Id of the template</param> /// <returns>A <see cref="ITemplate"/> object</returns> public ITemplate GetTemplate(int id) { using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork())) { return repository.Get(id); } } /// <summary> /// Returns a template as a template node which can be traversed (parent, children) /// </summary> /// <param name="alias"></param> /// <returns></returns> public TemplateNode GetTemplateNode(string alias) { using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork())) { return repository.GetTemplateNode(alias); } } /// <summary> /// Given a template node in a tree, this will find the template node with the given alias if it is found in the hierarchy, otherwise null /// </summary> /// <param name="anyNode"></param> /// <param name="alias"></param> /// <returns></returns> public TemplateNode FindTemplateInTree(TemplateNode anyNode, string alias) { using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork())) { return repository.FindTemplateInTree(anyNode, alias); } } /// <summary> /// Saves a <see cref="Template"/> /// </summary> /// <param name="template"><see cref="Template"/> to save</param> /// <param name="userId"></param> public void SaveTemplate(ITemplate template, int userId = 0) { if (SavingTemplate.IsRaisedEventCancelled(new SaveEventArgs<ITemplate>(template), this)) return; var uow = _dataUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateTemplateRepository(uow)) { repository.AddOrUpdate(template); uow.Commit(); SavedTemplate.RaiseEvent(new SaveEventArgs<ITemplate>(template, false), this); } Audit.Add(AuditTypes.Save, string.Format("Save Template performed by user"), userId, template.Id); } /// <summary> /// Saves a collection of <see cref="Template"/> objects /// </summary> /// <param name="templates">List of <see cref="Template"/> to save</param> /// <param name="userId">Optional id of the user</param> public void SaveTemplate(IEnumerable<ITemplate> templates, int userId = 0) { if (SavingTemplate.IsRaisedEventCancelled(new SaveEventArgs<ITemplate>(templates), this)) return; var uow = _dataUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateTemplateRepository(uow)) { foreach (var template in templates) { repository.AddOrUpdate(template); } uow.Commit(); SavedTemplate.RaiseEvent(new SaveEventArgs<ITemplate>(templates, false), this); } Audit.Add(AuditTypes.Save, string.Format("Save Template performed by user"), userId, -1); } /// <summary> /// Deletes a template by its alias /// </summary> /// <param name="alias">Alias of the <see cref="ITemplate"/> to delete</param> /// <param name="userId"></param> public void DeleteTemplate(string alias, int userId = 0) { var uow = _dataUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateTemplateRepository(uow)) { var template = repository.Get(alias); if (template == null) return; if (DeletingTemplate.IsRaisedEventCancelled(new DeleteEventArgs<ITemplate>(template), this)) return; repository.Delete(template); uow.Commit(); DeletedTemplate.RaiseEvent(new DeleteEventArgs<ITemplate>(template, false), this); Audit.Add(AuditTypes.Delete, string.Format("Delete Template performed by user"), userId, template.Id); } } /// <summary> /// Validates a <see cref="ITemplate"/> /// </summary> /// <param name="template"><see cref="ITemplate"/> to validate</param> /// <returns>True if Script is valid, otherwise false</returns> public bool ValidateTemplate(ITemplate template) { return template.IsValid(); } #endregion #region Partial Views public IEnumerable<string> GetPartialViewSnippetNames(params string[] filterNames) { var snippetPath = IOHelper.MapPath(string.Format("{0}/PartialViewMacros/Templates/", SystemDirectories.Umbraco)); var files = Directory.GetFiles(snippetPath, "*.cshtml") .Select(Path.GetFileNameWithoutExtension) .Except(filterNames, StringComparer.InvariantCultureIgnoreCase) .ToArray(); //Ensure the ones that are called 'Empty' are at the top var empty = files.Where(x => Path.GetFileName(x).InvariantStartsWith("Empty")) .OrderBy(x => x.Length) .ToArray(); return empty.Union(files.Except(empty)); } public void DeletePartialViewFolder(string folderPath) { var uow = _fileUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreatePartialViewRepository(uow)) { ((PartialViewRepository)repository).DeleteFolder(folderPath); uow.Commit(); } } public void DeletePartialViewMacroFolder(string folderPath) { var uow = _fileUowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreatePartialViewMacroRepository(uow)) { ((PartialViewMacroRepository)repository).DeleteFolder(folderPath); uow.Commit(); } } public IPartialView GetPartialView(string path) { using (var repository = _repositoryFactory.CreatePartialViewRepository(_fileUowProvider.GetUnitOfWork())) { return repository.Get(path); } } public IPartialView GetPartialViewMacro(string path) { using (var repository = _repositoryFactory.CreatePartialViewMacroRepository(_fileUowProvider.GetUnitOfWork())) { return repository.Get(path); } } public Attempt<IPartialView> CreatePartialView(IPartialView partialView, string snippetName = null, int userId = 0) { return CreatePartialViewMacro(partialView, PartialViewType.PartialView, snippetName, userId); } public Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, string snippetName = null, int userId = 0) { return CreatePartialViewMacro(partialView, PartialViewType.PartialViewMacro, snippetName, userId); } private Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, PartialViewType partialViewType, string snippetName = null, int userId = 0) { if (CreatingPartialView.IsRaisedEventCancelled(new NewEventArgs<IPartialView>(partialView, true, partialView.Alias, -1), this)) return Attempt<IPartialView>.Fail(); var uow = _fileUowProvider.GetUnitOfWork(); string partialViewHeader = null; IPartialViewRepository repository; switch (partialViewType) { case PartialViewType.PartialView: repository = _repositoryFactory.CreatePartialViewRepository(uow); partialViewHeader = PartialViewHeader; break; case PartialViewType.PartialViewMacro: default: repository = _repositoryFactory.CreatePartialViewMacroRepository(uow); partialViewHeader = PartialViewMacroHeader; break; } if (snippetName.IsNullOrWhiteSpace() == false) { //create the file var snippetPathAttempt = TryGetSnippetPath(snippetName); if (snippetPathAttempt.Success == false) { throw new InvalidOperationException("Could not load snippet with name " + snippetName); } using (var snippetFile = new StreamReader(System.IO.File.OpenRead(snippetPathAttempt.Result))) { var snippetContent = snippetFile.ReadToEnd().Trim(); //strip the @inherits if it's there snippetContent = StripPartialViewHeader(snippetContent); var content = string.Format("{0}{1}{2}", partialViewHeader, Environment.NewLine, snippetContent); partialView.Content = content; } } using (repository) { repository.AddOrUpdate(partialView); uow.Commit(); CreatedPartialView.RaiseEvent(new NewEventArgs<IPartialView>(partialView, false, partialView.Alias, -1), this); } Audit.Add(AuditTypes.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1); return Attempt<IPartialView>.Succeed(partialView); } public bool DeletePartialView(string path, int userId = 0) { return DeletePartialViewMacro(path, PartialViewType.PartialView, userId); } public bool DeletePartialViewMacro(string path, int userId = 0) { return DeletePartialViewMacro(path, PartialViewType.PartialViewMacro, userId); } private bool DeletePartialViewMacro(string path, PartialViewType partialViewType, int userId = 0) { var uow = _fileUowProvider.GetUnitOfWork(); IPartialViewRepository repository; switch (partialViewType) { case PartialViewType.PartialView: repository = _repositoryFactory.CreatePartialViewRepository(uow); break; case PartialViewType.PartialViewMacro: default: repository = _repositoryFactory.CreatePartialViewMacroRepository(uow); break; } using (repository) { var partialView = repository.Get(path); if (partialView == null) return true; if (DeletingPartialView.IsRaisedEventCancelled(new DeleteEventArgs<IPartialView>(partialView), this)) return false; repository.Delete(partialView); uow.Commit(); DeletedPartialView.RaiseEvent(new DeleteEventArgs<IPartialView>(partialView, false), this); Audit.Add(AuditTypes.Delete, string.Format("Delete {0} performed by user", partialViewType), userId, -1); } return true; } public Attempt<IPartialView> SavePartialView(IPartialView partialView, int userId = 0) { return SavePartialView(partialView, PartialViewType.PartialView, userId); } public Attempt<IPartialView> SavePartialViewMacro(IPartialView partialView, int userId = 0) { return SavePartialView(partialView, PartialViewType.PartialViewMacro, userId); } private Attempt<IPartialView> SavePartialView(IPartialView partialView, PartialViewType partialViewType, int userId = 0) { if (SavingPartialView.IsRaisedEventCancelled(new SaveEventArgs<IPartialView>(partialView), this)) return Attempt<IPartialView>.Fail(); var uow = _fileUowProvider.GetUnitOfWork(); IPartialViewRepository repository; switch (partialViewType) { case PartialViewType.PartialView: repository = _repositoryFactory.CreatePartialViewRepository(uow); break; case PartialViewType.PartialViewMacro: default: repository = _repositoryFactory.CreatePartialViewMacroRepository(uow); break; } using (repository) { repository.AddOrUpdate(partialView); uow.Commit(); SavedPartialView.RaiseEvent(new SaveEventArgs<IPartialView>(partialView, false), this); } Audit.Add(AuditTypes.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1); SavedPartialView.RaiseEvent(new SaveEventArgs<IPartialView>(partialView), this); return Attempt.Succeed(partialView); } internal bool ValidatePartialView(PartialView partialView) { return partialView.IsValid(); } internal string StripPartialViewHeader(string contents) { var headerMatch = new Regex("^@inherits\\s+?.*$", RegexOptions.Multiline); return headerMatch.Replace(contents, string.Empty); } internal Attempt<string> TryGetSnippetPath(string fileName) { if (fileName.EndsWith(".cshtml") == false) { fileName += ".cshtml"; } var snippetPath = IOHelper.MapPath(string.Format("{0}/PartialViewMacros/Templates/{1}", SystemDirectories.Umbraco, fileName)); return System.IO.File.Exists(snippetPath) ? Attempt<string>.Succeed(snippetPath) : Attempt<string>.Fail(); } private enum PartialViewType { PartialView, PartialViewMacro } #endregion //TODO Method to change name and/or alias of view/masterpage template #region Event Handlers /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<ITemplate>> DeletingTemplate; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<ITemplate>> DeletedTemplate; /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<Script>> DeletingScript; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<Script>> DeletedScript; /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<Stylesheet>> DeletingStylesheet; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<Stylesheet>> DeletedStylesheet; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<ITemplate>> SavingTemplate; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<ITemplate>> SavedTemplate; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<Script>> SavingScript; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<Script>> SavedScript; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<Stylesheet>> SavingStylesheet; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<Stylesheet>> SavedStylesheet; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<IPartialView>> SavingPartialView; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<IPartialView>> SavedPartialView; /// <summary> /// Occurs before Create /// </summary> public static event TypedEventHandler<IFileService, NewEventArgs<IPartialView>> CreatingPartialView; /// <summary> /// Occurs after Create /// </summary> public static event TypedEventHandler<IFileService, NewEventArgs<IPartialView>> CreatedPartialView; /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<IPartialView>> DeletingPartialView; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<IPartialView>> DeletedPartialView; #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; using System.Collections.Generic; using System.Reflection; using System.Text; using System.IO; using System.Xml; using NUnit.Framework; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.UnitTests { [TestFixture] public class SolutionWrapperProject_Tests { /// <summary> /// Verify the SolutionParser.AddNewErrorWarningMessageElement method /// </summary> /// <owner>LukaszG</owner> [Test] public void AddNewErrorWarningMessageElement() { MockLogger logger = new MockLogger(); Project project = ObjectModelHelpers.CreateInMemoryProject( "<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>" + "<Target Name=`Build`>" + "</Target>" + "</Project>", logger); Target target = project.Targets["Build"]; SolutionWrapperProject.AddErrorWarningMessageElement(target, XMakeElements.message, true, "SolutionVenusProjectNoClean"); SolutionWrapperProject.AddErrorWarningMessageElement(target, XMakeElements.warning, true, "SolutionParseUnknownProjectType", "proj1.csproj"); SolutionWrapperProject.AddErrorWarningMessageElement(target, XMakeElements.error, true, "SolutionVCProjectNoPublish"); project.Build(null, null); string code = null; string keyword = null; string text = ResourceUtilities.FormatResourceString(out code, out keyword, "SolutionParseUnknownProjectType", "proj1.csproj"); // check the error event Assertion.AssertEquals(1, logger.Warnings.Count); BuildWarningEventArgs warning = logger.Warnings[0]; Assertion.AssertEquals(text, warning.Message); Assertion.AssertEquals(code, warning.Code); Assertion.AssertEquals(keyword, warning.HelpKeyword); code = null; keyword = null; text = ResourceUtilities.FormatResourceString(out code, out keyword, "SolutionVCProjectNoPublish"); // check the warning event Assertion.AssertEquals(1, logger.Errors.Count); BuildErrorEventArgs error = logger.Errors[0]; Assertion.AssertEquals(text, error.Message); Assertion.AssertEquals(code, error.Code); Assertion.AssertEquals(keyword, error.HelpKeyword); code = null; keyword = null; text = ResourceUtilities.FormatResourceString(out code, out keyword, "SolutionVenusProjectNoClean"); // check the message event Assertion.Assert("Log should contain the regular message", logger.FullLog.Contains(text)); } /// <summary> /// Test to make sure we properly set the ToolsVersion attribute on the in-memory project based /// on the Solution File Format Version. /// </summary> [Test] public void EmitToolsVersionAttributeToInMemoryProject9() { if (FrameworkLocationHelper.PathToDotNetFrameworkV35 != null) { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Any CPU = Release|Any CPU Release|Win32 = Release|Win32 Other|Any CPU = Other|Any CPU Other|Win32 = Other|Win32 EndGlobalSection EndGlobal "; SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); Project msbuildProject = new Project(); SolutionWrapperProject.Generate(solution, msbuildProject, "3.5", new BuildEventContext(0, 0, 0, 0)); Assertion.AssertEquals("3.5", msbuildProject.DefaultToolsVersion); } else { Assert.Ignore(".NET Framework 3.5 is required for this test, but is not installed."); } } /// <summary> /// Test to make sure we properly set the ToolsVersion attribute on the in-memory project based /// on the Solution File Format Version. /// </summary> [Test] public void EmitToolsVersionAttributeToInMemoryProject10() { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 10.00 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Any CPU = Release|Any CPU Release|Win32 = Release|Win32 Other|Any CPU = Other|Any CPU Other|Win32 = Other|Win32 EndGlobalSection EndGlobal "; SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); Project msbuildProject = new Project(); SolutionWrapperProject.Generate(solution, msbuildProject, "4.0", new BuildEventContext(0, 0, 0, 0)); Assertion.AssertEquals("4.0", msbuildProject.DefaultToolsVersion); } /// <summary> /// Test the SolutionWrapperProject.AddPropertyGroupForSolutionConfiguration method /// </summary> /// <owner>LukaszG</owner> [Test] public void TestAddPropertyGroupForSolutionConfiguration() { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}' EndProject Project('{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}') = 'MainApp', 'MainApp\MainApp.vcxproj', '{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}' EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Mixed Platforms = Debug|Mixed Platforms Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = CSConfig1|Any CPU {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.Build.0 = CSConfig1|Any CPU {6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.ActiveCfg = CSConfig2|Any CPU {A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.ActiveCfg = VCConfig1|Win32 {A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.Build.0 = VCConfig1|Win32 EndGlobalSection EndGlobal "; SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); Engine engine = new Engine(); Project msbuildProject = new Project(engine); foreach (ConfigurationInSolution solutionConfiguration in solution.SolutionConfigurations) { SolutionWrapperProject.AddPropertyGroupForSolutionConfiguration(msbuildProject, solution, solutionConfiguration); } // Both projects configurations should be present for solution configuration "Debug|Mixed Platforms" msbuildProject.GlobalProperties.SetProperty("Configuration", "Debug"); msbuildProject.GlobalProperties.SetProperty("Platform", "Mixed Platforms"); string solutionConfigurationContents = msbuildProject.GetEvaluatedProperty("CurrentSolutionConfigurationContents"); Assertion.Assert(solutionConfigurationContents.Contains("{6185CC21-BE89-448A-B3C0-D1C27112E595}")); Assertion.Assert(solutionConfigurationContents.Contains("CSConfig1|AnyCPU")); Assertion.Assert(solutionConfigurationContents.Contains("{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}")); Assertion.Assert(solutionConfigurationContents.Contains("VCConfig1|Win32")); // Only the C# project should be present for solution configuration "Release|Any CPU", since the VC project // is missing msbuildProject.GlobalProperties.SetProperty("Configuration", "Release"); msbuildProject.GlobalProperties.SetProperty("Platform", "Any CPU"); solutionConfigurationContents = msbuildProject.GetEvaluatedProperty("CurrentSolutionConfigurationContents"); Assertion.Assert(solutionConfigurationContents.Contains("{6185CC21-BE89-448A-B3C0-D1C27112E595}")); Assertion.Assert(solutionConfigurationContents.Contains("CSConfig2|AnyCPU")); Assertion.Assert(!solutionConfigurationContents.Contains("{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}")); } /// <summary> /// Test that the in memory project created from a solution file exposes an MSBuild property which, /// if set when building a solution, will be specified as the ToolsVersion on the MSBuild task when /// building the projects contained within the solution. /// </summary> [Test] public void ToolsVersionOverrideShouldBeSpecifiedOnMSBuildTaskInvocations() { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}' EndProject Project('{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}') = 'MainApp', 'MainApp\MainApp.vcxproj', '{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}' EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Mixed Platforms = Debug|Mixed Platforms Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = CSConfig1|Any CPU {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.Build.0 = CSConfig1|Any CPU {6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.ActiveCfg = CSConfig2|Any CPU {A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.ActiveCfg = VCConfig1|Win32 {A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.Build.0 = VCConfig1|Win32 EndGlobalSection EndGlobal "; // We're not passing in a /tv:xx switch, so the solution project will have tools version 3.5 Project project = new Project(); SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); BuildEventContext buildEventContext = new BuildEventContext(0, 0, 0, 0); SolutionWrapperProject.Generate(solution, project, "3.5", buildEventContext); foreach (Target target in project.Targets) { foreach (XmlNode childNode in target.TargetElement) { if (0 == String.Compare(childNode.Name, "MSBuild", StringComparison.OrdinalIgnoreCase)) { // we found an MSBuild task invocation, now let's verify that it has the correct // ToolsVersion parameter set XmlAttribute toolsVersionAttribute = childNode.Attributes["ToolsVersion"]; Assertion.Assert(0 == String.Compare( toolsVersionAttribute.Value, "$(ProjectToolsVersion)", StringComparison.OrdinalIgnoreCase) ); } } } } /// <summary> /// Test the SolutionWrapperProject.Generate method with an invalid toolset -- will default to v4.0. /// </summary> /// <owner>jerelf</owner> [Test] public void ToolsVersionOverrideThrowsOnInvalidToolsVersion() { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}' EndProject Project('{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}') = 'MainApp', 'MainApp\MainApp.vcxproj', '{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}' EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Mixed Platforms = Debug|Mixed Platforms Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = CSConfig1|Any CPU {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.Build.0 = CSConfig1|Any CPU {6185CC21-BE89-448A-B3C0-D1C27112E595}.Release|Any CPU.ActiveCfg = CSConfig2|Any CPU {A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.ActiveCfg = VCConfig1|Win32 {A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Debug|Mixed Platforms.Build.0 = VCConfig1|Win32 EndGlobalSection EndGlobal "; string oldUseNoCacheValue = Environment.GetEnvironmentVariable("MSBuildUseNoSolutionCache"); try { // We want to avoid using the solution cache -- it could lead to circumstances where detritus left // on the disk leads us down paths we didn't mean to go. Environment.SetEnvironmentVariable("MSBuildUseNoSolutionCache", "1"); // We're not passing in a /tv:xx switch, so the solution project will have tools version 3.5 Project project = new Project(); SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); BuildEventContext buildEventContext = new BuildEventContext(0, 0, 0, 0); SolutionWrapperProject.Generate(solution, project, "invalid", buildEventContext); Assertion.AssertEquals("4.0", project.DefaultToolsVersion); } finally { Environment.SetEnvironmentVariable("MSBuildUseNoSolutionCache", oldUseNoCacheValue); } } /// <summary> /// Test the SolutionWrapperProject.AddPropertyGroupForSolutionConfiguration method /// </summary> /// <owner>LukaszG</owner> [Test] public void TestDisambiguateProjectTargetName() { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'Build', 'Build\Build.csproj', '{21397922-C38F-4A0E-B950-77B3FBD51881}' EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {21397922-C38F-4A0E-B950-77B3FBD51881}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {21397922-C38F-4A0E-B950-77B3FBD51881}.Debug|Any CPU.Build.0 = Debug|Any CPU {21397922-C38F-4A0E-B950-77B3FBD51881}.Release|Any CPU.ActiveCfg = Release|Any CPU {21397922-C38F-4A0E-B950-77B3FBD51881}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal "; SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); Project msbuildProject = new Project(); SolutionWrapperProject.Generate(solution, msbuildProject, null, null); Assertion.AssertNotNull(msbuildProject.Targets["Build"]); Assertion.AssertNotNull(msbuildProject.Targets["Solution:Build"]); Assertion.AssertNotNull(msbuildProject.Targets["Solution:Build:Clean"]); Assertion.AssertNotNull(msbuildProject.Targets["Solution:Build:Rebuild"]); Assertion.AssertNotNull(msbuildProject.Targets["Solution:Build:Publish"]); Assertion.AssertEquals(null, msbuildProject.Targets["Build"].TargetElement.ChildNodes[0].Attributes["Targets"]); Assertion.AssertEquals("Clean", msbuildProject.Targets["Clean"].TargetElement.ChildNodes[0].Attributes["Targets"].Value); Assertion.AssertEquals("Rebuild", msbuildProject.Targets["Rebuild"].TargetElement.ChildNodes[0].Attributes["Targets"].Value); Assertion.AssertEquals("Publish", msbuildProject.Targets["Publish"].TargetElement.ChildNodes[0].Attributes["Targets"].Value); Assertion.AssertEquals("@(BuildLevel0)", msbuildProject.Targets["Build"].TargetElement.ChildNodes[0].Attributes["Projects"].Value); Assertion.AssertEquals("@(BuildLevel0)", msbuildProject.Targets["Clean"].TargetElement.ChildNodes[0].Attributes["Projects"].Value); Assertion.AssertEquals("@(BuildLevel0)", msbuildProject.Targets["Rebuild"].TargetElement.ChildNodes[0].Attributes["Projects"].Value); Assertion.AssertEquals("@(BuildLevel0)", msbuildProject.Targets["Publish"].TargetElement.ChildNodes[0].Attributes["Projects"].Value); // Here we check that the set of standard entry point targets in the solution project // matches those defined in ProjectInSolution.projectNamesToDisambiguate = { "Build", "Rebuild", "Clean", "Publish" }; int countOfStandardTargets = 0; foreach (Target t in msbuildProject.Targets) { if (!t.Name.Contains(":")) { countOfStandardTargets += 1; } } // NOTE: ValidateSolutionConfiguration and ValidateToolsVersions are always added, so we need to add two extras Assertion.AssertEquals(ProjectInSolution.projectNamesToDisambiguate.Length + 2, countOfStandardTargets); } /// <summary> /// Tests the algorithm for choosing default configuration/platform values for solutions /// </summary> /// <owner>LukaszG</owner> [Test] public void TestConfigurationPlatformDefaults1() { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|Mixed Platforms = Debug|Mixed Platforms Debug|Win32 = Debug|Win32 Release|Any CPU = Release|Any CPU Release|Mixed Platforms = Release|Mixed Platforms Release|Win32 = Release|Win32 EndGlobalSection EndGlobal "; SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); Project msbuildProject = new Project(); SolutionWrapperProject.Generate(solution, msbuildProject, null, null); // Default for Configuration is "Debug", if present Assertion.AssertEquals("Debug", msbuildProject.GetEvaluatedProperty("Configuration")); // Default for Platform is "Mixed Platforms", if present Assertion.AssertEquals("Mixed Platforms", msbuildProject.GetEvaluatedProperty("Platform")); } /// <summary> /// Tests the algorithm for choosing default configuration/platform values for solutions /// </summary> /// <owner>LukaszG</owner> [Test] public void TestConfigurationPlatformDefaults2() { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Any CPU = Release|Any CPU Release|Win32 = Release|Win32 Other|Any CPU = Other|Any CPU Other|Win32 = Other|Win32 EndGlobalSection EndGlobal "; SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); Project msbuildProject = new Project(); SolutionWrapperProject.Generate(solution, msbuildProject, null, null); // If "Debug" is not present, just pick the first configuration name Assertion.AssertEquals("Release", msbuildProject.GetEvaluatedProperty("Configuration")); // if "Mixed Platforms" is not present, just pick the first platform name Assertion.AssertEquals("Any CPU", msbuildProject.GetEvaluatedProperty("Platform")); } /// <summary> /// Tests the algorithm for choosing default Venus configuration values for solutions /// </summary> /// <owner>LukaszG</owner> [Test] public void TestVenusConfigurationDefaults() { Project msbuildProject = CreateVenusSolutionProject(); // ASP.NET configuration should match the selected solution configuration msbuildProject.GlobalProperties.SetProperty("Configuration", "Debug"); Assertion.AssertEquals("Debug", msbuildProject.GetEvaluatedProperty("AspNetConfiguration")); msbuildProject.GlobalProperties.SetProperty("Configuration", "Release"); Assertion.AssertEquals("Release", msbuildProject.GetEvaluatedProperty("AspNetConfiguration")); msbuildProject.GlobalProperties.SetProperty("Configuration", "Other"); Assertion.AssertEquals("Other", msbuildProject.GetEvaluatedProperty("AspNetConfiguration")); // Check that the two standard Asp.net configurations are represented on the targets Assertion.Assert(msbuildProject.Targets["C:\\solutions\\WebSite2\\"].Condition.Contains("'$(Configuration)' == 'Release'")); Assertion.Assert(msbuildProject.Targets["C:\\solutions\\WebSite2\\"].Condition.Contains("'$(Configuration)' == 'Debug'")); } [Test] public void DefaultTargetFrameworkVersion() { Project msbuildProject = CreateVenusSolutionProject(); // v3.5 by default Assertion.AssertEquals("v4.0", msbuildProject.EvaluatedProperties["TargetFrameworkVersion"].Value); // may be user defined msbuildProject.SetProperty("TargetFrameworkVersion", "userdefined"); Assertion.AssertEquals("userdefined", msbuildProject.EvaluatedProperties["TargetFrameworkVersion"].Value); // v2.0 if MSBuildToolsVersion is 2.0 msbuildProject.SetProperty("TargetFrameworkVersion", String.Empty); msbuildProject.ToolsVersion = "2.0"; Assertion.AssertEquals("v2.0", msbuildProject.EvaluatedProperties["TargetFrameworkVersion"].Value); } /// <summary> /// Tests the algorithm for choosing target framework paths for ResolveAssemblyReferences for Venus /// </summary> [Test] public void TestTargetFrameworkPaths0() { BuildPropertyGroup globalProperties = new BuildPropertyGroup(); globalProperties.SetProperty("TargetFrameworkVersion", "v2.0"); Project msbuildProject = CreateVenusSolutionProject(globalProperties, "4.0"); // ToolsVersion is 2.0, TargetFrameworkVersion is v2.0 --> one item pointing to v2.0 msbuildProject.ToolsVersion = "4.0"; bool success = msbuildProject.Build("GetFrameworkPathAndRedistList"); Assertion.AssertEquals(true, success); AssertProjectContainsItem(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", FrameworkLocationHelper.PathToDotNetFrameworkV20); AssertProjectItemNameCount(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", 1); } /// <summary> /// Tests the algorithm for choosing target framework paths for ResolveAssemblyReferences for Venus /// </summary> [Test] public void TestTargetFrameworkPaths1() { Project msbuildProject = CreateVenusSolutionProject(); // ToolsVersion is 3.5, TargetFrameworkVersion is v2.0 --> one item pointing to v2.0 msbuildProject.SetProperty("TargetFrameworkVersion", "v2.0"); bool success = msbuildProject.Build("GetFrameworkPathAndRedistList"); Assertion.AssertEquals(true, success); AssertProjectContainsItem(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", FrameworkLocationHelper.PathToDotNetFrameworkV20); AssertProjectItemNameCount(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", 1); } /// <summary> /// Tests the algorithm for choosing target framework paths for ResolveAssemblyReferences for Venus /// </summary> [Test] public void TestTargetFrameworkPaths2() { Project msbuildProject = CreateVenusSolutionProject(); // ToolsVersion is 3.5, TargetFrameworkVersion is v3.5 --> items for v2.0 and v3.5 msbuildProject.SetProperty("TargetFrameworkVersion", "v3.5"); bool success = msbuildProject.Build("GetFrameworkPathAndRedistList"); Assertion.AssertEquals(true, success); AssertProjectContainsItem(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", FrameworkLocationHelper.PathToDotNetFrameworkV20); if (FrameworkLocationHelper.PathToDotNetFrameworkV35 != null && FrameworkLocationHelper.PathToDotNetFrameworkV30 != null) { AssertProjectContainsItem(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", FrameworkLocationHelper.PathToDotNetFrameworkV35); AssertProjectContainsItem(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", FrameworkLocationHelper.PathToDotNetFrameworkV30); AssertProjectItemNameCount(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", 3); } else if (FrameworkLocationHelper.PathToDotNetFrameworkV30 != null) { AssertProjectContainsItem(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", FrameworkLocationHelper.PathToDotNetFrameworkV30); AssertProjectItemNameCount(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", 2); } else if (FrameworkLocationHelper.PathToDotNetFrameworkV35 != null) { AssertProjectContainsItem(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", FrameworkLocationHelper.PathToDotNetFrameworkV35); AssertProjectItemNameCount(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", 2); } else { AssertProjectItemNameCount(msbuildProject, "_CombinedTargetFrameworkDirectoriesItem", 1); } } private static Project CreateVenusSolutionProject() { return CreateVenusSolutionProject(null); } private static Project CreateVenusSolutionProject(BuildPropertyGroup globalProperties) { return CreateVenusSolutionProject(globalProperties, "4.0"); } private static Project CreateVenusSolutionProject(BuildPropertyGroup globalProperties, string toolsVersion) { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project('{E24C65DC-7377-472B-9ABA-BC803B73C61A}') = 'C:\solutions\WebSite2\', '..\..\solutions\WebSite2\', '{F90528C4-6989-4D33-AFE8-F53173597CC2}' ProjectSection(WebsiteProperties) = preProject Debug.AspNetCompiler.VirtualPath = '/WebSite2' Debug.AspNetCompiler.PhysicalPath = '..\..\solutions\WebSite2\' Debug.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite2\' Debug.AspNetCompiler.Updateable = 'true' Debug.AspNetCompiler.ForceOverwrite = 'true' Debug.AspNetCompiler.FixedNames = 'true' Debug.AspNetCompiler.Debug = 'True' Release.AspNetCompiler.VirtualPath = '/WebSite2' Release.AspNetCompiler.PhysicalPath = '..\..\solutions\WebSite2\' Release.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite2\' Release.AspNetCompiler.Updateable = 'true' Release.AspNetCompiler.ForceOverwrite = 'true' Release.AspNetCompiler.FixedNames = 'true' Release.AspNetCompiler.Debug = 'False' VWDPort = '2776' DefaultWebSiteLanguage = 'Visual C#' EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {F90528C4-6989-4D33-AFE8-F53173597CC2}.Debug|Any CPU.ActiveCfg = Debug|.NET {F90528C4-6989-4D33-AFE8-F53173597CC2}.Debug|Any CPU.Build.0 = Debug|.NET EndGlobalSection EndGlobal "; SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); Engine engine = new Engine(globalProperties); Project msbuildProject = new Project(engine); SolutionWrapperProject.Generate(solution, msbuildProject, toolsVersion, null); return msbuildProject; } private void AssertProjectContainsItem(Project msbuildProject, string itemName, string itemSpec) { BuildItemGroup itemGroup = (BuildItemGroup)msbuildProject.EvaluatedItemsByName[itemName]; Assertion.AssertNotNull(itemGroup); foreach(BuildItem item in itemGroup) { if (item.Name == itemName && item.EvaluatedItemSpec == itemSpec) { return; } } Assertion.Assert(false); } private void AssertProjectItemNameCount(Project msbuildProject, string itemName, int count) { BuildItemGroup itemGroup = (BuildItemGroup)msbuildProject.EvaluatedItemsByName[itemName]; Assertion.AssertNotNull(itemGroup); Assertion.AssertEquals(count, itemGroup.Count); } /// <summary> /// Test the PredictActiveSolutionConfigurationName method /// </summary> /// <owner>LukaszG</owner> [Test] public void TestPredictSolutionConfigurationName() { string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Release|Mixed Platforms = Release|Mixed Platforms Release|Win32 = Release|Win32 Debug|Mixed Platforms = Debug|Mixed Platforms Debug|Win32 = Debug|Win32 EndGlobalSection EndGlobal "; SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); Engine engine = new Engine(); Assertion.AssertEquals("Debug|Mixed Platforms", SolutionWrapperProject.PredictActiveSolutionConfigurationName(solution, engine)); engine.GlobalProperties.SetProperty("Configuration", "Release"); Assertion.AssertEquals("Release|Mixed Platforms", SolutionWrapperProject.PredictActiveSolutionConfigurationName(solution, engine)); engine.GlobalProperties.SetProperty("Platform", "Win32"); Assertion.AssertEquals("Release|Win32", SolutionWrapperProject.PredictActiveSolutionConfigurationName(solution, engine)); engine.GlobalProperties.SetProperty("Configuration", "Nonexistent"); Assertion.AssertEquals(null, SolutionWrapperProject.PredictActiveSolutionConfigurationName(solution, engine)); } /// <summary> /// We had a bug where turning on the environment variable MSBuildEmitSolution=1 caused /// a VerifyThrow to get fired in the engine, because the temp project that is saved /// to disk gets loaded into the engine when it shouldn't have. /// </summary> /// <owner>RGoel</owner> [Test] public void SolutionParserShouldNotIncreaseNumberOfProjectsLoadedByHost() { string oldValueForMSBuildEmitSolution = Environment.GetEnvironmentVariable("MSBuildEmitSolution"); Environment.SetEnvironmentVariable("MSBuildEmitSolution", "1"); string solutionFileContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project('{F184B08F-C81C-45F6-A57F-5ABD9991F28F}') = 'ConsoleApplication1', 'ConsoleApplication1\ConsoleApplication1.vbproj', '{AB3413A6-D689-486D-B7F0-A095371B3F13}' EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|AnyCPU = Debug|AnyCPU Release|AnyCPU = Release|AnyCPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {AB3413A6-D689-486D-B7F0-A095371B3F13}.Debug|AnyCPU.ActiveCfg = Debug|AnyCPU {AB3413A6-D689-486D-B7F0-A095371B3F13}.Debug|AnyCPU.Build.0 = Debug|AnyCPU {AB3413A6-D689-486D-B7F0-A095371B3F13}.Release|AnyCPU.ActiveCfg = Release|AnyCPU {AB3413A6-D689-486D-B7F0-A095371B3F13}.Release|AnyCPU.Build.0 = Release|AnyCPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal "; SolutionParser solution = SolutionParser_Tests.ParseSolutionHelper(solutionFileContents); Engine engine = new Engine(); Project project = new Project(engine, null); // This project considers itself loaded-by-host. Setting a file name on it, causes it to // ensure the engine believes it is loaded-by-host... project.FullFileName = "my project"; Assertion.AssertEquals(1, engine.ProjectsLoadedByHost.Count); // Create a bogus cache file in the same place -- just to exercise the solution wrapper code that creates a new project string solutionCacheFile = solution.SolutionFile + ".cache"; using (StreamWriter writer = new StreamWriter(solutionCacheFile)) { writer.WriteLine("xxx"); } SolutionWrapperProject.Generate(solution, project, null, null); Assertion.AssertEquals(1, engine.ProjectsLoadedByHost.Count); // Clean up. Delete temp files and reset environment variables. Assertion.Assert("Solution parser should have written in-memory project to disk", File.Exists(solution.SolutionFile + ".proj")); File.Delete(solution.SolutionFile + ".proj"); File.Delete(solutionCacheFile); Environment.SetEnvironmentVariable("MSBuildEmitSolution", oldValueForMSBuildEmitSolution); } /// <summary> /// Make sure that we output a warning and don't build anything when we're given an invalid /// solution configuration and SkipInvalidConfigurations is set to true. /// </summary> /// <owner>LukaszG</owner> [Test] public void TestSkipInvalidConfigurationsCase() { string tmpFileName = Path.GetTempFileName(); File.Delete(tmpFileName); string projectFilePath = tmpFileName + ".sln"; string solutionContents = @" Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project('{E24C65DC-7377-472B-9ABA-BC803B73C61A}') = 'C:\solutions\WebSite2\', '..\..\solutions\WebSite2\', '{F90528C4-6989-4D33-AFE8-F53173597CC2}' ProjectSection(WebsiteProperties) = preProject Debug.AspNetCompiler.VirtualPath = '/WebSite2' Debug.AspNetCompiler.PhysicalPath = '..\..\solutions\WebSite2\' Debug.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite2\' Debug.AspNetCompiler.Updateable = 'true' Debug.AspNetCompiler.ForceOverwrite = 'true' Debug.AspNetCompiler.FixedNames = 'true' Debug.AspNetCompiler.Debug = 'True' Release.AspNetCompiler.VirtualPath = '/WebSite2' Release.AspNetCompiler.PhysicalPath = '..\..\solutions\WebSite2\' Release.AspNetCompiler.TargetPath = 'PrecompiledWeb\WebSite2\' Release.AspNetCompiler.Updateable = 'true' Release.AspNetCompiler.ForceOverwrite = 'true' Release.AspNetCompiler.FixedNames = 'true' Release.AspNetCompiler.Debug = 'False' VWDPort = '2776' DefaultWebSiteLanguage = 'Visual C#' EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {F90528C4-6989-4D33-AFE8-F53173597CC2}.Debug|Any CPU.ActiveCfg = Debug|.NET {F90528C4-6989-4D33-AFE8-F53173597CC2}.Debug|Any CPU.Build.0 = Debug|.NET EndGlobalSection EndGlobal"; File.WriteAllText(projectFilePath, solutionContents.Replace('\'', '"')); try { MockLogger logger = new MockLogger(); Engine engine = new Engine(); engine.RegisterLogger(logger); Project solutionWrapperProject = new Project(engine); solutionWrapperProject.Load(projectFilePath); solutionWrapperProject.SetProperty("Configuration", "Nonexistent"); solutionWrapperProject.SetProperty("SkipInvalidConfigurations", "true"); solutionWrapperProject.ToolsVersion = "4.0"; // Build should complete successfully even with an invalid solution config if SkipInvalidConfigurations is true Assertion.AssertEquals(true, solutionWrapperProject.Build(null, null)); // We should get the invalid solution configuration warning Assertion.AssertEquals(1, logger.Warnings.Count); BuildWarningEventArgs warning = logger.Warnings[0]; // Don't look at warning.Code here -- it may be null if PseudoLoc has messed // with our resource strings. The code will still be in the log -- it just wouldn't get // pulled out into the code field. logger.AssertLogContains("MSB4126"); // No errors expected Assertion.AssertEquals(0, logger.Errors.Count); } finally { File.Delete(projectFilePath); } } /// <summary> /// Convert passed in solution file to an MSBuild project. This method is used by Sln2Proj /// </summary> /// <owner>vladf</owner> public bool ConvertSLN2Proj(string nameSolutionFile) { // Set the environment variable to cause the SolutionWrapperProject to emit the project to disk string oldValueForMSBuildEmitSolution = Environment.GetEnvironmentVariable("MSBuildEmitSolution"); Environment.SetEnvironmentVariable("MSBuildEmitSolution", "1"); if (nameSolutionFile == null || !File.Exists(nameSolutionFile)) { return false; } // Parse the solution SolutionParser solution = new SolutionParser(); solution.SolutionFile = nameSolutionFile; solution.ParseSolutionFile(); // Generate the in-memory MSBuild project and output it to disk Project project = new Project(); SolutionWrapperProject.Generate(solution, project, "4.0", null); //Reset the environment variable Environment.SetEnvironmentVariable("MSBuildEmitSolution", oldValueForMSBuildEmitSolution); return true; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.ExpressRoute; using Microsoft.WindowsAzure.Management.ExpressRoute.Models; namespace Microsoft.WindowsAzure.Management.ExpressRoute { /// <summary> /// The Express Route API provides programmatic access to the functionality /// needed by the customer to set up Dedicated Circuits and Dedicated /// Circuit Links. The Express Route Customer API is a REST API. All API /// operations are performed over SSL and mutually authenticated using /// X.509 v3 certificates. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for /// more information) /// </summary> public partial class ExpressRouteManagementClient : ServiceClient<ExpressRouteManagementClient>, IExpressRouteManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IAuthorizedDedicatedCircuitOperations _authorizedDedicatedCircuits; public virtual IAuthorizedDedicatedCircuitOperations AuthorizedDedicatedCircuits { get { return this._authorizedDedicatedCircuits; } } private IBorderGatewayProtocolPeeringOperations _borderGatewayProtocolPeerings; public virtual IBorderGatewayProtocolPeeringOperations BorderGatewayProtocolPeerings { get { return this._borderGatewayProtocolPeerings; } } private ICrossConnectionOperations _crossConnections; public virtual ICrossConnectionOperations CrossConnections { get { return this._crossConnections; } } private IDedicatedCircuitLinkAuthorizationMicrosoftIdOperations _dedicatedCircuitLinkAuthorizationMicrosoftIds; public virtual IDedicatedCircuitLinkAuthorizationMicrosoftIdOperations DedicatedCircuitLinkAuthorizationMicrosoftIds { get { return this._dedicatedCircuitLinkAuthorizationMicrosoftIds; } } private IDedicatedCircuitLinkAuthorizationOperations _dedicatedCircuitLinkAuthorizations; public virtual IDedicatedCircuitLinkAuthorizationOperations DedicatedCircuitLinkAuthorizations { get { return this._dedicatedCircuitLinkAuthorizations; } } private IDedicatedCircuitLinkOperations _dedicatedCircuitLinks; public virtual IDedicatedCircuitLinkOperations DedicatedCircuitLinks { get { return this._dedicatedCircuitLinks; } } private IDedicatedCircuitOperations _dedicatedCircuits; public virtual IDedicatedCircuitOperations DedicatedCircuits { get { return this._dedicatedCircuits; } } private IDedicatedCircuitServiceProviderOperations _dedicatedCircuitServiceProviders; public virtual IDedicatedCircuitServiceProviderOperations DedicatedCircuitServiceProviders { get { return this._dedicatedCircuitServiceProviders; } } /// <summary> /// Initializes a new instance of the ExpressRouteManagementClient /// class. /// </summary> public ExpressRouteManagementClient() : base() { this._authorizedDedicatedCircuits = new AuthorizedDedicatedCircuitOperations(this); this._borderGatewayProtocolPeerings = new BorderGatewayProtocolPeeringOperations(this); this._crossConnections = new CrossConnectionOperations(this); this._dedicatedCircuitLinkAuthorizationMicrosoftIds = new DedicatedCircuitLinkAuthorizationMicrosoftIdOperations(this); this._dedicatedCircuitLinkAuthorizations = new DedicatedCircuitLinkAuthorizationOperations(this); this._dedicatedCircuitLinks = new DedicatedCircuitLinkOperations(this); this._dedicatedCircuits = new DedicatedCircuitOperations(this); this._dedicatedCircuitServiceProviders = new DedicatedCircuitServiceProviderOperations(this); this._apiVersion = "2011-10-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ExpressRouteManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public ExpressRouteManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ExpressRouteManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public ExpressRouteManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ExpressRouteManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public ExpressRouteManagementClient(HttpClient httpClient) : base(httpClient) { this._authorizedDedicatedCircuits = new AuthorizedDedicatedCircuitOperations(this); this._borderGatewayProtocolPeerings = new BorderGatewayProtocolPeeringOperations(this); this._crossConnections = new CrossConnectionOperations(this); this._dedicatedCircuitLinkAuthorizationMicrosoftIds = new DedicatedCircuitLinkAuthorizationMicrosoftIdOperations(this); this._dedicatedCircuitLinkAuthorizations = new DedicatedCircuitLinkAuthorizationOperations(this); this._dedicatedCircuitLinks = new DedicatedCircuitLinkOperations(this); this._dedicatedCircuits = new DedicatedCircuitOperations(this); this._dedicatedCircuitServiceProviders = new DedicatedCircuitServiceProviderOperations(this); this._apiVersion = "2011-10-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ExpressRouteManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ExpressRouteManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ExpressRouteManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ExpressRouteManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// ExpressRouteManagementClient instance /// </summary> /// <param name='client'> /// Instance of ExpressRouteManagementClient to clone to /// </param> protected override void Clone(ServiceClient<ExpressRouteManagementClient> client) { base.Clone(client); if (client is ExpressRouteManagementClient) { ExpressRouteManagementClient clonedClient = ((ExpressRouteManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// Parse enum values for type BgpPeeringAccessType. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static BgpPeeringAccessType ParseBgpPeeringAccessType(string value) { if ("private".Equals(value, StringComparison.OrdinalIgnoreCase)) { return BgpPeeringAccessType.Private; } if ("public".Equals(value, StringComparison.OrdinalIgnoreCase)) { return BgpPeeringAccessType.Public; } if ("microsoft".Equals(value, StringComparison.OrdinalIgnoreCase)) { return BgpPeeringAccessType.Microsoft; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type BgpPeeringAccessType to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string BgpPeeringAccessTypeToString(BgpPeeringAccessType value) { if (value == BgpPeeringAccessType.Private) { return "private"; } if (value == BgpPeeringAccessType.Public) { return "public"; } if (value == BgpPeeringAccessType.Microsoft) { return "microsoft"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type UpdateCrossConnectionOperation. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static UpdateCrossConnectionOperation ParseUpdateCrossConnectionOperation(string value) { if ("NotifyCrossConnectionProvisioned".Equals(value, StringComparison.OrdinalIgnoreCase)) { return UpdateCrossConnectionOperation.NotifyCrossConnectionProvisioned; } if ("NotifyCrossConnectionNotProvisioned".Equals(value, StringComparison.OrdinalIgnoreCase)) { return UpdateCrossConnectionOperation.NotifyCrossConnectionNotProvisioned; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type UpdateCrossConnectionOperation to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string UpdateCrossConnectionOperationToString(UpdateCrossConnectionOperation value) { if (value == UpdateCrossConnectionOperation.NotifyCrossConnectionProvisioned) { return "NotifyCrossConnectionProvisioned"; } if (value == UpdateCrossConnectionOperation.NotifyCrossConnectionNotProvisioned) { return "NotifyCrossConnectionNotProvisioned"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// The Get Express Route operation status gets information on the /// status of Express Route operations in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx /// for more information) /// </summary> /// <param name='operationId'> /// Required. The id of the operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<ExpressRouteOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken) { // Validate if (operationId == null) { throw new ArgumentNullException("operationId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationId", operationId); TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId); } url = url + "/services/networking/operation/"; url = url + Uri.EscapeDataString(operationId); string baseUrl = this.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", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.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 ExpressRouteOperationStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationElement = responseDoc.Element(XName.Get("GatewayOperation", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationElement != null) { XElement idElement = gatewayOperationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = gatewayOperationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { ExpressRouteOperationStatus statusInstance = ((ExpressRouteOperationStatus)Enum.Parse(typeof(ExpressRouteOperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = gatewayOperationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement dataElement = gatewayOperationElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { string dataInstance = dataElement.Value; result.Data = dataInstance; } XElement errorElement = gatewayOperationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { ExpressRouteOperationStatusResponse.ErrorDetails errorInstance = new ExpressRouteOperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } } 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 Microsoft.Win32.SafeHandles; using System.Security; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.IO.Pipes { /// <summary> /// Named pipe client. Use this to open the client end of a named pipes created with /// NamedPipeServerStream. /// </summary> public sealed partial class NamedPipeClientStream : PipeStream { // Maximum interval in milliseconds between which cancellation is checked. // Used by ConnectInternal. 50ms is fairly responsive time but really long time for processor. private const int CancellationCheckInterval = 50; private readonly string _normalizedPipePath; private readonly TokenImpersonationLevel _impersonationLevel; private readonly PipeOptions _pipeOptions; private readonly HandleInheritability _inheritability; private readonly PipeDirection _direction; // Creates a named pipe client using default server (same machine, or "."), and PipeDirection.InOut public NamedPipeClientStream(string pipeName) : this(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None) { } public NamedPipeClientStream(string serverName, string pipeName) : this(serverName, pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None) { } public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction) : this(serverName, pipeName, direction, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None) { } public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction, PipeOptions options) : this(serverName, pipeName, direction, options, TokenImpersonationLevel.None, HandleInheritability.None) { } public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction, PipeOptions options, TokenImpersonationLevel impersonationLevel) : this(serverName, pipeName, direction, options, impersonationLevel, HandleInheritability.None) { } public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction, PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability) : base(direction, 0) { if (pipeName == null) { throw new ArgumentNullException(nameof(pipeName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName), SR.ArgumentNull_ServerName); } if (pipeName.Length == 0) { throw new ArgumentException(SR.Argument_NeedNonemptyPipeName); } if (serverName.Length == 0) { throw new ArgumentException(SR.Argument_EmptyServerName); } if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly)) != 0) { throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_OptionsInvalid); } if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation) { throw new ArgumentOutOfRangeException(nameof(impersonationLevel), SR.ArgumentOutOfRange_ImpersonationInvalid); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException(nameof(inheritability), SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable); } if ((options & PipeOptions.CurrentUserOnly) != 0) { IsCurrentUserOnly = true; } _normalizedPipePath = GetPipePath(serverName, pipeName); _direction = direction; _inheritability = inheritability; _impersonationLevel = impersonationLevel; _pipeOptions = options; } // Create a NamedPipeClientStream from an existing server pipe handle. public NamedPipeClientStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle) : base(direction, 0) { if (safePipeHandle == null) { throw new ArgumentNullException(nameof(safePipeHandle)); } if (safePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, nameof(safePipeHandle)); } ValidateHandleIsPipe(safePipeHandle); InitializeHandle(safePipeHandle, true, isAsync); if (isConnected) { State = PipeState.Connected; } } ~NamedPipeClientStream() { Dispose(false); } public void Connect() { Connect(Timeout.Infinite); } public void Connect(int timeout) { CheckConnectOperationsClient(); if (timeout < 0 && timeout != Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_InvalidTimeout); } ConnectInternal(timeout, CancellationToken.None, Environment.TickCount); } private void ConnectInternal(int timeout, CancellationToken cancellationToken, int startTime) { // This is the main connection loop. It will loop until the timeout expires. int elapsed = 0; var sw = new SpinWait(); do { cancellationToken.ThrowIfCancellationRequested(); // Determine how long we should wait in this connection attempt int waitTime = timeout - elapsed; if (cancellationToken.CanBeCanceled && waitTime > CancellationCheckInterval) { waitTime = CancellationCheckInterval; } // Try to connect. if (TryConnect(waitTime, cancellationToken)) { return; } // Some platforms may return immediately from TryConnect if the connection could not be made, // e.g. WaitNamedPipe on Win32 will return immediately if the pipe hasn't yet been created, // and open on Unix will fail if the file isn't yet available. Rather than just immediately // looping around again, do slightly smarter busy waiting. sw.SpinOnce(); } while (timeout == Timeout.Infinite || (elapsed = unchecked(Environment.TickCount - startTime)) < timeout); throw new TimeoutException(); } public Task ConnectAsync() { // We cannot avoid creating lambda here by using Connect method // unless we don't care about start time to be measured before the thread is started return ConnectAsync(Timeout.Infinite, CancellationToken.None); } public Task ConnectAsync(int timeout) { return ConnectAsync(timeout, CancellationToken.None); } public Task ConnectAsync(CancellationToken cancellationToken) { return ConnectAsync(Timeout.Infinite, cancellationToken); } public Task ConnectAsync(int timeout, CancellationToken cancellationToken) { CheckConnectOperationsClient(); if (timeout < 0 && timeout != Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_InvalidTimeout); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } int startTime = Environment.TickCount; // We need to measure time here, not in the lambda return Task.Run(() => ConnectInternal(timeout, cancellationToken, startTime), cancellationToken); } // override because named pipe clients can't get/set properties when waiting to connect // or broken protected internal override void CheckPipePropertyOperations() { base.CheckPipePropertyOperations(); if (State == PipeState.WaitingToConnect) { throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected); } if (State == PipeState.Broken) { throw new IOException(SR.IO_PipeBroken); } } // named client is allowed to connect from broken private void CheckConnectOperationsClient() { if (State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } if (State == PipeState.Closed) { throw Error.GetPipeNotOpen(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Readonlyproperty operations. /// </summary> public partial class Readonlyproperty : IServiceOperations<AutoRestComplexTestService>, IReadonlyproperty { /// <summary> /// Initializes a new instance of the Readonlyproperty class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Readonlyproperty(AutoRestComplexTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex types that have readonly properties /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<ReadonlyObj>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<ReadonlyObj>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ReadonlyObj>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types that have readonly properties /// </summary> /// <param name='size'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(int? size = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { ReadonlyObj complexBody = new ReadonlyObj(); if (size != null) { complexBody.Size = size; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System.Text; using NDatabase.Api; using NDatabase.Tool.Wrappers; namespace NDatabase.Meta { /// <summary> /// Some basic info about an object info like position, its class info,... /// </summary> internal sealed class ObjectInfoHeader { private int[] _attributeIds; /// <summary> /// Can be position(for native object) or id(for non native object, positions are positive e ids are negative /// </summary> private long[] _attributesIdentification; private OID _classInfoId; private long _creationDate; private OID _nextObjectOID; private int _objectVersion; private OID _oid; private long _position; private OID _previousObjectOID; private long _updateDate; public ObjectInfoHeader(long position, OID previousObjectOID, OID nextObjectOID, OID classInfoId, long[] attributesIdentification, int[] attributeIds) { _position = position; _oid = null; _previousObjectOID = previousObjectOID; _nextObjectOID = nextObjectOID; _classInfoId = classInfoId; _attributesIdentification = attributesIdentification; _attributeIds = attributeIds; _objectVersion = 1; _creationDate = OdbTime.GetCurrentTimeInTicks(); } public ObjectInfoHeader() { _position = -1; _oid = null; _objectVersion = 1; _creationDate = OdbTime.GetCurrentTimeInTicks(); } public OID GetNextObjectOID() { return _nextObjectOID; } public void SetNextObjectOID(OID nextObjectOID) { _nextObjectOID = nextObjectOID; } public long GetPosition() { return _position; } public void SetPosition(long position) { _position = position; } public OID GetPreviousObjectOID() { return _previousObjectOID; } public void SetPreviousObjectOID(OID previousObjectOID) { _previousObjectOID = previousObjectOID; } public OID GetClassInfoId() { return _classInfoId; } public override string ToString() { var buffer = new StringBuilder(); buffer.Append("oid=").Append(_oid); buffer.Append(" - class info id=").Append(_classInfoId); buffer.Append(" - position=").Append(_position).Append(" | prev=").Append(_previousObjectOID); buffer.Append(" | next=").Append(_nextObjectOID); buffer.Append(" attrs =["); if (_attributesIdentification != null) { foreach (var value in _attributesIdentification) buffer.Append(value).Append(" "); } else { buffer.Append(" nulls "); } buffer.Append(" ]"); return buffer.ToString(); } public long[] GetAttributesIdentification() { return _attributesIdentification; } public void SetAttributesIdentification(long[] attributesIdentification) { _attributesIdentification = attributesIdentification; } public OID GetOid() { return _oid; } public void SetOid(OID oid) { _oid = oid; } public long GetCreationDate() { return _creationDate; } public void SetCreationDate(long creationDate) { _creationDate = creationDate; } public long GetUpdateDate() { return _updateDate; } public void SetUpdateDate(long updateDate) { _updateDate = updateDate; } /// <summary> /// Return the attribute identification (position or id) from the attribute id FIXME Remove dependency from StorageEngineConstant /// </summary> /// <param name="attributeId"> </param> /// <returns> -1 if attribute with this id does not exist </returns> public long GetAttributeIdentificationFromId(int attributeId) { if (_attributeIds == null) return StorageEngineConstant.NullObjectIdId; for (var i = 0; i < _attributeIds.Length; i++) { if (_attributeIds[i] == attributeId) return _attributesIdentification[i]; } return StorageEngineConstant.NullObjectIdId; } public void SetAttributesIds(int[] ids) { _attributeIds = ids; } public int[] GetAttributeIds() { return _attributeIds; } public void SetClassInfoId(OID classInfoId2) { _classInfoId = classInfoId2; } public int GetObjectVersion() { return _objectVersion; } public void SetObjectVersion(int objectVersion) { _objectVersion = objectVersion; } public long RefCounter { get; set; } public bool IsRoot { get; set; } public override int GetHashCode() { var result = 1; result = 31 * result + (int) (_position ^ ((_position) >> (32 & 0x1f))); return result; } public override bool Equals(object obj) { if (this == obj) return true; if (obj == null) return false; if (GetType() != obj.GetType()) return false; var other = (ObjectInfoHeader) obj; return _position == other._position; } public void IncrementVersionAndUpdateDate() { _objectVersion++; _updateDate = OdbTime.GetCurrentTimeInTicks(); } } }
using System.Diagnostics; namespace CocosSharp { /// <summary> /// This is a special sprite container that represents a 9 point sprite region, where 8 of hte /// points are along the perimeter, and the 9th is the center area. This special sprite is capable of resizing /// itself to arbitrary scales. /// </summary> public class CCScale9Sprite : CCNode { #region Enums private enum Positions { Centre = 0, Top, Left, Right, Bottom, TopRight, TopLeft, BottomRight, BottomLeft }; #endregion Enums bool positionsAreDirty; bool opacityModifyRGB; bool spriteFrameRotated; bool spritesGenerated; float insetBottom; float insetLeft; float insetRight; float insetTop; /** * The end-cap insets. * On a non-resizeable sprite, this property is set to CGRectZero; the sprite * does not use end caps and the entire sprite is subject to stretching. */ CCRect capInsets; CCRect capInsetsInternal; CCRect spriteRect; CCSize originalSize; CCSize preferredSize; CCSpriteBatchNode scale9Image; CCSprite top; CCSprite topLeft; CCSprite topRight; CCSprite bottom; CCSprite bottomLeft; CCSprite bottomRight; CCSprite centre; CCSprite left; CCSprite right; #region Properties public override CCSize ContentSize { get { return base.ContentSize; } set { base.ContentSize = value; positionsAreDirty = true; } } public CCSize PreferredSize { get { return preferredSize; } set { ContentSize = value; preferredSize = value; } } public CCRect CapInsets { get { return capInsets; } set { CCSize contentSize = ContentSize; UpdateWithBatchNode(scale9Image, spriteRect, spriteFrameRotated, value); ContentSize = contentSize; } } public float InsetLeft { set { insetLeft = value; UpdateCapInset(); } get { return insetLeft; } } public float InsetTop { set { insetTop = value; UpdateCapInset(); } get { return insetTop; } } public float InsetRight { set { insetRight = value; UpdateCapInset(); } get { return insetRight; } } public float InsetBottom { set { insetBottom = value; UpdateCapInset(); } get { return insetBottom; } } public override CCColor3B Color { get { return RealColor; } set { base.Color = value; if (scale9Image != null && scale9Image.Children != null) { foreach(CCNode child in Children) { var node = child; if (node != null) { node.Color = value; } } } } } public override byte Opacity { get { return RealOpacity; } set { base.Opacity = value; if (scale9Image != null && scale9Image.Children != null) { foreach(CCNode child in Children) { var node = child; if (node != null) { node.Opacity = value; } } } } } public override bool IsColorModifiedByOpacity { get { return opacityModifyRGB; } set { opacityModifyRGB = value; if (scale9Image != null && scale9Image.Children != null) { foreach(CCNode child in Children) { var node = child; if (node != null) { node.IsColorModifiedByOpacity = value; } } } } } public CCSpriteFrame SpriteFrame { set { CCSpriteBatchNode batchnode = new CCSpriteBatchNode (value.Texture, 9); UpdateWithBatchNode (batchnode, value.TextureRectInPixels, value.IsRotated, CCRect.Zero); // Reset insets insetLeft = 0; insetTop = 0; insetRight = 0; insetBottom = 0; } } #endregion Properties #region Constructors public CCScale9Sprite(CCSpriteBatchNode batchnode, CCRect rect, bool rotated, CCRect capInsets) { InitCCScale9Sprite(batchnode, rect, rotated, capInsets); } public CCScale9Sprite(CCSpriteBatchNode batchnode, CCRect rect, CCRect capInsets) : this(batchnode, rect, false, capInsets) { } public CCScale9Sprite() : this((CCSpriteBatchNode)null, CCRect.Zero, CCRect.Zero) { } public CCScale9Sprite(CCRect capInsets) : this((CCSpriteBatchNode)null, CCRect.Zero, capInsets) { } // File public CCScale9Sprite(string file, CCRect rect, CCRect capInsets) : this(new CCSpriteBatchNode(file, 9), rect, capInsets) { } public CCScale9Sprite(string file, CCRect rect) : this(file, rect, CCRect.Zero) { } public CCScale9Sprite(string file) : this(file, CCRect.Zero) { } // Sprite frame public CCScale9Sprite(CCSpriteFrame spriteFrame, CCRect capInsets) : this(new CCSpriteBatchNode(spriteFrame.Texture, 9), spriteFrame.TextureRectInPixels, spriteFrame.IsRotated, capInsets) { } public CCScale9Sprite(CCSpriteFrame spriteFrame) : this(spriteFrame, CCRect.Zero) { } // Sprite frame name // A constructor with argument string already exists (filename), so create this factory method instead public static CCScale9Sprite SpriteWithFrameName(string spriteFrameName, CCRect capInsets) { CCScale9Sprite sprite = new CCScale9Sprite(); sprite.InitWithSpriteFrameName(spriteFrameName, capInsets); return sprite; } public static CCScale9Sprite SpriteWithFrameName(string spriteFrameName) { return CCScale9Sprite.SpriteWithFrameName(spriteFrameName, CCRect.Zero); } void InitCCScale9Sprite(CCSpriteBatchNode batchnode, CCRect rect, bool rotated, CCRect capInsets) { if (batchnode != null) { UpdateWithBatchNode(batchnode, rect, rotated, capInsets); } AnchorPoint = new CCPoint(0.5f, 0.5f); positionsAreDirty = true; } // Init calls that are called externally for objects that are already instantiated internal void InitWithSpriteFrame(CCSpriteFrame spriteFrame) { InitCCScale9Sprite(new CCSpriteBatchNode(spriteFrame.Texture, 9), spriteFrame.TextureRectInPixels, spriteFrame.IsRotated, CCRect.Zero); } internal void InitWithSpriteFrameName(string spriteFrameName) { InitWithSpriteFrameName(spriteFrameName, CCRect.Zero); } internal void InitWithSpriteFrameName(string spriteFrameName, CCRect capInsets) { CCSpriteFrame spriteFrame = CCSpriteFrameCache.SharedSpriteFrameCache[spriteFrameName]; InitCCScale9Sprite(new CCSpriteBatchNode(spriteFrame.Texture, 9), spriteFrame.TextureRectInPixels, spriteFrame.IsRotated, capInsets); } #endregion Constructors public override void Visit() { if (positionsAreDirty) { UpdatePositions(); positionsAreDirty = false; } base.Visit(); } public override void UpdateDisplayedColor(CCColor3B parentColor) { base.UpdateDisplayedColor(parentColor); if (scale9Image != null && scale9Image.Children != null) { foreach(CCNode child in Children) { var node = child; if (node != null) { node.UpdateDisplayedColor(parentColor); } } } } public bool UpdateWithBatchNode(CCSpriteBatchNode batchnode, CCRect rect, bool rotated, CCRect capInsets) { var opacity = Opacity; var color = Color; // Release old sprites RemoveAllChildren(true); scale9Image = batchnode; scale9Image.RemoveAllChildren(true); this.capInsets = capInsets; spriteFrameRotated = rotated; // If there is no given rect if (rect.Equals(CCRect.Zero)) { // Get the texture size as original CCSize textureSize = scale9Image.TextureAtlas.Texture.ContentSizeInPixels; rect = new CCRect(0, 0, textureSize.Width, textureSize.Height); } // Set the given rect's size as original size spriteRect = rect; originalSize = rect.Size; preferredSize = originalSize; capInsetsInternal = capInsets; float h = rect.Size.Height; float w = rect.Size.Width; // If there is no specified center region if (capInsetsInternal.Equals(CCRect.Zero)) { capInsetsInternal = new CCRect(w / 3, h / 3, w / 3, h / 3); } float left_w = capInsetsInternal.Origin.X; float center_w = capInsetsInternal.Size.Width; float right_w = rect.Size.Width - (left_w + center_w); float top_h = capInsetsInternal.Origin.Y; float center_h = capInsetsInternal.Size.Height; float bottom_h = rect.Size.Height - (top_h + center_h); // calculate rects // ... top row float x = 0.0f; float y = 0.0f; // top left CCRect lefttopbounds = new CCRect(x, y, left_w, top_h); // top center x += left_w; CCRect centertopbounds = new CCRect(x, y, center_w, top_h); // top right x += center_w; CCRect righttopbounds = new CCRect(x, y, right_w, top_h); // ... center row x = 0.0f; y = 0.0f; y += top_h; // center left CCRect leftcenterbounds = new CCRect(x, y, left_w, center_h); // center center x += left_w; CCRect centerbounds = new CCRect(x, y, center_w, center_h); // center right x += center_w; CCRect rightcenterbounds = new CCRect(x, y, right_w, center_h); // ... bottom row x = 0.0f; y = 0.0f; y += top_h; y += center_h; // bottom left CCRect leftbottombounds = new CCRect(x, y, left_w, bottom_h); // bottom center x += left_w; CCRect centerbottombounds = new CCRect(x, y, center_w, bottom_h); // bottom right x += center_w; CCRect rightbottombounds = new CCRect(x, y, right_w, bottom_h); if (!rotated) { CCAffineTransform t = CCAffineTransform.Identity; t = CCAffineTransform.Translate(t, rect.Origin.X, rect.Origin.Y); centerbounds = CCAffineTransform.Transform(centerbounds, t); rightbottombounds = CCAffineTransform.Transform(rightbottombounds, t); leftbottombounds = CCAffineTransform.Transform(leftbottombounds, t); righttopbounds = CCAffineTransform.Transform(righttopbounds, t); lefttopbounds = CCAffineTransform.Transform(lefttopbounds, t); rightcenterbounds = CCAffineTransform.Transform(rightcenterbounds, t); leftcenterbounds = CCAffineTransform.Transform(leftcenterbounds, t); centerbottombounds = CCAffineTransform.Transform(centerbottombounds, t); centertopbounds = CCAffineTransform.Transform(centertopbounds, t); // Centre centre = new CCSprite(scale9Image.Texture, centerbounds); scale9Image.AddChild(centre, 0, (int)Positions.Centre); // Top top = new CCSprite(scale9Image.Texture, centerbounds); scale9Image.AddChild(top, 1, (int)Positions.Top); // Bottom bottom = new CCSprite(scale9Image.Texture, centerbottombounds); scale9Image.AddChild(bottom, 1, (int)Positions.Bottom); // Left left = new CCSprite(scale9Image.Texture, leftcenterbounds); scale9Image.AddChild(left, 1, (int)Positions.Left); // Right right = new CCSprite(scale9Image.Texture, rightcenterbounds); scale9Image.AddChild(right, 1, (int)Positions.Right); // Top left topLeft = new CCSprite(scale9Image.Texture, lefttopbounds); scale9Image.AddChild(topLeft, 2, (int)Positions.TopLeft); // Top right topRight = new CCSprite(scale9Image.Texture, righttopbounds); scale9Image.AddChild(topRight, 2, (int)Positions.TopRight); // Bottom left bottomLeft = new CCSprite(scale9Image.Texture, leftbottombounds); scale9Image.AddChild(bottomLeft, 2, (int)Positions.BottomLeft); // Bottom right bottomRight = new CCSprite(scale9Image.Texture, rightbottombounds); scale9Image.AddChild(bottomRight, 2, (int)Positions.BottomRight); } else { // set up transformation of coordinates // to handle the case where the sprite is stored rotated // in the spritesheet // CCLog("rotated"); CCAffineTransform t = CCAffineTransform.Identity; CCRect rotatedcenterbounds = centerbounds; CCRect rotatedrightbottombounds = rightbottombounds; CCRect rotatedleftbottombounds = leftbottombounds; CCRect rotatedrighttopbounds = righttopbounds; CCRect rotatedlefttopbounds = lefttopbounds; CCRect rotatedrightcenterbounds = rightcenterbounds; CCRect rotatedleftcenterbounds = leftcenterbounds; CCRect rotatedcenterbottombounds = centerbottombounds; CCRect rotatedcentertopbounds = centertopbounds; t = CCAffineTransform.Translate(t, rect.Size.Height + rect.Origin.X, rect.Origin.Y); t = CCAffineTransform.Rotate(t, 1.57079633f); centerbounds = CCAffineTransform.Transform(centerbounds, t); rightbottombounds = CCAffineTransform.Transform(rightbottombounds, t); leftbottombounds = CCAffineTransform.Transform(leftbottombounds, t); righttopbounds = CCAffineTransform.Transform(righttopbounds, t); lefttopbounds = CCAffineTransform.Transform(lefttopbounds, t); rightcenterbounds = CCAffineTransform.Transform(rightcenterbounds, t); leftcenterbounds = CCAffineTransform.Transform(leftcenterbounds, t); centerbottombounds = CCAffineTransform.Transform(centerbottombounds, t); centertopbounds = CCAffineTransform.Transform(centertopbounds, t); rotatedcenterbounds.Origin = centerbounds.Origin; rotatedrightbottombounds.Origin = rightbottombounds.Origin; rotatedleftbottombounds.Origin = leftbottombounds.Origin; rotatedrighttopbounds.Origin = righttopbounds.Origin; rotatedlefttopbounds.Origin = lefttopbounds.Origin; rotatedrightcenterbounds.Origin = rightcenterbounds.Origin; rotatedleftcenterbounds.Origin = leftcenterbounds.Origin; rotatedcenterbottombounds.Origin = centerbottombounds.Origin; rotatedcentertopbounds.Origin = centertopbounds.Origin; // Centre centre = new CCSprite(scale9Image.Texture, rotatedcenterbounds, true); //centre.InitWithTexture(scale9Image.Texture, rotatedcenterbounds, true); scale9Image.AddChild(centre, 0, (int)Positions.Centre); // Top top = new CCSprite(scale9Image.Texture, rotatedcentertopbounds, true); //top.InitWithTexture(scale9Image.Texture, rotatedcentertopbounds, true); scale9Image.AddChild(top, 1, (int)Positions.Top); // Bottom bottom = new CCSprite(scale9Image.Texture, rotatedcenterbottombounds, true); //bottom.InitWithTexture(scale9Image.Texture, rotatedcenterbottombounds, true); scale9Image.AddChild(bottom, 1, (int)Positions.Bottom); // Left left = new CCSprite(scale9Image.Texture, rotatedleftcenterbounds, true); //left.InitWithTexture(scale9Image.Texture, rotatedleftcenterbounds, true); scale9Image.AddChild(left, 1, (int)Positions.Left); // Right right = new CCSprite(scale9Image.Texture, rotatedrightcenterbounds, true); //right.InitWithTexture(scale9Image.Texture, rotatedrightcenterbounds, true); scale9Image.AddChild(right, 1, (int)Positions.Right); // Top left topLeft = new CCSprite(scale9Image.Texture, rotatedlefttopbounds, true); //topLeft.InitWithTexture(scale9Image.Texture, rotatedlefttopbounds, true); scale9Image.AddChild(topLeft, 2, (int)Positions.TopLeft); // Top right topRight = new CCSprite(scale9Image.Texture, rotatedrighttopbounds, true); //topRight.InitWithTexture(scale9Image.Texture, rotatedrighttopbounds, true); scale9Image.AddChild(topRight, 2, (int)Positions.TopRight); // Bottom left bottomLeft = new CCSprite(scale9Image.Texture, rotatedleftbottombounds, true); //bottomLeft.InitWithTexture(scale9Image.Texture, rotatedleftbottombounds, true); scale9Image.AddChild(bottomLeft, 2, (int)Positions.BottomLeft); // Bottom right bottomRight = new CCSprite(scale9Image.Texture, rotatedrightbottombounds, true); //bottomRight.InitWithTexture(scale9Image.Texture, rotatedrightbottombounds, true); scale9Image.AddChild(bottomRight, 2, (int)Positions.BottomRight); } ContentSize = rect.Size; AddChild(scale9Image); if (spritesGenerated) { // Restore color and opacity Opacity = opacity; Color = color; } spritesGenerated = true; return true; } protected void UpdatePositions() { // Check that instances are non-NULL if (!((topLeft != null) && (topRight != null) && (bottomRight != null) && (bottomLeft != null) && (centre != null))) { // if any of the above sprites are NULL, return return; } CCSize size = ContentSize; float sizableWidth = size.Width - topLeft.ContentSize.Width - topRight.ContentSize.Width; float sizableHeight = size.Height - topLeft.ContentSize.Height - bottomRight.ContentSize.Height; float horizontalScale = sizableWidth / centre.ContentSize.Width; float verticalScale = sizableHeight / centre.ContentSize.Height; centre.ScaleX = horizontalScale; centre.ScaleY = verticalScale; float rescaledWidth = centre.ContentSize.Width * horizontalScale; float rescaledHeight = centre.ContentSize.Height * verticalScale; float leftWidth = bottomLeft.ContentSize.Width; float bottomHeight = bottomLeft.ContentSize.Height; bottomLeft.AnchorPoint = CCPoint.Zero; bottomRight.AnchorPoint = CCPoint.Zero; topLeft.AnchorPoint = CCPoint.Zero; topRight.AnchorPoint = CCPoint.Zero; left.AnchorPoint = CCPoint.Zero; right.AnchorPoint = CCPoint.Zero; top.AnchorPoint = CCPoint.Zero; bottom.AnchorPoint = CCPoint.Zero; centre.AnchorPoint = CCPoint.Zero; // Position corners bottomLeft.Position = CCPoint.Zero; bottomRight.Position = new CCPoint(leftWidth + rescaledWidth, 0); topLeft.Position = new CCPoint(0, bottomHeight + rescaledHeight); topRight.Position = new CCPoint(leftWidth + rescaledWidth, bottomHeight + rescaledHeight); // Scale and position borders left.Position = new CCPoint(0, bottomHeight); left.ScaleY = verticalScale; right.Position = new CCPoint(leftWidth + rescaledWidth, bottomHeight); right.ScaleY = verticalScale; bottom.Position = new CCPoint(leftWidth, 0); bottom.ScaleX = horizontalScale; top.Position = new CCPoint(leftWidth, bottomHeight + rescaledHeight); top.ScaleX = horizontalScale; // Position centre centre.Position = new CCPoint(leftWidth, bottomHeight); } protected void UpdateCapInset() { CCRect insets; if (insetLeft == 0 && insetTop == 0 && insetRight == 0 && insetBottom == 0) { insets = CCRect.Zero; } else { insets = new CCRect(insetLeft, insetTop, spriteRect.Size.Width - insetLeft - insetRight, spriteRect.Size.Height - insetTop - insetBottom); } CapInsets = insets; } } }
// 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; using System.Text; namespace System.IO { // Provides methods for processing file system strings in a cross-platform manner. // Most of the methods don't do a complete parsing (such as examining a UNC hostname), // but they will handle most string operations. public static partial class Path { // Platform specific alternate directory separator character. // There is only one directory separator char on Unix, which is the same // as the alternate separator on Windows, so same definition is used for both. public static readonly char AltDirectorySeparatorChar = '/'; // Changes the extension of a file path. The path parameter // specifies a file path, and the extension parameter // specifies a file extension (with a leading period, such as // ".exe" or ".cs"). // // The function returns a file path with the same root, directory, and base // name parts as path, but with the file extension changed to // the specified extension. If path is null, the function // returns null. If path does not contain a file extension, // the new file extension is appended to the path. If extension // is null, any existing extension is removed from path. public static string ChangeExtension(string path, string extension) { if (path != null) { PathInternal.CheckInvalidPathChars(path); string s = path; for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { s = path.Substring(0, i); break; } if (IsDirectoryOrVolumeSeparator(ch)) break; } if (extension != null && path.Length != 0) { s = (extension.Length == 0 || extension[0] != '.') ? s + "." + extension : s + extension; } return s; } return null; } // Returns the directory path of a file path. This method effectively // removes the last element of the given file path, i.e. it returns a // string consisting of all characters up to but not including the last // backslash ("\") in the file path. The returned value is null if the file // path is null or if the file path denotes a root (such as "\", "C:", or // "\\server\share"). public static string GetDirectoryName(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); path = PathInternal.NormalizeDirectorySeparators(path); int root = PathInternal.GetRootLength(path); int i = path.Length; if (i > root) { while (i > root && !PathInternal.IsDirectorySeparator(path[--i])) ; return path.Substring(0, i); } } return null; } public static char[] GetInvalidPathChars() { return (char[])PathInternal.InvalidPathChars.Clone(); } public static char[] GetInvalidFileNameChars() { return (char[])InvalidFileNameChars.Clone(); } // Returns the extension of the given path. The returned value includes the // period (".") character of the extension except when you have a terminal period when you get string.Empty, such as ".exe" or // ".cpp". The returned value is null if the given path is // null or if the given path does not include an extension. [Pure] public static string GetExtension(string path) { if (path == null) return null; PathInternal.CheckInvalidPathChars(path); int length = path.Length; for (int i = length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { if (i != length - 1) return path.Substring(i, length - i); else return string.Empty; } if (IsDirectoryOrVolumeSeparator(ch)) break; } return string.Empty; } // Returns the name and extension parts of the given path. The resulting // string contains the characters of path that follow the last // separator in path. The resulting string is null if path is null. [Pure] public static string GetFileName(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); int length = path.Length; for (int i = length - 1; i >= 0; i--) { char ch = path[i]; if (IsDirectoryOrVolumeSeparator(ch)) return path.Substring(i + 1, length - i - 1); } } return path; } [Pure] public static string GetFileNameWithoutExtension(string path) { if (path == null) return null; path = GetFileName(path); int i; return (i = path.LastIndexOf('.')) == -1 ? path : // No path extension found path.Substring(0, i); } // Returns a cryptographically strong random 8.3 string that can be // used as either a folder name or a file name. public static unsafe string GetRandomFileName() { // 8 random bytes provides 12 chars in our encoding for the 8.3 name. const int KeyLength = 8; byte* pKey = stackalloc byte[KeyLength]; GetCryptoRandomBytes(pKey, KeyLength); const int RandomFileNameLength = 12; char* pRandomFileName = stackalloc char[RandomFileNameLength]; Populate83FileNameFromRandomBytes(pKey, KeyLength, pRandomFileName, RandomFileNameLength); return new string(pRandomFileName, 0, RandomFileNameLength); } // Tests if a path includes a file extension. The result is // true if the characters that follow the last directory // separator ('\\' or '/') or volume separator (':') in the path include // a period (".") other than a terminal period. The result is false otherwise. [Pure] public static bool HasExtension(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == '.') { return i != path.Length - 1; } if (IsDirectoryOrVolumeSeparator(ch)) break; } } return false; } public static string Combine(string path1, string path2) { if (path1 == null || path2 == null) throw new ArgumentNullException((path1 == null) ? "path1" : "path2"); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); return CombineNoChecks(path1, path2); } public static string Combine(string path1, string path2, string path3) { if (path1 == null || path2 == null || path3 == null) throw new ArgumentNullException((path1 == null) ? "path1" : (path2 == null) ? "path2" : "path3"); Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); PathInternal.CheckInvalidPathChars(path3); return CombineNoChecks(path1, path2, path3); } public static string Combine(params string[] paths) { if (paths == null) { throw new ArgumentNullException(nameof(paths)); } Contract.EndContractBlock(); int finalSize = 0; int firstComponent = 0; // We have two passes, the first calculates how large a buffer to allocate and does some precondition // checks on the paths passed in. The second actually does the combination. for (int i = 0; i < paths.Length; i++) { if (paths[i] == null) { throw new ArgumentNullException(nameof(paths)); } if (paths[i].Length == 0) { continue; } PathInternal.CheckInvalidPathChars(paths[i]); if (IsPathRooted(paths[i])) { firstComponent = i; finalSize = paths[i].Length; } else { finalSize += paths[i].Length; } char ch = paths[i][paths[i].Length - 1]; if (!IsDirectoryOrVolumeSeparator(ch)) finalSize++; } StringBuilder finalPath = StringBuilderCache.Acquire(finalSize); for (int i = firstComponent; i < paths.Length; i++) { if (paths[i].Length == 0) { continue; } if (finalPath.Length == 0) { finalPath.Append(paths[i]); } else { char ch = finalPath[finalPath.Length - 1]; if (!IsDirectoryOrVolumeSeparator(ch)) { finalPath.Append(DirectorySeparatorChar); } finalPath.Append(paths[i]); } } return StringBuilderCache.GetStringAndRelease(finalPath); } private static string CombineNoChecks(string path1, string path2) { if (path2.Length == 0) return path1; if (path1.Length == 0) return path2; if (IsPathRooted(path2)) return path2; char ch = path1[path1.Length - 1]; return IsDirectoryOrVolumeSeparator(ch) ? path1 + path2 : path1 + DirectorySeparatorCharAsString + path2; } private static string CombineNoChecks(string path1, string path2, string path3) { if (path1.Length == 0) return CombineNoChecks(path2, path3); if (path2.Length == 0) return CombineNoChecks(path1, path3); if (path3.Length == 0) return CombineNoChecks(path1, path2); if (IsPathRooted(path3)) return path3; if (IsPathRooted(path2)) return CombineNoChecks(path2, path3); bool hasSep1 = IsDirectoryOrVolumeSeparator(path1[path1.Length - 1]); bool hasSep2 = IsDirectoryOrVolumeSeparator(path2[path2.Length - 1]); if (hasSep1 && hasSep2) { return path1 + path2 + path3; } else if (hasSep1) { return path1 + path2 + DirectorySeparatorCharAsString + path3; } else if (hasSep2) { return path1 + DirectorySeparatorCharAsString + path2 + path3; } else { // string.Concat only has string-based overloads up to four arguments; after that requires allocating // a params string[]. Instead, try to use a cached StringBuilder. StringBuilder sb = StringBuilderCache.Acquire(path1.Length + path2.Length + path3.Length + 2); sb.Append(path1) .Append(DirectorySeparatorChar) .Append(path2) .Append(DirectorySeparatorChar) .Append(path3); return StringBuilderCache.GetStringAndRelease(sb); } } private static readonly char[] s_base32Char = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5'}; private static unsafe void Populate83FileNameFromRandomBytes(byte* bytes, int byteCount, char* chars, int charCount) { Debug.Assert(bytes != null); Debug.Assert(chars != null); // This method requires bytes of length 8 and chars of length 12. Debug.Assert(byteCount == 8, $"Unexpected {nameof(byteCount)}"); Debug.Assert(charCount == 12, $"Unexpected {nameof(charCount)}"); byte b0 = bytes[0]; byte b1 = bytes[1]; byte b2 = bytes[2]; byte b3 = bytes[3]; byte b4 = bytes[4]; // Consume the 5 Least significant bits of the first 5 bytes chars[0] = s_base32Char[b0 & 0x1F]; chars[1] = s_base32Char[b1 & 0x1F]; chars[2] = s_base32Char[b2 & 0x1F]; chars[3] = s_base32Char[b3 & 0x1F]; chars[4] = s_base32Char[b4 & 0x1F]; // Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4 chars[5] = s_base32Char[( ((b0 & 0xE0) >> 5) | ((b3 & 0x60) >> 2))]; chars[6] = s_base32Char[( ((b1 & 0xE0) >> 5) | ((b4 & 0x60) >> 2))]; // Consume 3 MSB bits of b2, 1 MSB bit of b3, b4 b2 >>= 5; Debug.Assert(((b2 & 0xF8) == 0), "Unexpected set bits"); if ((b3 & 0x80) != 0) b2 |= 0x08; if ((b4 & 0x80) != 0) b2 |= 0x10; chars[7] = s_base32Char[b2]; // Set the file extension separator chars[8] = '.'; // Consume the 5 Least significant bits of the remaining 3 bytes chars[9] = s_base32Char[(bytes[5] & 0x1F)]; chars[10] = s_base32Char[(bytes[6] & 0x1F)]; chars[11] = s_base32Char[(bytes[7] & 0x1F)]; } } }
// 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.Text.Unicode; namespace System.Text { public readonly ref partial struct Utf8Span { public static bool operator ==(Utf8Span left, Utf8Span right) => Equals(left, right); public static bool operator !=(Utf8Span left, Utf8Span right) => !Equals(left, right); public int CompareTo(Utf8Span other) { // TODO_UTF8STRING: This is ordinal, but String.CompareTo uses CurrentCulture. // Is this acceptable? // TODO_UTF8STRING: To avoid allocations, use Utf8StringComparer instead of StringComparer once it's submitted. return StringComparer.Ordinal.Compare(this.ToString(), other.ToString()); } public int CompareTo(Utf8Span other, StringComparison comparison) { // TODO_UTF8STRING: We can avoid the virtual dispatch by moving the switch into this method. // TODO_UTF8STRING: To avoid allocations, use Utf8StringComparer instead of StringComparer once it's submitted. return StringComparer.FromComparison(comparison).Compare(this.ToString(), other.ToString()); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains /// <paramref name="value"/>. An ordinal comparison is used. /// </summary> public bool Contains(char value) { return Rune.TryCreate(value, out Rune rune) && Contains(rune); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains /// <paramref name="value"/>. The specified comparison is used. /// </summary> public bool Contains(char value, StringComparison comparison) { return Rune.TryCreate(value, out Rune rune) && Contains(rune, comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains /// the specified <see cref="Rune"/>. An ordinal comparison is used. /// </summary> public bool Contains(Rune value) { // TODO_UTF8STRING: This should be split into two methods: // One which operates on a single-byte (ASCII) search value, // the other which operates on a multi-byte (non-ASCII) search value. Span<byte> runeBytes = stackalloc byte[Utf8Utility.MaxBytesPerScalar]; int runeBytesWritten = value.EncodeToUtf8(runeBytes); return (this.Bytes.IndexOf(runeBytes.Slice(0, runeBytesWritten)) >= 0); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains /// the specified <see cref="Rune"/>. The specified comparison is used. /// </summary> public bool Contains(Rune value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().Contains(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains <paramref name="value"/>. /// An ordinal comparison is used. /// </summary> public bool Contains(Utf8Span value) { return (this.Bytes.IndexOf(value.Bytes) >= 0); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains <paramref name="value"/>. /// The specified comparison is used. /// </summary> public bool Contains(Utf8Span value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().Contains(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with /// <paramref name="value"/>. An ordinal comparison is used. /// </summary> public bool EndsWith(char value) { return Rune.TryCreate(value, out Rune rune) && EndsWith(rune); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with /// <paramref name="value"/>. The specified comparison is used. /// </summary> public bool EndsWith(char value, StringComparison comparison) { return Rune.TryCreate(value, out Rune rune) && EndsWith(rune, comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with /// the specified <see cref="Rune"/>. An ordinal comparison is used. /// </summary> public bool EndsWith(Rune value) { // TODO_UTF8STRING: This should be split into two methods: // One which operates on a single-byte (ASCII) search value, // the other which operates on a multi-byte (non-ASCII) search value. Span<byte> runeBytes = stackalloc byte[Utf8Utility.MaxBytesPerScalar]; int runeBytesWritten = value.EncodeToUtf8(runeBytes); return this.Bytes.EndsWith(runeBytes.Slice(0, runeBytesWritten)); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with /// the specified <see cref="Rune"/>. The specified comparison is used. /// </summary> public bool EndsWith(Rune value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().EndsWith(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with <paramref name="value"/>. /// An ordinal comparison is used. /// </summary> public bool EndsWith(Utf8Span value) { return this.Bytes.EndsWith(value.Bytes); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with <paramref name="value"/>. /// The specified comparison is used. /// </summary> public bool EndsWith(Utf8Span value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().EndsWith(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with /// <paramref name="value"/>. An ordinal comparison is used. /// </summary> public bool StartsWith(char value) { return Rune.TryCreate(value, out Rune rune) && StartsWith(rune); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with /// <paramref name="value"/>. The specified comparison is used. /// </summary> public bool StartsWith(char value, StringComparison comparison) { return Rune.TryCreate(value, out Rune rune) && StartsWith(rune, comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with /// the specified <see cref="Rune"/>. An ordinal comparison is used. /// </summary> public bool StartsWith(Rune value) { // TODO_UTF8STRING: This should be split into two methods: // One which operates on a single-byte (ASCII) search value, // the other which operates on a multi-byte (non-ASCII) search value. Span<byte> runeBytes = stackalloc byte[Utf8Utility.MaxBytesPerScalar]; int runeBytesWritten = value.EncodeToUtf8(runeBytes); return this.Bytes.StartsWith(runeBytes.Slice(0, runeBytesWritten)); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with /// the specified <see cref="Rune"/>. The specified comparison is used. /// </summary> public bool StartsWith(Rune value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().StartsWith(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with <paramref name="value"/>. /// An ordinal comparison is used. /// </summary> public bool StartsWith(Utf8Span value) { return this.Bytes.StartsWith(value.Bytes); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with <paramref name="value"/>. /// The specified comparison is used. /// </summary> public bool StartsWith(Utf8Span value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().StartsWith(value.ToString(), comparison); } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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; namespace SharpDX.XAudio2 { public partial class XAudio2 { private EngineCallbackImpl engineCallbackImpl; private IntPtr engineShadowPtr; ///// <summary>Constant None.</summary> //internal static Guid CLSID_XAudio2 = new Guid("5a508685-a254-4fba-9b82-9a24b00306af"); ///// <summary>Constant None.</summary> //internal static Guid CLSID_XAudio2_Debug = new Guid("db05ea35-0329-4d4b-a53a-6dead03d3852"); ///// <summary>Constant None.</summary> //internal static Guid IID_IXAudio2 = new Guid("8bcf1f58-9fe7-4583-8ac6-e2adc465c8bb"); /// <summary> /// Called by XAudio2 just before an audio processing pass begins. /// </summary> public event EventHandler ProcessingPassStart; /// <summary> /// Called by XAudio2 just after an audio processing pass ends. /// </summary> public event EventHandler ProcessingPassEnd; /// <summary> /// Called if a critical system error occurs that requires XAudio2 to be closed down and restarted. /// </summary> public event EventHandler<ErrorEventArgs> CriticalError; /// <summary> /// Initializes a new instance of the <see cref="XAudio2"/> class. /// </summary> public XAudio2() : this(XAudio2Flags.None, ProcessorSpecifier.DefaultProcessor) { } /// <summary> /// Initializes a new instance of the <see cref="XAudio2"/> class. /// </summary> /// <param name="flags">Specify a Debug or Normal XAudio2 instance.</param> /// <param name="processorSpecifier">The processor specifier.</param> public XAudio2(XAudio2Flags flags, ProcessorSpecifier processorSpecifier) : base(IntPtr.Zero) { #if !DIRECTX11_1 Guid clsid = (flags == XAudio2Flags.DebugEngine) ? CLSID_XAudio2_Debug : CLSID_XAudio2; // Initialize for multithreaded //var result = Utilities.CoInitializeEx(IntPtr.Zero, Utilities.CoInit.MultiThreaded); //result.CheckError(); Utilities.CreateComInstance(clsid, Utilities.CLSCTX.ClsctxInprocServer, Utilities.GetGuidFromType(typeof(XAudio2)), this); // Initialize XAudio2 Initialize(0, processorSpecifier); #else XAudio2Functions.XAudio2Create(this, 0, (int)processorSpecifier); #endif // Register engine callback engineCallbackImpl = new EngineCallbackImpl(this); engineShadowPtr = EngineShadow.ToIntPtr(engineCallbackImpl); RegisterForCallbacks_(engineShadowPtr); } #if !DIRECTX11_1 /// <summary> /// Returns information about an audio output device. /// </summary> /// <param name="index">[in] Index of the device to be queried. This value must be less than the count returned by <see cref="SharpDX.XAudio2.XAudio2.GetDeviceCount"/>. </param> /// <returns>On success, pointer to an <see cref="SharpDX.XAudio2.DeviceDetails"/> structure that is returned. </returns> /// <unmanaged>HRESULT IXAudio2::GetDeviceDetails([None] UINT32 Index,[Out] XAUDIO2_DEVICE_DETAILS* pDeviceDetails)</unmanaged> public SharpDX.XAudio2.DeviceDetails GetDeviceDetails(int index) { DeviceDetails details; GetDeviceDetails(index, out details); return details; } #endif /// <summary> /// Calculate a decibel from a volume. /// </summary> /// <param name="volume">The volume.</param> /// <returns>a dB value</returns> public static float AmplitudeRatioToDecibels(float volume) { if (volume == 0f) return float.MinValue; return (float)(Math.Log10(volume) * 20); } /// <summary> /// Calculate radians from a cutoffs frequency. /// </summary> /// <param name="cutoffFrequency">The cutoff frequency.</param> /// <param name="sampleRate">The sample rate.</param> /// <returns>radian</returns> public static float CutoffFrequencyToRadians(float cutoffFrequency, int sampleRate) { if (((int)cutoffFrequency * 6.0) >= sampleRate) return 1f; return (float)(Math.Sin(cutoffFrequency*Math.PI/sampleRate)*2); } /// <summary> /// Calculate a cutoff frequency from a radian. /// </summary> /// <param name="radians">The radians.</param> /// <param name="sampleRate">The sample rate.</param> /// <returns>cutoff frequency</returns> public static float RadiansToCutoffFrequency(float radians, float sampleRate) { return (float)((Math.Asin(radians * 0.5) * sampleRate) / Math.PI); } /// <summary> /// Calculate a volume from a decibel /// </summary> /// <param name="decibels">a dB value</param> /// <returns>an amplitude value</returns> public static float DecibelsToAmplitudeRatio(float decibels) { return (float)Math.Pow(10, decibels / 20); } /// <summary> /// Calculate semitones from a Frequency ratio /// </summary> /// <param name="frequencyRatio">The frequency ratio.</param> /// <returns>semitones</returns> public static float FrequencyRatioToSemitones(float frequencyRatio) { return (float)(Math.Log10(frequencyRatio) * 12 * Math.PI); } /// <summary> /// Calculate frequency from semitones. /// </summary> /// <param name="semitones">The semitones.</param> /// <returns>the frequency</returns> public static float SemitonesToFrequencyRatio(float semitones) { return (float)Math.Pow(2, semitones / 12); } /// <summary> /// Atomically applies a set of operations for all pending operations. /// </summary> /// <unmanaged>HRESULT IXAudio2::CommitChanges([None] UINT32 OperationSet)</unmanaged> public void CommitChanges() { this.CommitChanges(0); } protected override void Dispose(bool disposing) { if (engineShadowPtr != IntPtr.Zero) UnregisterForCallbacks_(engineShadowPtr); if (disposing) { if (engineCallbackImpl != null) engineCallbackImpl.Dispose(); } base.Dispose(disposing); } private class EngineCallbackImpl : CallbackBase, EngineCallback { XAudio2 XAudio2 { get; set; } public EngineCallbackImpl(XAudio2 xAudio2) { XAudio2 = xAudio2; } public void OnProcessingPassStart() { EventHandler handler = XAudio2.ProcessingPassStart; if (handler != null) handler(this, EventArgs.Empty); } public void OnProcessingPassEnd() { EventHandler handler = XAudio2.ProcessingPassEnd; if (handler != null) handler(this, EventArgs.Empty); } public void OnCriticalError(Result error) { EventHandler<ErrorEventArgs> handler = XAudio2.CriticalError; if (handler != null) handler(this, new ErrorEventArgs(error)); } IDisposable ICallbackable.Shadow { get; set; } } } }
// Copyright 2018 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 // // 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 Google.Api.Ads.Common.Lib; using System; namespace Google.Api.Ads.AdWords.Lib { /// <summary> /// Lists all the services available through this library. /// </summary> public partial class AdWordsService : AdsService { /// <summary> /// All the services available in v201809. /// </summary> public class v201809 { #region Campaign Management. /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdGroupAdService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature AdGroupAdService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdGroupBidModifierService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupBidModifierService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdGroupCriterionService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupCriterionService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdGroupFeedService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupFeedService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdGroupService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdParamService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdParamService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AssetService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AssetService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/BatchJobService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BatchJobService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/BiddingStrategyService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BiddingStrategyService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/BudgetService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BudgetService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CampaignCriterionService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignCriterionService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CampaignFeedService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignFeedService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CampaignBidModifierService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignBidModifierService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CampaignGroupService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignGroupService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CampaignGroupPerformanceTargetService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignGroupPerformanceTargetService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CampaignService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/cm/v201809/CampaignSharedSetService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignSharedSetService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/ConstantDataService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ConstantDataService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/ConversionTrackerService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ConversionTrackerService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CustomerFeedService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomerFeedService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CustomerNegativeCriterionService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomerNegativeCriterionService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/DataService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature DataService; /// <summary> /// Factory type for v201809 services. /// </summary> public static readonly Type factoryType = typeof(AdWordsServiceFactory); /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/FeedItemService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedItemService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/FeedMappingService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedMappingService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/FeedService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/FeedItemTargetService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature FeedItemTargetService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/cm/v201809/SharedSetService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LabelService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/cm/v201809/AccountLabelService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AccountLabelService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/LocationCriterionService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LocationCriterionService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/MediaService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature MediaService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/OfflineConversionFeedService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature OfflineConversionFeedService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/OfflineConversionFeedService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature OfflineCallConversionFeedService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/ReportDefinitionService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ReportDefinitionService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/cm/v201809/SharedCriterionService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SharedCriterionService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/cm/v201809/SharedCriterionService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SharedSetService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/cm/v201809/DraftService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature DraftService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/cm/v201809/DraftAsyncErrorService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature DraftAsyncErrorService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/OfflineConversionAdjustmentFeedService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature OfflineConversionAdjustmentFeedService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/cm/v201809/TrialService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TrialService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/cm/v201809/TrialAsyncErrorService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TrialAsyncErrorService; #endregion Campaign Management. #region Billing. /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/BudgetOrderService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature BudgetOrderService; #endregion Billing. #region Remarketing. /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdwordsUserListService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdwordsUserListService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/OfflineDataUploadService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature OfflineDataUploadService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CustomAffinityService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomAffinityService; #endregion Remarketing. #region Optimization /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/TargetingIdeaService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TargetingIdeaService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/TrafficEstimatorService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TrafficEstimatorService; #endregion Optimization #region Account Management. /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CustomerService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomerService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/ManagedCustomerService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ManagedCustomerService; #endregion Account Management. #region Change history. /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CustomerSyncService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomerSyncService; #endregion Change history. #region Extension setting /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdCustomizerFeedService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdCustomizerFeedService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/AdGroupExtensionSettingService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdGroupExtensionSettingService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CampaignExtensionSettingService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CampaignExtensionSettingService; /// <summary> /// See <a href="https://developers.google.com/adwords/api/docs/reference/v201809/CustomerExtensionSettingService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CustomerExtensionSettingService; #endregion Extension setting /// <summary> /// Static constructor to initialize the service constants. /// </summary> static v201809() { #region Campaign Management. AdGroupAdService = AdWordsService.MakeServiceSignature("v201809", "cm", "AdGroupAdService"); AdGroupBidModifierService = AdWordsService.MakeServiceSignature("v201809", "cm", "AdGroupBidModifierService"); AdGroupCriterionService = AdWordsService.MakeServiceSignature("v201809", "cm", "AdGroupCriterionService"); AdGroupFeedService = AdWordsService.MakeServiceSignature("v201809", "cm", "AdGroupFeedService"); AdGroupService = AdWordsService.MakeServiceSignature("v201809", "cm", "AdGroupService"); AssetService = AdWordsService.MakeServiceSignature("v201809", "cm", "AssetService"); AdService = AdWordsService.MakeServiceSignature("v201809", "cm", "AdService"); AdParamService = AdWordsService.MakeServiceSignature("v201809", "cm", "AdParamService"); BatchJobService = AdWordsService.MakeServiceSignature("v201809", "cm", "BatchJobService"); BiddingStrategyService = AdWordsService.MakeServiceSignature("v201809", "cm", "BiddingStrategyService"); BudgetService = AdWordsService.MakeServiceSignature("v201809", "cm", "BudgetService"); CampaignCriterionService = AdWordsService.MakeServiceSignature("v201809", "cm", "CampaignCriterionService"); CampaignFeedService = AdWordsService.MakeServiceSignature("v201809", "cm", "CampaignFeedService"); CampaignService = AdWordsService.MakeServiceSignature("v201809", "cm", "CampaignService"); CampaignBidModifierService = AdWordsService.MakeServiceSignature("v201809", "cm", "CampaignBidModifierService"); CampaignGroupService = AdWordsService.MakeServiceSignature("v201809", "cm", "CampaignGroupService"); CampaignGroupPerformanceTargetService = AdWordsService.MakeServiceSignature("v201809", "cm", "CampaignGroupPerformanceTargetService"); CampaignSharedSetService = AdWordsService.MakeServiceSignature("v201809", "cm", "CampaignSharedSetService"); ConstantDataService = AdWordsService.MakeServiceSignature("v201809", "cm", "ConstantDataService"); ConversionTrackerService = AdWordsService.MakeServiceSignature("v201809", "cm", "ConversionTrackerService"); CustomerNegativeCriterionService = AdWordsService.MakeServiceSignature("v201809", "cm", "CustomerNegativeCriterionService"); CustomerFeedService = AdWordsService.MakeServiceSignature("v201809", "cm", "CustomerFeedService"); DataService = AdWordsService.MakeServiceSignature("v201809", "cm", "DataService"); FeedItemService = AdWordsService.MakeServiceSignature("v201809", "cm", "FeedItemService"); FeedMappingService = AdWordsService.MakeServiceSignature("v201809", "cm", "FeedMappingService"); FeedService = AdWordsService.MakeServiceSignature("v201809", "cm", "FeedService"); FeedItemTargetService = AdWordsService.MakeServiceSignature("v201809", "cm", "FeedItemTargetService"); LabelService = AdWordsService.MakeServiceSignature("v201809", "cm", "LabelService"); LocationCriterionService = AdWordsService.MakeServiceSignature("v201809", "cm", "LocationCriterionService"); MediaService = AdWordsService.MakeServiceSignature("v201809", "cm", "MediaService"); OfflineConversionAdjustmentFeedService = AdWordsService.MakeServiceSignature("v201809", "cm", "OfflineConversionAdjustmentFeedService"); OfflineConversionFeedService = AdWordsService.MakeServiceSignature("v201809", "cm", "OfflineConversionFeedService"); OfflineCallConversionFeedService = AdWordsService.MakeServiceSignature("v201809", "cm", "OfflineCallConversionFeedService"); ReportDefinitionService = AdWordsService.MakeServiceSignature("v201809", "cm", "ReportDefinitionService"); SharedCriterionService = AdWordsService.MakeServiceSignature("v201809", "cm", "SharedCriterionService"); SharedSetService = AdWordsService.MakeServiceSignature("v201809", "cm", "SharedSetService"); DraftService = AdWordsService.MakeServiceSignature("v201809", "cm", "DraftService"); DraftAsyncErrorService = AdWordsService.MakeServiceSignature("v201809", "cm", "DraftAsyncErrorService"); TrialService = AdWordsService.MakeServiceSignature("v201809", "cm", "TrialService"); TrialAsyncErrorService = AdWordsService.MakeServiceSignature("v201809", "cm", "TrialAsyncErrorService"); #endregion Campaign Management. #region Blling. BudgetOrderService = AdWordsService.MakeServiceSignature("v201809", "billing", "BudgetOrderService"); #endregion Blling. #region Remarketing. AdwordsUserListService = AdWordsService.MakeServiceSignature("v201809", "rm", "AdwordsUserListService"); OfflineDataUploadService = AdWordsService.MakeServiceSignature("v201809", "rm", "OfflineDataUploadService"); CustomAffinityService = AdWordsService.MakeServiceSignature("v201809", "rm", "CustomAffinityService"); #endregion Remarketing. #region Optimization. TargetingIdeaService = AdWordsService.MakeServiceSignature("v201809", "o", "TargetingIdeaService"); TrafficEstimatorService = AdWordsService.MakeServiceSignature("v201809", "o", "TrafficEstimatorService"); #endregion Optimization. #region Change History. CustomerSyncService = AdWordsService.MakeServiceSignature("v201809", "ch", "CustomerSyncService"); #endregion Change History. #region Account Management. AccountLabelService = AdWordsService.MakeServiceSignature("v201809", "mcm", "AccountLabelService"); CustomerService = AdWordsService.MakeServiceSignature("v201809", "mcm", "CustomerService"); ManagedCustomerService = AdWordsService.MakeServiceSignature("v201809", "mcm", "ManagedCustomerService"); #endregion Account Management. #region Extension setting AdCustomizerFeedService = AdWordsService.MakeServiceSignature("v201809", "cm", "AdCustomizerFeedService"); AdGroupExtensionSettingService = AdWordsService.MakeServiceSignature("v201809", "cm", "AdGroupExtensionSettingService"); CampaignExtensionSettingService = AdWordsService.MakeServiceSignature("v201809", "cm", "CampaignExtensionSettingService"); CustomerExtensionSettingService = AdWordsService.MakeServiceSignature("v201809", "cm", "CustomerExtensionSettingService"); #endregion Extension setting } } } }
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading; using Remotion.Linq.Parsing.Structure.IntermediateModel; namespace Remotion.Linq.Parsing.Structure.NodeTypeProviders { /// <summary> /// Maps the <see cref="MethodInfo"/> objects used in <see cref="MethodCallExpression"/> objects to the respective <see cref="IExpressionNode"/> /// types. This is used by <see cref="ExpressionTreeParser"/> when a <see cref="MethodCallExpression"/> is encountered to instantiate the /// right <see cref="IExpressionNode"/> for the given method. /// </summary> public sealed class MethodInfoBasedNodeTypeRegistry : INodeTypeProvider { private static readonly Dictionary<MethodInfo, Lazy<MethodInfo[]>> s_genericMethodDefinitionCandidates = new Dictionary<MethodInfo, Lazy<MethodInfo[]>>(); /// <summary> /// Creates a <see cref="MethodInfoBasedNodeTypeRegistry"/> and automatically registers all types implementing <see cref="IExpressionNode"/> /// from a given type sequence that offer a public static <c>SupportedMethods</c> field. /// </summary> /// <returns>A <see cref="MethodInfoBasedNodeTypeRegistry"/> with all <see cref="IExpressionNode"/> types with a <c>SupportedMethods</c> /// field registered.</returns> public static MethodInfoBasedNodeTypeRegistry CreateFromTypes(IEnumerable<Type> searchedTypes) { var expressionNodeTypes = from t in searchedTypes where typeof(IExpressionNode).IsAssignableFrom(t) select t; var supportedMethodsForTypes = from t in expressionNodeTypes let supportedMethodsField = t.GetField("SupportedMethods") select new { Type = t, Methods = supportedMethodsField != null && supportedMethodsField.IsStatic ? (IEnumerable<MethodInfo>)supportedMethodsField.GetValue(null) : Enumerable.Empty<MethodInfo>() }; var registry = new MethodInfoBasedNodeTypeRegistry(); foreach (var methodsForType in supportedMethodsForTypes) { registry.Register(methodsForType.Methods, methodsForType.Type); } return registry; } /// <summary> /// Gets the registerable method definition from a given <see cref="MethodInfo"/>. A registerable method is a <see cref="MethodInfo"/> object /// that can be registered via a call to <see cref="Register"/>. When the given <paramref name="method"/> is passed to /// <see cref="GetNodeType"/> and its corresponding registerable method was registered, the correct node type is returned. /// </summary> /// <param name="method">The method for which the registerable method should be retrieved. Must not be <see langword="null" />.</param> /// <param name="throwOnAmbiguousMatch"> /// <see langword="true" /> to throw a <see cref="NotSupportedException"/> if the method cannot be matched to a distinct generic method definition, /// <see langword="false" /> to return <see langword="null" /> if an unambiguous match is not possible. /// </param> /// <returns> /// <para> /// <paramref name="method"/> itself, unless it is a closed generic method or declared in a closed generic type. In the latter cases, /// the corresponding generic method definition respectively the method declared in a generic type definition is returned. /// </para><para> /// If no generic method definition could be matched and <paramref name="throwOnAmbiguousMatch"/> was set to <see langword="false" />, /// <see langword="null" /> is returned. /// </para> /// </returns> /// <exception cref="NotSupportedException"> /// Thrown if <paramref name="throwOnAmbiguousMatch"/> is set to <see langword="true" /> and no distinct generic method definition could be resolved. /// </exception> public static MethodInfo GetRegisterableMethodDefinition(MethodInfo method, bool throwOnAmbiguousMatch) { var genericMethodDefinition = method.IsGenericMethod ? method.GetGenericMethodDefinition() : method; if (!genericMethodDefinition.DeclaringType.IsGenericType) return genericMethodDefinition; // Simple, fast solution, not possible in PCL because of missing MethodHandle property on MethodInfo type: // var declaringTypeDefinition = genericMethodDefinition.DeclaringType.GetGenericTypeDefinition(); // return (MethodInfo) MethodBase.GetMethodFromHandle (genericMethodDefinition.MethodHandle, declaringTypeDefinition.TypeHandle); Lazy<MethodInfo[]> candidates; lock (s_genericMethodDefinitionCandidates) { if (!s_genericMethodDefinitionCandidates.TryGetValue(method, out candidates)) { candidates = new Lazy<MethodInfo[]>( () => GetGenericMethodDefinitionCandidates(genericMethodDefinition), LazyThreadSafetyMode.ExecutionAndPublication); s_genericMethodDefinitionCandidates.Add(method, candidates); } } if (candidates.Value.Length == 1) return candidates.Value[0]; if (!throwOnAmbiguousMatch) return null; throw new NotSupportedException( string.Format( "A generic method definition cannot be resolved for method '{0}' on type '{1}' because a distinct match is not possible. " + @"The method can still be registered using the following syntax: public static readonly NameBasedRegistrationInfo[] SupportedMethodNames = new[] {{ new NameBasedRegistrationInfo ( ""{2}"", mi => /* match rule based on MethodInfo */ ) }};", method, genericMethodDefinition.DeclaringType.GetGenericTypeDefinition(), method.Name)); } private static MethodInfo[] GetGenericMethodDefinitionCandidates(MethodInfo referenceMethodDefinition) { var declaringTypeDefinition = referenceMethodDefinition.DeclaringType.GetGenericTypeDefinition(); var referenceMethodSignature = new[] { new { Name = "returnValue", Type = referenceMethodDefinition.ReturnType } } .Concat(referenceMethodDefinition.GetParameters().Select(p => new { Name = p.Name, Type = p.ParameterType })) .ToArray(); var candidates = declaringTypeDefinition.GetMethods() .Select( m => new { Method = m, SignatureNames = new[] { "returnValue" }.Concat(m.GetParameters().Select(p => p.Name)).ToArray(), SignatureTypes = new[] { m.ReturnType }.Concat(m.GetParameters().Select(p => p.ParameterType)).ToArray() }) .Where(c => c.Method.Name == referenceMethodDefinition.Name && c.SignatureTypes.Length == referenceMethodSignature.Length) .ToArray(); for (int i = 0; i < referenceMethodSignature.Length; i++) { candidates = candidates .Where(c => c.SignatureNames[i] == referenceMethodSignature[i].Name) .Where(c => c.SignatureTypes[i] == referenceMethodSignature[i].Type || c.SignatureTypes[i].ContainsGenericParameters) .ToArray(); } return candidates.Select(c => c.Method).ToArray(); } private readonly Dictionary<MethodInfo, Type> _registeredMethodInfoTypes = new Dictionary<MethodInfo, Type>(); /// <summary> /// Returns the count of the registered <see cref="MethodInfo"/>s. /// </summary> public int RegisteredMethodInfoCount { get { return _registeredMethodInfoTypes.Count; } } /// <summary> /// Registers the specific <paramref name="methods"/> with the given <paramref name="nodeType"/>. The given methods must either be non-generic /// or open generic method definitions. If a method has already been registered before, the later registration overwrites the earlier one. /// </summary> public void Register(IEnumerable<MethodInfo> methods, Type nodeType) { foreach (var method in methods) { if (method.IsGenericMethod && !method.IsGenericMethodDefinition) { var message = string.Format( "Cannot register closed generic method '{0}', try to register its generic method definition instead.", method.Name); throw new InvalidOperationException(message); } if (method.DeclaringType.IsGenericType && !method.DeclaringType.IsGenericTypeDefinition) { var message = string.Format( "Cannot register method '{0}' in closed generic type '{1}', try to register its equivalent in the generic type definition instead.", method.Name, method.DeclaringType); throw new InvalidOperationException(message); } _registeredMethodInfoTypes[method] = nodeType; } } /// <summary> /// Determines whether the specified method was registered with this <see cref="MethodInfoBasedNodeTypeRegistry"/>. /// </summary> public bool IsRegistered(MethodInfo method) { return GetNodeType(method) != null; } /// <summary> /// Gets the type of <see cref="IExpressionNode"/> registered with this <see cref="MethodInfoBasedNodeTypeRegistry"/> instance that /// matches the given <paramref name="method"/>, returning <see langword="null" /> if none can be found. /// </summary> public Type GetNodeType(MethodInfo method) { var methodDefinition = GetRegisterableMethodDefinition(method, throwOnAmbiguousMatch: false); if (methodDefinition == null) return null; Type result; _registeredMethodInfoTypes.TryGetValue(methodDefinition, out result); return result; } } }
/* * Copyright (c) 2016 Robert Adams * * 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. */ /* * Some code covered by: Copyright (c) Contributors, http://opensimulator.org/ */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Nini.Config; namespace org.herbal3d.BasilOS { public class BasilParams { private static readonly string LogHeader = "[BASIL PARAMS]"; public BasilParams() { SetParameterDefaultValues(); } #pragma warning disable CS0649 // disable 'never assigned' warnings public bool Enabled; // True if, well, enabled. public string AssetDirectory; // root directory of asset storage public int WebSocketPort; // port to open WebSocket listener public bool MergeStaticMeshes; // whether to merge meshes with similar materials public bool MergeNonStaticMeshes; // whether to merge meshes with non-static entities public string GltfTargetDir; // where to store all the Gltf files public bool ExportTextures; // also export textures to the target dir public int MaxTextureSize; // the maximum pixel dimension for images if exporting public bool AddTerrainMesh; // whether to create and add a terrain mesh public bool CreateTerrainSplat; // whether to generate a terrain mesh splat texture public int VerticesMaxForBuffer; // Number of vertices to cause splitting of buffer files public bool HalfRezTerrain; // whether to reduce the terrain resolution by 2 public bool DisplayTimeScaling; // 'true' if to delay mesh scaling to display/GPU time public string URIBase; // the URI base to be added to the beginning of the asset name public bool UseOpenSimImageDecoder; // Use the OpenSimulator image decoder to process JPEG2000 images public bool LogConversionStats; // output numbers about number of entities converted public bool LogDetailedSharedFaceStats; // output numbers about face mesh sharing public bool LogDetailedEntityInfo; // output detailed information about each entity #pragma warning restore CS0649 // ===================================================================================== // ===================================================================================== // List of all of the externally visible parameters. // For each parameter, this table maps a text name to getter and setters. // To add a new externally referencable/settable parameter, add the paramter storage // location somewhere in the program and make an entry in this table with the // getters and setters. // It is easiest to find an existing definition and copy it. // // A ParameterDefn<T>() takes the following parameters: // -- the text name of the parameter. This is used for console input and ini file. // -- a short text description of the parameter. This shows up in the console listing. // -- a default value // -- a delegate for getting the value // -- a delegate for setting the value // -- an optional delegate to update the value in the world. Most often used to // push the new value to an in-world object. // // The single letter parameters for the delegates are: // v = value (appropriate type) private readonly ParameterDefnBase[] ParameterDefinitions = { new ParameterDefn<bool>("Enabled", "If false, module is not enabled to operate", false ), new ParameterDefn<string>("AssetDirectory", "The directory (relative to simulator) to hold Basil assets", "./BasilAssets" ), new ParameterDefn<int>("WebSocketPort", "Port for the WebSocket to listen on", 34343 ), new ParameterDefn<bool>("MergeStaticMeshes", "whether to merge meshes with similar materials", true ), new ParameterDefn<bool>("MergeNonStaticMeshes", "whether to merge meshes within non-static entities ", true ), new ParameterDefn<string>("GltfTargetDir", "Where to store all the Gltf files", "./gltf" ), new ParameterDefn<bool>("ExportTextures", "Convert textures to PNGs and export to target dir", true ), new ParameterDefn<int>("MaxTextureSize", "The maximum pixel dimension for images if exporting", 256 ), new ParameterDefn<bool>("AddTerrainMesh", "whether to create and add a terrain mesh", true ), new ParameterDefn<bool>("CreateTerrainSplat", "whether to generate a terrain mesh splat texture", true ), new ParameterDefn<int>("VerticesMaxForBuffer", "Number of vertices to cause splitting of buffer files", 50000 ), new ParameterDefn<bool>("HalfRezTerrain", "Whether to reduce the terrain resolution by 2", false ), new ParameterDefn<bool>("DisplayTimeScaling", "If to delay mesh scaling to display/GPU time", false ), new ParameterDefn<string>("URIBase", "the string added to be beginning of asset name to create URI", "./" ), new ParameterDefn<bool>("UseOpenSimImageDecoder", "Use the OpenSimulator image decoder to process JPEG2000 images", false ), new ParameterDefn<bool>("LogConversionStats", "output numbers about number of entities converted", true ), new ParameterDefn<bool>("LogDetailedSharedFaceStats", "output numbers about face mesh sharing", true ), new ParameterDefn<bool>("LogDetailedEntityInfo", "output detailed information about each entity", false ), }; // ===================================================================================== // ===================================================================================== // Base parameter definition that gets and sets parameter values via a string public abstract class ParameterDefnBase { public string name; // string name of the parameter public string desc; // a short description of what the parameter means public BasilParams context; // context for setting and getting values public ParameterDefnBase(string pName, string pDesc) { name = pName; desc = pDesc; } // Set the parameter value to the default public abstract void AssignDefault(); // Get the value as a string public abstract string GetValue(); // Set the value to this string value public abstract void SetValue(string valAsString); } // Specific parameter definition for a parameter of a specific type. public delegate T PGetValue<T>(); public delegate void PSetValue<T>(T val); public sealed class ParameterDefn<T> : ParameterDefnBase { private readonly T defaultValue; private readonly PSetValue<T> setter; private readonly PGetValue<T> getter; public ParameterDefn(string pName, string pDesc, T pDefault, PGetValue<T> pGetter, PSetValue<T> pSetter) : base(pName, pDesc) { defaultValue = pDefault; setter = pSetter; getter = pGetter; } // Simple parameter variable where property name is the same as the INI file name // and the value is only a simple get and set. public ParameterDefn(string pName, string pDesc, T pDefault) : base(pName, pDesc) { defaultValue = pDefault; setter = (v) => { SetValueByName(name, v); }; getter = () => { return GetValueByName(name); }; } // Use reflection to find the property named 'pName' in Param and assign 'val' to same. private void SetValueByName(string pName, T val) { FieldInfo prop = context.GetType().GetField(pName); if (prop == null) { // This should only be output when someone adds a new INI parameter and misspells the name. // m_log.ErrorFormat("{0} SetValueByName: did not find '{1}'. Verify specified property name is the same as the given INI parameters name.", LogHeader, pName); System.Console.WriteLine("{0} SetValueByName: did not find '{1}'. Verify specified field name is the same as the given INI parameters name.", LogHeader, pName); } else { prop.SetValue(context, val); } } // Use reflection to find the property named 'pName' in Param and return the value in same. private T GetValueByName(string pName) { FieldInfo prop = context.GetType().GetField(pName); if (prop == null) { // This should only be output when someone adds a new INI parameter and misspells the name. // m_log.ErrorFormat("{0} GetValueByName: did not find '{1}'. Verify specified property name is the same as the given INI parameter name.", LogHeader, pName); System.Console.WriteLine("{0} GetValueByName: did not find '{1}'. Verify specified field name is the same as the given INI parameter name.", LogHeader, pName); } return (T)prop.GetValue(context); } public override void AssignDefault() { setter(defaultValue); } public override string GetValue() { return getter().ToString(); } public override void SetValue(string valAsString) { // Get the generic type of the setter Type genericType = setter.GetType().GetGenericArguments()[0]; // Find the 'Parse' method on that type System.Reflection.MethodInfo parser = null; try { parser = genericType.GetMethod("Parse", new Type[] { typeof(String) } ); } catch (Exception e) { System.Console.WriteLine("{0} Exception getting parser for type '{1}': {2}", LogHeader, genericType, e); parser = null; } if (parser != null) { // Parse the input string try { T setValue = (T)parser.Invoke(genericType, new Object[] { valAsString }); // Store the parsed value setter(setValue); // // m_log.DebugFormat("{0} Parameter {1} = {2}", LogHeader, name, setValue); } catch { // m_log.ErrorFormat("{0} Failed parsing parameter value '{1}' as type '{2}'", LogHeader, valAsString, genericType); } } else { // m_log.ErrorFormat("{0} Could not find parameter parser for type '{1}'", LogHeader, genericType); } } } // Search through the parameter definitions and return the matching // ParameterDefn structure. // Case does not matter as names are compared after converting to lower case. // Returns 'false' if the parameter is not found. public bool TryGetParameter(string paramName, out ParameterDefnBase defn) { bool ret = false; ParameterDefnBase foundDefn = null; string pName = paramName.ToLower(); foreach (ParameterDefnBase parm in ParameterDefinitions) { if (pName == parm.name.ToLower()) { foundDefn = parm; ret = true; break; } } defn = foundDefn; return ret; } // Pass through the settable parameters and set the default values public void SetParameterDefaultValues() { foreach (ParameterDefnBase parm in ParameterDefinitions) { parm.context = this; parm.AssignDefault(); } } // Get user set values out of the ini file. public void SetParameterConfigurationValues(IConfig cfg) { foreach (ParameterDefnBase parm in ParameterDefinitions) { System.Console.WriteLine("BasilParams: parm={0}, desc='{1}'", parm.name, parm.desc); parm.context = this; parm.SetValue(cfg.GetString(parm.name, parm.GetValue())); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; using OpenSim.Capabilities.Handlers; using OpenSim.Framework.Monitoring; namespace OpenSim.Region.ClientStack.Linden { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GetTextureModule")] public class GetTextureModule : INonSharedRegionModule { struct aPollRequest { public PollServiceTextureEventArgs thepoll; public UUID reqID; public Hashtable request; public bool send503; } public class aPollResponse { public Hashtable response; public int bytes; } private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private static GetTextureHandler m_getTextureHandler; private IAssetService m_assetService = null; private Dictionary<UUID, string> m_capsDict = new Dictionary<UUID, string>(); private static Thread[] m_workerThreads = null; private string m_Url = "localhost"; private static OpenMetaverse.BlockingQueue<aPollRequest> m_queue = new OpenMetaverse.BlockingQueue<aPollRequest>(); private Dictionary<UUID,PollServiceTextureEventArgs> m_pollservices = new Dictionary<UUID,PollServiceTextureEventArgs>(); #region ISharedRegionModule Members public void Initialise(IConfigSource source) { IConfig config = source.Configs["ClientStack.LindenCaps"]; if (config == null) return; /* m_URL = config.GetString("Cap_GetTexture", string.Empty); // Cap doesn't exist if (m_URL != string.Empty) { m_Enabled = true; m_RedirectURL = config.GetString("GetTextureRedirectURL"); } */ m_Url = config.GetString("Cap_GetTexture", "localhost"); } public void AddRegion(Scene s) { m_scene = s; m_assetService = s.AssetService; } public void RemoveRegion(Scene s) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; m_scene.EventManager.OnDeregisterCaps -= DeregisterCaps; m_scene.EventManager.OnThrottleUpdate -= ThrottleUpdate; m_scene = null; } public void RegionLoaded(Scene s) { // We'll reuse the same handler for all requests. m_getTextureHandler = new GetTextureHandler(m_assetService); m_scene.EventManager.OnRegisterCaps += RegisterCaps; m_scene.EventManager.OnDeregisterCaps += DeregisterCaps; m_scene.EventManager.OnThrottleUpdate += ThrottleUpdate; if (m_workerThreads == null) { m_workerThreads = new Thread[2]; for (uint i = 0; i < 2; i++) { m_workerThreads[i] = WorkManager.StartThread(DoTextureRequests, String.Format("TextureWorkerThread{0}", i), ThreadPriority.Normal, false, false, null, int.MaxValue); } } } private int ExtractImageThrottle(byte[] pthrottles) { byte[] adjData; int pos = 0; if (!BitConverter.IsLittleEndian) { byte[] newData = new byte[7 * 4]; Buffer.BlockCopy(pthrottles, 0, newData, 0, 7 * 4); for (int i = 0; i < 7; i++) Array.Reverse(newData, i * 4, 4); adjData = newData; } else { adjData = pthrottles; } // 0.125f converts from bits to bytes //int resend = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); //pos += 4; // int land = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); //pos += 4; // int wind = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); // pos += 4; // int cloud = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); // pos += 4; // int task = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); // pos += 4; pos = pos + 20; int texture = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); //pos += 4; //int asset = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); return texture; } // Now we know when the throttle is changed by the client in the case of a root agent or by a neighbor region in the case of a child agent. public void ThrottleUpdate(ScenePresence p) { byte[] throttles = p.ControllingClient.GetThrottlesPacked(1); UUID user = p.UUID; int imagethrottle = ExtractImageThrottle(throttles); PollServiceTextureEventArgs args; if (m_pollservices.TryGetValue(user,out args)) { args.UpdateThrottle(imagethrottle); } } public void PostInitialise() { } public void Close() { } public string Name { get { return "GetTextureModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion ~GetTextureModule() { foreach (Thread t in m_workerThreads) Watchdog.AbortThread(t.ManagedThreadId); } private class PollServiceTextureEventArgs : PollServiceEventArgs { private List<Hashtable> requests = new List<Hashtable>(); private Dictionary<UUID, aPollResponse> responses = new Dictionary<UUID, aPollResponse>(); private Scene m_scene; private CapsDataThrottler m_throttler = new CapsDataThrottler(100000, 1400000,10000); public PollServiceTextureEventArgs(UUID pId, Scene scene) : base(null, "", null, null, null, pId, int.MaxValue) { m_scene = scene; // x is request id, y is userid HasEvents = (x, y) => { lock (responses) { bool ret = m_throttler.hasEvents(x, responses); m_throttler.ProcessTime(); return ret; } }; GetEvents = (x, y) => { lock (responses) { try { return responses[x].response; } finally { responses.Remove(x); } } }; // x is request id, y is request data hashtable Request = (x, y) => { aPollRequest reqinfo = new aPollRequest(); reqinfo.thepoll = this; reqinfo.reqID = x; reqinfo.request = y; reqinfo.send503 = false; lock (responses) { if (responses.Count > 0) { if (m_queue.Count >= 4) { // Never allow more than 4 fetches to wait reqinfo.send503 = true; } } } m_queue.Enqueue(reqinfo); }; // this should never happen except possible on shutdown NoEvents = (x, y) => { /* lock (requests) { Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString()); requests.Remove(request); } */ Hashtable response = new Hashtable(); response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; return response; }; } public void Process(aPollRequest requestinfo) { Hashtable response; UUID requestID = requestinfo.reqID; if (requestinfo.send503) { response = new Hashtable(); response["int_response_code"] = 503; response["str_response_string"] = "Throttled"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; Hashtable headers = new Hashtable(); headers["Retry-After"] = 30; response["headers"] = headers; lock (responses) responses[requestID] = new aPollResponse() {bytes = 0, response = response}; return; } // If the avatar is gone, don't bother to get the texture if (m_scene.GetScenePresence(Id) == null) { response = new Hashtable(); response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; lock (responses) responses[requestID] = new aPollResponse() {bytes = 0, response = response}; return; } response = m_getTextureHandler.Handle(requestinfo.request); lock (responses) { responses[requestID] = new aPollResponse() { bytes = (int) response["int_bytes"], response = response }; } m_throttler.ProcessTime(); } internal void UpdateThrottle(int pimagethrottle) { m_throttler.ThrottleBytes = pimagethrottle; } } private void RegisterCaps(UUID agentID, Caps caps) { if (m_Url == "localhost") { string capUrl = "/CAPS/" + UUID.Random() + "/"; // Register this as a poll service PollServiceTextureEventArgs args = new PollServiceTextureEventArgs(agentID, m_scene); args.Type = PollServiceEventArgs.EventType.Texture; MainServer.Instance.AddPollServiceHTTPHandler(capUrl, args); string hostName = m_scene.RegionInfo.ExternalHostName; uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port; string protocol = "http"; if (MainServer.Instance.UseSSL) { hostName = MainServer.Instance.SSLCommonName; port = MainServer.Instance.SSLPort; protocol = "https"; } IExternalCapsModule handler = m_scene.RequestModuleInterface<IExternalCapsModule>(); if (handler != null) handler.RegisterExternalUserCapsHandler(agentID, caps, "GetTexture", capUrl); else caps.RegisterHandler("GetTexture", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl)); m_pollservices[agentID] = args; m_capsDict[agentID] = capUrl; } else { caps.RegisterHandler("GetTexture", m_Url); } } private void DeregisterCaps(UUID agentID, Caps caps) { PollServiceTextureEventArgs args; MainServer.Instance.RemoveHTTPHandler("", m_Url); m_capsDict.Remove(agentID); if (m_pollservices.TryGetValue(agentID, out args)) { m_pollservices.Remove(agentID); } } private void DoTextureRequests() { while (true) { aPollRequest poolreq = m_queue.Dequeue(); poolreq.thepoll.Process(poolreq); } } internal sealed class CapsDataThrottler { private volatile int currenttime = 0; private volatile int lastTimeElapsed = 0; private volatile int BytesSent = 0; private int oversizedImages = 0; public CapsDataThrottler(int pBytes, int max, int min) { ThrottleBytes = pBytes; lastTimeElapsed = Util.EnvironmentTickCount(); } public bool hasEvents(UUID key, Dictionary<UUID, GetTextureModule.aPollResponse> responses) { PassTime(); // Note, this is called IN LOCK bool haskey = responses.ContainsKey(key); if (!haskey) { return false; } GetTextureModule.aPollResponse response; if (responses.TryGetValue(key, out response)) { // This is any error response if (response.bytes == 0) return true; // Normal if (BytesSent + response.bytes <= ThrottleBytes) { BytesSent += response.bytes; //TimeBasedAction timeBasedAction = new TimeBasedAction { byteRemoval = response.bytes, requestId = key, timeMS = currenttime + 1000, unlockyn = false }; //m_actions.Add(timeBasedAction); return true; } // Big textures else if (response.bytes > ThrottleBytes && oversizedImages <= ((ThrottleBytes % 50000) + 1)) { Interlocked.Increment(ref oversizedImages); BytesSent += response.bytes; //TimeBasedAction timeBasedAction = new TimeBasedAction { byteRemoval = response.bytes, requestId = key, timeMS = currenttime + (((response.bytes % ThrottleBytes)+1)*1000) , unlockyn = false }; //m_actions.Add(timeBasedAction); return true; } else { return false; } } return haskey; } public void ProcessTime() { PassTime(); } private void PassTime() { currenttime = Util.EnvironmentTickCount(); int timeElapsed = Util.EnvironmentTickCountSubtract(currenttime, lastTimeElapsed); //processTimeBasedActions(responses); if (Util.EnvironmentTickCountSubtract(currenttime, timeElapsed) >= 1000) { lastTimeElapsed = Util.EnvironmentTickCount(); BytesSent -= ThrottleBytes; if (BytesSent < 0) BytesSent = 0; if (BytesSent < ThrottleBytes) { oversizedImages = 0; } } } public int ThrottleBytes; } } }
// Copyright 2020 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 // // 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 CommandLine; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V10.Errors; using Google.Ads.GoogleAds.V10.Services; using Google.Protobuf.Collections; using System; using System.Collections.Generic; using System.Linq; using static Google.Ads.GoogleAds.V10.Enums.ExtensionTypeEnum.Types; namespace Google.Ads.GoogleAds.Examples.V10 { /// <summary> /// Removes the entire sitelink campaign extension setting by removing both the sitelink /// campaign extension setting itself and its associated sitelink extension feed items. This /// requires two steps, since removing the campaign extension setting doesn't automatically /// remove its extension feed items. /// /// To make this example work with other types of extensions, find references to 'Sitelink' and /// replace it with the extension type you wish to remove. /// </summary> public class RemoveEntireSitelinkCampaignExtensionSetting : ExampleBase { /// <summary> /// Command line options for running the /// <see cref="RemoveEntireSitelinkCampaignExtensionSetting"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The Google Ads customer ID. /// </summary> [Option("customerId", Required = true, HelpText = "The Google Ads customer ID.")] public long CustomerId { get; set; } /// <summary> /// ID of the campaign from which sitelinks will be removed. /// </summary> [Option("campaignId", Required = true, HelpText = "ID of the campaign from which sitelinks will be removed.")] public long CampaignId { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = new Options(); CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult( delegate (Options o) { options = o; return 0; }, delegate (IEnumerable<Error> errors) { // The Google Ads customer ID. options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); // ID of the campaign from which sitelinks will be removed. options.CampaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE"); return 0; }); RemoveEntireSitelinkCampaignExtensionSetting codeExample = new RemoveEntireSitelinkCampaignExtensionSetting(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "Removes the entire sitelink campaign extension setting by removing both the" + " sitelink campaign extension setting itself and its associated sitelink extension " + "feed items. This requires two steps, since removing the campaign extension setting " + "doesn't automatically remove its extension feed items.\n\n" + "To make this example work with other types of extensions, find " + "references to 'Sitelink' and replace it with the extension type you wish to remove."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="campaignId">ID of the campaign from which sitelinks will be removed. /// </param> // [START remove_entire_sitelink_campaign_extension_setting] public void Run(GoogleAdsClient client, long customerId, long campaignId) { // Get the GoogleAdsService client. GoogleAdsServiceClient googleAdsServiceClient = client.GetService(Services.V10.GoogleAdsService); List<MutateOperation> mutateOperations = new List<MutateOperation>(); try { // Create a mutate operation the contains the campaign extension setting operation // to remove the specified sitelink campaign extension setting. mutateOperations.Add( CreateSitelinkCampaignExtensionSettingMutateOperation(customerId, campaignId)); // Get all sitelink extension feed items of the specified campaign. List<string> extensionFeedItemResourceNames = GetAllSitelinkExtensionFeedItems(googleAdsServiceClient, customerId, campaignId); // Create mutate operations, each of which contains an extension feed item // operation to remove the specified extension feed items. mutateOperations.AddRange(CreateExtensionFeedItemMutateOperations( extensionFeedItemResourceNames)); // Issue a mutate request to remove the campaign extension setting and its // extension feed items. MutateGoogleAdsResponse mutateGoogleAdsResponse = googleAdsServiceClient.Mutate( customerId .ToString(), mutateOperations); RepeatedField<MutateOperationResponse> mutateOpResponses = mutateGoogleAdsResponse.MutateOperationResponses; // Print the information on the removed campaign extension setting and its // extension feed items. // Each mutate operation response is returned in the same order as we passed its // corresponding operation. Therefore, the first belongs to the campaign setting // operation, and the rest belong to the extension feed item operations. Console.WriteLine("Removed a campaign extension setting with resource name: " + $"'{mutateOpResponses.First().CampaignExtensionSettingResult.ResourceName}'."); foreach (MutateOperationResponse response in mutateOpResponses.Skip(1)) { Console.WriteLine("Removed an extension feed item with resource name: " + $"'{response.ExtensionFeedItemResult.ResourceName}'."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } catch (ArgumentException e) { Console.WriteLine("Argument Exception:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine(e.StackTrace); throw; } } // [END remove_entire_sitelink_campaign_extension_setting] /// <summary> /// Creates a mutate operation for the sitelink campaign extension setting that will be /// removed. /// </summary> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="campaignId">The campaign ID from which the sitelink campaign extension /// setting will be removed.</param> /// <returns>The mutate operation for the sitelink campaign extension setting.</returns> private MutateOperation CreateSitelinkCampaignExtensionSettingMutateOperation( in long customerId, in long campaignId) { // Construct the resource name of the campaign extension setting to remove. string campaignExtensionSettingResourceName = ResourceNames.CampaignExtensionSetting (customerId, campaignId, ExtensionType.Sitelink); Console.WriteLine($"***name: {campaignExtensionSettingResourceName}"); // Create a campaign extension setting operation. CampaignExtensionSettingOperation campaignExtensionSettingOperation = new CampaignExtensionSettingOperation { Remove = campaignExtensionSettingResourceName }; // Create and return a mutate operation for the campaign extension setting operation. return new MutateOperation { CampaignExtensionSettingOperation = campaignExtensionSettingOperation }; } /// <summary> /// Return all sitelink extension feed items associated to the specified campaign extension /// setting. /// </summary> /// <param name="googleAdsServiceClient">An initialized Google Ads API Service client. /// </param> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="campaignId">The campaign ID from which to fetch sitelink extension feed /// items.</param> /// <returns>A list of resource names of extension feed items.</returns> // [START remove_entire_sitelink_campaign_extension_setting_1] private List<string> GetAllSitelinkExtensionFeedItems( GoogleAdsServiceClient googleAdsServiceClient, in long customerId, in long campaignId) { // Create a query that retrieves all campaigns. string query = $@" SELECT campaign_extension_setting.campaign, campaign_extension_setting.extension_type, campaign_extension_setting.extension_feed_items FROM campaign_extension_setting WHERE campaign_extension_setting.campaign = '{ResourceNames.Campaign(customerId, campaignId)}' AND campaign_extension_setting.extension_type = 'SITELINK'"; // Issue a search stream request, then iterate over all responses. // Print out and store in a list each extension feed item's resource name. List<string> extensionFeedItemResourceNames = new List<string>(); googleAdsServiceClient.SearchStream(customerId.ToString(), query, delegate (SearchGoogleAdsStreamResponse resp) { foreach (GoogleAdsRow googleAdsRow in resp.Results) { foreach (string extensionFeedItemResourceName in googleAdsRow .CampaignExtensionSetting.ExtensionFeedItems) { extensionFeedItemResourceNames.Add(extensionFeedItemResourceName); Console.WriteLine("Extension feed item with resource name " + $"'{extensionFeedItemResourceName}' was found."); } } } ); if (!extensionFeedItemResourceNames.Any()) { throw new ArgumentException("The specified campaign does not contain a sitelink " + "campaign extension setting."); } return extensionFeedItemResourceNames; } // [END remove_entire_sitelink_campaign_extension_setting_1] /// <summary> /// Creates mutate operations for the sitelink extension feed items that will be removed. /// </summary> /// <param name="extensionFeedItemResourceNames">The extension feed item resource /// names.</param> /// <returns>An array of mutate operations for the extension feed items.</returns> private List<MutateOperation> CreateExtensionFeedItemMutateOperations( List<string> extensionFeedItemResourceNames) { return extensionFeedItemResourceNames .Select(extensionFeedItemResourceName => new ExtensionFeedItemOperation { Remove = extensionFeedItemResourceName }) .Select(extensionFeedItemOperation => new MutateOperation { ExtensionFeedItemOperation = extensionFeedItemOperation }) .ToList(); } } }
// <copyright file="SvdTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Single; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization { /// <summary> /// Svd factorization tests for a dense matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class SvdTests { /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = DenseMatrix.CreateIdentity(order); var factorSvd = matrixI.Svd(); var u = factorSvd.U; var vt = factorSvd.VT; var w = factorSvd.W; Assert.AreEqual(matrixI.RowCount, u.RowCount); Assert.AreEqual(matrixI.RowCount, u.ColumnCount); Assert.AreEqual(matrixI.ColumnCount, vt.RowCount); Assert.AreEqual(matrixI.ColumnCount, vt.ColumnCount); Assert.AreEqual(matrixI.RowCount, w.RowCount); Assert.AreEqual(matrixI.ColumnCount, w.ColumnCount); for (var i = 0; i < w.RowCount; i++) { for (var j = 0; j < w.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0 : 0.0, w[i, j]); } } } /// <summary> /// Can factorize a random matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(10, 6)] [TestCase(50, 48)] [TestCase(100, 98)] public void CanFactorizeRandomMatrix(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var factorSvd = matrixA.Svd(); var u = factorSvd.U; var vt = factorSvd.VT; var w = factorSvd.W; // Make sure the U has the right dimensions. Assert.AreEqual(row, u.RowCount); Assert.AreEqual(row, u.ColumnCount); // Make sure the VT has the right dimensions. Assert.AreEqual(column, vt.RowCount); Assert.AreEqual(column, vt.ColumnCount); // Make sure the W has the right dimensions. Assert.AreEqual(row, w.RowCount); Assert.AreEqual(column, w.ColumnCount); // Make sure the U*W*VT is the original matrix. var matrix = u*w*vt; for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(matrixA[i, j], matrix[i, j], 1e-4); } } } /// <summary> /// Can check rank of a non-square matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(10, 8)] [TestCase(48, 52)] [TestCase(100, 93)] public void CanCheckRankOfNonSquare(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var factorSvd = matrixA.Svd(); var mn = Math.Min(row, column); Assert.AreEqual(factorSvd.Rank, mn); } /// <summary> /// Can check rank of a square matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(9)] [TestCase(50)] [TestCase(90)] public void CanCheckRankSquare(int order) { var matrixA = Matrix<float>.Build.Random(order, order, 1); var factorSvd = matrixA.Svd(); if (factorSvd.Determinant != 0) { Assert.AreEqual(factorSvd.Rank, order); } else { Assert.AreEqual(factorSvd.Rank, order - 1); } } /// <summary> /// Can check rank of a square singular matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanCheckRankOfSquareSingular(int order) { var matrixA = new DenseMatrix(order, order); matrixA[0, 0] = 1; matrixA[order - 1, order - 1] = 1; for (var i = 1; i < order - 1; i++) { matrixA[i, i - 1] = 1; matrixA[i, i + 1] = 1; matrixA[i - 1, i] = 1; matrixA[i + 1, i] = 1; } var factorSvd = matrixA.Svd(); Assert.AreEqual(factorSvd.Determinant, 0); Assert.AreEqual(factorSvd.Rank, order - 1); } /// <summary> /// Solve for matrix if vectors are not computed throws <c>InvalidOperationException</c>. /// </summary> [Test] public void SolveMatrixIfVectorsNotComputedThrowsInvalidOperationException() { var matrixA = Matrix<float>.Build.Random(10, 10, 1); var factorSvd = matrixA.Svd(false); var matrixB = Matrix<float>.Build.Random(10, 10, 1); Assert.That(() => factorSvd.Solve(matrixB), Throws.InvalidOperationException); } /// <summary> /// Solve for vector if vectors are not computed throws <c>InvalidOperationException</c>. /// </summary> [Test] public void SolveVectorIfVectorsNotComputedThrowsInvalidOperationException() { var matrixA = Matrix<float>.Build.Random(10, 10, 1); var factorSvd = matrixA.Svd(false); var vectorb = Vector<float>.Build.Random(10, 1); Assert.That(() => factorSvd.Solve(vectorb), Throws.InvalidOperationException); } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(9, 10)] [TestCase(50, 50)] [TestCase(90, 100)] public void CanSolveForRandomVector(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var vectorb = Vector<float>.Build.Random(row, 1); var resultx = factorSvd.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(4, 4)] [TestCase(7, 8)] [TestCase(10, 10)] [TestCase(45, 50)] [TestCase(80, 100)] public void CanSolveForRandomMatrix(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var matrixB = Matrix<float>.Build.Random(row, column, 1); var matrixX = factorSvd.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(9, 10)] [TestCase(50, 50)] [TestCase(90, 100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var vectorb = Vector<float>.Build.Random(row, 1); var vectorbCopy = vectorb.Clone(); var resultx = new DenseVector(column); factorSvd.Solve(vectorb, resultx); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(4, 4)] [TestCase(7, 8)] [TestCase(10, 10)] [TestCase(45, 50)] [TestCase(80, 100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int column) { var matrixA = Matrix<float>.Build.Random(row, column, 1); var matrixACopy = matrixA.Clone(); var factorSvd = matrixA.Svd(); var matrixB = Matrix<float>.Build.Random(row, column, 1); var matrixBCopy = matrixB.Clone(); var matrixX = new DenseMatrix(column, column); factorSvd.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1e-4); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Tests { public class HttpWebRequestTest { private const string RequestBody = "This is data to POST."; private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody); private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain"); private HttpWebRequest _savedHttpWebRequest = null; private WebHeaderCollection _savedResponseHeaders = null; private Exception _savedRequestStreamException = null; private Exception _savedResponseException = null; private int _requestStreamCallbackCallCount = 0; private int _responseCallbackCallCount = 0; private readonly ITestOutputHelper _output; public readonly static object[][] EchoServers = HttpTestServers.EchoServers; public HttpWebRequestTest(ITestOutputHelper output) { _output = output; } [Theory, MemberData("EchoServers")] public void Ctor_VerifyDefaults_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Null(request.Accept); Assert.False(request.AllowReadStreamBuffering); Assert.Null(request.ContentType); Assert.Equal(350, request.ContinueTimeout); Assert.Null(request.CookieContainer); Assert.Null(request.Credentials); Assert.False(request.HaveResponse); Assert.NotNull(request.Headers); Assert.Equal(0, request.Headers.Count); Assert.Equal("GET", request.Method); Assert.NotNull(request.Proxy); Assert.Equal(remoteServer, request.RequestUri); Assert.True(request.SupportsCookieContainer); Assert.False(request.UseDefaultCredentials); } [Theory, MemberData("EchoServers")] public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer) { string remoteServerString = remoteServer.ToString(); HttpWebRequest request = WebRequest.CreateHttp(remoteServerString); Assert.NotNull(request); } [Theory, MemberData("EchoServers")] public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request); } [Theory, MemberData("EchoServers")] public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string acceptType = "*/*"; request.Accept = acceptType; Assert.Equal(acceptType, request.Accept); } [Theory, MemberData("EchoServers")] public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = string.Empty; Assert.Null(request.Accept); } [Theory, MemberData("EchoServers")] public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = null; Assert.Null(request.Accept); } [Theory, MemberData("EchoServers")] public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowReadStreamBuffering = false; Assert.False(request.AllowReadStreamBuffering); } [Theory, MemberData("EchoServers")] public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowReadStreamBuffering = true; Assert.True(request.AllowReadStreamBuffering); } [Theory, MemberData("EchoServers")] public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } long length = response.ContentLength; Assert.Equal(strContent.Length, length); } [Theory, MemberData("EchoServers")] public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string myContent = "application/x-www-form-urlencoded"; request.ContentType = myContent; Assert.Equal(myContent, request.ContentType); } [Theory, MemberData("EchoServers")] public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContentType = string.Empty; Assert.Null(request.ContentType); } [Theory, MemberData("EchoServers")] public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = 0; Assert.Equal(0, request.ContinueTimeout); } [Theory, MemberData("EchoServers")] public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = -1; } [Theory, MemberData("EchoServers")] public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<ArgumentOutOfRangeException>(() => request.ContinueTimeout = -2); } [Theory, MemberData("EchoServers")] public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = CredentialCache.DefaultCredentials; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData("EchoServers")] public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; Assert.Equal(_explicitCredential, request.Credentials); } [Theory, MemberData("EchoServers")] public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = true; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData("EchoServers")] public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = false; Assert.Equal(null, request.Credentials); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Head.Method; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = "CONNECT"; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Method = "POST"; IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetRequestStream(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetRequestStream(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetResponse(null, null); }); } [Theory, MemberData("EchoServers")] public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } [Theory, MemberData("EchoServers")] public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Stream requestStream; using (requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } Assert.Throws<ArgumentException>(() => { var sr = new StreamReader(requestStream); }); } [Theory, MemberData("EchoServers")] public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Stream requestStream = await request.GetRequestStreamAsync(); Assert.NotNull(requestStream); } [Theory, MemberData("EchoServers")] public async Task GetResponseAsync_GetResponseStream_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.NotNull(response.GetResponseStream()); } [Theory, MemberData("EchoServers")] public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); Assert.NotNull(myStream); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } Assert.True(strContent.Contains("\"Host\": \"" + HttpTestServers.Host + "\"")); } [Theory, MemberData("EchoServers")] public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } Assert.True(strContent.Contains(RequestBody)); } [Theory, MemberData("EchoServers")] public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.UseDefaultCredentials = true; WebResponse response = await request.GetResponseAsync(); } [OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses [Fact] public void GetResponseAsync_ServerNameNotInDns_ThrowsWebException() { string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString()); HttpWebRequest request = WebRequest.CreateHttp(serverUrl); WebException ex = Assert.Throws<WebException>(() => request.GetResponseAsync().GetAwaiter().GetResult()); Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status); } public static object[][] StatusCodeServers = { new object[] { HttpTestServers.StatusCodeUri(false, 404) }, new object[] { HttpTestServers.StatusCodeUri(true, 404) }, }; [Theory, MemberData("StatusCodeServers")] public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync()); Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status); } [Theory, MemberData("EchoServers")] public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.True(request.HaveResponse); } [Theory, MemberData("EchoServers")] public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); String headersString = response.Headers.ToString(); string headersPartialContent = "Content-Type: application/json"; Assert.True(headersString.Contains(headersPartialContent)); } [Theory, MemberData("EchoServers")] public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; Assert.Equal(HttpMethod.Get.Method, request.Method); } [Theory, MemberData("EchoServers")] public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Assert.Equal(HttpMethod.Post.Method, request.Method); } [Theory, MemberData("EchoServers")] public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request.Proxy); } [Theory, MemberData("EchoServers")] public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Equal(remoteServer, request.RequestUri); } [Theory, MemberData("EchoServers")] public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.Equal(remoteServer, response.ResponseUri); } [Theory, MemberData("EchoServers")] public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.True(request.SupportsCookieContainer); } [Theory, MemberData("EchoServers")] public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Theory, MemberData("EchoServers")] public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Theory, MemberData("EchoServers")] public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } _output.WriteLine(responseBody); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(responseBody.Contains("Content-Type")); } [Theory, MemberData("EchoServers")] public void Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Method = "POST"; _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(RequestStreamCallback), null); _savedHttpWebRequest.Abort(); _savedHttpWebRequest = null; WebException wex = _savedRequestStreamException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); } [Theory, MemberData("EchoServers")] public void Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); Assert.Equal(1, _responseCallbackCallCount); } [Theory, MemberData("EchoServers")] public void Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); WebException wex = _savedResponseException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); } [Theory, MemberData("EchoServers")] public void Abort_BeginGetResponseUsingNoCallbackThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(null, null); _savedHttpWebRequest.Abort(); } [Theory, MemberData("EchoServers")] public void Abort_CreateRequestThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Abort(); } private void RequestStreamCallback(IAsyncResult asynchronousResult) { _requestStreamCallbackCallCount++; try { Stream stream = (Stream)_savedHttpWebRequest.EndGetRequestStream(asynchronousResult); stream.Dispose(); } catch (Exception ex) { _savedRequestStreamException = ex; } } private void ResponseCallback(IAsyncResult asynchronousResult) { _responseCallbackCallCount++; try { using (HttpWebResponse response = (HttpWebResponse)_savedHttpWebRequest.EndGetResponse(asynchronousResult)) { _savedResponseHeaders = response.Headers; } } catch (Exception ex) { _savedResponseException = ex; } } } }
using System.Collections.Generic; using System.Diagnostics; using System.IO; using Newtonsoft.Json.Linq; public class Game { public const int MAXTICKS = 200; private Scorer scorer; private CombatResolver combat; public Game() { GameWorld = new World("maps.csv"); Manager = new ArmyManager(); scorer = new Scorer(); combat = new CombatResolver(Manager); Players = new List<Player>(); CurrentPlayerIndex = 0; } public World GameWorld { get; private set; } public List<Player> Players { get; private set; } public ArmyManager Manager { get; private set; } public bool Finished { get; private set; } public int Ticks { get; private set; } public Player CurrentPlayer { get { return Players[CurrentPlayerIndex]; } } public int CurrentPlayerIndex { get; private set; } public static Game LoadFromFile(string filename) { return FromJSON(File.ReadAllText(filename)); } public static Game FromJSON(string input) { var data = JObject.Parse(input); var result = new Game(); result.CurrentPlayerIndex = data.GetValue("current").ToObject<int>(); result.Ticks = data.GetValue("ticks").ToObject<int>(); result.Finished = data.GetValue("finished").ToObject<bool>(); foreach (JObject playerJSON in (JArray)data.GetValue("players")) { var player = new Player(result.Manager, playerJSON.GetValue("color").ToObject<Color>()); player.Resources.Add(playerJSON.GetValue("resources").ToObject<ResourceBag>()); foreach (JObject armyJSON in (JArray)playerJSON.GetValue("armies")) { var army = armyJSON.GetValue("army").ToObject<Army>(); player.AddArmy(army, armyJSON.GetValue("origin").ToObject<Pos>()); var dest = armyJSON.GetValue("destination"); if (dest != null) { result.Manager.MoveArmy(army, dest.ToObject<Pos>()); } } result.Players.Add(player); } var ownersArray = (JArray)data.GetValue("owners"); for (int x = 0; x < World.WIDTH; x++) { for (int y = 0; y < World.HEIGHT; y++) { var playerNumber = ownersArray[(x * World.HEIGHT) + y].ToObject<int>(); if (playerNumber == -1) { result.GameWorld.GetProvinceAt(new Pos(x, y)).Owner = null; } else { result.GameWorld.GetProvinceAt(new Pos(x, y)).Owner = result.Players[playerNumber]; } } } return result; } public static Game DefaultGame() { var result = new Game(); result.Players.Add(new Player(result.Manager, Color.RED)); result.Players.Add(new Player(result.Manager, Color.BLUE)); result.Players[0].AddArmy(new Army(100), new Pos(0, 0)); result.Players[1].AddArmy(new Army(100), new Pos(1, 1)); return result; } public void AdvancePlayer() { CurrentPlayerIndex = (CurrentPlayerIndex + 1) % Players.Count; } public void Tick() { GameWorld.Tick(); Manager.Tick(); foreach (var player in Players) { player.Tick(); } combat.Engage(CurrentPlayer, Players); foreach (var player in Players) { foreach (var army in player.ArmyList) { if (army.Health > 0) { GameWorld.GetProvinceAt(Manager.ArmyPosition(army)).Owner = player; } } } scorer.UpdateScores(GameWorld); Ticks += 1; } public void EndTurn() { if (WinCondition() < 0) { Tick(); AdvancePlayer(); } else { Finished = true; } } public int ScorePlayer(Player player) { return scorer.GetScore(player); } public string SerializeJSON() { var root = new JObject(); var playersArray = new JArray(); var ownersArray = new JArray(); root.Add("ticks", Ticks); root.Add("players", playersArray); root.Add("owners", ownersArray); root.Add("current", new JValue(CurrentPlayerIndex)); root.Add("finished", new JValue(Finished)); foreach (var player in Players) { var playerObject = new JObject(); var armyArray = new JArray(); playerObject.Add("color", JObject.FromObject(player.Color)); playerObject.Add("resources", JObject.FromObject(player.Resources)); playerObject.Add("armies", armyArray); foreach (var army in player.ArmyList) { var positionedArmy = new JObject(); positionedArmy.Add("army", JObject.FromObject(army)); positionedArmy.Add("origin", JObject.FromObject(Manager.ArmyStartingPosition(army))); if (Manager.HasArmyMoved(army)) { positionedArmy.Add("destination", JObject.FromObject(Manager.ArmyPosition(army))); } armyArray.Add(positionedArmy); } playersArray.Add(playerObject); } for (int x = 0; x < World.WIDTH; x++) { for (int y = 0; y < World.HEIGHT; y++) { ownersArray.Add(new JValue(Players.IndexOf(GameWorld.GetProvinceAt(new Pos(x, y)).Owner))); } } return root.ToString(); } public void SaveToFile() { const string PREFIX = "ww3"; const string SUFFIX = ".json"; var data = SerializeJSON(); var name = PREFIX + System.DateTime.Now.Ticks + SUFFIX; File.WriteAllText(name, data); } public int WinCondition() { int winner = -1; if (Ticks >= MAXTICKS) { var maxScore = int.MinValue; for (int i = 0; i < Players.Count; i++) { var score = scorer.GetScore(Players[i]); if (score > maxScore) { maxScore = score; winner = i; } } } return winner; } }
using System; using System.Collections; using System.IO; using System.Text; using NUnit.Framework; using Raksha.Bcpg; using Raksha.Bcpg.OpenPgp; using Raksha.Crypto; using Raksha.Crypto.Generators; using Raksha.Crypto.Parameters; using Raksha.Security; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; namespace Raksha.Tests.Bcpg.OpenPgp { [TestFixture] public class PgpDsaTest : SimpleTest { private static readonly byte[] testPubKey = Base64.Decode( "mQGiBD9HBzURBACzkxRCVGJg5+Ld9DU4Xpnd4LCKgMq7YOY7Gi0EgK92gbaa6+zQ" + "oQFqz1tt3QUmpz3YVkm/zLESBBtC1ACIXGggUdFMUr5I87+1Cb6vzefAtGt8N5VV" + "1F/MXv1gJz4Bu6HyxL/ncfe71jsNhav0i4yAjf2etWFj53zK6R+Ojg5H6wCgpL9/" + "tXVfGP8SqFvyrN/437MlFSUEAIN3V6j/MUllyrZglrtr2+RWIwRrG/ACmrF6hTug" + "Ol4cQxaDYNcntXbhlTlJs9MxjTH3xxzylyirCyq7HzGJxZzSt6FTeh1DFYzhJ7Qu" + "YR1xrSdA6Y0mUv0ixD5A4nPHjupQ5QCqHGeRfFD/oHzD4zqBnJp/BJ3LvQ66bERJ" + "mKl5A/4uj3HoVxpb0vvyENfRqKMmGBISycY4MoH5uWfb23FffsT9r9KL6nJ4syLz" + "aRR0gvcbcjkc9Z3epI7gr3jTrb4d8WPxsDbT/W1tv9bG/EHawomLcihtuUU68Uej" + "6/wZot1XJqu2nQlku57+M/V2X1y26VKsipolPfja4uyBOOyvbLQzRXJpYyBFY2hp" + "ZG5hIChEU0EgVGVzdCBLZXkpIDxlcmljQGJvdW5jeWNhc3RsZS5vcmc+iFkEExEC" + "ABkFAj9HBzUECwcDAgMVAgMDFgIBAh4BAheAAAoJEM0j9enEyjRDAlwAn2rrom0s" + "MhufWK5vIRwg7gj5qsLEAJ4vnT5dPBVblofsG+pDoCVeJXGGng=="); private static readonly byte[] testPrivKey = Base64.Decode( "lQHhBD9HBzURBACzkxRCVGJg5+Ld9DU4Xpnd4LCKgMq7YOY7Gi0EgK92gbaa6+zQ" + "oQFqz1tt3QUmpz3YVkm/zLESBBtC1ACIXGggUdFMUr5I87+1Cb6vzefAtGt8N5VV" + "1F/MXv1gJz4Bu6HyxL/ncfe71jsNhav0i4yAjf2etWFj53zK6R+Ojg5H6wCgpL9/" + "tXVfGP8SqFvyrN/437MlFSUEAIN3V6j/MUllyrZglrtr2+RWIwRrG/ACmrF6hTug" + "Ol4cQxaDYNcntXbhlTlJs9MxjTH3xxzylyirCyq7HzGJxZzSt6FTeh1DFYzhJ7Qu" + "YR1xrSdA6Y0mUv0ixD5A4nPHjupQ5QCqHGeRfFD/oHzD4zqBnJp/BJ3LvQ66bERJ" + "mKl5A/4uj3HoVxpb0vvyENfRqKMmGBISycY4MoH5uWfb23FffsT9r9KL6nJ4syLz" + "aRR0gvcbcjkc9Z3epI7gr3jTrb4d8WPxsDbT/W1tv9bG/EHawomLcihtuUU68Uej" + "6/wZot1XJqu2nQlku57+M/V2X1y26VKsipolPfja4uyBOOyvbP4DAwIDIBTxWjkC" + "GGAWQO2jy9CTvLHJEoTO7moHrp1FxOVpQ8iJHyRqZzLllO26OzgohbiPYz8u9qCu" + "lZ9Xn7QzRXJpYyBFY2hpZG5hIChEU0EgVGVzdCBLZXkpIDxlcmljQGJvdW5jeWNh" + "c3RsZS5vcmc+iFkEExECABkFAj9HBzUECwcDAgMVAgMDFgIBAh4BAheAAAoJEM0j" + "9enEyjRDAlwAnjTjjt57NKIgyym7OTCwzIU3xgFpAJ0VO5m5PfQKmGJRhaewLSZD" + "4nXkHg=="); private static readonly byte[] testPrivKey2 = Base64.Decode( "lQHhBEAnoewRBADRvKgDhbV6pMzqYfUgBsLxSHzmycpuxGbjMrpyKHDOEemj" + "iQb6TyyBKUoR28/pfshFP9R5urtKIT7wjVrDuOkxYkgRhNm+xmPXW2Lw3D++" + "MQrC5VWe8ywBltz6T9msmChsaKo2hDhIiRI/mg9Q6rH9pJKtVGi4R7CgGxM2" + "STQ5fwCgub38qGS1W2O4hUsa+3gva5gaNZUEAItegda4/H4t88XdWxW3D8pv" + "RnFz26/ADdImVaQlBoumD15VmcgYoT1Djizey7X8vfV+pntudESzLbn3GHlI" + "6C09seH4e8eYP63t7KU/qbUCDomlSswd1OgQ/RxfN86q765K2t3K1i3wDSxe" + "EgSRyGKee0VNvOBFOFhuWt+patXaBADE1riNkUxg2P4lBNWwu8tEZRmsl/Ys" + "DBIzXBshoMzZCvS5PnNXMW4G3SAaC9OC9jvKSx9IEWhKjfjs3QcWzXR28mcm" + "5na0bTxeOMlaPPhBdkTCmFl0IITWlH/pFlR2ah9WYoWYhZEL2tqB82wByzxH" + "SkSeD9V5oeSCdCcqiqkEmv4DAwLeNsQ2XGJVRmA4lld+CR5vRxpT/+/2xklp" + "lxVf/nx0+thrHDpro3u/nINIIObk0gh59+zaEEe3APlHqbQVYWFhIGJiYiA8" + "Y2NjQGRkZC5lZWU+iFoEExECABoFAkAnoewFCwcDAgEDFQIDAxYCAQIeAQIX" + "gAAKCRA5nBpCS63az85BAKCbPfU8ATrFvkXhzGNGlc1BJo6DWQCgnK125xVK" + "lWLpt6ZJJ7TXcx3nkm6wAgAAnQFXBEAnoe0QBACsQxPvaeBcv2TkbgU/5Wc/" + "tO222dPE1mxFbXjGTKfb+6ge96iyD8kTRLrKCkEEeVBa8AZqMSoXUVN6tV8j" + "/zD8Bc76o5iJ6wgpg3Mmy2GxInVfsfZN6/G3Y2ukmouz+CDNvQdUw8cTguIb" + "QoV3XhQ03MLbfVmNcHsku9F4CuKNWwADBQP0DSSe8v5PXF9CSCXOIxBDcQ5x" + "RKjyYOveqoH/4lbOV0YNUbIDZq4RaUdotpADuPREFmWf0zTB6KV/WIiag8XU" + "WU9zdDvLKR483Bo6Do5pDBcN+NqfQ+ntGY9WJ7BSFnhQ3+07i1K+NsfFTRfv" + "hf9X3MP75rCf7MxAIWHTabEmUf4DAwLeNsQ2XGJVRmA8DssBUCghogG9n8T3" + "qfBeKsplGyCcF+JjPeQXkKQaoYGJ0aJz36qFP9d8DuWtT9soQcqIxVf6mTa8" + "kN1594hGBBgRAgAGBQJAJ6HtAAoJEDmcGkJLrdrPpMkAnRyjQSKugz0YJqOB" + "yGasMLQLxd2OAKCEIlhtCarlufVQNGZsuWxHVbU8crACAAA="); private static readonly byte[] sig1 = Base64.Decode( "owGbwMvMwCR4VvnryyOnTJwZ10gncZSkFpfolVSU2Ltz78hIzcnJVyjPL8pJUeTq" + "sGdmZQCJwpQLMq3ayTA/0Fj3xf4jbwPfK/H3zj55Z9L1n2k/GOapKJrvMZ4tLiCW" + "GtP/XeDqX4fORDUA"); private static readonly byte[] sig1crc = Base64.Decode("OZa/"); private static readonly byte[] testPubWithUserAttr = Base64.Decode( "mQGiBD2Rqv0RBADqKCkhVEtB/lEEr/9CubuHEy2oN/yU5j+2GXSdcNdVnRI/rwFy" + "fHEQIk3uU7zHSUKFrC59yDm0sODYyjEdE3BVb0xvEJ5LE/OdndcIMXT1DungZ1vB" + "zIK/3lr33W/PHixYxv9jduH3WrTehBpiKkgMZp8XloSFj2Cnw9LDyfqB7QCg/8K1" + "o2k75NkOd9ZjnA9ye7Ri3bEEAKyr61Mo7viPWBK1joWAEsxG0OBWM+iSlG7kwh31" + "8efgC/7Os6x4Y0jzs8mpcbBjeZtZjS9lRbfp7RinhF269xL0TZ3JxIdtaAV/6yDQ" + "9NXfZY9dskN++HIR/5GCEEgq/qTJZt6ti5k7aV19ZFfO6wiK3NUy08wOrVsdOkVE" + "w9IcBADaplhpcel3201uU3OCboogJtw81R5MJMZ4Y9cKL/ca2jGISn0nA7KrAw9v" + "ShheSixGO4BV9JECkLEbtg7i+W/j/De6S+x2GLNcphuTP3UmgtKbhs0ItRqzW561" + "s6gLkqi6aWmgaFLd8E1pMJcd9DSY95P13EYB9VJIUxFNUopzo7QcUmFsZiBIYXVz" + "ZXIgPGhhdXNlckBhY20ub3JnPokAWAQQEQIAGAUCPZGq/QgLAwkIBwIBCgIZAQUb" + "AwAAAAAKCRAqIBiOh4JvOKg4AJ9j14yygOqqzqiLKeaasIzqT8LCIgCggx14WuLO" + "wOUTUswTaVKMFnU7tseJAJwEEAECAAYFAj2Rqx8ACgkQ9aWTKMpUDFV+9QP/RiWT" + "5FAF5Rgb7beaApsgXsME+Pw7HEYFtqGa6VcXEpbcUXO6rjaXsgMgY90klWlWCF1T" + "HOyKITvj2FdhE+0j8NQn4vaGpiTwORW/zMf/BZ0abdSWQybp10Yjs8gXw30UheO+" + "F1E524MC+s2AeUi2hwHMiS+AVYd4WhxWHmWuBpTRypP/AAALTgEQAAEBAAAAAQAA" + "AAABAAAA/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQ" + "Dg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/" + "2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7" + "Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCABqAF0DASIAAhEBAxEB/8QAHwAAAQUB" + "AQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQID" + "AAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0" + "NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKT" + "lJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl" + "5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL" + "/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHB" + "CSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpj" + "ZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3" + "uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIR" + "AxEAPwD2aiiq9xcxWsRllcKqjOT06E/0oAsVm6jrmm6VGXvLuOPGflz8x+grzXxV" + "8U51u5LXRgBGowZHXknnkc9OQcV51caneXdw9xPOXlckl2AJHY4J6cD1oA9J1z4p" + "TRkrYQhRyQ0hIY5/2QRx7k9ulczN8SvEEshdZkX0UorDrznI759a5Mksckkknqec" + "mkoA7WD4oavEoEttbTepYEZ+mCMVv6H8SLTULhbe/gFozAYkD5Unp3Ax/kV5XRQB" + "9EAhgCDkHkEcgilryTwd4zn0m4WzvpTJZSMBuY5MfbueletKyugZWDKwyCOc/j3o" + "AduyWLDeWB5Ynj8jSUUUAdFXn/xU15dO0RbGGYC5uWwUB6L1Jx+n413F1cJa2stz" + "J92JC5+gGa+bdfvp9S1q4urmRneQg5Yk4HGAPYZoAzySxySSSep5yaSvQvAPhOHU" + "rB7u5iLGUlIwQRx7HPr/AJ9LGsfC+dJGngc+X12gc8nvx1/rQB5rRXS3Xg28t9ye" + "VLvA7Ddj8MDt6Vnx6JKJCsocnBwqqQSOxPH+fWgDKorTl0SaLGXxkZ+ZcZ4z1yfb" + "P1qg0MqLueN1A6kqRigCOvVPh74mF9YjS7tgLi3GIm6b17c+oOfrXlda3haeW38R" + "WjxfeMgBOCcD/PHpzQB7nRRRQBqarZjUNLubPJXz4yhI64PFfO3iDRrnRtdm0+cq" + "0ocEbehzyOv1xX0vXnHxU8Kf2hYf23aRk3VsMTAZO6MZ5x7UAbfga1W00WzjRSF8" + "kbsg5z744HT/ADmuoysikdQSVP8AI1yPgq6il0axk27V8sDcTg5x7V1qSxOcJIrH" + "/ZOaAKV5p8JgJSPJGMr97PNcxqOiRXLiRI8nONoIGO55z/8AqyeldhPcQxwyOzoQ" + "owRkflXH6t4q0nTLjy57mNXfJCA5x+Qx0NAGXd6LD5iiaPYwTAAx07+vXvXOXmiR" + "Qu6u5VTk/MQQV7cdvxPT866KbxTpt7HGR8p7SMw5HuOP8/Ws/ULlb2No0bKMOGBJ" + "BHrjHHXn6D8QDzWZQk8iAYVWIA9K6LwDZNeeJ4sEqsaF2YHBHpz2/wA/WsG+V0vZ" + "kkGGVsEZz9OcntXffC62iiS7vJTsklKxRFuAw6nBP+eKAPRKKKKAOiqOSNJYzHIo" + "ZGGCD0NSUUAeRajIunwzQG4e3tYZTHGsPzOxJ6ADuQcH8Pw5v+19Q0rVJVgl1JG3" + "cxykEj13cnHT1r1C38OQ3l063cIkkhmkZDKSeCfx9R/kVLeeGIRKs7hVVDn5OCx9" + "yeTjqMf0oAo3k1xP4biuJFeKV4w7gDaQcen1/wAjt5gbK81HW41kIiJBZppULe47" + "eoxx+YzivW9Vh/0FAE+XPIJGCOR0rnbPT7eG+LyxlkAG1wQSPXrjvg9MfjQBycNj" + "4hMRZgJkUjETQqAy/UAY6DoO/wCNbVlYTNbSNJbmBlBwoUfM30B7j2/lz20VhbKA" + "wHmZOQWbOfyrO1G3jil8tBhWToOcdu+c/wAvagDzbUdGlu9aRxFiB/vsuBggZOfq" + "cfWujSIR2dnNZTEeXKgMcb4BUHjofbjNKmI5juiabaGGxVJLcdh/nFWtI0oxagsD" + "DIkkWXYp4VQDnOemSfyHbigDtgSQMjBI6HqKKKKAOiopoPXjGKdQBnXLiDUI5SMK" + "VwxHGf8APFUtW1A+YkMKmbnc23njuf6D/ObWquoaNSQCM/rwP1rMYxxTGWR1UsoU" + "biAcdep+o/KgDG1LxdpracIirCVRjaykHr6cHGQe1cv/AGjNcXBW3sntyT/rHcjj" + "Hp6Z+nQdAK6PXIdIvcE3Fv5rEfNgP9eRn8c8d/rgzX2i2sqo1y8745CD5WPseOnH" + "f8aANiz1O9gjiR5FMUhAV1wcH0Ix6jHHSrMsskz7pGy2MZNc8PEEM7xxWsM/lr8r" + "b4jtI9CcHt7nr7Vqi4JuEjB2qse9y2Ace47dRn/OQDMuRMl8RHw7SgDBPGT6jpwf" + "yzXa2NmbYF3IMrDB2kkAe3HP5Vwk99u1hdg3ANuOOOB0z6ZwPz6c8eiAhgCDkHkE" + "cgigBaKKKAOiqJiMEb9mBknjim3LFIGcOU285ArNa8mKIN3QclScn6+/FADL9xOc" + "K2Tj7xAxnAwQPqOmawdSNpeSJBfQyGNXwQpIAPvjqOPyPT12nYsxYnJIGSeMnHP+" + "e9UL7TUumEqOYp1GNw6N/vDv/wDXoA5+70vSbFGlhtopUxkBl3EZ45z7/kKwTdpN" + "cIsOmeSCduUiCnB9cdeg/M/j0v8AbFtY5hu0gjmGSRICT19cdMDt3+lULzxPZGZv" + "LXcBnCrwB6Y4PX+ZoAptMRbiMDAGSSMksf8A9Q6DuKzJtVYs+BvcPgMTkEdOTnrx" + "/KoLzVmvZZQjjaT82DyPbqcdx+GKitLf7TNsLYAGWPfH+TQBcsYJDE0rOyu4wjHk" + "gfQ+p/zzWjpnja5sdSOm6yyK0Z2pMCQjZ+6SM9CCMdhnp3E1hYy393FaW0eXfjAx" + "gAdT26D+X4Vg/EuFLbxOsCYBitkQkEdsgcADsB+lAHplvqUbsu5vlYA5PIB7468e" + "nPf8lfUlDkRRrIvqZNn6EV41o3iO/wBFcCJ/MhBP7pjwD6g9ua7G08b6TcRl7h5L" + "eTPKvGz5+hUH9cUAeo3uFDrt+Y4O7HOOB69Pr/8AXqhUlx/r2/z2qOgBCQoJJwBy" + "SeABXHeIfHVvbXcemaW4luHlVJJlIKxjODgg8nqKq/Em6uItOhWOeVAx5CuRnrXn" + "+jf8hyw/6+Y//QhQB6xrmlxzXc0NyuHVyQcdjnBz379D1BGeK5u88LMJGlt2RlX7" + "qkEsPXn6/pXo/ilVzbttG7DDOOeornqAONbRpI4v3pKOQcAqQD+Y/P6j052NK0p5" + "HWHy3IBPyqrfN6gZz+P4/hpXoGzOOiP/ACNdH4XRftsp2jIBxx70AX9E0pdMtvMm" + "VRNt5xyEGOgPf3NeDeLdVOs+J768zlGkKx+yjgfy/WvoPXeNEvMcfujXzJQAUUUU" + "Af/ZiQBGBBARAgAGBQI9katEAAoJECogGI6Hgm84xz8AoNGz1fJrVPxqkBrUDmWA" + "GsP6qVGYAJ0ZOftw/GfQHzdGR8pOK85DLUPEErQkUmFsZiBIYXVzZXIgPGhhdXNl" + "ckBwcml2YXNwaGVyZS5jb20+iQBGBBARAgAGBQI9katmAAoJECogGI6Hgm84m0oA" + "oJS3CTrgpqRZfhgPtHGtUVjRCJbbAJ9stJgPcbqA2xXEg9yl2TQToWdWxbQkUmFs" + "ZiBIYXVzZXIgPGhhdXNlckBwcml2YXNwaGVyZS5vcmc+iQBGBBARAgAGBQI9kauJ" + "AAoJECogGI6Hgm84GfAAnRswktLMzDfIjv6ni76Qp5B850byAJ90I0LEHOLhda7r" + "kqTwZ8rguNssUrQkUmFsZiBIYXVzZXIgPGhhdXNlckBwcml2YXNwaGVyZS5uZXQ+" + "iQBGBBARAgAGBQI9kaubAAoJECogGI6Hgm84zi0An16C4s/B9Z0/AtfoN4ealMh3" + "i3/7AJ9Jg4GOUqGCGRRKUA9Gs5pk8yM8GbQmUmFsZiBDLiBIYXVzZXIgPHJhbGZo" + "YXVzZXJAYmx1ZXdpbi5jaD6JAEYEEBECAAYFAj2Rq8oACgkQKiAYjoeCbzhPOACg" + "iiTohKuIa66FNiI24mQ+XR9nTisAoLmh3lJf16/06qLPsRd9shTkLfmHtB9SYWxm" + "IEhhdXNlciA8cmFsZmhhdXNlckBnbXguY2g+iQBGBBARAgAGBQI9kavvAAoJECog" + "GI6Hgm84ZE8An0RlgL8mPBa/P08S5e/lD35MlDdgAJ99pjCeY46S9+nVyx7ACyKO" + "SZ4OcLQmUmFsZiBIYXVzZXIgPGhhdXNlci5yYWxmQG15c3VucmlzZS5jaD6JAEYE" + "EBECAAYFAj2RrEEACgkQKiAYjoeCbzjz0wCg+q801XrXk+Rf+koSI50MW5OaaKYA" + "oKOVA8SLxE29qSR/bJeuW0ryzRLqtCVSYWxmIEhhdXNlciA8aGF1c2VyLnJhbGZA" + "ZnJlZXN1cmYuY2g+iQBGBBARAgAGBQI9kaxXAAoJECogGI6Hgm848zoAnRBtWH6e" + "fTb3is63s8J2zTfpsyS0AKDxTjl+ZZV0COHLrSCaNLZVcpImFrkEDQQ9kar+EBAA" + "+RigfloGYXpDkJXcBWyHhuxh7M1FHw7Y4KN5xsncegus5D/jRpS2MEpT13wCFkiA" + "tRXlKZmpnwd00//jocWWIE6YZbjYDe4QXau2FxxR2FDKIldDKb6V6FYrOHhcC9v4" + "TE3V46pGzPvOF+gqnRRh44SpT9GDhKh5tu+Pp0NGCMbMHXdXJDhK4sTw6I4TZ5dO" + "khNh9tvrJQ4X/faY98h8ebByHTh1+/bBc8SDESYrQ2DD4+jWCv2hKCYLrqmus2UP" + "ogBTAaB81qujEh76DyrOH3SET8rzF/OkQOnX0ne2Qi0CNsEmy2henXyYCQqNfi3t" + "5F159dSST5sYjvwqp0t8MvZCV7cIfwgXcqK61qlC8wXo+VMROU+28W65Szgg2gGn" + "VqMU6Y9AVfPQB8bLQ6mUrfdMZIZJ+AyDvWXpF9Sh01D49Vlf3HZSTz09jdvOmeFX" + "klnN/biudE/F/Ha8g8VHMGHOfMlm/xX5u/2RXscBqtNbno2gpXI61Brwv0YAWCvl" + "9Ij9WE5J280gtJ3kkQc2azNsOA1FHQ98iLMcfFstjvbzySPAQ/ClWxiNjrtVjLhd" + "ONM0/XwXV0OjHRhs3jMhLLUq/zzhsSlAGBGNfISnCnLWhsQDGcgHKXrKlQzZlp+r" + "0ApQmwJG0wg9ZqRdQZ+cfL2JSyIZJrqrol7DVes91hcAAgIQAKD9MGkS8SUD2irI" + "AiwVHU0WXLBnk2CvvueSmT9YtC34UKkIkDPZ7VoeuXDfqTOlbiE6T16zPvArZfbl" + "JGdrU7HhsTdu+ADxRt1dPur0G0ICJ3pBD3ydGWpdLI/94x1BvTY4rsR5mS4YWmpf" + "e2kWc7ZqezhP7Xt9q7m4EK456ddeUZWtkwGU+PKyRAZ+CK82Uhouw+4aW0NjiqmX" + "hfH9/BUhI1P/8R9VkTfAFGPmZzqoHr4AuO5tLRLD2RFSmQCP8nZTiP9nP+wBBvn7" + "vuqKRQsj9PwwPD4V5SM+kpW+rUIWr9TZYl3UqSnlXlpEZFd2Bfl6NloeH0cfU69E" + "gtjcWGvGxYKPS0cg5yhVb4okka6RqIPQiYl6eJgv4tRTKoPRX29o0aUVdqVvDr5u" + "tnFzcINq7jTo8GiO8Ia3cIFWfo0LyQBd1cf1U+eEOz+DleEFqyljaz9VCbDPE4GP" + "o+ALESBlOwn5daUSaah9iU8aVPaSjn45hoQqxOKPwJxnCKKQ01iy0Gir+CDU8JJB" + "7bmbvQN4bke30EGAeED3oi+3VaBHrhjYLv7SHIxP5jtCJKWMJuLRV709HsWJi3kn" + "fGHwH+yCDF8+PDeROAzpXBaD2EFhKgeUTjP5Rgn6ltRf8TQnfbW4qlwyiXMhPOfC" + "x6qNmwaFPKQJpIkVq5VGfRXAERfkiQBMBBgRAgAMBQI9kar+BRsMAAAAAAoJECog" + "GI6Hgm84CDMAoNrNeP4c8XqFJnsLLPcjk5YGLaVIAKCrL5KFuLQVIp7d0Fkscx3/" + "7DGrzw=="); private static readonly byte[] aesSecretKey = Base64.Decode( "lQHpBEBSdIYRBADpd7MeIxRk4RsvyMnJNIYe4FiVv6i7I7+LPRvnIjDct0bN" + "1gCV48QFej7g/PsvXRjYSowV3VIvchWX8OERd/5i10cLbcs7X52EP1vwYaLj" + "uRfNUBg8Q51RQsKR+/rBmnVsi68rjU4yTH6wpo6FOO4pz4wFV+tWwGOwOitA" + "K31L4wCgqh59eFFBrOlRFAbDvaL7emoCIR8EAOLxDKiLQJYQrKZfXdZnifeo" + "dhEP0uuV4O5TG6nrqkhWffzC9cSoFD0BhMl979d8IB2Uft4FNvQc2u8hbJL5" + "7OCGDCUAidlB9jSdu0/J+kfRaTGhYDjBgw7AA42576BBSMNouJg/aOOQENEN" + "Nn4n7NxR3viBzIsL/OIeU8HSkBgaA/41PsvcgZ3kwpdltJ/FVRWhmMmv/q/X" + "qp1YOnF8xPU9bv2ofELrxJfRsbS4GW1etzD+nXs/woW4Vfixs01x+cutR4iF" + "3hw+eU+yLToMPmmo8D2LUvX1SRODJpx5yBBeRIYv6nz9H3sQRDx3kaLASxDV" + "jTxKmrLYnZz5w5qyVpvRyv4JAwKyWlhdblPudWBFXNkW5ydKn0AV2f51wEtj" + "Zy0aLIeutVMSJf1ytLqjFqrnFe6pdJrHO3G00TE8OuFhftWosLGLbEGytDtF" + "cmljIEguIEVjaGlkbmEgKHRlc3Qga2V5IC0gQUVTMjU2KSA8ZXJpY0Bib3Vu" + "Y3ljYXN0bGUub3JnPohZBBMRAgAZBQJAUnSGBAsHAwIDFQIDAxYCAQIeAQIX" + "gAAKCRBYt1NnUiCgeFKaAKCiqtOO+NQES1gJW6XuOGmSkXt8bQCfcuW7SXZH" + "zxK1FfdcG2HEDs3YEVawAgAA"); private static readonly byte[] aesPublicKey = Base64.Decode( "mQGiBEBSdIYRBADpd7MeIxRk4RsvyMnJNIYe4FiVv6i7I7+LPRvnIjDct0bN" + "1gCV48QFej7g/PsvXRjYSowV3VIvchWX8OERd/5i10cLbcs7X52EP1vwYaLj" + "uRfNUBg8Q51RQsKR+/rBmnVsi68rjU4yTH6wpo6FOO4pz4wFV+tWwGOwOitA" + "K31L4wCgqh59eFFBrOlRFAbDvaL7emoCIR8EAOLxDKiLQJYQrKZfXdZnifeo" + "dhEP0uuV4O5TG6nrqkhWffzC9cSoFD0BhMl979d8IB2Uft4FNvQc2u8hbJL5" + "7OCGDCUAidlB9jSdu0/J+kfRaTGhYDjBgw7AA42576BBSMNouJg/aOOQENEN" + "Nn4n7NxR3viBzIsL/OIeU8HSkBgaA/41PsvcgZ3kwpdltJ/FVRWhmMmv/q/X" + "qp1YOnF8xPU9bv2ofELrxJfRsbS4GW1etzD+nXs/woW4Vfixs01x+cutR4iF" + "3hw+eU+yLToMPmmo8D2LUvX1SRODJpx5yBBeRIYv6nz9H3sQRDx3kaLASxDV" + "jTxKmrLYnZz5w5qyVpvRyrQ7RXJpYyBILiBFY2hpZG5hICh0ZXN0IGtleSAt" + "IEFFUzI1NikgPGVyaWNAYm91bmN5Y2FzdGxlLm9yZz6IWQQTEQIAGQUCQFJ0" + "hgQLBwMCAxUCAwMWAgECHgECF4AACgkQWLdTZ1IgoHhSmgCfU83BLBF2nCua" + "zk2dXB9zO1l6XS8AnA07U4cq5W0GrKM6/kP9HWtPhgOFsAIAAA=="); private static readonly byte[] twofishSecretKey = Base64.Decode( "lQHpBEBSdtIRBACf7WfrqTl8F051+EbaljPf/8/ajFpAfMq/7p3Hri8OCsuc" + "fJJIufEEOV1/Lt/wkN67MmSyrU0fUCsRbEckRiB4EJ0zGHVFfAnku2lzdgc8" + "AVounqcHOmqA/gliFDEnhYOx3bOIAOav+yiOqfKVBhWRCpFdOTE+w/XoDM+p" + "p8bH5wCgmP2FuWpzfSut7GVKp51xNEBRNuED/3t2Q+Mq834FVynmLKEmeXB/" + "qtIz5reHEQR8eMogsOoJS3bXs6v3Oblj4in1gLyTVfcID5tku6kLP20xMRM2" + "zx2oRbz7TyOCrs15IpRXyqqJxUWD8ipgJPkPXE7hK8dh4YSTUi4i5a1ug8xG" + "314twlPzrchpWZiutDvZ+ks1rzOtBACHrEFG2frUu+qVkL43tySE0cV2bnuK" + "LVhXbpzF3Qdkfxou2nuzsCbl6m87OWocJX8uYcQGlHLKv8Q2cfxZyieLFg6v" + "06LSFdE9drGBWz7mbrT4OJjxPyvnkffPfLOOqae3PMYIIuscvswuhm4X5aoj" + "KJs01YT3L6f0iIj03hCeV/4KAwLcGrxT3X0qR2CZyZYSVBdjXeNYKXuGBtOf" + "ood26WOtwLw4+l9sHVoiXNv0LomkO58ndJRPGCeZWZEDMVrfkS7rcOlktDxF" + "cmljIEguIEVjaGlkbmEgKHRlc3Qga2V5IC0gdHdvZmlzaCkgPGVyaWNAYm91" + "bmN5Y2FzdGxlLm9yZz6IWQQTEQIAGQUCQFJ20gQLBwMCAxUCAwMWAgECHgEC" + "F4AACgkQaCCMaHh9zR2+RQCghcQwlt4B4YmNxp2b3v6rP3E8M0kAn2Gspi4u" + "A/ynoqnC1O8HNlbjPdlVsAIAAA=="); private static readonly byte[] twofishPublicKey = Base64.Decode( "mQGiBEBSdtIRBACf7WfrqTl8F051+EbaljPf/8/ajFpAfMq/7p3Hri8OCsuc" + "fJJIufEEOV1/Lt/wkN67MmSyrU0fUCsRbEckRiB4EJ0zGHVFfAnku2lzdgc8" + "AVounqcHOmqA/gliFDEnhYOx3bOIAOav+yiOqfKVBhWRCpFdOTE+w/XoDM+p" + "p8bH5wCgmP2FuWpzfSut7GVKp51xNEBRNuED/3t2Q+Mq834FVynmLKEmeXB/" + "qtIz5reHEQR8eMogsOoJS3bXs6v3Oblj4in1gLyTVfcID5tku6kLP20xMRM2" + "zx2oRbz7TyOCrs15IpRXyqqJxUWD8ipgJPkPXE7hK8dh4YSTUi4i5a1ug8xG" + "314twlPzrchpWZiutDvZ+ks1rzOtBACHrEFG2frUu+qVkL43tySE0cV2bnuK" + "LVhXbpzF3Qdkfxou2nuzsCbl6m87OWocJX8uYcQGlHLKv8Q2cfxZyieLFg6v" + "06LSFdE9drGBWz7mbrT4OJjxPyvnkffPfLOOqae3PMYIIuscvswuhm4X5aoj" + "KJs01YT3L6f0iIj03hCeV7Q8RXJpYyBILiBFY2hpZG5hICh0ZXN0IGtleSAt" + "IHR3b2Zpc2gpIDxlcmljQGJvdW5jeWNhc3RsZS5vcmc+iFkEExECABkFAkBS" + "dtIECwcDAgMVAgMDFgIBAh4BAheAAAoJEGggjGh4fc0dvkUAn2QGdNk8Wrrd" + "+DvKECrO5+yoPRx3AJ91DhCMme6uMrQorKSDYxHlgc7iT7ACAAA="); private static readonly char[] pass = "hello world".ToCharArray(); /** * Generated signature test * * @param sKey * @param pgpPrivKey * @return test result */ public void GenerateTest( PgpSecretKeyRing sKey, PgpPublicKey pgpPubKey, PgpPrivateKey pgpPrivKey) { string data = "hello world!"; MemoryStream bOut = new MemoryStream(); byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); IEnumerator enumerator = sKey.GetSecretKey().PublicKey.GetUserIds().GetEnumerator(); enumerator.MoveNext(); string primaryUserId = (string) enumerator.Current; spGen.SetSignerUserId(true, primaryUserId); sGen.SetHashedSubpackets(spGen.Generate()); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData) pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pgpPubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte) ch); } PgpSignatureList p3 = (PgpSignatureList) pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } } public override void PerformTest() { PgpPublicKey pubKey = null; // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); pubKey = pgpPub.GetPublicKey(); // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey); PgpSecretKey secretKey = sKey.GetSecretKey(); PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // test signature message // PgpObjectFactory pgpFact = new PgpObjectFactory(sig1); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte) ch); } PgpSignatureList p3 = (PgpSignatureList) pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } // // signature generation // GenerateTest(sKey, pubKey, pgpPrivKey); // // signature generation - canonical text // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Text, "_CONSOLE", dataBytes.Length, testDateTime); while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature - canconical text // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData) pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList) pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData) pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList) pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // Read the public key with user attributes // pgpPub = new PgpPublicKeyRing(testPubWithUserAttr); pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes()) { int sigCount = 0; foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes)) { if (sigs == null) Fail("null signature found"); sigCount++; } if (sigCount != 1) { Fail("Failed user attributes signature check"); } count++; } if (count != 1) { Fail("Failed user attributes check"); } byte[] pgpPubBytes = pgpPub.GetEncoded(); pgpPub = new PgpPublicKeyRing(pgpPubBytes); pubKey = pgpPub.GetPublicKey(); count = 0; foreach (object ua in pubKey.GetUserAttributes()) { if (ua == null) Fail("null user attribute found"); count++; } if (count != 1) { Fail("Failed user attributes reread"); } // // reading test extra data - key with edge condition for DSA key password. // char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; sKey = new PgpSecretKeyRing(testPrivKey2); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase); // // reading test - aes256 encrypted passphrase. // sKey = new PgpSecretKeyRing(aesSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // reading test - twofish encrypted passphrase. // sKey = new PgpSecretKeyRing(twofishSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // use of PgpKeyPair // DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay? DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpg.Init(kgp); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; } public override string Name { get { return "PGPDSATest"; } } public static void Main( string[] args) { RunTest(new PgpDsaTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// 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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedDivideNullableTests { #region Test methods [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableByte(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableFloat(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableInt(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableLong(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableSByte(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableShort(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUInt(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableULong(values[i], values[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLiftedDivideNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyDivideNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Helpers public static byte DivideNullableByte(byte a, byte b) { return (byte)(a / b); } public static char DivideNullableChar(char a, char b) { return (char)(a / b); } public static decimal DivideNullableDecimal(decimal a, decimal b) { return (decimal)(a / b); } public static double DivideNullableDouble(double a, double b) { return (double)(a / b); } public static float DivideNullableFloat(float a, float b) { return (float)(a / b); } public static int DivideNullableInt(int a, int b) { return (int)(a / b); } public static long DivideNullableLong(long a, long b) { return (long)(a / b); } public static sbyte DivideNullableSByte(sbyte a, sbyte b) { return (sbyte)(a / b); } public static short DivideNullableShort(short a, short b) { return (short)(a / b); } public static uint DivideNullableUInt(uint a, uint b) { return (uint)(a / b); } public static ulong DivideNullableULong(ulong a, ulong b) { return (ulong)(a / b); } public static ushort DivideNullableUShort(ushort a, ushort b) { return (ushort)(a / b); } #endregion #region Test verifiers private static void VerifyDivideNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Divide( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableByte"))); Func<byte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((byte?)(a / b), f()); } private static void VerifyDivideNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.Divide( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableChar"))); Func<char?> f = e.Compile(useInterpreter); if (a.HasValue && b == '\0') Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((char?)(a / b), f()); } private static void VerifyDivideNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Divide( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableDecimal"))); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Divide( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableDouble"))); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDivideNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Divide( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableFloat"))); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDivideNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Divide( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableInt"))); Func<int?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == int.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Divide( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableLong"))); Func<long?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == long.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Divide( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableSByte"))); Func<sbyte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((sbyte?)(a / b), f()); } private static void VerifyDivideNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Divide( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableShort"))); Func<short?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((short?)(a / b), f()); } private static void VerifyDivideNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Divide( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableUInt"))); Func<uint?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Divide( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableULong"))); Func<ulong?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyDivideNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Divide( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(LiftedDivideNullableTests).GetTypeInfo().GetDeclaredMethod("DivideNullableUShort"))); Func<ushort?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((ushort?)(a / b), f()); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.SiteRecovery; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { public static partial class RecoveryPlanOperationsExtensions { /// <summary> /// Creates a recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='input'> /// Required. Create recovery plan input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginCreating(this IRecoveryPlanOperations operations, string recoveryPlanName, CreateRecoveryPlanInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).BeginCreatingAsync(recoveryPlanName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='input'> /// Required. Create recovery plan input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginCreatingAsync(this IRecoveryPlanOperations operations, string recoveryPlanName, CreateRecoveryPlanInput input, CustomRequestHeaders customRequestHeaders) { return operations.BeginCreatingAsync(recoveryPlanName, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Deletes a recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginDeleting(this IRecoveryPlanOperations operations, string recoveryPlanName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).BeginDeletingAsync(recoveryPlanName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginDeletingAsync(this IRecoveryPlanOperations operations, string recoveryPlanName, CustomRequestHeaders customRequestHeaders) { return operations.BeginDeletingAsync(recoveryPlanName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Updates the given recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='input'> /// Required. Update recovery plan input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginUpdating(this IRecoveryPlanOperations operations, string recoveryPlanName, UpdateRecoveryPlanInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).BeginUpdatingAsync(recoveryPlanName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the given recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='input'> /// Required. Update recovery plan input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginUpdatingAsync(this IRecoveryPlanOperations operations, string recoveryPlanName, UpdateRecoveryPlanInput input, CustomRequestHeaders customRequestHeaders) { return operations.BeginUpdatingAsync(recoveryPlanName, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Creates a recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='input'> /// Required. Create recovery plan input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Create(this IRecoveryPlanOperations operations, string recoveryPlanName, CreateRecoveryPlanInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).CreateAsync(recoveryPlanName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='input'> /// Required. Create recovery plan input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> CreateAsync(this IRecoveryPlanOperations operations, string recoveryPlanName, CreateRecoveryPlanInput input, CustomRequestHeaders customRequestHeaders) { return operations.CreateAsync(recoveryPlanName, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Deletes a recovery plan /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Delete(this IRecoveryPlanOperations operations, string recoveryPlanName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).DeleteAsync(recoveryPlanName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a recovery plan /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> DeleteAsync(this IRecoveryPlanOperations operations, string recoveryPlanName, CustomRequestHeaders customRequestHeaders) { return operations.DeleteAsync(recoveryPlanName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Gets the recovery plan by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the recovery plan object. /// </returns> public static RecoveryPlanResponse Get(this IRecoveryPlanOperations operations, string recoveryPlanName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).GetAsync(recoveryPlanName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the recovery plan by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the recovery plan object. /// </returns> public static Task<RecoveryPlanResponse> GetAsync(this IRecoveryPlanOperations operations, string recoveryPlanName, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(recoveryPlanName, customRequestHeaders, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static CreateRecoveryPlanOperationResponse GetCreateStatus(this IRecoveryPlanOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).GetCreateStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<CreateRecoveryPlanOperationResponse> GetCreateStatusAsync(this IRecoveryPlanOperations operations, string operationStatusLink) { return operations.GetCreateStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static DeleteRecoveryPlanOperationResponse GetDeleteStatus(this IRecoveryPlanOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).GetDeleteStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<DeleteRecoveryPlanOperationResponse> GetDeleteStatusAsync(this IRecoveryPlanOperations operations, string operationStatusLink) { return operations.GetDeleteStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static UpdateRecoveryPlanOperationResponse GetUpdateStatus(this IRecoveryPlanOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).GetUpdateStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<UpdateRecoveryPlanOperationResponse> GetUpdateStatusAsync(this IRecoveryPlanOperations operations, string operationStatusLink) { return operations.GetUpdateStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Gets the list of all recovery plans under the vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list recovery plan operation. /// </returns> public static RecoveryPlanListResponse List(this IRecoveryPlanOperations operations, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).ListAsync(customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of all recovery plans under the vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list recovery plan operation. /// </returns> public static Task<RecoveryPlanListResponse> ListAsync(this IRecoveryPlanOperations operations, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(customRequestHeaders, CancellationToken.None); } /// <summary> /// Updates the given recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='input'> /// Required. Update recovery plan input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Update(this IRecoveryPlanOperations operations, string recoveryPlanName, UpdateRecoveryPlanInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IRecoveryPlanOperations)s).UpdateAsync(recoveryPlanName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the given recovery plan. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IRecoveryPlanOperations. /// </param> /// <param name='recoveryPlanName'> /// Required. Recovery plan name. /// </param> /// <param name='input'> /// Required. Update recovery plan input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> UpdateAsync(this IRecoveryPlanOperations operations, string recoveryPlanName, UpdateRecoveryPlanInput input, CustomRequestHeaders customRequestHeaders) { return operations.UpdateAsync(recoveryPlanName, input, customRequestHeaders, CancellationToken.None); } } }
using NDiagnostics.Metering.Extensions; using NDiagnostics.Metering.Types; namespace NDiagnostics.Metering.Samples { public abstract class Sample { #region Constructors and Destructors protected Sample(TimeStamp timeStamp, TimeStamp100Ns timeStamp100Ns) { this.TimeStamp = timeStamp; this.TimeStamp100Ns = timeStamp100Ns; } #endregion #region Properties internal TimeStamp TimeStamp { get; } internal TimeStamp100Ns TimeStamp100Ns { get; } #endregion #region Public Methods // Instant Meters public static long ComputeValue(InstantValueSample sample) { sample.ThrowIfNull("sample"); return sample.Value; } public static float ComputeValue(InstantTimeSample sample) { sample.ThrowIfNull("sample"); return (float)(sample.TimeStamp100Ns - sample.StartTime).Seconds; } public static float ComputeValue(InstantPercentageSample sample) { sample.ThrowIfNull("sample"); if(sample.Denominator == 0) { return 0.0F; } return (float) sample.Numerator / sample.Denominator * 100.0F; } // Average Meters public static float ComputeValue(AverageValueSample sample0, AverageValueSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp > sample1.TimeStamp && sample0.Count != sample1.Count) { return (float) (sample0.Value - sample1.Value) / (sample0.Count - sample1.Count); } if(sample1.TimeStamp > sample0.TimeStamp && sample1.Count != sample0.Count) { return (float) (sample1.Value - sample0.Value) / (sample1.Count - sample0.Count); } return 0.0F; } public static float ComputeValue(AverageTimeSample sample0, AverageTimeSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp > sample1.TimeStamp && sample0.Count != sample1.Count) { return (float)(sample0.ElapsedTime - sample1.ElapsedTime).Seconds / (sample0.Count - sample1.Count); } if(sample1.TimeStamp > sample0.TimeStamp && sample1.Count != sample0.Count) { return (float)(sample1.ElapsedTime - sample0.ElapsedTime).Seconds / (sample1.Count - sample0.Count); } return 0.0F; } public static float ComputeValue(SampleRateSample sample0, SampleRateSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp > sample1.TimeStamp) { return (sample0.Count - sample1.Count) / (float)(sample0.TimeStamp - sample1.TimeStamp).Seconds; } if(sample1.TimeStamp > sample0.TimeStamp) { return (sample1.Count - sample0.Count) / (float)(sample1.TimeStamp - sample0.TimeStamp).Seconds; } return 0.0F; } public static float ComputeValue(SamplePercentageSample sample0, SamplePercentageSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp > sample1.TimeStamp) { return (float) (sample0.Numerator - sample1.Numerator) / (sample0.Denominator - sample1.Denominator) * 100.0F; } if(sample1.TimeStamp > sample0.TimeStamp) { return (float) (sample1.Numerator - sample0.Numerator) / (sample1.Denominator - sample0.Denominator) * 100.0F; } return 0.0F; } // Difference Counters public static long ComputeValue(DifferentialValueSample sample0, DifferentialValueSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp > sample1.TimeStamp) { return sample0.Value - sample1.Value; } if(sample1.TimeStamp > sample0.TimeStamp) { return sample1.Value - sample0.Value; } return 0L; } // Percentage Counters public static float ComputeValue(TimerSample sample0, TimerSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp > sample1.TimeStamp) { return (float) (sample0.ElapsedTimeOfActivity - sample1.ElapsedTimeOfActivity).Ticks / (sample0.TimeStamp - sample1.TimeStamp).Ticks * 100.0F; } if(sample1.TimeStamp > sample0.TimeStamp) { return (float) (sample1.ElapsedTimeOfActivity - sample0.ElapsedTimeOfActivity).Ticks / (sample1.TimeStamp - sample0.TimeStamp).Ticks * 100.0F; } return 0.0F; } public static float ComputeValue(TimerInverseSample sample0, TimerInverseSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp > sample1.TimeStamp) { return (1.0F - ((float) (sample0.ElapsedTimeOfInactivity - sample1.ElapsedTimeOfInactivity).Ticks / (sample0.TimeStamp - sample1.TimeStamp).Ticks)) * 100.0F; } if(sample1.TimeStamp > sample0.TimeStamp) { return (1.0F - ((float) (sample1.ElapsedTimeOfInactivity - sample0.ElapsedTimeOfInactivity).Ticks / (sample1.TimeStamp - sample0.TimeStamp).Ticks)) * 100.0F; } return 0.0F; } public static float ComputeValue(Timer100NsSample sample0, Timer100NsSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp100Ns > sample1.TimeStamp100Ns) { return (float) (sample0.ElapsedTimeOfActivity - sample1.ElapsedTimeOfActivity).Ticks / (sample0.TimeStamp100Ns - sample1.TimeStamp100Ns).Ticks * 100.0F; } if(sample1.TimeStamp100Ns > sample0.TimeStamp100Ns) { return (float) (sample1.ElapsedTimeOfActivity - sample0.ElapsedTimeOfActivity).Ticks / (sample1.TimeStamp100Ns - sample0.TimeStamp100Ns).Ticks * 100.0F; } return 0.0F; } public static float ComputeValue(Timer100NsInverseSample sample0, Timer100NsInverseSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp100Ns > sample1.TimeStamp100Ns) { return (1.0F - ((float) (sample0.ElapsedTimeOfInactivity - sample1.ElapsedTimeOfInactivity).Ticks / (sample0.TimeStamp100Ns - sample1.TimeStamp100Ns).Ticks)) * 100.0F; } if(sample1.TimeStamp100Ns > sample0.TimeStamp100Ns) { return (1.0F - ((float) (sample1.ElapsedTimeOfInactivity - sample0.ElapsedTimeOfInactivity).Ticks / (sample1.TimeStamp100Ns - sample0.TimeStamp100Ns).Ticks)) * 100.0F; } return 0.0F; } public static float ComputeValue(MultiTimerSample sample0, MultiTimerSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp > sample1.TimeStamp) { return (float) (sample0.ElapsedTimeOfActivity - sample1.ElapsedTimeOfActivity).Ticks / (sample0.TimeStamp - sample1.TimeStamp).Ticks * 100.0F / (sample0.Count - sample1.Count); } if(sample1.TimeStamp > sample0.TimeStamp) { return (float) (sample1.ElapsedTimeOfActivity - sample0.ElapsedTimeOfActivity).Ticks / (sample1.TimeStamp - sample0.TimeStamp).Ticks * 100.0F / (sample1.Count - sample0.Count); } return 0.0F; } public static float ComputeValue(MultiTimerInverseSample sample0, MultiTimerInverseSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp > sample1.TimeStamp) { return ((sample0.Count - sample1.Count) - ((float) (sample0.ElapsedTimeOfInactivity - sample1.ElapsedTimeOfInactivity).Ticks / (sample0.TimeStamp - sample1.TimeStamp).Ticks)) * 100.0F; } if(sample1.TimeStamp > sample0.TimeStamp) { return ((sample1.Count - sample0.Count) - ((float) (sample1.ElapsedTimeOfInactivity - sample0.ElapsedTimeOfInactivity).Ticks / (sample1.TimeStamp - sample0.TimeStamp).Ticks)) * 100.0F; } return 0.0F; } public static float ComputeValue(MultiTimer100NsSample sample0, MultiTimer100NsSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp100Ns > sample1.TimeStamp100Ns) { return (float) (sample0.ElapsedTimeOfActivity - sample1.ElapsedTimeOfActivity).Ticks / (sample0.TimeStamp100Ns - sample1.TimeStamp100Ns).Ticks * 100.0F / (sample0.Count - sample1.Count); } if(sample1.TimeStamp100Ns > sample0.TimeStamp100Ns) { return (float) (sample1.ElapsedTimeOfActivity - sample0.ElapsedTimeOfActivity).Ticks / (sample1.TimeStamp100Ns - sample0.TimeStamp100Ns).Ticks * 100.0F / (sample1.Count - sample0.Count); } return 0.0F; } public static float ComputeValue(MultiTimer100NsInverseSample sample0, MultiTimer100NsInverseSample sample1) { sample0.ThrowIfNull("sample0"); sample1.ThrowIfNull("sample1"); if(sample0.TimeStamp100Ns > sample1.TimeStamp100Ns) { return ((sample0.Count - sample1.Count) - ((float) (sample0.ElapsedTimeOfInactivity - sample1.ElapsedTimeOfInactivity).Ticks / (sample0.TimeStamp100Ns - sample1.TimeStamp100Ns).Ticks)) * 100.0F; } if(sample1.TimeStamp100Ns > sample0.TimeStamp100Ns) { return ((sample1.Count - sample0.Count) - ((float) (sample1.ElapsedTimeOfInactivity - sample0.ElapsedTimeOfInactivity).Ticks / (sample1.TimeStamp100Ns - sample0.TimeStamp100Ns).Ticks)) * 100.0F; } return 0.0F; } #endregion } }
//#define DEBUGREADERS using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Globalization; using ExcelDataReader.Portable.Async; using ExcelDataReader.Portable.Core; using ExcelDataReader.Portable.Core.OpenXmlFormat; using ExcelDataReader.Portable.Data; using ExcelDataReader.Portable.IO; using PCLStorage; namespace ExcelDataReader.Portable { public class ExcelOpenXmlReader : IExcelDataReader { private readonly IFileSystem fileSystem; private readonly IFileHelper fileHelper; private readonly IDataHelper dataHelper; #region Members private XlsxWorkbook _workbook; private bool _isValid; private bool _isClosed; private bool _isFirstRead; private string _exceptionMessage; private int _depth; private int _resultIndex; private int _emptyRowCount; private ZipWorker _zipWorker; private XmlReader _xmlReader; private Stream _sheetStream; private object[] _cellsValues; private object[] _savedCellsValues; private bool disposed; private bool _isFirstRowAsColumnNames; private const string COLUMN = "Column"; private string instanceId = Guid.NewGuid().ToString(); private List<int> _defaultDateTimeStyles; private string _namespaceUri; #endregion public ExcelOpenXmlReader(IFileSystem fileSystem, IFileHelper fileHelper, IDataHelper dataHelper) { this.fileSystem = fileSystem; this.fileHelper = fileHelper; this.dataHelper = dataHelper; _isValid = true; _isFirstRead = true; _defaultDateTimeStyles = new List<int>(new int[] { 14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47 }); } private async Task ReadGlobalsAsync() { _workbook = new XlsxWorkbook( await _zipWorker.GetWorkbookStream(), await _zipWorker.GetWorkbookRelsStream(), await _zipWorker.GetSharedStringsStream(), await _zipWorker.GetStylesStream()); CheckDateTimeNumFmts(_workbook.Styles.NumFmts); } private void CheckDateTimeNumFmts(List<XlsxNumFmt> list) { if (list.Count == 0) return; foreach (XlsxNumFmt numFmt in list) { if (string.IsNullOrEmpty(numFmt.FormatCode)) continue; string fc = numFmt.FormatCode.ToLower(); int pos; while ((pos = fc.IndexOf('"')) > 0) { int endPos = fc.IndexOf('"', pos + 1); if (endPos > 0) fc = fc.Remove(pos, endPos - pos + 1); } //it should only detect it as a date if it contains //dd mm mmm yy yyyy //h hh ss //AM PM //and only if these appear as "words" so either contained in [ ] //or delimted in someway //updated to not detect as date if format contains a # var formatReader = new FormatReader() {FormatString = fc}; if (formatReader.IsDateFormatString()) { _defaultDateTimeStyles.Add(numFmt.Id); } } } private async Task ReadSheetGlobalsAsync(XlsxWorksheet sheet) { if (_xmlReader != null) _xmlReader.Dispose(); if (_sheetStream != null) _sheetStream.Dispose(); _sheetStream = await _zipWorker.GetWorksheetStream(sheet.Path); if (null == _sheetStream) return; _xmlReader = XmlReader.Create(_sheetStream); //count rows and cols in case there is no dimension elements int rows = 0; int cols = 0; _namespaceUri = null; int biggestColumn = 0; //used when no col elements and no dimension while (_xmlReader.Read()) { if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_worksheet) { //grab the namespaceuri from the worksheet element _namespaceUri = _xmlReader.NamespaceURI; } if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_dimension) { string dimValue = _xmlReader.GetAttribute(XlsxWorksheet.A_ref); sheet.Dimension = new XlsxDimension(dimValue); break; } //removed: Do not use col to work out number of columns as this is really for defining formatting, so may not contain all columns //if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_col) // cols++; if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row) rows++; //check cells so we can find size of sheet if can't work it out from dimension or col elements (dimension should have been set before the cells if it was available) //ditto for cols if (sheet.Dimension == null && cols == 0 && _xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_c) { var refAttribute = _xmlReader.GetAttribute(XlsxWorksheet.A_r); if (refAttribute != null) { var thisRef = ReferenceHelper.ReferenceToColumnAndRow(refAttribute); if (thisRef[1] > biggestColumn) biggestColumn = thisRef[1]; } } } //if we didn't get a dimension element then use the calculated rows/cols to create it if (sheet.Dimension == null) { if (cols == 0) cols = biggestColumn; if (rows == 0 || cols == 0) { sheet.IsEmpty = true; return; } sheet.Dimension = new XlsxDimension(rows, cols); //we need to reset our position to sheet data _xmlReader.Dispose(); _sheetStream.Dispose(); _sheetStream = await _zipWorker.GetWorksheetStream(sheet.Path); _xmlReader = XmlReader.Create(_sheetStream); } //read up to the sheetData element. if this element is empty then there aren't any rows and we need to null out dimension _xmlReader.ReadToFollowing(XlsxWorksheet.N_sheetData, _namespaceUri); if (_xmlReader.IsEmptyElement) { sheet.IsEmpty = true; } } private bool ReadSheetRow(XlsxWorksheet sheet) { if (null == _xmlReader) return false; if (_emptyRowCount != 0) { _cellsValues = new object[sheet.ColumnsCount]; _emptyRowCount--; _depth++; return true; } if (_savedCellsValues != null) { _cellsValues = _savedCellsValues; _savedCellsValues = null; _depth++; return true; } if ((_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row) || _xmlReader.ReadToFollowing(XlsxWorksheet.N_row, _namespaceUri)) { _cellsValues = new object[sheet.ColumnsCount]; int rowIndex = int.Parse(_xmlReader.GetAttribute(XlsxWorksheet.A_r)); if (rowIndex != (_depth + 1)) if (rowIndex != (_depth + 1)) { _emptyRowCount = rowIndex - _depth - 1; } bool hasValue = false; string a_s = String.Empty; string a_t = String.Empty; string a_r = String.Empty; int col = 0; int row = 0; while (_xmlReader.Read()) { if (_xmlReader.Depth == 2) break; if (_xmlReader.NodeType == XmlNodeType.Element) { hasValue = false; if (_xmlReader.LocalName == XlsxWorksheet.N_c) { a_s = _xmlReader.GetAttribute(XlsxWorksheet.A_s); a_t = _xmlReader.GetAttribute(XlsxWorksheet.A_t); a_r = _xmlReader.GetAttribute(XlsxWorksheet.A_r); XlsxDimension.XlsxDim(a_r, out col, out row); } else if (_xmlReader.LocalName == XlsxWorksheet.N_v || _xmlReader.LocalName == XlsxWorksheet.N_t) { hasValue = true; } } if (_xmlReader.NodeType == XmlNodeType.Text && hasValue) { double number; object o = _xmlReader.Value; var style = NumberStyles.Any; var culture = CultureInfo.InvariantCulture; if (double.TryParse(o.ToString(), style, culture, out number)) o = number; if (null != a_t && a_t == XlsxWorksheet.A_s) //if string { o = Helpers.ConvertEscapeChars(_workbook.SST[int.Parse(o.ToString())]); } // Requested change 4: missing (it appears that if should be else if) else if (null != a_t && a_t == XlsxWorksheet.N_inlineStr) //if string inline { o = Helpers.ConvertEscapeChars(o.ToString()); } else if (a_t == "b") //boolean { o = _xmlReader.Value == "1"; } else if (null != a_s) //if something else { XlsxXf xf = _workbook.Styles.CellXfs[int.Parse(a_s)]; if (o != null && o.ToString() != string.Empty && IsDateTimeStyle(xf.NumFmtId)) o = Helpers.ConvertFromOATime(number); else if (xf.NumFmtId == 49) o = o.ToString(); } if (col - 1 < _cellsValues.Length) _cellsValues[col - 1] = o; } } if (_emptyRowCount > 0) { _savedCellsValues = _cellsValues; return ReadSheetRow(sheet); } _depth++; return true; } _xmlReader.Dispose(); if (_sheetStream != null) _sheetStream.Dispose(); return false; } private async Task<bool> InitializeSheetReadAsync() { if (ResultsCount <= 0) return false; await ReadSheetGlobalsAsync(_workbook.Sheets[_resultIndex]); if (_workbook.Sheets[_resultIndex].Dimension == null) return false; _isFirstRead = false; _depth = 0; _emptyRowCount = 0; return true; } private bool IsDateTimeStyle(int styleId) { return _defaultDateTimeStyles.Contains(styleId); } #region IExcelDataReader Members public async Task InitializeAsync(System.IO.Stream fileStream) { _zipWorker = new ZipWorker(fileSystem, fileHelper); await _zipWorker.Extract(fileStream); if (!_zipWorker.IsValid) { _isValid = false; _exceptionMessage = _zipWorker.ExceptionMessage; Close(); return; } await ReadGlobalsAsync(); } public async Task LoadDataSetAsync(IDatasetHelper datasetHelper) { await LoadDataSetAsync(datasetHelper, true); } public async Task LoadDataSetAsync(IDatasetHelper datasetHelper, bool convertOADateTime) { if (!_isValid) { datasetHelper.IsValid = false; } datasetHelper.IsValid = true; datasetHelper.CreateNew(); for (int ind = 0; ind < _workbook.Sheets.Count; ind++) { datasetHelper.CreateNewTable(_workbook.Sheets[ind].Name); datasetHelper.AddExtendedPropertyToTable("visiblestate", _workbook.Sheets[ind].VisibleState); await ReadSheetGlobalsAsync(_workbook.Sheets[ind]); if (_workbook.Sheets[ind].Dimension == null) continue; _depth = 0; _emptyRowCount = 0; //DataTable columns //todo: all very similar to sheet load in binary reader if (!_isFirstRowAsColumnNames) { for (int i = 0; i < _workbook.Sheets[ind].ColumnsCount; i++) { datasetHelper.AddColumn(null); } } else if (ReadSheetRow(_workbook.Sheets[ind])) { for (int index = 0; index < _cellsValues.Length; index++) { if (_cellsValues[index] != null && _cellsValues[index].ToString().Length > 0) datasetHelper.AddColumn(_cellsValues[index].ToString()); else datasetHelper.AddColumn(string.Concat(COLUMN, index)); } } else continue; datasetHelper.BeginLoadData(); var hasRows = false; while (ReadSheetRow(_workbook.Sheets[ind])) { hasRows = true; datasetHelper.AddRow(_cellsValues); } if (hasRows) datasetHelper.EndLoadTable(); } datasetHelper.DatasetLoadComplete(); } public bool IsFirstRowAsColumnNames { get { return _isFirstRowAsColumnNames; } set { _isFirstRowAsColumnNames = value; } } public bool ConvertOaDate { get; set; } public ReadOption ReadOption { get; set; } public Encoding Encoding { get { return null; } } public Encoding DefaultEncoding { get { return Encoding.UTF8; } } public bool IsValid { get { return _isValid; } } public string ExceptionMessage { get { return _exceptionMessage; } } public string Name { get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].Name : null; } } public string VisibleState { get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].VisibleState : null; } } public void Close() { _isClosed = true; if (_xmlReader != null) _xmlReader.Dispose(); if (_sheetStream != null) _sheetStream.Dispose(); if (_zipWorker != null) _zipWorker.Dispose(); } public int Depth { get { return _depth; } } public int ResultsCount { get { return _workbook == null ? -1 : _workbook.Sheets.Count; } } public bool IsClosed { get { return _isClosed; } } public bool NextResult() { if (_resultIndex >= (this.ResultsCount - 1)) return false; _resultIndex++; _isFirstRead = true; _savedCellsValues = null; return true; } public bool Read() { if (!_isValid) return false; if (_isFirstRead) { var initializeSheetRead = AsyncHelper.RunSync(() => InitializeSheetReadAsync()); if (!initializeSheetRead) return false; } return ReadSheetRow(_workbook.Sheets[_resultIndex]); } public int FieldCount { get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].ColumnsCount : -1; } } public bool GetBoolean(int i) { if (IsDBNull(i)) return false; return Boolean.Parse(_cellsValues[i].ToString()); } public DateTime GetDateTime(int i) { if (IsDBNull(i)) return DateTime.MinValue; try { return (DateTime)_cellsValues[i]; } catch (InvalidCastException) { return DateTime.MinValue; } } public decimal GetDecimal(int i) { if (IsDBNull(i)) return decimal.MinValue; return decimal.Parse(_cellsValues[i].ToString()); } public double GetDouble(int i) { if (IsDBNull(i)) return double.MinValue; return double.Parse(_cellsValues[i].ToString()); } public float GetFloat(int i) { if (IsDBNull(i)) return float.MinValue; return float.Parse(_cellsValues[i].ToString()); } public short GetInt16(int i) { if (IsDBNull(i)) return short.MinValue; return short.Parse(_cellsValues[i].ToString()); } public int GetInt32(int i) { if (IsDBNull(i)) return int.MinValue; return int.Parse(_cellsValues[i].ToString()); } public long GetInt64(int i) { if (IsDBNull(i)) return long.MinValue; return long.Parse(_cellsValues[i].ToString()); } public string GetString(int i) { if (IsDBNull(i)) return null; return _cellsValues[i].ToString(); } public object GetValue(int i) { return _cellsValues[i]; } public bool IsDBNull(int i) { return (null == _cellsValues[i]) || (dataHelper.IsDBNull(_cellsValues[i])); } public object this[int i] { get { return _cellsValues[i]; } } #endregion #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { if (disposing) { if (_xmlReader != null) ((IDisposable) _xmlReader).Dispose(); if (_sheetStream != null) _sheetStream.Dispose(); if (_zipWorker != null) _zipWorker.Dispose(); } _zipWorker = null; _xmlReader = null; _sheetStream = null; _workbook = null; _cellsValues = null; _savedCellsValues = null; disposed = true; } } ~ExcelOpenXmlReader() { Dispose(false); } #endregion #region Not Supported IDataReader Members public int RecordsAffected { get { throw new NotSupportedException(); } } #endregion #region Not Supported IDataRecord Members public byte GetByte(int i) { throw new NotSupportedException(); } public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } public char GetChar(int i) { throw new NotSupportedException(); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotSupportedException(); } public IDataReader GetData(int i) { throw new NotSupportedException(); } public string GetDataTypeName(int i) { throw new NotSupportedException(); } public Type GetFieldType(int i) { throw new NotSupportedException(); } public Guid GetGuid(int i) { throw new NotSupportedException(); } public string GetName(int i) { throw new NotSupportedException(); } public int GetOrdinal(string name) { throw new NotSupportedException(); } public int GetValues(object[] values) { throw new NotSupportedException(); } public object this[string name] { get { throw new NotSupportedException(); } } #endregion } }
namespace StockSharp.Algo { using System; using System.Collections.Generic; using System.Linq; using StockSharp.Algo.Candles; using StockSharp.Algo.Positions; using StockSharp.BusinessEntities; using StockSharp.Logging; using StockSharp.Messages; using StockSharp.Localization; partial class TraderHelper { ///// <summary> ///// To get the position by the order. ///// </summary> ///// <param name="order">The order, used for the position calculation. At buy the position is taken with positive sign, at sell - with negative.</param> ///// <param name="connector">The connection of interaction with trade systems.</param> ///// <returns>Position.</returns> //public static decimal GetPosition(this Order order, IConnector connector) //{ // var volume = order.GetMatchedVolume(connector); // return order.Direction == Sides.Buy ? volume : -volume; //} ///// <summary> ///// To get the position by the portfolio. ///// </summary> ///// <param name="portfolio">The portfolio, for which the position needs to be got.</param> ///// <param name="connector">The connection of interaction with trade systems.</param> ///// <returns>The position by the portfolio.</returns> //public static decimal GetPosition(this Portfolio portfolio, IConnector connector) //{ // if (portfolio == null) // throw new ArgumentNullException(nameof(portfolio)); // if (connector == null) // throw new ArgumentNullException(nameof(connector)); // return connector.Positions.Filter(portfolio).Sum(p => p.CurrentValue); //} ///// <summary> ///// To get the position by My trades. ///// </summary> ///// <param name="trades">My trades, used for the position calculation using the <see cref="GetPosition(StockSharp.BusinessEntities.MyTrade)"/> method.</param> ///// <returns>Position.</returns> //public static decimal GetPosition(this IEnumerable<MyTrade> trades) //{ // return trades.Sum(t => t.GetPosition()); //} ///// <summary> ///// To get the trade volume, collatable with the position size. ///// </summary> ///// <param name="position">The position by the instrument.</param> ///// <returns>Order volume.</returns> //public static decimal GetOrderVolume(this Position position) //{ // if (position == null) // throw new ArgumentNullException(nameof(position)); // return (position.CurrentValue / position.Security.VolumeStep ?? 1m).Abs(); //} ///// <summary> ///// To group orders by instrument and portfolio. ///// </summary> ///// <param name="orders">Initial orders.</param> ///// <returns>Grouped orders.</returns> ///// <remarks> ///// Recommended to use to reduce trade costs. ///// </remarks> //public static IEnumerable<Order> Join(this IEnumerable<Order> orders) //{ // if (orders == null) // throw new ArgumentNullException(nameof(orders)); // return orders.GroupBy(o => Tuple.Create(o.Security, o.Portfolio)).Select(g => // { // Order firstOrder = null; // foreach (var order in g) // { // if (firstOrder == null) // { // firstOrder = order; // } // else // { // var sameDir = firstOrder.Direction == order.Direction; // firstOrder.Volume += (sameDir ? 1 : -1) * order.Volume; // if (firstOrder.Volume < 0) // { // firstOrder.Direction = firstOrder.Direction.Invert(); // firstOrder.Volume = firstOrder.Volume.Abs(); // } // firstOrder.Price = sameDir ? firstOrder.Price.GetMiddle(order.Price) : order.Price; // } // } // if (firstOrder == null) // throw new InvalidOperationException(LocalizedStrings.Str1211); // if (firstOrder.Volume == 0) // return null; // firstOrder.ShrinkPrice(); // return firstOrder; // }) // .Where(o => o != null); //} ///// <summary> ///// To calculate profit-loss based on trades. ///// </summary> ///// <param name="trades">Trades, for which the profit-loss shall be calculated.</param> ///// <returns>Profit-loss.</returns> //public static decimal GetPnL(this IEnumerable<MyTrade> trades) //{ // return trades.Select(t => t.ToMessage()).GetPnL(); //} ///// <summary> ///// To calculate profit-loss based on trades. ///// </summary> ///// <param name="trades">Trades, for which the profit-loss shall be calculated.</param> ///// <returns>Profit-loss.</returns> //public static decimal GetPnL(this IEnumerable<ExecutionMessage> trades) //{ // return trades.GroupBy(t => t.SecurityId).Sum(g => // { // var queue = new PnLQueue(g.Key); // g.OrderBy(t => t.ServerTime).ForEach(t => queue.Process(t)); // return queue.RealizedPnL + queue.UnrealizedPnL; // }); //} ///// <summary> ///// To calculate profit-loss for trade. ///// </summary> ///// <param name="trade">The trade for which the profit-loss shall be calculated.</param> ///// <param name="currentPrice">The current price of the instrument.</param> ///// <returns>Profit-loss.</returns> //public static decimal GetPnL(this MyTrade trade, decimal currentPrice) //{ // if (trade == null) // throw new ArgumentNullException(nameof(trade)); // return trade.ToMessage().GetPnL(currentPrice); //} ///// <summary> ///// To calculate profit-loss for trade. ///// </summary> ///// <param name="trade">The trade for which the profit-loss shall be calculated.</param> ///// <param name="currentPrice">The current price of the instrument.</param> ///// <returns>Profit-loss.</returns> //public static decimal GetPnL(this ExecutionMessage trade, decimal currentPrice) //{ // return GetPnL(trade.GetTradePrice(), trade.SafeGetVolume(), trade.Side, currentPrice); //} ///// <summary> ///// To calculate the position cost. ///// </summary> ///// <param name="position">Position.</param> ///// <param name="currentPrice">The current price of the instrument.</param> ///// <returns>Position price.</returns> //public static decimal GetPrice(this Position position, decimal currentPrice) //{ // if (position == null) // throw new ArgumentNullException(nameof(position)); // var security = position.Security; // return currentPrice * position.CurrentValue * security.StepPrice / security.PriceStep ?? 1; //} ///// <summary> ///// To calculate delay based on difference between the server and local time. ///// </summary> ///// <param name="security">Security.</param> ///// <param name="serverTime">Server time.</param> ///// <param name="localTime">Local time.</param> ///// <returns>Latency.</returns> //public static TimeSpan GetLatency(this Security security, DateTimeOffset serverTime, DateTimeOffset localTime) //{ // return localTime - serverTime; //} ///// <summary> ///// To calculate delay based on difference between the server and local time. ///// </summary> ///// <param name="securityId">Security ID.</param> ///// <param name="serverTime">Server time.</param> ///// <param name="localTime">Local time.</param> ///// <returns>Latency.</returns> //public static TimeSpan GetLatency(this SecurityId securityId, DateTimeOffset serverTime, DateTimeOffset localTime) //{ // var board = ExchangeBoard.GetBoard(securityId.BoardCode); // if (board == null) // throw new ArgumentException(LocalizedStrings.Str1217Params.Put(securityId.BoardCode), nameof(securityId)); // return localTime - serverTime; //} ///// <summary> ///// To get the size of clear funds in the portfolio. ///// </summary> ///// <param name="portfolio">Portfolio.</param> ///// <param name="useLeverage">Whether to use shoulder size for calculation.</param> ///// <returns>The size of clear funds.</returns> //public static decimal GetFreeMoney(this Portfolio portfolio, bool useLeverage = false) //{ // if (portfolio == null) // throw new ArgumentNullException(nameof(portfolio)); // var freeMoney = portfolio.Board == ExchangeBoard.Forts // ? portfolio.BeginValue - portfolio.CurrentValue + portfolio.VariationMargin // : portfolio.CurrentValue; // return useLeverage ? freeMoney * portfolio.Leverage : freeMoney; //} //private sealed class CashPosition : Position, IDisposable //{ // private readonly Portfolio _portfolio; // private readonly IConnector _connector; // public CashPosition(Portfolio portfolio, IConnector connector) // { // if (portfolio == null) // throw new ArgumentNullException(nameof(portfolio)); // if (connector == null) // throw new ArgumentNullException(nameof(connector)); // _portfolio = portfolio; // _connector = connector; // Portfolio = _portfolio; // Security = new Security // { // Id = _portfolio.Name, // Name = _portfolio.Name, // }; // UpdatePosition(); // _connector.PortfoliosChanged += TraderOnPortfoliosChanged; // } // private void UpdatePosition() // { // BeginValue = _portfolio.BeginValue; // CurrentValue = _portfolio.CurrentValue; // BlockedValue = _portfolio.Commission; // } // private void TraderOnPortfoliosChanged(IEnumerable<Portfolio> portfolios) // { // if (portfolios.Contains(_portfolio)) // UpdatePosition(); // } // void IDisposable.Dispose() // { // _connector.PortfoliosChanged -= TraderOnPortfoliosChanged; // } //} ///// <summary> ///// To convert portfolio into the monetary position. ///// </summary> ///// <param name="portfolio">Portfolio with trading account.</param> ///// <param name="connector">The connection of interaction with trading system.</param> ///// <returns>Money position.</returns> //public static Position ToCashPosition(this Portfolio portfolio, IConnector connector) //{ // return new CashPosition(portfolio, connector); //} //private sealed class LookupSecurityUpdate : Disposable //{ // private readonly IConnector _connector; // private TimeSpan _timeOut; // private readonly SyncObject _syncRoot = new SyncObject(); // private readonly SynchronizedList<Security> _securities; // public LookupSecurityUpdate(IConnector connector, Security criteria, TimeSpan timeOut) // { // if (connector == null) // throw new ArgumentNullException(nameof(connector)); // if (criteria == null) // throw new ArgumentNullException(nameof(criteria)); // _securities = new SynchronizedList<Security>(); // _connector = connector; // _timeOut = timeOut; // _connector.LookupSecuritiesResult += OnLookupSecuritiesResult; // _connector.LookupSecurities(criteria); // } // public IEnumerable<Security> Wait() // { // while (true) // { // if (!_syncRoot.Wait(_timeOut)) // break; // } // return _securities; // } // private void OnLookupSecuritiesResult(IEnumerable<Security> securities) // { // _securities.AddRange(securities); // _timeOut = securities.Any() // ? TimeSpan.FromSeconds(10) // : TimeSpan.Zero; // _syncRoot.Pulse(); // } // protected override void DisposeManaged() // { // _connector.LookupSecuritiesResult -= OnLookupSecuritiesResult; // } //} ///// <summary> ///// To perform blocking search of instruments, corresponding to the criteria filter. ///// </summary> ///// <param name="connector">The connection of interaction with trading system.</param> ///// <param name="criteria">Instruments search criteria.</param> ///// <returns>Found instruments.</returns> //public static IEnumerable<Security> SyncLookupSecurities(this IConnector connector, Security criteria) //{ // if (connector == null) // throw new ArgumentNullException(nameof(connector)); // if (criteria == null) // throw new ArgumentNullException(nameof(criteria)); // using (var lsu = new LookupSecurityUpdate(connector, criteria, TimeSpan.FromSeconds(180))) // { // return lsu.Wait(); // } //} /// <summary> /// To get order trades. /// </summary> /// <param name="order">Orders.</param> /// <param name="connector">The connection of interaction with trade systems.</param> /// <returns>Trades.</returns> [Obsolete] public static IEnumerable<MyTrade> GetTrades(this Order order, IConnector connector) { if (order == null) throw new ArgumentNullException(nameof(order)); if (connector == null) throw new ArgumentNullException(nameof(connector)); return connector.MyTrades.Filter(order); } /// <summary> /// To get weighted mean price of order matching. /// </summary> /// <param name="order">The order, for which the weighted mean matching price shall be got.</param> /// <param name="connector">The connection of interaction with trade systems.</param> /// <returns>The weighted mean price. If no order exists no trades, 0 is returned.</returns> [Obsolete] public static decimal GetAveragePrice(this Order order, IConnector connector) { return order.GetTrades(connector).GetAveragePrice(); } /// <summary> /// To calculate the implemented part of volume for order. /// </summary> /// <param name="order">The order, for which the implemented part of volume shall be calculated.</param> /// <param name="connector">The connection of interaction with trade systems.</param> /// <returns>The implemented part of volume.</returns> [Obsolete] public static decimal GetMatchedVolume(this Order order, IConnector connector) { if (order == null) throw new ArgumentNullException(nameof(order)); if (order.Type == OrderTypes.Conditional) throw new ArgumentException(nameof(order)); return order.GetTrades(connector).Sum(o => o.Trade.Volume); } /// <summary> /// To get the position on own trade. /// </summary> /// <param name="message">Own trade, used for position calculation. At buy the trade volume <see cref="ExecutionMessage.TradeVolume"/> is taken with positive sign, at sell - with negative.</param> /// <param name="byOrder">To check implemented volume by order balance (<see cref="ExecutionMessage.Balance"/>) or by received trades. The default is checked by the order.</param> /// <returns>Position.</returns> [Obsolete] public static decimal? GetPosition(this ExecutionMessage message, bool byOrder) { if (message == null) throw new ArgumentNullException(nameof(message)); var sign = message.Side == Sides.Buy ? 1 : -1; decimal? position; if (byOrder) position = message.OrderVolume - message.Balance; else position = message.TradeVolume; return position * sign; } private sealed class NativePositionManager : IPositionManager { //private readonly Position _position; public NativePositionManager(Position position) { if (position is null) throw new ArgumentNullException(nameof(position)); //_position = position ?? throw new ArgumentNullException(nameof(position)); } PositionChangeMessage IPositionManager.ProcessMessage(Message message) => null; } /// <summary> /// Convert the position object to the type <see cref="IPositionManager"/>. /// </summary> /// <param name="position">Position.</param> /// <returns>Position calc manager.</returns> [Obsolete] public static IPositionManager ToPositionManager(this Position position) => new NativePositionManager(position); /// <summary> /// Subscribe on orders changes. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">Security for subscription.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <param name="count">Max count.</param> /// <param name="states">Filter order by the specified states.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="skip">Skip count.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeOrders(this ISubscriptionProvider provider, Security security = null, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, IEnumerable<OrderStates> states = null, IMessageAdapter adapter = null, long? skip = null) { if (provider is null) throw new ArgumentNullException(nameof(provider)); var message = new OrderStatusMessage { IsSubscribe = true, SecurityId = security?.ToSecurityId() ?? default, From = from, To = to, Adapter = adapter, Count = count, Skip = skip, }; if (states != null) message.States = states.ToArray(); var subscription = new Subscription(message, (SecurityMessage)null); provider.Subscribe(subscription); return subscription; } /// <summary> /// Subscribe on positions changes. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument on which the position should be found.</param> /// <param name="portfolio">The portfolio on which the position should be found.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <param name="count">Max count.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="skip">Skip count.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribePositions(this ISubscriptionProvider provider, Security security = null, Portfolio portfolio = null, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, IMessageAdapter adapter = null, long? skip = null) { if (provider is null) throw new ArgumentNullException(nameof(provider)); var subscription = new Subscription(new PortfolioLookupMessage { Adapter = adapter, IsSubscribe = true, SecurityId = security?.ToSecurityId(), PortfolioName = portfolio?.Name, From = from, To = to, Count = count, Skip = skip, }, (SecurityMessage)null); provider.Subscribe(subscription); return subscription; } /// <summary> /// To find instruments that match the filter <paramref name="criteria" />. Found instruments will be passed through the event <see cref="IMarketDataProvider.LookupSecuritiesResult"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The criterion which fields will be used as a filter.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="offlineMode">Offline mode handling message.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription LookupSecurities(this ISubscriptionProvider provider, Security criteria, IMessageAdapter adapter = null, MessageOfflineModes offlineMode = MessageOfflineModes.None) { var msg = criteria.ToLookupMessage(); msg.Adapter = adapter; msg.OfflineMode = offlineMode; return provider.LookupSecurities(msg); } /// <summary> /// To find orders that match the filter <paramref name="criteria" />. Found orders will be passed through the event <see cref="ITransactionProvider.NewOrder"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The order which fields will be used as a filter.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="offlineMode">Offline mode handling message.</param> /// <returns>Subscription.</returns> [Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription LookupOrders(this ISubscriptionProvider provider, Order criteria, IMessageAdapter adapter = null, MessageOfflineModes offlineMode = MessageOfflineModes.None) { var msg = criteria.ToLookupCriteria(null, null); msg.Adapter = adapter; msg.OfflineMode = offlineMode; return provider.LookupOrders(msg); } /// <summary> /// Subscribe to receive new candles. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="series">Candles series.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <param name="count">Candles count.</param> /// <param name="transactionId">Transaction ID.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="skip">Skip count.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeCandles(this ISubscriptionProvider provider, CandleSeries series, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, long? transactionId = null, IMessageAdapter adapter = null, long? skip = null) { if (provider is null) throw new ArgumentNullException(nameof(provider)); if (provider is ILogReceiver logs) logs.AddInfoLog(nameof(SubscribeCandles)); var subscription = new Subscription(series); var mdMsg = (MarketDataMessage)subscription.SubscriptionMessage; if (from != null) mdMsg.From = from.Value; if (to != null) mdMsg.To = to.Value; if (count != null) mdMsg.Count = count.Value; if (skip != null) mdMsg.Skip = skip.Value; mdMsg.Adapter = adapter; if (transactionId != null) subscription.TransactionId = transactionId.Value; provider.Subscribe(subscription); return subscription; } /// <summary> /// To stop the candles receiving subscription, previously created by <see cref="SubscribeCandles"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="series">Candles series.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeCandles(this ISubscriptionProvider provider, CandleSeries series) { if (provider is null) throw new ArgumentNullException(nameof(provider)); if (series is null) throw new ArgumentNullException(nameof(series)); var subscription = provider.Subscriptions.FirstOrDefault(s => s.CandleSeries == series); if (subscription is null) { if (provider is ILogReceiver logs) logs.AddWarningLog(LocalizedStrings.SubscriptionNonExist, series); } else provider.UnSubscribe(subscription); } /// <summary> /// To find portfolios that match the filter <paramref name="criteria" />. Found portfolios will be passed through the event <see cref="ITransactionProvider.LookupPortfoliosResult"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The criterion which fields will be used as a filter.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribePositions(this ISubscriptionProvider provider, PortfolioLookupMessage criteria) { if (provider is null) throw new ArgumentNullException(nameof(provider)); var subscription = new Subscription(criteria, (SecurityMessage)null); provider.Subscribe(subscription); return subscription; } /// <summary> /// Unsubscribe from positions changes. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="originalTransactionId">ID of the original message <see cref="SubscribePositions(ISubscriptionProvider, PortfolioLookupMessage)"/> for which this message is a response.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribePositions(this ISubscriptionProvider provider, long originalTransactionId = 0) { var subscription = provider.TryGetSubscription(originalTransactionId, DataType.PositionChanges, null); if (subscription != null) provider.UnSubscribe(subscription); } /// <summary> /// To find instruments that match the filter <paramref name="criteria" />. Found instruments will be passed through the event <see cref="IMarketDataProvider.LookupSecuritiesResult"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The criterion which fields will be used as a filter.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription LookupSecurities(this ISubscriptionProvider provider, SecurityLookupMessage criteria) { if (provider is null) throw new ArgumentNullException(nameof(provider)); var subscription = new Subscription(criteria, (SecurityMessage)null); provider.Subscribe(subscription); return subscription; } /// <summary> /// To find time-frames that match the filter <paramref name="criteria" />. Found time-frames will be passed through the event <see cref="IMarketDataProvider.LookupTimeFramesResult"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The criterion which fields will be used as a filter.</param> /// <returns>Subscription.</returns> [Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription LookupTimeFrames(this ISubscriptionProvider provider, TimeFrameLookupMessage criteria) { if (provider is null) throw new ArgumentNullException(nameof(provider)); var subscription = new Subscription(criteria, (SecurityMessage)null); provider.Subscribe(subscription); return subscription; } /// <summary> /// To find orders that match the filter <paramref name="criteria" />. Found orders will be passed through the event <see cref="ITransactionProvider.NewOrder"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The order which fields will be used as a filter.</param> /// <returns>Subscription.</returns> [Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription LookupOrders(this ISubscriptionProvider provider, OrderStatusMessage criteria) { return provider.SubscribeOrders(criteria); } /// <summary> /// To find portfolios that match the filter <paramref name="criteria" />. Found portfolios will be passed through the event <see cref="ITransactionProvider.LookupPortfoliosResult"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The criterion which fields will be used as a filter.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="offlineMode">Offline mode handling message.</param> /// <returns>Subscription.</returns> [Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription LookupPortfolios(this ISubscriptionProvider provider, Portfolio criteria, IMessageAdapter adapter = null, MessageOfflineModes offlineMode = MessageOfflineModes.None) { if (criteria == null) throw new ArgumentNullException(nameof(criteria)); var msg = criteria.ToLookupCriteria(); msg.Adapter = adapter; msg.OfflineMode = offlineMode; return provider.LookupPortfolios(msg); } /// <summary> /// To find portfolios that match the filter <paramref name="criteria" />. Found portfolios will be passed through the event <see cref="ITransactionProvider.LookupPortfoliosResult"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The criterion which fields will be used as a filter.</param> /// <returns>Subscription.</returns> [Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription LookupPortfolios(this ISubscriptionProvider provider, PortfolioLookupMessage criteria) { return provider.SubscribePositions(criteria); } /// <summary> /// To find boards that match the filter <paramref name="criteria" />. Found boards will be passed through the event <see cref="IMarketDataProvider.LookupBoardsResult"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The criterion which fields will be used as a filter.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="offlineMode">Offline mode handling message.</param> /// <returns>Subscription.</returns> [Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription LookupBoards(this ISubscriptionProvider provider, ExchangeBoard criteria, IMessageAdapter adapter = null, MessageOfflineModes offlineMode = MessageOfflineModes.None) { if (criteria == null) throw new ArgumentNullException(nameof(criteria)); var msg = new BoardLookupMessage { Like = criteria.Code, Adapter = adapter, OfflineMode = offlineMode, }; return provider.LookupBoards(msg); } /// <summary> /// To find boards that match the filter <paramref name="criteria" />. Found boards will be passed through the event <see cref="IMarketDataProvider.LookupBoardsResult"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The criterion which fields will be used as a filter.</param> /// <returns>Subscription.</returns> [Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription LookupBoards(this ISubscriptionProvider provider, BoardLookupMessage criteria) { if (provider is null) throw new ArgumentNullException(nameof(provider)); var subscription = new Subscription(criteria, (SecurityMessage)null); provider.Subscribe(subscription); return subscription; } /// <summary> /// Subscribe on the board changes. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="board">Board for subscription.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <param name="count">Max count.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="skip">Skip count.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeBoard(this ISubscriptionProvider provider, ExchangeBoard board, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, IMessageAdapter adapter = null, long? skip = null) { if (board is null) throw new ArgumentNullException(nameof(board)); return provider.SubscribeMarketData(null, DataType.BoardState, from, to, count, adapter: adapter, skip: skip); } /// <summary> /// Unsubscribe from the board changes. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="board">Board for unsubscription.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeBoard(this ISubscriptionProvider provider, ExchangeBoard board) { if (board is null) throw new ArgumentNullException(nameof(board)); var subscription = provider.TryGetSubscription(0, DataType.BoardState, null); if (subscription != null) provider.UnSubscribe(subscription); } /// <summary> /// Unsubscribe. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="subscriptionId">Subscription id.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribe(this ISubscriptionProvider provider, long subscriptionId) { var subscription = provider.TryGetSubscription(subscriptionId, null, null); if (subscription != null) provider.UnSubscribe(subscription); } /// <summary> /// To find orders that match the filter <paramref name="criteria" />. Found orders will be passed through the event <see cref="ITransactionProvider.NewOrder"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="criteria">The order which fields will be used as a filter.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeOrders(this ISubscriptionProvider provider, OrderStatusMessage criteria) { if (provider is null) throw new ArgumentNullException(nameof(provider)); var subscription = new Subscription(criteria, (SecurityMessage)null); provider.Subscribe(subscription); return subscription; } /// <summary> /// Unsubscribe from orders changes. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="originalTransactionId">ID of the original message <see cref="SubscribeOrders(ISubscriptionProvider, OrderStatusMessage)"/> for which this message is a response.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeOrders(this ISubscriptionProvider provider, long originalTransactionId = 0) { var security = provider.TryGetSubscription(originalTransactionId, DataType.Transactions, null); if (security != null) provider.UnSubscribe(security); } /// <summary> /// To start getting quotes (order book) by the instrument. Quotes values are available through the event <see cref="IMarketDataProvider.MarketDepthChanged"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument by which quotes getting should be started.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <param name="count">Max count.</param> /// <param name="buildMode">Build mode.</param> /// <param name="buildFrom">Which market-data type is used as a source value.</param> /// <param name="maxDepth">Max depth of requested order book.</param> /// <param name="refreshSpeed">Interval for data refresh.</param> /// <param name="depthBuilder">Order log to market depth builder.</param> /// <param name="passThroughOrderBookInrement">Pass through incremental <see cref="QuoteChangeMessage"/>.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="skip">Skip count.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeMarketDepth(this ISubscriptionProvider provider, Security security, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, MarketDataBuildModes buildMode = MarketDataBuildModes.LoadAndBuild, DataType buildFrom = null, int? maxDepth = null, TimeSpan? refreshSpeed = null, IOrderLogMarketDepthBuilder depthBuilder = null, bool passThroughOrderBookInrement = false, IMessageAdapter adapter = null, long? skip = null) { return provider.SubscribeMarketData(security, DataType.MarketDepth, from, to, count, buildMode, buildFrom, null, maxDepth, refreshSpeed, depthBuilder, passThroughOrderBookInrement, adapter, skip: skip); } /// <summary> /// To stop getting quotes by the instrument. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument by which quotes getting should be stopped.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeMarketDepth(this ISubscriptionProvider provider, Security security) { provider.UnSubscribeMarketData(security, DataType.MarketDepth); } /// <summary> /// To start getting trades (tick data) by the instrument. New trades will come through the event <see cref="IMarketDataProvider.NewTrade"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument by which trades getting should be started.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <param name="count">Max count.</param> /// <param name="buildMode">Build mode.</param> /// <param name="buildFrom">Which market-data type is used as a source value.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="skip">Skip count.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeTrades(this ISubscriptionProvider provider, Security security, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, MarketDataBuildModes buildMode = MarketDataBuildModes.LoadAndBuild, DataType buildFrom = null, IMessageAdapter adapter = null, long? skip = null) { return provider.SubscribeMarketData(security, DataType.Ticks, from, to, count, buildMode, buildFrom, adapter: adapter, skip: skip); } /// <summary> /// To stop getting trades (tick data) by the instrument. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument by which trades getting should be stopped.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeTrades(this ISubscriptionProvider provider, Security security) { provider.UnSubscribeMarketData(security, DataType.Ticks); } /// <summary> /// To start getting new information (for example, <see cref="Security.LastTrade"/> or <see cref="Security.BestBid"/>) by the instrument. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument by which new information getting should be started.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <param name="count">Max count.</param> /// <param name="buildMode">Build mode.</param> /// <param name="buildFrom">Which market-data type is used as a source value.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="skip">Skip count.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeLevel1(this ISubscriptionProvider provider, Security security, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, MarketDataBuildModes buildMode = MarketDataBuildModes.LoadAndBuild, DataType buildFrom = null, IMessageAdapter adapter = null, long? skip = null) { return provider.SubscribeMarketData(security, DataType.Level1, from, to, count, buildMode, buildFrom, adapter: adapter, skip: skip); } /// <summary> /// To stop getting new information. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument by which new information getting should be stopped.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeLevel1(this ISubscriptionProvider provider, Security security) { provider.UnSubscribeMarketData(security, DataType.Level1); } /// <summary> /// Subscribe on order log for the security. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">Security for subscription.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <param name="count">Max count.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <returns>Subscription.</returns> /// <param name="skip">Skip count.</param> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeOrderLog(this ISubscriptionProvider provider, Security security, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, IMessageAdapter adapter = null, long? skip = null) { return provider.SubscribeMarketData(security, DataType.OrderLog, from, to, count, adapter: adapter, skip: skip); } /// <summary> /// Unsubscribe from order log for the security. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">Security for unsubscription.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeOrderLog(this ISubscriptionProvider provider, Security security) { provider.UnSubscribeMarketData(security, DataType.OrderLog); } /// <summary> /// Subscribe on news. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">Security for subscription.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> /// <param name="count">Max count.</param> /// <param name="adapter">Target adapter. Can be <see langword="null" />.</param> /// <param name="skip">Skip count.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeNews(this ISubscriptionProvider provider, Security security = null, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, IMessageAdapter adapter = null, long? skip = null) { return provider.SubscribeMarketData(security, DataType.News, from, to, count, adapter: adapter, skip: skip); } /// <summary> /// Unsubscribe from news. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">Security for subscription.</param> [Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeNews(this ISubscriptionProvider provider, Security security = null) { provider.UnSubscribeMarketData(security, DataType.News); } /// <summary> /// To subscribe to get market data by the instrument. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument by which new information getting should be started.</param> /// <param name="message">The message that contain subscribe info.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeMarketData(this ISubscriptionProvider provider, Security security, MarketDataMessage message) { if (provider is null) throw new ArgumentNullException(nameof(provider)); var subscription = new Subscription(message, security); provider.Subscribe(subscription); return subscription; } /// <summary> /// To unsubscribe from getting market data by the instrument. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument by which new information getting should be started.</param> /// <param name="message">The message that contain unsubscribe info.</param> //[Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeMarketData(this ISubscriptionProvider provider, Security security, MarketDataMessage message) { if (message == null) throw new ArgumentNullException(nameof(message)); var subscription = provider.TryGetSubscription(0, message.DataType2, security); if (subscription != null) provider.UnSubscribe(subscription); } /// <summary> /// To subscribe to get market data. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="message">The message that contain subscribe info.</param> /// <returns>Subscription.</returns> //[Obsolete("Use ISubscriptionProvider.Subscribe method.")] public static Subscription SubscribeMarketData(this ISubscriptionProvider provider, MarketDataMessage message) { return provider.SubscribeMarketData(null, message); } /// <summary> /// To unsubscribe from getting market data. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="message">The message that contain unsubscribe info.</param> //[Obsolete("Use ISubscriptionProvider.UnSubscribe method.")] public static void UnSubscribeMarketData(this ISubscriptionProvider provider, MarketDataMessage message) { provider.UnSubscribeMarketData(null, message); } /// <summary> /// To start getting filtered quotes (order book) by the instrument. Quotes values are available through the event <see cref="IMarketDataProvider.FilteredMarketDepthChanged"/>. /// </summary> /// <param name="provider">Subscription provider.</param> /// <param name="security">The instrument by which quotes getting should be started.</param> /// <returns>Subscription.</returns> public static Subscription SubscribeFilteredMarketDepth(this ISubscriptionProvider provider, Security security) { return provider.SubscribeMarketData(security, DataType.FilteredMarketDepth); } private static Subscription SubscribeMarketData(this ISubscriptionProvider provider, Security security, DataType type, DateTimeOffset? from = null, DateTimeOffset? to = null, long? count = null, MarketDataBuildModes buildMode = MarketDataBuildModes.LoadAndBuild, DataType buildFrom = null, Level1Fields? buildField = null, int? maxDepth = null, TimeSpan? refreshSpeed = null, IOrderLogMarketDepthBuilder depthBuilder = null, bool doNotBuildOrderBookInrement = false, IMessageAdapter adapter = null, long? skip = null) { return provider.SubscribeMarketData(security, new MarketDataMessage { DataType2 = type, IsSubscribe = true, From = from, To = to, Count = count, BuildMode = buildMode, BuildFrom = buildFrom, BuildField = buildField, MaxDepth = maxDepth, RefreshSpeed = refreshSpeed, DepthBuilder = depthBuilder, DoNotBuildOrderBookInrement = doNotBuildOrderBookInrement, Adapter = adapter, Skip = skip, }); } private static void UnSubscribeMarketData(this ISubscriptionProvider provider, Security security, DataType type) { provider.UnSubscribeMarketData(security, new MarketDataMessage { DataType2 = type, IsSubscribe = false, }); } private static Subscription TryGetSubscription(this ISubscriptionProvider provider, long id, DataType dataType, Security security) { if (provider is null) throw new ArgumentNullException(nameof(provider)); var secId = security?.ToSecurityId(); var subscription = id > 0 ? provider.Subscriptions.FirstOrDefault(s => s.TransactionId == id) : provider.Subscriptions.FirstOrDefault(s => s.DataType == dataType && s.SecurityId == secId && s.State.IsActive()); if (subscription != null && id > 0 && !subscription.State.IsActive()) { subscription = null; } if (subscription == null) { if (provider is ILogReceiver logs) logs.AddWarningLog(LocalizedStrings.SubscriptionNonExist, id > 0 ? id : Tuple.Create(dataType, security)); } return subscription; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UIntPtr ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.Serialization; using System.Security; using System.Diagnostics.Contracts; [Serializable] [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public struct UIntPtr : ISerializable { [SecurityCritical] unsafe private void* m_value; public static readonly UIntPtr Zero; [System.Security.SecuritySafeCritical] // auto-generated public unsafe UIntPtr(uint value) { m_value = (void *)value; } [System.Security.SecuritySafeCritical] // auto-generated public unsafe UIntPtr(ulong value) { #if WIN32 m_value = (void*)checked((uint)value); #else m_value = (void *)value; #endif } [System.Security.SecurityCritical] [CLSCompliant(false)] public unsafe UIntPtr(void* value) { m_value = value; } [System.Security.SecurityCritical] // auto-generated private unsafe UIntPtr(SerializationInfo info, StreamingContext context) { ulong l = info.GetUInt64("value"); if (Size==4 && l>UInt32.MaxValue) { throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue")); } m_value = (void *)l; } #if FEATURE_SERIALIZATION [System.Security.SecurityCritical] unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); info.AddValue("value", (ulong)m_value); } #endif [System.Security.SecuritySafeCritical] // auto-generated public unsafe override bool Equals(Object obj) { if (obj is UIntPtr) { return (m_value == ((UIntPtr)obj).m_value); } return false; } [System.Security.SecuritySafeCritical] // auto-generated public unsafe override int GetHashCode() { return unchecked((int)((long)m_value)) & 0x7fffffff; } [System.Security.SecuritySafeCritical] // auto-generated public unsafe uint ToUInt32() { #if WIN32 return (uint)m_value; #else return checked((uint)m_value); #endif } [System.Security.SecuritySafeCritical] // auto-generated public unsafe ulong ToUInt64() { return (ulong)m_value; } [System.Security.SecuritySafeCritical] // auto-generated public unsafe override String ToString() { Contract.Ensures(Contract.Result<String>() != null); #if WIN32 return ((uint)m_value).ToString(CultureInfo.InvariantCulture); #else return ((ulong)m_value).ToString(CultureInfo.InvariantCulture); #endif } public static explicit operator UIntPtr (uint value) { return new UIntPtr(value); } public static explicit operator UIntPtr (ulong value) { return new UIntPtr(value); } [System.Security.SecuritySafeCritical] // auto-generated public unsafe static explicit operator uint(UIntPtr value) { #if WIN32 return (uint)value.m_value; #else return checked((uint)value.m_value); #endif } [System.Security.SecuritySafeCritical] // auto-generated public unsafe static explicit operator ulong (UIntPtr value) { return (ulong)value.m_value; } [System.Security.SecurityCritical] [CLSCompliant(false)] public static unsafe explicit operator UIntPtr (void* value) { return new UIntPtr(value); } [System.Security.SecurityCritical] [CLSCompliant(false)] public static unsafe explicit operator void* (UIntPtr value) { return value.ToPointer(); } [System.Security.SecuritySafeCritical] // auto-generated public unsafe static bool operator == (UIntPtr value1, UIntPtr value2) { return value1.m_value == value2.m_value; } [System.Security.SecuritySafeCritical] // auto-generated public unsafe static bool operator != (UIntPtr value1, UIntPtr value2) { return value1.m_value != value2.m_value; } public static UIntPtr Add(UIntPtr pointer, int offset) { return pointer + offset; } public static UIntPtr operator +(UIntPtr pointer, int offset) { #if WIN32 return new UIntPtr(pointer.ToUInt32() + (uint)offset); #else return new UIntPtr(pointer.ToUInt64() + (ulong)offset); #endif } public static UIntPtr Subtract(UIntPtr pointer, int offset) { return pointer - offset; } public static UIntPtr operator -(UIntPtr pointer, int offset) { #if WIN32 return new UIntPtr(pointer.ToUInt32() - (uint)offset); #else return new UIntPtr(pointer.ToUInt64() - (ulong)offset); #endif } public static int Size { get { #if WIN32 return 4; #else return 8; #endif } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public unsafe void* ToPointer() { return m_value; } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: HttpModuleRegistry.cs 633 2009-05-30 01:58:12Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Web; #endregion internal static class HttpModuleRegistry { private static Dictionary<HttpApplication, IList<IHttpModule>> _moduleListByApp; private static readonly object _lock = new object(); public static bool RegisterInPartialTrust(HttpApplication application, IHttpModule module) { if (application == null) throw new ArgumentNullException("application"); if (module == null) throw new ArgumentNullException("module"); if (IsHighlyTrusted()) return false; lock (_lock) { // // On-demand allocate a map of modules per application. // if (_moduleListByApp == null) _moduleListByApp = new Dictionary<HttpApplication, IList<IHttpModule>>(); // // Get the list of modules for the application. If this is // the first registration for the supplied application object // then setup a new and empty list. // var moduleList = _moduleListByApp.Find(application); if (moduleList == null) { moduleList = new List<IHttpModule>(); _moduleListByApp.Add(application, moduleList); } else if (moduleList.Contains(module)) throw new ApplicationException("Duplicate module registration."); // // Add the module to list of registered modules for the // given application object. // moduleList.Add(module); } // // Setup a closure to automatically unregister the module // when the application fires its Disposed event. // Housekeeper housekeeper = new Housekeeper(module); application.Disposed += new EventHandler(housekeeper.OnApplicationDisposed); return true; } private static bool UnregisterInPartialTrust(HttpApplication application, IHttpModule module) { Debug.Assert(application != null); Debug.Assert(module != null); if (module == null) throw new ArgumentNullException("module"); if (IsHighlyTrusted()) return false; lock (_lock) { // // Get the module list for the given application object. // if (_moduleListByApp == null) return false; var moduleList = _moduleListByApp.Find(application); if (moduleList == null) return false; // // Remove the module from the list if it's in there. // int index = moduleList.IndexOf(module); if (index < 0) return false; moduleList.RemoveAt(index); // // If the list is empty then remove the application entry. // If this results in the entire map becoming empty then // release it. // if (moduleList.Count == 0) { _moduleListByApp.Remove(application); if (_moduleListByApp.Count == 0) _moduleListByApp = null; } } return true; } public static IEnumerable<IHttpModule> GetModules(HttpApplication application) { if (application == null) throw new ArgumentNullException("application"); try { IHttpModule[] modules = new IHttpModule[application.Modules.Count]; application.Modules.CopyTo(modules, 0); return modules; } catch (SecurityException) { // // Pass through because probably this is a partially trusted // environment that does not have access to the modules // collection over HttpApplication so we have to resort // to our own devices... // } lock (_lock) { if (_moduleListByApp == null) return Enumerable.Empty<IHttpModule>(); var moduleList = _moduleListByApp.Find(application); if (moduleList == null) return Enumerable.Empty<IHttpModule>(); IHttpModule[] modules = new IHttpModule[moduleList.Count]; moduleList.CopyTo(modules, 0); return modules; } } private static bool IsHighlyTrusted() { try { AspNetHostingPermission permission = new AspNetHostingPermission(AspNetHostingPermissionLevel.High); permission.Demand(); return true; } catch (SecurityException) { return false; } } internal sealed class Housekeeper { private readonly IHttpModule _module; public Housekeeper(IHttpModule module) { _module = module; } public void OnApplicationDisposed(object sender, EventArgs e) { UnregisterInPartialTrust((HttpApplication) sender, _module); } } } }
// // Mono.System.Xml.XmlAttributeCollection // // Author: // Jason Diamond (jason@injektilo.org) // Atsushi Enomoto (ginga@kit.hi-ho.ne.jp) // // (C) 2002 Jason Diamond http://injektilo.org/ // (C) 2002 Atsushi Enomoto // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using Mono.Xml; namespace Mono.System.Xml { #if NET_2_0 public sealed class XmlAttributeCollection : XmlNamedNodeMap, ICollection #else public class XmlAttributeCollection : XmlNamedNodeMap, ICollection #endif { XmlElement ownerElement; XmlDocument ownerDocument; internal XmlAttributeCollection (XmlNode parent) : base (parent) { ownerElement = parent as XmlElement; ownerDocument = parent.OwnerDocument; if(ownerElement == null) throw new XmlException ("invalid construction for XmlAttributeCollection."); } bool ICollection.IsSynchronized { get { return false; } } bool IsReadOnly { get { return ownerElement.IsReadOnly; } } [global::System.Runtime.CompilerServices.IndexerName ("ItemOf")] #if NET_2_0 public XmlAttribute this [string name] { #else public virtual XmlAttribute this [string name] { #endif get { return (XmlAttribute) GetNamedItem (name); } } [global::System.Runtime.CompilerServices.IndexerName ("ItemOf")] #if NET_2_0 public XmlAttribute this [int i] { #else public virtual XmlAttribute this [int i] { #endif get { return (XmlAttribute) Nodes [i]; } } [global::System.Runtime.CompilerServices.IndexerName ("ItemOf")] #if NET_2_0 public XmlAttribute this [string localName, string namespaceURI] { #else public virtual XmlAttribute this [string localName, string namespaceURI] { #endif get { return (XmlAttribute) GetNamedItem (localName, namespaceURI); } } object ICollection.SyncRoot { get { return this; } } #if NET_2_0 public XmlAttribute Append (XmlAttribute node) #else public virtual XmlAttribute Append (XmlAttribute node) #endif { SetNamedItem (node); return node; } public void CopyTo (XmlAttribute[] array, int index) { // assuming that Nodes is a correct collection. for(int i=0; i<Count; i++) array [index + i] = Nodes [i] as XmlAttribute; } void ICollection.CopyTo (Array array, int index) { // assuming that Nodes is a correct collection. array.CopyTo (Nodes.ToArray (typeof(XmlAttribute)), index); } #if NET_2_0 public XmlAttribute InsertAfter (XmlAttribute newNode, XmlAttribute refNode) #else public virtual XmlAttribute InsertAfter (XmlAttribute newNode, XmlAttribute refNode) #endif { if (refNode == null) { if (Count == 0) return InsertBefore (newNode, null); else return InsertBefore (newNode, this [0]); } for (int i = 0; i < Count; i++) if (refNode == Nodes [i]) return InsertBefore (newNode, Count == i + 1 ? null : this [i + 1]); throw new ArgumentException ("refNode not found in this collection."); } #if NET_2_0 public XmlAttribute InsertBefore (XmlAttribute newNode, XmlAttribute refNode) #else public virtual XmlAttribute InsertBefore (XmlAttribute newNode, XmlAttribute refNode) #endif { if (newNode.OwnerDocument != ownerDocument) throw new ArgumentException ("different document created this newNode."); ownerDocument.onNodeInserting (newNode, null); int pos = Count; if (refNode != null) { for (int i = 0; i < Count; i++) { XmlNode n = Nodes [i] as XmlNode; if (n == refNode) { pos = i; break; } } if (pos == Count) throw new ArgumentException ("refNode not found in this collection."); } SetNamedItem (newNode, pos, false); ownerDocument.onNodeInserted (newNode, null); return newNode; } #if NET_2_0 public XmlAttribute Prepend (XmlAttribute node) #else public virtual XmlAttribute Prepend (XmlAttribute node) #endif { return this.InsertAfter (node, null); } #if NET_2_0 public XmlAttribute Remove (XmlAttribute node) #else public virtual XmlAttribute Remove (XmlAttribute node) #endif { if (IsReadOnly) throw new ArgumentException ("This attribute collection is read-only."); if (node == null) throw new ArgumentException ("Specified node is null."); if (node.OwnerDocument != ownerDocument) throw new ArgumentException ("Specified node is in a different document."); if (node.OwnerElement != this.ownerElement) throw new ArgumentException ("The specified attribute is not contained in the element."); XmlAttribute retAttr = null; for (int i = 0; i < Count; i++) { XmlAttribute attr = (XmlAttribute) Nodes [i]; if (attr == node) { retAttr = attr; break; } } if(retAttr != null) { ownerDocument.onNodeRemoving (node, ownerElement); base.RemoveNamedItem (retAttr.LocalName, retAttr.NamespaceURI); RemoveIdenticalAttribute (retAttr); ownerDocument.onNodeRemoved (node, ownerElement); } // If it is default, then directly create new attribute. DTDAttributeDefinition def = retAttr.GetAttributeDefinition (); if (def != null && def.DefaultValue != null) { XmlAttribute attr = ownerDocument.CreateAttribute ( retAttr.Prefix, retAttr.LocalName, retAttr.NamespaceURI, true, false); attr.Value = def.DefaultValue; attr.SetDefault (); this.SetNamedItem (attr); } retAttr.AttributeOwnerElement = null; return retAttr; } #if NET_2_0 public void RemoveAll () #else public virtual void RemoveAll () #endif { int current = 0; while (current < Count) { XmlAttribute attr = this [current]; if (!attr.Specified) current++; // It is called for the purpose of event support. Remove (attr); } } #if NET_2_0 public XmlAttribute RemoveAt (int i) #else public virtual XmlAttribute RemoveAt (int i) #endif { if(Count <= i) return null; return Remove ((XmlAttribute)Nodes [i]); } public override XmlNode SetNamedItem (XmlNode node) { if(IsReadOnly) throw new ArgumentException ("this AttributeCollection is read only."); XmlAttribute attr = node as XmlAttribute; if (attr.OwnerElement == ownerElement) return node; // do nothing if (attr.OwnerElement != null) throw new ArgumentException ("This attribute is already set to another element."); ownerElement.OwnerDocument.onNodeInserting (node, ownerElement); attr.AttributeOwnerElement = ownerElement; XmlNode n = base.SetNamedItem (node, -1, false); AdjustIdenticalAttributes (node as XmlAttribute, n == node ? null : n); ownerElement.OwnerDocument.onNodeInserted (node, ownerElement); return n as XmlAttribute; } internal void AddIdenticalAttribute () { SetIdenticalAttribute (false); } internal void RemoveIdenticalAttribute () { SetIdenticalAttribute (true); } private void SetIdenticalAttribute (bool remove) { if (ownerElement == null) return; // Check if new attribute's datatype is ID. XmlDocumentType doctype = ownerDocument.DocumentType; if (doctype == null || doctype.DTD == null) return; DTDElementDeclaration elem = doctype.DTD.ElementDecls [ownerElement.Name]; for (int i = 0; i < Count; i++) { XmlAttribute node = (XmlAttribute) Nodes [i]; DTDAttributeDefinition attdef = elem == null ? null : elem.Attributes [node.Name]; if (attdef == null || attdef.Datatype.TokenizedType != XmlTokenizedType.ID) continue; if (remove) { if (ownerDocument.GetIdenticalAttribute (node.Value) != null) { ownerDocument.RemoveIdenticalAttribute (node.Value); return; } } else { // adding new identical attribute, but // MS.NET is pity for ID support, so I'm wondering how to correct it... if (ownerDocument.GetIdenticalAttribute (node.Value) != null) throw new XmlException (String.Format ( "ID value {0} already exists in this document.", node.Value)); ownerDocument.AddIdenticalAttribute (node); return; } } } private void AdjustIdenticalAttributes (XmlAttribute node, XmlNode existing) { // If owner element is not appended to the document, // ID table should not be filled. if (ownerElement == null) return; if (existing != null) RemoveIdenticalAttribute (existing); // Check if new attribute's datatype is ID. XmlDocumentType doctype = node.OwnerDocument.DocumentType; if (doctype == null || doctype.DTD == null) return; DTDAttListDeclaration attList = doctype.DTD.AttListDecls [ownerElement.Name]; DTDAttributeDefinition attdef = attList == null ? null : attList.Get (node.Name); if (attdef == null || attdef.Datatype.TokenizedType != XmlTokenizedType.ID) return; ownerDocument.AddIdenticalAttribute (node); } private XmlNode RemoveIdenticalAttribute (XmlNode existing) { // If owner element is not appended to the document, // ID table should not be filled. if (ownerElement == null) return existing; if (existing != null) { // remove identical attribute (if it is). if (ownerDocument.GetIdenticalAttribute (existing.Value) != null) ownerDocument.RemoveIdenticalAttribute (existing.Value); } return existing; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //testing float narrowing upon conv.r4 explicit cast using System; public struct VT { public float f1; public float delta1; public int a1; public float b1; public float temp; } public class CL { //used for add and sub public float f1 = 1.0F; public float delta1 = 1.0E-10F; //used for mul and div public int a1 = 3; public float b1 = (1.0F / 3.0F); //used as temp variable public float temp; } public class ConvR4test { //static field of a1 class private static float s_f1 = 1.0F; private static float s_delta1 = 1.0E-10F; private static int s_a1 = 3; private static float s_b1 = (1.0F / 3.0F); private static void disableInline(ref int x) { } //f1 and delta1 are static filed of a1 class private static float floatadd() { int i = 0; disableInline(ref i); return s_f1 + s_delta1; } private static float floatsub() { int i = 0; disableInline(ref i); return s_f1 - s_delta1; } private static float floatmul() { int i = 0; disableInline(ref i); return s_a1 * s_b1; } private static float floatdiv() { int i = 0; disableInline(ref i); return s_f1 / s_a1; } private static float floatadd_inline() { return s_f1 + s_delta1; } private static float floatsub_inline() { return s_f1 - s_delta1; } private static float floatmul_inline() { return s_a1 * s_b1; } private static float floatdiv_inline() { return s_f1 / s_a1; } public static int Main() { bool pass = true; float temp; float[] arr = new float[3]; VT vt1; CL cl1 = new CL(); //*** add *** Console.WriteLine(); Console.WriteLine("***add***"); //local, in-line if (((float)(s_f1 + s_delta1)) != s_f1) { Console.WriteLine("((float)(f1+delta1))!=f1"); pass = false; } //local temp = s_f1 + s_delta1; if (((float)temp) != s_f1) { Console.WriteLine("((float)temp)!=f1, temp=f1+delta1"); pass = false; } //method call if (((float)floatadd()) != s_f1) { Console.WriteLine("((float)floatadd())!=f1"); pass = false; } //inline method call if (((float)floatadd_inline()) != s_f1) { Console.WriteLine("((float)floatadd_inline())!=f1"); pass = false; } //array element arr[0] = s_f1; arr[1] = s_delta1; arr[2] = arr[0] + arr[1]; if (((float)arr[2]) != s_f1) { Console.WriteLine("((float)arr[2])!=f1"); pass = false; } //struct vt1.f1 = 1.0F; vt1.delta1 = 1.0E-10F; vt1.temp = vt1.f1 + vt1.delta1; if (((float)vt1.temp) != s_f1) { Console.WriteLine("((float)vt1.temp)!=f1"); pass = false; } //class cl1.temp = cl1.f1 + cl1.delta1; if (((float)cl1.temp) != s_f1) { Console.WriteLine("((float)cl1.temp)!=f1"); pass = false; } //*** minus *** Console.WriteLine(); Console.WriteLine("***sub***"); //local, in-line if (((float)(s_f1 - s_delta1)) != s_f1) { Console.WriteLine("((float)(f1-delta1))!=f1"); pass = false; } //local temp = s_f1 - s_delta1; if (((float)temp) != s_f1) { Console.WriteLine("((float)temp)!=f1, temp=f1-delta1"); pass = false; } //method call if (((float)floatsub()) != s_f1) { Console.WriteLine("((float)floatsub())!=f1"); pass = false; } //inline method call if (((float)floatsub_inline()) != s_f1) { Console.WriteLine("((float)floatsub_inline())!=f1"); pass = false; } //array element arr[0] = s_f1; arr[1] = s_delta1; arr[2] = arr[0] - arr[1]; if (((float)arr[2]) != s_f1) { Console.WriteLine("((float)arr[2])!=f1"); pass = false; } //struct vt1.f1 = 1.0F; vt1.delta1 = 1.0E-10F; vt1.temp = vt1.f1 - vt1.delta1; if (((float)vt1.temp) != s_f1) { Console.WriteLine("((float)vt1.temp)!=f1"); pass = false; } //class cl1.temp = cl1.f1 - cl1.delta1; if (((float)cl1.temp) != s_f1) { Console.WriteLine("((float)cl1.temp)!=f1"); pass = false; } //*** multiply *** Console.WriteLine(); Console.WriteLine("***mul***"); //local, in-line if (((float)(s_a1 * s_b1)) != s_f1) { Console.WriteLine("((float)(a1*b1))!=f1"); pass = false; } //local temp = s_a1 * s_b1; if (((float)temp) != s_f1) { Console.WriteLine("((float)temp)!=f1, temp=a1*b1"); pass = false; } //method call if (((float)floatmul()) != s_f1) { Console.WriteLine("((float)floatmul())!=f1"); pass = false; } //inline method call if (((float)floatmul_inline()) != s_f1) { Console.WriteLine("((float)floatmul_inline())!=f1"); pass = false; } //array element arr[0] = s_a1; arr[1] = s_b1; arr[2] = arr[0] * arr[1]; if (((float)arr[2]) != s_f1) { Console.WriteLine("((float)arr[2])!=f1"); pass = false; } //struct vt1.a1 = 3; vt1.b1 = 1.0F / 3.0F; vt1.temp = vt1.a1 * vt1.b1; if (((float)vt1.temp) != s_f1) { Console.WriteLine("((float)vt1.temp)!=f1"); pass = false; } //class cl1.temp = cl1.a1 * cl1.b1; if (((float)cl1.temp) != s_f1) { Console.WriteLine("((float)cl1.temp)!=f1"); pass = false; } //*** divide *** Console.WriteLine(); Console.WriteLine("***div***"); //local, in-line if (((float)(s_f1 / s_a1)) != s_b1) { Console.WriteLine("((float)(f1/a1))!=b1"); pass = false; } //local temp = s_f1 / s_a1; if (((float)temp) != s_b1) { Console.WriteLine("((float)temp)!=f1, temp=f1/a1"); pass = false; } //method call if (((float)floatdiv()) != s_b1) { Console.WriteLine("((float)floatdivl())!=b1"); pass = false; } //method call if (((float)floatdiv_inline()) != s_b1) { Console.WriteLine("((float)floatdiv_inline())!=b1"); pass = false; } //array element arr[0] = s_f1; arr[1] = s_a1; arr[2] = arr[0] / arr[1]; if (((float)arr[2]) != s_b1) { Console.WriteLine("((float)arr[2])!=b1"); pass = false; } //struct vt1.f1 = 1.0F; vt1.a1 = 3; vt1.temp = vt1.f1 / vt1.a1; if (((float)vt1.temp) != s_b1) { Console.WriteLine("((float)vt1.temp)!=b1"); pass = false; } //class cl1.temp = cl1.f1 / cl1.a1; if (((float)cl1.temp) != s_b1) { Console.WriteLine("((float)cl1.temp)!=b1"); pass = false; } Console.WriteLine(); if (pass) { Console.WriteLine("SUCCESS"); return 100; } else { Console.WriteLine("FAILURE: float not truncated properly"); return 1; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Reflection; using OpenSim.Framework; using OpenMetaverse; using log4net; namespace OpenSim.Services.Interfaces { public interface IGridService { /// <summary> /// Register a region with the grid service. /// </summary> /// <param name="regionInfos"> </param> /// <returns></returns> /// <exception cref="System.Exception">Thrown if region registration failed</exception> string RegisterRegion(UUID scopeID, GridRegion regionInfos); /// <summary> /// Deregister a region with the grid service. /// </summary> /// <param name="regionID"></param> /// <returns></returns> /// <exception cref="System.Exception">Thrown if region deregistration failed</exception> bool DeregisterRegion(UUID regionID); /// <summary> /// Get information about the regions neighbouring the given co-ordinates (in meters). /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID); GridRegion GetRegionByUUID(UUID scopeID, UUID regionID); /// <summary> /// Get the region at the given position (in meters) /// </summary> /// <param name="scopeID"></param> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> GridRegion GetRegionByPosition(UUID scopeID, int x, int y); /// <summary> /// Get information about a region which exactly matches the name given. /// </summary> /// <param name="scopeID"></param> /// <param name="regionName"></param> /// <returns>Returns the region information if the name matched. Null otherwise.</returns> GridRegion GetRegionByName(UUID scopeID, string regionName); /// <summary> /// Get information about regions starting with the provided name. /// </summary> /// <param name="name"> /// The name to match against. /// </param> /// <param name="maxNumber"> /// The maximum number of results to return. /// </param> /// <returns> /// A list of <see cref="RegionInfo"/>s of regions with matching name. If the /// grid-server couldn't be contacted or returned an error, return null. /// </returns> List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber); List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax); List<GridRegion> GetDefaultRegions(UUID scopeID); List<GridRegion> GetDefaultHypergridRegions(UUID scopeID); List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y); List<GridRegion> GetHyperlinks(UUID scopeID); /// <summary> /// Get internal OpenSimulator region flags. /// </summary> /// <remarks> /// See OpenSimulator.Framework.RegionFlags. These are not returned in the GridRegion structure - /// they currently need to be requested separately. Possibly this should change to avoid multiple service calls /// in some situations. /// </remarks> /// <returns> /// The region flags. /// </returns> /// <param name='scopeID'></param> /// <param name='regionID'></param> int GetRegionFlags(UUID scopeID, UUID regionID); Dictionary<string,object> GetExtraFeatures(); } public class GridRegion { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #pragma warning disable 414 private static readonly string LogHeader = "[GRID REGION]"; #pragma warning restore 414 /// <summary> /// The port by which http communication occurs with the region /// </summary> public uint HttpPort { get; set; } /// <summary> /// A well-formed URI for the host region server (namely "http://" + ExternalHostName) /// </summary> public string ServerURI { get { if (!String.IsNullOrEmpty(m_serverURI)) { return m_serverURI; } else { if (HttpPort == 0) return "http://" + m_externalHostName + "/"; else return "http://" + m_externalHostName + ":" + HttpPort + "/"; } } set { if (value.EndsWith("/")) { m_serverURI = value; } else { m_serverURI = value + '/'; } } } protected string m_serverURI; /// <summary> /// Provides direct access to the 'm_serverURI' field, without returning a generated URL if m_serverURI is missing. /// </summary> public string RawServerURI { get { return m_serverURI; } set { m_serverURI = value; } } public string RegionName { get { return m_regionName; } set { m_regionName = value; } } protected string m_regionName = String.Empty; /// <summary> /// Region flags. /// </summary> /// <remarks> /// If not set (chiefly if a robust service is running code pre OpenSim 0.8.1) then this will be null and /// should be ignored. If you require flags information please use the separate IGridService.GetRegionFlags() call /// XXX: This field is currently ignored when used in RegisterRegion, but could potentially be /// used to set flags at this point. /// </remarks> public OpenSim.Framework.RegionFlags? RegionFlags { get; set; } protected string m_externalHostName; protected IPEndPoint m_internalEndPoint; /// <summary> /// The co-ordinate of this region in region units. /// </summary> public int RegionCoordX { get { return (int)Util.WorldToRegionLoc((uint)RegionLocX); } } /// <summary> /// The co-ordinate of this region in region units /// </summary> public int RegionCoordY { get { return (int)Util.WorldToRegionLoc((uint)RegionLocY); } } /// <summary> /// The location of this region in meters. /// DANGER DANGER! Note that this name means something different in RegionInfo. /// </summary> public int RegionLocX { get { return m_regionLocX; } set { m_regionLocX = value; } } protected int m_regionLocX; public int RegionSizeX { get; set; } public int RegionSizeY { get; set; } /// <summary> /// The location of this region in meters. /// DANGER DANGER! Note that this name means something different in RegionInfo. /// </summary> public int RegionLocY { get { return m_regionLocY; } set { m_regionLocY = value; } } protected int m_regionLocY; protected UUID m_estateOwner; public UUID EstateOwner { get { return m_estateOwner; } set { m_estateOwner = value; } } public UUID RegionID = UUID.Zero; public UUID ScopeID = UUID.Zero; public UUID TerrainImage = UUID.Zero; public UUID ParcelImage = UUID.Zero; public byte Access; public int Maturity; public string RegionSecret = string.Empty; public string Token = string.Empty; public GridRegion() { RegionSizeX = (int)Constants.RegionSize; RegionSizeY = (int)Constants.RegionSize; m_serverURI = string.Empty; } /* public GridRegion(int regionLocX, int regionLocY, IPEndPoint internalEndPoint, string externalUri) { m_regionLocX = regionLocX; m_regionLocY = regionLocY; RegionSizeX = (int)Constants.RegionSize; RegionSizeY = (int)Constants.RegionSize; m_internalEndPoint = internalEndPoint; m_externalHostName = externalUri; } public GridRegion(int regionLocX, int regionLocY, string externalUri, uint port) { m_regionLocX = regionLocX; m_regionLocY = regionLocY; RegionSizeX = (int)Constants.RegionSize; RegionSizeY = (int)Constants.RegionSize; m_externalHostName = externalUri; m_internalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)port); } */ public GridRegion(uint xcell, uint ycell) { m_regionLocX = (int)Util.RegionToWorldLoc(xcell); m_regionLocY = (int)Util.RegionToWorldLoc(ycell); RegionSizeX = (int)Constants.RegionSize; RegionSizeY = (int)Constants.RegionSize; } public GridRegion(RegionInfo ConvertFrom) { m_regionName = ConvertFrom.RegionName; m_regionLocX = (int)(ConvertFrom.WorldLocX); m_regionLocY = (int)(ConvertFrom.WorldLocY); RegionSizeX = (int)ConvertFrom.RegionSizeX; RegionSizeY = (int)ConvertFrom.RegionSizeY; m_internalEndPoint = ConvertFrom.InternalEndPoint; m_externalHostName = ConvertFrom.ExternalHostName; HttpPort = ConvertFrom.HttpPort; RegionID = ConvertFrom.RegionID; ServerURI = ConvertFrom.ServerURI; TerrainImage = ConvertFrom.RegionSettings.TerrainImageID; ParcelImage = ConvertFrom.RegionSettings.ParcelImageID; Access = ConvertFrom.AccessLevel; Maturity = ConvertFrom.RegionSettings.Maturity; RegionSecret = ConvertFrom.regionSecret; EstateOwner = ConvertFrom.EstateSettings.EstateOwner; } public GridRegion(GridRegion ConvertFrom) { m_regionName = ConvertFrom.RegionName; RegionFlags = ConvertFrom.RegionFlags; m_regionLocX = ConvertFrom.RegionLocX; m_regionLocY = ConvertFrom.RegionLocY; RegionSizeX = ConvertFrom.RegionSizeX; RegionSizeY = ConvertFrom.RegionSizeY; m_internalEndPoint = ConvertFrom.InternalEndPoint; m_externalHostName = ConvertFrom.ExternalHostName; HttpPort = ConvertFrom.HttpPort; RegionID = ConvertFrom.RegionID; ServerURI = ConvertFrom.ServerURI; TerrainImage = ConvertFrom.TerrainImage; ParcelImage = ConvertFrom.ParcelImage; Access = ConvertFrom.Access; Maturity = ConvertFrom.Maturity; RegionSecret = ConvertFrom.RegionSecret; EstateOwner = ConvertFrom.EstateOwner; } public GridRegion(Dictionary<string, object> kvp) { if (kvp.ContainsKey("uuid")) RegionID = new UUID((string)kvp["uuid"]); if (kvp.ContainsKey("locX")) RegionLocX = Convert.ToInt32((string)kvp["locX"]); if (kvp.ContainsKey("locY")) RegionLocY = Convert.ToInt32((string)kvp["locY"]); if (kvp.ContainsKey("sizeX")) RegionSizeX = Convert.ToInt32((string)kvp["sizeX"]); else RegionSizeX = (int)Constants.RegionSize; if (kvp.ContainsKey("sizeY")) RegionSizeY = Convert.ToInt32((string)kvp["sizeY"]); else RegionSizeX = (int)Constants.RegionSize; if (kvp.ContainsKey("regionName")) RegionName = (string)kvp["regionName"]; if (kvp.ContainsKey("flags") && kvp["flags"] != null) RegionFlags = (OpenSim.Framework.RegionFlags?)Convert.ToInt32((string)kvp["flags"]); if (kvp.ContainsKey("serverIP")) { //int port = 0; //Int32.TryParse((string)kvp["serverPort"], out port); //IPEndPoint ep = new IPEndPoint(IPAddress.Parse((string)kvp["serverIP"]), port); ExternalHostName = (string)kvp["serverIP"]; } else ExternalHostName = "127.0.0.1"; if (kvp.ContainsKey("serverPort")) { Int32 port = 0; Int32.TryParse((string)kvp["serverPort"], out port); InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), port); } if (kvp.ContainsKey("serverHttpPort")) { UInt32 port = 0; UInt32.TryParse((string)kvp["serverHttpPort"], out port); HttpPort = port; } if (kvp.ContainsKey("serverURI")) ServerURI = (string)kvp["serverURI"]; if (kvp.ContainsKey("regionMapTexture")) UUID.TryParse((string)kvp["regionMapTexture"], out TerrainImage); if (kvp.ContainsKey("parcelMapTexture")) UUID.TryParse((string)kvp["parcelMapTexture"], out ParcelImage); if (kvp.ContainsKey("access")) Access = Byte.Parse((string)kvp["access"]); if (kvp.ContainsKey("regionSecret")) RegionSecret =(string)kvp["regionSecret"]; if (kvp.ContainsKey("owner_uuid")) EstateOwner = new UUID(kvp["owner_uuid"].ToString()); if (kvp.ContainsKey("Token")) Token = kvp["Token"].ToString(); // m_log.DebugFormat("{0} New GridRegion. id={1}, loc=<{2},{3}>, size=<{4},{5}>", // LogHeader, RegionID, RegionLocX, RegionLocY, RegionSizeX, RegionSizeY); } public Dictionary<string, object> ToKeyValuePairs() { Dictionary<string, object> kvp = new Dictionary<string, object>(); kvp["uuid"] = RegionID.ToString(); kvp["locX"] = RegionLocX.ToString(); kvp["locY"] = RegionLocY.ToString(); kvp["sizeX"] = RegionSizeX.ToString(); kvp["sizeY"] = RegionSizeY.ToString(); kvp["regionName"] = RegionName; if (RegionFlags != null) kvp["flags"] = ((int)RegionFlags).ToString(); kvp["serverIP"] = ExternalHostName; //ExternalEndPoint.Address.ToString(); kvp["serverHttpPort"] = HttpPort.ToString(); kvp["serverURI"] = ServerURI; kvp["serverPort"] = InternalEndPoint.Port.ToString(); kvp["regionMapTexture"] = TerrainImage.ToString(); kvp["parcelMapTexture"] = ParcelImage.ToString(); kvp["access"] = Access.ToString(); kvp["regionSecret"] = RegionSecret; kvp["owner_uuid"] = EstateOwner.ToString(); kvp["Token"] = Token.ToString(); // Maturity doesn't seem to exist in the DB return kvp; } #region Definition of equality /// <summary> /// Define equality as two regions having the same, non-zero UUID. /// </summary> public bool Equals(GridRegion region) { if ((object)region == null) return false; // Return true if the non-zero UUIDs are equal: return (RegionID != UUID.Zero) && RegionID.Equals(region.RegionID); } public override bool Equals(Object obj) { if (obj == null) return false; return Equals(obj as GridRegion); } public override int GetHashCode() { return RegionID.GetHashCode() ^ TerrainImage.GetHashCode() ^ ParcelImage.GetHashCode(); } #endregion /// <value> /// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw. /// /// XXX Isn't this really doing too much to be a simple getter, rather than an explict method? /// </value> public IPEndPoint ExternalEndPoint { get { // Old one defaults to IPv6 //return new IPEndPoint(Dns.GetHostAddresses(m_externalHostName)[0], m_internalEndPoint.Port); IPAddress ia = null; // If it is already an IP, don't resolve it - just return directly if (IPAddress.TryParse(m_externalHostName, out ia)) return new IPEndPoint(ia, m_internalEndPoint.Port); // Reset for next check ia = null; try { foreach (IPAddress Adr in Dns.GetHostAddresses(m_externalHostName)) { if (ia == null) ia = Adr; if (Adr.AddressFamily == AddressFamily.InterNetwork) { ia = Adr; break; } } } catch (SocketException e) { throw new Exception( "Unable to resolve local hostname " + m_externalHostName + " innerException of type '" + e + "' attached to this exception", e); } return new IPEndPoint(ia, m_internalEndPoint.Port); } } public string ExternalHostName { get { return m_externalHostName; } set { m_externalHostName = value; } } public IPEndPoint InternalEndPoint { get { return m_internalEndPoint; } set { m_internalEndPoint = value; } } public ulong RegionHandle { get { return Util.UIntsToLong((uint)RegionLocX, (uint)RegionLocY); } } } }
// ----------------------------------------------------------------------- // <copyright file="Control.cs" company="Steven Kirk"> // Copyright 2013 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- using System; using Avalonia.Core; using Avalonia.Data.Data; using Avalonia.Document; using Avalonia.Input; using Avalonia.Media; namespace Avalonia.Controls { public class Control : FrameworkElement { public static readonly DependencyProperty BackgroundProperty = Panel.BackgroundProperty.AddOwner( typeof(Control), new FrameworkPropertyMetadata( new SolidColorBrush(Colors.White), FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty BorderBrushProperty = Border.BorderBrushProperty.AddOwner( typeof(Control), new FrameworkPropertyMetadata( new SolidColorBrush(Colors.White), FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty BorderThicknessProperty = Border.BorderThicknessProperty.AddOwner( typeof(Control), new FrameworkPropertyMetadata( new Thickness(), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner( typeof(Control), new FrameworkPropertyMetadata( new FontFamily("Segoe UI"), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner( typeof(Control), new FrameworkPropertyMetadata( 12.0, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner( typeof(Control), new FrameworkPropertyMetadata( new FontStretch(), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner( typeof(Control), new FrameworkPropertyMetadata( FontStyles.Normal, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner( typeof(Control), new FrameworkPropertyMetadata( FontWeights.Normal, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits)); public static readonly DependencyProperty ForegroundProperty = TextElement.ForegroundProperty.AddOwner( typeof(Control), new FrameworkPropertyMetadata( new SolidColorBrush(Colors.Black), FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender | FrameworkPropertyMetadataOptions.Inherits)); public static readonly DependencyProperty HorizontalContentAlignmentProperty = DependencyProperty.Register( "HorizontalContentAlignment", typeof(HorizontalAlignment), typeof(Control), new FrameworkPropertyMetadata(HorizontalAlignment.Left)); public static readonly DependencyProperty PaddingProperty = DependencyProperty.Register( "Padding", typeof(Thickness), typeof(Control), new FrameworkPropertyMetadata( new Thickness(), FrameworkPropertyMetadataOptions.AffectsMeasure)); public static readonly DependencyProperty TemplateProperty = DependencyProperty.Register( "Template", typeof(ControlTemplate), typeof(Control), new FrameworkPropertyMetadata( null, FrameworkPropertyMetadataOptions.AffectsMeasure)); public static readonly DependencyProperty VerticalContentAlignmentProperty = DependencyProperty.Register( "VerticalContentAlignment", typeof(VerticalAlignment), typeof(Control), new FrameworkPropertyMetadata(VerticalAlignment.Top)); private Visual child; static Control() { FocusableProperty.OverrideMetadata(typeof(Control), new PropertyMetadata(true)); } public Control() { this.Background = new SolidColorBrush(Colors.White); this.AddHandler(Control.KeyDownEvent, (KeyEventHandler)((s, e) => this.OnKeyDown(e))); } public Brush Background { get { return (Brush)this.GetValue(BackgroundProperty); } set { this.SetValue(BackgroundProperty, value); } } public Brush BorderBrush { get { return (Brush)this.GetValue(BorderBrushProperty); } set { this.SetValue(BorderBrushProperty, value); } } public Thickness BorderThickness { get { return (Thickness)this.GetValue(BorderThicknessProperty); } set { this.SetValue(BorderThicknessProperty, value); } } public FontFamily FontFamily { get { return (FontFamily)this.GetValue(FontFamilyProperty); } set { this.SetValue(FontFamilyProperty, value); } } public double FontSize { get { return (double)this.GetValue(FontSizeProperty); } set { this.SetValue(FontSizeProperty, value); } } public FontStretch FontStretch { get { return (FontStretch)this.GetValue(FontStretchProperty); } set { this.SetValue(FontStretchProperty, value); } } public FontStyle FontStyle { get { return (FontStyle)this.GetValue(FontStyleProperty); } set { this.SetValue(FontStyleProperty, value); } } public FontWeight FontWeight { get { return (FontWeight)this.GetValue(FontWeightProperty); } set { this.SetValue(FontWeightProperty, value); } } public Brush Foreground { get { return (Brush)this.GetValue(ForegroundProperty); } set { this.SetValue(ForegroundProperty, value); } } public HorizontalAlignment HorizontalContentAlignment { get { return (HorizontalAlignment)this.GetValue(HorizontalContentAlignmentProperty); } set { this.SetValue(HorizontalContentAlignmentProperty, value); } } public Thickness Padding { get { return (Thickness)this.GetValue(PaddingProperty); } set { this.SetValue(PaddingProperty, value); } } public ControlTemplate Template { get { return (ControlTemplate)this.GetValue(TemplateProperty); } set { this.SetValue(TemplateProperty, value); } } public VerticalAlignment VerticalContentAlignment { get { return (VerticalAlignment)this.GetValue(VerticalContentAlignmentProperty); } set { this.SetValue(VerticalContentAlignmentProperty, value); } } protected internal override int VisualChildrenCount { get { return (this.child != null) ? 1 : 0; } } public sealed override bool ApplyTemplate() { if (this.IsInitialized && this.child == null) { if (this.Template == null) { this.ApplyTheme(); } if (this.Template != null) { this.child = this.Template.CreateVisualTree(this); this.AddVisualChild(this.child); this.OnApplyTemplate(); return true; } } return false; } protected internal sealed override DependencyObject GetTemplateChild(string childName) { if (this.child != null) { INameScope nameScope = NameScope.GetNameScope(this.child); if (nameScope != null) { return nameScope.FindName(childName) as DependencyObject; } } return null; } protected internal override Visual GetVisualChild(int index) { if (this.child != null && index == 0) { return this.child; } else { throw new IndexOutOfRangeException(); } } protected override Size MeasureOverride(Size constraint) { UIElement ui = this.child as UIElement; if (ui != null) { ui.Measure(constraint); return ui.DesiredSize; } return base.MeasureOverride(constraint); } protected override Size ArrangeOverride(Size finalSize) { UIElement ui = this.child as UIElement; if (ui != null) { ui.Arrange(new Rect(finalSize)); return finalSize; } return base.ArrangeOverride(finalSize); } protected virtual void OnKeyDown(KeyEventArgs e) { } private void ApplyTheme() { object defaultStyleKey = this.DefaultStyleKey; if (defaultStyleKey == null) { throw new InvalidOperationException("DefaultStyleKey must be set."); } Style style = (Style)this.FindResource(this.DefaultStyleKey); style.Attach(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.InteropServices; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { /// <summary> /// Tests for MemoryMappedFile.CreateFromFile. /// </summary> public class MemoryMappedFileTests_CreateFromFile : MemoryMappedFilesTestBase { /// <summary> /// Tests invalid arguments to the CreateFromFile path parameter. /// </summary> [Fact] public void InvalidArguments_Path() { // null is an invalid path AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null)); AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open)); AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName())); AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096)); AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read)); } /// <summary> /// Tests invalid arguments to the CreateFromFile fileStream parameter. /// </summary> [Fact] public void InvalidArguments_FileStream() { // null is an invalid stream AssertExtensions.Throws<ArgumentNullException>("fileStream", () => MemoryMappedFile.CreateFromFile(null, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); } /// <summary> /// Tests invalid arguments to the CreateFromFile mode parameter. /// </summary> [Fact] public void InvalidArguments_Mode() { // FileMode out of range AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42)); AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null)); AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096)); AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite)); // FileMode.Append never allowed AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append)); AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null)); AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096)); AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite)); // FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate)); // FileMode.Truncate can't be used with default capacity, as resulting file will be empty using (TempFile file = new TempFile(GetTestFilePath())) { Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate)); } } [Fact] public void InvalidArguments_Mode_Truncate() { // FileMode.Truncate never allowed AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate)); AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null)); AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096)); AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096, MemoryMappedFileAccess.ReadWrite)); } /// <summary> /// Tests invalid arguments to the CreateFromFile access parameter. /// </summary> [Fact] public void InvalidArguments_Access() { // Out of range access values with a path AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2))); AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42))); // Write-only access is not allowed on maps (only on views) AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write)); // Test the same things, but with a FileStream instead of a path using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // Out of range values with a stream AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2), HandleInheritability.None, true)); AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42), HandleInheritability.None, true)); // Write-only access is not allowed AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, HandleInheritability.None, true)); } } /// <summary> /// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used /// to construct a map over that stream. The combinations should all be valid. /// </summary> [Theory] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)] public void FileAccessAndMapAccessCombinations_Valid(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true)) { ValidateMemoryMappedFile(mmf, Capacity, mmfAccess); } } /// <summary> /// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used /// to construct a map over that stream on Windows. The combinations should all be invalid, resulting in exception. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // On Windows, permission errors come from CreateFromFile [Theory] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] // this and the next are explicitly left off of the Unix test due to differences in Unix permissions [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)] public void FileAccessAndMapAccessCombinations_Invalid_Windows(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess) { // On Windows, creating the file mapping does the permissions checks, so the exception comes from CreateFromFile. const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess)) { Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true)); } } /// <summary> /// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used /// to construct a map over that stream on Unix. The combinations should all be invalid, resulting in exception. /// </summary> [PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, permission errors come from CreateView* [Theory] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)] public void FileAccessAndMapAccessCombinations_Invalid_Unix(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess) { // On Unix we don't actually create the OS map until the view is created; this results in the permissions // error being thrown from CreateView* instead of from CreateFromFile. const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true)) { Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor()); } } /// <summary> /// Tests invalid arguments to the CreateFromFile mapName parameter. /// </summary> [Fact] public void InvalidArguments_MapName() { using (TempFile file = new TempFile(GetTestFilePath())) { // Empty string is an invalid map name Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read)); using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)); } } } /// <summary> /// Test to verify that map names are left unsupported on Unix. /// </summary> [PlatformSpecific(TestPlatforms.AnyUnix)] // Check map names are unsupported on Unix [Theory] [MemberData(nameof(CreateValidMapNames))] public void MapNamesNotSupported_Unix(string mapName) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite)); using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(fs, mapName, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)); } } } /// <summary> /// Tests invalid arguments to the CreateFromFile capacity parameter. /// </summary> [Fact] public void InvalidArguments_Capacity() { using (TempFile file = new TempFile(GetTestFilePath())) { // Out of range values for capacity Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1, MemoryMappedFileAccess.Read)); // Positive capacity required when creating a map from an empty file Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read)); // With Read, the capacity can't be larger than the backing file's size. Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read)); // Now with a FileStream... using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // The subsequent tests are only valid we if we start with an empty FileStream, which we should have. // This also verifies the previous failed tests didn't change the length of the file. Assert.Equal(0, fs.Length); // Out of range values for capacity Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(fs, null, -1, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); // Default (0) capacity with an empty file Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); // Larger capacity than the underlying file, but read-only such that we can't expand the file fs.SetLength(4096); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); // Capacity can't be less than the file size (for such cases a view can be created with the smaller size) AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(fs, null, 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)); } // Capacity can't be less than the file size AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read)); } } /// <summary> /// Tests invalid arguments to the CreateFromFile inheritability parameter. /// </summary> [Theory] [InlineData((HandleInheritability)(-1))] [InlineData((HandleInheritability)(42))] public void InvalidArguments_Inheritability(HandleInheritability inheritability) { // Out of range values for inheritability using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { AssertExtensions.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, inheritability, true)); } } /// <summary> /// Test various combinations of arguments to CreateFromFile, focusing on the Open and OpenOrCreate modes, /// and validating the creating maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath), new FileMode[] { FileMode.Open, FileMode.OpenOrCreate }, new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })] public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate( FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { // Test each of the four path-based CreateFromFile overloads using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } // Finally, re-test the last overload, this time with an empty file to start using (TempFile file = new TempFile(GetTestFilePath())) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } } /// <summary> /// Test various combinations of arguments to CreateFromFile, focusing on the CreateNew mode, /// and validating the creating maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath), new FileMode[] { FileMode.CreateNew }, new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })] public void ValidArgumentCombinationsWithPath_ModeCreateNew( FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { // For FileMode.CreateNew, the file will be created new and thus be empty, so we can only use the overloads // that take a capacity, since the default capacity doesn't work with an empty file. using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } } /// <summary> /// Test various combinations of arguments to CreateFromFile, focusing on the Create mode, /// and validating the creating maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidNameCapacityCombinationsWithPath), new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 })] public void ValidArgumentCombinationsWithPath_ModeCreate(string mapName, long capacity) { using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity, MemoryMappedFileAccess.ReadWrite)) { ValidateMemoryMappedFile(mmf, capacity, MemoryMappedFileAccess.ReadWrite); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } } /// <summary> /// Provides input data to the ValidArgumentCombinationsWithPath tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="modes">The modes to yield.</param> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses"> /// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it. /// </param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithPath( FileMode[] modes, string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses) { foreach (object[] namesCaps in MemberData_ValidNameCapacityCombinationsWithPath(mapNames, capacities)) { foreach (FileMode mode in modes) { foreach (MemoryMappedFileAccess access in accesses) { if ((mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate) && !IsWritable(access)) { continue; } yield return new object[] { mode, namesCaps[0], namesCaps[1], access }; } } } } public static IEnumerable<object[]> MemberData_ValidNameCapacityCombinationsWithPath( string[] mapNames, long[] capacities) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mapName, capacity, }; } } } /// <summary> /// Test various combinations of arguments to CreateFromFile that accepts a FileStream. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithStream), new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite }, new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable }, new bool[] { false, true })] public void ValidArgumentCombinationsWithStream( string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { // Create a file of the right size, then create the map for it. using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (FileStream fs = File.Open(file.Path, FileMode.Open)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } // Start with an empty file and let the map grow it to the right size. This requires write access. if (IsWritable(access)) { using (FileStream fs = File.Create(GetTestFilePath())) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } } } /// <summary> /// Provides input data to the ValidArgumentCombinationsWithStream tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses"> /// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it. /// </param> /// <param name="inheritabilities">The inheritabilities to yield.</param> /// <param name="inheritabilities">The leaveOpen values to yield.</param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithStream( string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, HandleInheritability[] inheritabilities, bool[] leaveOpens) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { foreach (HandleInheritability inheritability in inheritabilities) { foreach (bool leaveOpen in leaveOpens) { string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mapName, capacity, access, inheritability, leaveOpen }; } } } } } } /// <summary> /// Test that a map using the default capacity (0) grows to the size of the underlying file. /// </summary> [Fact] public void DefaultCapacityIsFileLength() { const int DesiredCapacity = 8192; const int DefaultCapacity = 0; // With path using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, DefaultCapacity)) { ValidateMemoryMappedFile(mmf, DesiredCapacity); } // With stream using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity)) using (FileStream fs = File.Open(file.Path, FileMode.Open)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, DefaultCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) { ValidateMemoryMappedFile(mmf, DesiredCapacity); } } /// <summary> /// Test that appropriate exceptions are thrown creating a map with a non-existent file and a mode /// that requires the file to exist. /// </summary> [Fact] public void FileDoesNotExist_OpenFileMode() { Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath())); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open)); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null)); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096)); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096, MemoryMappedFileAccess.ReadWrite)); } /// <summary> /// Test that appropriate exceptions are thrown creating a map with an existing file and a mode /// that requires the file to not exist. /// </summary> [Fact] public void FileAlreadyExists() { using (TempFile file = new TempFile(GetTestFilePath())) { // FileMode.CreateNew invalid when the file already exists Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew)); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName())); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096)); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite)); } } /// <summary> /// Test exceptional behavior when trying to create a map for a read-write file that's currently in use. /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent public void FileInUse_CreateFromFile_FailsWithExistingReadWriteFile() { // Already opened with a FileStream using (TempFile file = new TempFile(GetTestFilePath(), 4096)) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path)); } } /// <summary> /// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use. /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent public void FileInUse_CreateFromFile_FailsWithExistingReadWriteMap() { // Already opened with another read-write map using (TempFile file = new TempFile(GetTestFilePath(), 4096)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path)) { Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path)); } } /// <summary> /// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use. /// </summary> [Fact] public void FileInUse_CreateFromFile_FailsWithExistingNoShareFile() { // Already opened with a FileStream using (TempFile file = new TempFile(GetTestFilePath(), 4096)) using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path)); } } /// <summary> /// Test to validate we can create multiple concurrent read-only maps from the same file path. /// </summary> [Fact] public void FileInUse_CreateFromFile_SucceedsWithReadOnly() { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read)) { Assert.Equal(acc1.Capacity, acc2.Capacity); } } /// <summary> /// Test the exceptional behavior of *Execute access levels. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Unix model for executable differs from Windows [Theory] [InlineData(MemoryMappedFileAccess.ReadExecute)] [InlineData(MemoryMappedFileAccess.ReadWriteExecute)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "CreateFromFile in desktop uses FileStream's ctor that takes a FileSystemRights in order to specify execute privileges.")] public void FileNotOpenedForExecute(MemoryMappedFileAccess access) { using (TempFile file = new TempFile(GetTestFilePath(), 4096)) { // The FileStream created by the map doesn't have GENERIC_EXECUTE set Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 4096, access)); // The FileStream opened explicitly doesn't have GENERIC_EXECUTE set using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, 4096, access, HandleInheritability.None, true)); } } } /// <summary> /// On Unix, modifying a file that is ReadOnly will fail under normal permissions. /// If the test is being run under the superuser, however, modification of a ReadOnly /// file is allowed. /// </summary> public void WriteToReadOnlyFile(MemoryMappedFileAccess access, bool succeeds) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) { FileAttributes original = File.GetAttributes(file.Path); File.SetAttributes(file.Path, FileAttributes.ReadOnly); try { if (succeeds) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access)) ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Read); else Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access)); } finally { File.SetAttributes(file.Path, original); } } } [Theory] [InlineData(MemoryMappedFileAccess.Read)] [InlineData(MemoryMappedFileAccess.ReadWrite)] public void WriteToReadOnlyFile_ReadWrite(MemoryMappedFileAccess access) { WriteToReadOnlyFile(access, access == MemoryMappedFileAccess.Read || (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "CreateFromFile in desktop uses FileStream's ctor that takes a FileSystemRights in order to specify execute privileges.")] public void WriteToReadOnlyFile_CopyOnWrite() { WriteToReadOnlyFile(MemoryMappedFileAccess.CopyOnWrite, (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0)); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "CreateFromFile in desktop uses FileStream's ctor that takes a FileSystemRights in order to specify execute privileges.")] public void WriteToReadOnlyFile_CopyOnWrite_netfx() { WriteToReadOnlyFile(MemoryMappedFileAccess.CopyOnWrite, succeeds: true); } /// <summary> /// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open /// or closing it on disposal. /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void LeaveOpenRespected_Basic(bool leaveOpen) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // Handle should still be open SafeFileHandle handle = fs.SafeFileHandle; Assert.False(handle.IsClosed); // Create and close the map MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen).Dispose(); // The handle should now be open iff leaveOpen Assert.NotEqual(leaveOpen, handle.IsClosed); } } /// <summary> /// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open /// or closing it on disposal. /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void LeaveOpenRespected_OutstandingViews(bool leaveOpen) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // Handle should still be open SafeFileHandle handle = fs.SafeFileHandle; Assert.False(handle.IsClosed); // Create the map, create each of the views, then close the map using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen)) using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity)) using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity)) { // Explicitly close the map. The handle should now be open iff leaveOpen. mmf.Dispose(); Assert.NotEqual(leaveOpen, handle.IsClosed); // But the views should still be usable. ValidateMemoryMappedViewAccessor(acc, Capacity, MemoryMappedFileAccess.ReadWrite); ValidateMemoryMappedViewStream(s, Capacity, MemoryMappedFileAccess.ReadWrite); } } } /// <summary> /// Test to validate we can create multiple maps from the same FileStream. /// </summary> [Fact] public void MultipleMapsForTheSameFileStream() { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open)) using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor()) using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor()) { // The capacity of the two maps should be equal Assert.Equal(acc1.Capacity, acc2.Capacity); var rand = new Random(); for (int i = 1; i <= 10; i++) { // Write a value to one map, then read it from the other, // ping-ponging between the two. int pos = rand.Next((int)acc1.Capacity - 1); MemoryMappedViewAccessor reader = acc1, writer = acc2; if (i % 2 == 0) { reader = acc2; writer = acc1; } writer.Write(pos, (byte)i); writer.Flush(); Assert.Equal(i, reader.ReadByte(pos)); } } } /// <summary> /// Test to verify that the map's size increases the underlying file size if the map's capacity is larger. /// </summary> [Fact] public void FileSizeExpandsToCapacity() { const int InitialCapacity = 256; using (TempFile file = new TempFile(GetTestFilePath(), InitialCapacity)) { // Create a map with a larger capacity, and verify the file has expanded. MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, InitialCapacity * 2).Dispose(); using (FileStream fs = File.OpenRead(file.Path)) { Assert.Equal(InitialCapacity * 2, fs.Length); } // Do the same thing again but with a FileStream. using (FileStream fs = File.Open(file.Path, FileMode.Open)) { MemoryMappedFile.CreateFromFile(fs, null, InitialCapacity * 4, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose(); Assert.Equal(InitialCapacity * 4, fs.Length); } } } /// <summary> /// Test the exceptional behavior when attempting to create a map so large it's not supported. /// </summary> [PlatformSpecific(~TestPlatforms.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately) [Fact] public void TooLargeCapacity() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.CreateNew)) { try { long length = long.MaxValue; MemoryMappedFile.CreateFromFile(fs, null, length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose(); Assert.Equal(length, fs.Length); // if it didn't fail to create the file, the length should be what was requested. } catch (IOException) { // Expected exception for too large a capacity } } } /// <summary> /// Test to verify map names are handled appropriately, causing a conflict when they're active but /// reusable in a sequential manner. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Tests reusability of map names on Windows [Theory] [MemberData(nameof(CreateValidMapNames))] public void ReusingNames_Windows(string name) { const int Capacity = 4096; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity)) { ValidateMemoryMappedFile(mmf, Capacity); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity)); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity)) { ValidateMemoryMappedFile(mmf, Capacity); } } } }
// Copyright 2022 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! namespace Google.Cloud.WebRisk.V1.Snippets { using Google.Api.Gax.ResourceNames; using Google.Protobuf; using System.Collections.Generic; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedWebRiskServiceClientSnippets { /// <summary>Snippet for ComputeThreatListDiff</summary> public void ComputeThreatListDiffRequestObject() { // Snippet: ComputeThreatListDiff(ComputeThreatListDiffRequest, CallSettings) // Create client WebRiskServiceClient webRiskServiceClient = WebRiskServiceClient.Create(); // Initialize request argument(s) ComputeThreatListDiffRequest request = new ComputeThreatListDiffRequest { ThreatType = ThreatType.Unspecified, VersionToken = ByteString.Empty, Constraints = new ComputeThreatListDiffRequest.Types.Constraints(), }; // Make the request ComputeThreatListDiffResponse response = webRiskServiceClient.ComputeThreatListDiff(request); // End snippet } /// <summary>Snippet for ComputeThreatListDiffAsync</summary> public async Task ComputeThreatListDiffRequestObjectAsync() { // Snippet: ComputeThreatListDiffAsync(ComputeThreatListDiffRequest, CallSettings) // Additional: ComputeThreatListDiffAsync(ComputeThreatListDiffRequest, CancellationToken) // Create client WebRiskServiceClient webRiskServiceClient = await WebRiskServiceClient.CreateAsync(); // Initialize request argument(s) ComputeThreatListDiffRequest request = new ComputeThreatListDiffRequest { ThreatType = ThreatType.Unspecified, VersionToken = ByteString.Empty, Constraints = new ComputeThreatListDiffRequest.Types.Constraints(), }; // Make the request ComputeThreatListDiffResponse response = await webRiskServiceClient.ComputeThreatListDiffAsync(request); // End snippet } /// <summary>Snippet for ComputeThreatListDiff</summary> public void ComputeThreatListDiff() { // Snippet: ComputeThreatListDiff(ThreatType, ByteString, ComputeThreatListDiffRequest.Types.Constraints, CallSettings) // Create client WebRiskServiceClient webRiskServiceClient = WebRiskServiceClient.Create(); // Initialize request argument(s) ThreatType threatType = ThreatType.Unspecified; ByteString versionToken = ByteString.Empty; ComputeThreatListDiffRequest.Types.Constraints constraints = new ComputeThreatListDiffRequest.Types.Constraints(); // Make the request ComputeThreatListDiffResponse response = webRiskServiceClient.ComputeThreatListDiff(threatType, versionToken, constraints); // End snippet } /// <summary>Snippet for ComputeThreatListDiffAsync</summary> public async Task ComputeThreatListDiffAsync() { // Snippet: ComputeThreatListDiffAsync(ThreatType, ByteString, ComputeThreatListDiffRequest.Types.Constraints, CallSettings) // Additional: ComputeThreatListDiffAsync(ThreatType, ByteString, ComputeThreatListDiffRequest.Types.Constraints, CancellationToken) // Create client WebRiskServiceClient webRiskServiceClient = await WebRiskServiceClient.CreateAsync(); // Initialize request argument(s) ThreatType threatType = ThreatType.Unspecified; ByteString versionToken = ByteString.Empty; ComputeThreatListDiffRequest.Types.Constraints constraints = new ComputeThreatListDiffRequest.Types.Constraints(); // Make the request ComputeThreatListDiffResponse response = await webRiskServiceClient.ComputeThreatListDiffAsync(threatType, versionToken, constraints); // End snippet } /// <summary>Snippet for SearchUris</summary> public void SearchUrisRequestObject() { // Snippet: SearchUris(SearchUrisRequest, CallSettings) // Create client WebRiskServiceClient webRiskServiceClient = WebRiskServiceClient.Create(); // Initialize request argument(s) SearchUrisRequest request = new SearchUrisRequest { Uri = "", ThreatTypes = { ThreatType.Unspecified, }, }; // Make the request SearchUrisResponse response = webRiskServiceClient.SearchUris(request); // End snippet } /// <summary>Snippet for SearchUrisAsync</summary> public async Task SearchUrisRequestObjectAsync() { // Snippet: SearchUrisAsync(SearchUrisRequest, CallSettings) // Additional: SearchUrisAsync(SearchUrisRequest, CancellationToken) // Create client WebRiskServiceClient webRiskServiceClient = await WebRiskServiceClient.CreateAsync(); // Initialize request argument(s) SearchUrisRequest request = new SearchUrisRequest { Uri = "", ThreatTypes = { ThreatType.Unspecified, }, }; // Make the request SearchUrisResponse response = await webRiskServiceClient.SearchUrisAsync(request); // End snippet } /// <summary>Snippet for SearchUris</summary> public void SearchUris() { // Snippet: SearchUris(string, IEnumerable<ThreatType>, CallSettings) // Create client WebRiskServiceClient webRiskServiceClient = WebRiskServiceClient.Create(); // Initialize request argument(s) string uri = ""; IEnumerable<ThreatType> threatTypes = new ThreatType[] { ThreatType.Unspecified, }; // Make the request SearchUrisResponse response = webRiskServiceClient.SearchUris(uri, threatTypes); // End snippet } /// <summary>Snippet for SearchUrisAsync</summary> public async Task SearchUrisAsync() { // Snippet: SearchUrisAsync(string, IEnumerable<ThreatType>, CallSettings) // Additional: SearchUrisAsync(string, IEnumerable<ThreatType>, CancellationToken) // Create client WebRiskServiceClient webRiskServiceClient = await WebRiskServiceClient.CreateAsync(); // Initialize request argument(s) string uri = ""; IEnumerable<ThreatType> threatTypes = new ThreatType[] { ThreatType.Unspecified, }; // Make the request SearchUrisResponse response = await webRiskServiceClient.SearchUrisAsync(uri, threatTypes); // End snippet } /// <summary>Snippet for SearchHashes</summary> public void SearchHashesRequestObject() { // Snippet: SearchHashes(SearchHashesRequest, CallSettings) // Create client WebRiskServiceClient webRiskServiceClient = WebRiskServiceClient.Create(); // Initialize request argument(s) SearchHashesRequest request = new SearchHashesRequest { HashPrefix = ByteString.Empty, ThreatTypes = { ThreatType.Unspecified, }, }; // Make the request SearchHashesResponse response = webRiskServiceClient.SearchHashes(request); // End snippet } /// <summary>Snippet for SearchHashesAsync</summary> public async Task SearchHashesRequestObjectAsync() { // Snippet: SearchHashesAsync(SearchHashesRequest, CallSettings) // Additional: SearchHashesAsync(SearchHashesRequest, CancellationToken) // Create client WebRiskServiceClient webRiskServiceClient = await WebRiskServiceClient.CreateAsync(); // Initialize request argument(s) SearchHashesRequest request = new SearchHashesRequest { HashPrefix = ByteString.Empty, ThreatTypes = { ThreatType.Unspecified, }, }; // Make the request SearchHashesResponse response = await webRiskServiceClient.SearchHashesAsync(request); // End snippet } /// <summary>Snippet for SearchHashes</summary> public void SearchHashes() { // Snippet: SearchHashes(ByteString, IEnumerable<ThreatType>, CallSettings) // Create client WebRiskServiceClient webRiskServiceClient = WebRiskServiceClient.Create(); // Initialize request argument(s) ByteString hashPrefix = ByteString.Empty; IEnumerable<ThreatType> threatTypes = new ThreatType[] { ThreatType.Unspecified, }; // Make the request SearchHashesResponse response = webRiskServiceClient.SearchHashes(hashPrefix, threatTypes); // End snippet } /// <summary>Snippet for SearchHashesAsync</summary> public async Task SearchHashesAsync() { // Snippet: SearchHashesAsync(ByteString, IEnumerable<ThreatType>, CallSettings) // Additional: SearchHashesAsync(ByteString, IEnumerable<ThreatType>, CancellationToken) // Create client WebRiskServiceClient webRiskServiceClient = await WebRiskServiceClient.CreateAsync(); // Initialize request argument(s) ByteString hashPrefix = ByteString.Empty; IEnumerable<ThreatType> threatTypes = new ThreatType[] { ThreatType.Unspecified, }; // Make the request SearchHashesResponse response = await webRiskServiceClient.SearchHashesAsync(hashPrefix, threatTypes); // End snippet } /// <summary>Snippet for CreateSubmission</summary> public void CreateSubmissionRequestObject() { // Snippet: CreateSubmission(CreateSubmissionRequest, CallSettings) // Create client WebRiskServiceClient webRiskServiceClient = WebRiskServiceClient.Create(); // Initialize request argument(s) CreateSubmissionRequest request = new CreateSubmissionRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Submission = new Submission(), }; // Make the request Submission response = webRiskServiceClient.CreateSubmission(request); // End snippet } /// <summary>Snippet for CreateSubmissionAsync</summary> public async Task CreateSubmissionRequestObjectAsync() { // Snippet: CreateSubmissionAsync(CreateSubmissionRequest, CallSettings) // Additional: CreateSubmissionAsync(CreateSubmissionRequest, CancellationToken) // Create client WebRiskServiceClient webRiskServiceClient = await WebRiskServiceClient.CreateAsync(); // Initialize request argument(s) CreateSubmissionRequest request = new CreateSubmissionRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Submission = new Submission(), }; // Make the request Submission response = await webRiskServiceClient.CreateSubmissionAsync(request); // End snippet } /// <summary>Snippet for CreateSubmission</summary> public void CreateSubmission() { // Snippet: CreateSubmission(string, Submission, CallSettings) // Create client WebRiskServiceClient webRiskServiceClient = WebRiskServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; Submission submission = new Submission(); // Make the request Submission response = webRiskServiceClient.CreateSubmission(parent, submission); // End snippet } /// <summary>Snippet for CreateSubmissionAsync</summary> public async Task CreateSubmissionAsync() { // Snippet: CreateSubmissionAsync(string, Submission, CallSettings) // Additional: CreateSubmissionAsync(string, Submission, CancellationToken) // Create client WebRiskServiceClient webRiskServiceClient = await WebRiskServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; Submission submission = new Submission(); // Make the request Submission response = await webRiskServiceClient.CreateSubmissionAsync(parent, submission); // End snippet } /// <summary>Snippet for CreateSubmission</summary> public void CreateSubmissionResourceNames() { // Snippet: CreateSubmission(ProjectName, Submission, CallSettings) // Create client WebRiskServiceClient webRiskServiceClient = WebRiskServiceClient.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Submission submission = new Submission(); // Make the request Submission response = webRiskServiceClient.CreateSubmission(parent, submission); // End snippet } /// <summary>Snippet for CreateSubmissionAsync</summary> public async Task CreateSubmissionResourceNamesAsync() { // Snippet: CreateSubmissionAsync(ProjectName, Submission, CallSettings) // Additional: CreateSubmissionAsync(ProjectName, Submission, CancellationToken) // Create client WebRiskServiceClient webRiskServiceClient = await WebRiskServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Submission submission = new Submission(); // Make the request Submission response = await webRiskServiceClient.CreateSubmissionAsync(parent, submission); // End snippet } } }
namespace Gu.State { using System; using System.Collections; using System.Reflection; /// <summary> /// Exposes methods for verifying copying is supported for types. /// </summary> public static partial class Copy { /// <summary> /// Check if the properties of <typeparamref name="T"/> can be copied. /// This method will throw an exception if copy cannot be performed for <typeparamref name="T"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <typeparam name="T">The type to get ignore properties for settings for.</typeparam> /// <param name="referenceHandling"> /// If Structural is used property values for sub properties are copied for the entire graph. /// Activator.CreateInstance is used to new up references so a default constructor is required, can be private. /// </param> /// <param name="bindingFlags">The binding flags to use when getting properties.</param> public static void VerifyCanCopyPropertyValues<T>( ReferenceHandling referenceHandling = ReferenceHandling.Structural, BindingFlags bindingFlags = Constants.DefaultPropertyBindingFlags) { var settings = PropertiesSettings.GetOrCreate(referenceHandling, bindingFlags); VerifyCanCopyPropertyValues<T>(settings); } /// <summary> /// Check if the properties of <typeparamref name="T"/> can be copied. /// This method will throw an exception if copy cannot be performed for <typeparamref name="T"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <typeparam name="T">The type to check.</typeparam> /// <param name="settings">Contains configuration for how copy will be performed.</param> public static void VerifyCanCopyPropertyValues<T>(PropertiesSettings settings) { var type = typeof(T); VerifyCanCopyPropertyValues(type, settings); } /// <summary> /// Check if the properties of <paramref name="type"/> can be copied. /// This method will throw an exception if copy cannot be performed for <paramref name="type"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <param name="type">The type to check.</param> /// <param name="settings">Contains configuration for how copy will be performed.</param> public static void VerifyCanCopyPropertyValues(Type type, PropertiesSettings settings) { if (type is null) { throw new ArgumentNullException(nameof(type)); } if (settings is null) { throw new ArgumentNullException(nameof(settings)); } Verify.CanCopyRoot(type, settings); Verify.CanCopyMemberValues(type, settings, typeof(Copy).Name, nameof(VerifyCanCopyPropertyValues)); } /// <summary> /// Check if the fields of <typeparamref name="T"/> can be copied. /// This method will throw an exception if copy cannot be performed for <typeparamref name="T"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <typeparam name="T">The type to get ignore fields for settings for.</typeparam> /// <param name="referenceHandling"> /// If Structural is used property values for sub properties are copied for the entire graph. /// Activator.CreateInstance is sued to new up references so a default constructor is required, can be private. /// </param> /// <param name="bindingFlags">The binding flags to use when getting fields.</param> public static void VerifyCanCopyFieldValues<T>( ReferenceHandling referenceHandling = ReferenceHandling.Structural, BindingFlags bindingFlags = Constants.DefaultFieldBindingFlags) { var settings = FieldsSettings.GetOrCreate(referenceHandling, bindingFlags); VerifyCanCopyFieldValues<T>(settings); } /// <summary> /// Check if the fields of <typeparamref name="T"/> can be copied. /// This method will throw an exception if copy cannot be performed for <typeparamref name="T"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <typeparam name="T">The type to get ignore fields for settings for.</typeparam> /// <param name="settings">Contains configuration for how copy is performed.</param> public static void VerifyCanCopyFieldValues<T>(FieldsSettings settings) { var type = typeof(T); VerifyCanCopyFieldValues(type, settings); } /// <summary> /// Check if the fields of <paramref name="type"/> can be copied. /// This method will throw an exception if copy cannot be performed for <paramref name="type"/> /// Read the exception message for detailed instructions about what is wrong. /// Use this to fail fast or in unit tests. /// </summary> /// <param name="type">The type to get ignore fields for settings for.</param> /// <param name="settings">Contains configuration for how copy is performed.</param> public static void VerifyCanCopyFieldValues(Type type, FieldsSettings settings) { if (type is null) { throw new ArgumentNullException(nameof(type)); } if (settings is null) { throw new ArgumentNullException(nameof(settings)); } Verify.CanCopyRoot(type, settings); Verify.CanCopyMemberValues(type, settings, typeof(Copy).Name, nameof(VerifyCanCopyFieldValues)); } internal static void VerifyCanCopyPropertyValues(Type type, PropertiesSettings settings, string classname, string methodName) { Verify.CanCopyRoot(type, settings); Verify.GetOrCreateErrors(type, settings) .ThrowIfHasErrors(settings, classname, methodName); } private static ErrorBuilder.TypeErrorsBuilder CheckIsCopyableEnumerable(this ErrorBuilder.TypeErrorsBuilder typeErrors, Type type, MemberSettings settings) { if (!typeof(IEnumerable).IsAssignableFrom(type)) { return typeErrors; } switch (settings.ReferenceHandling) { case ReferenceHandling.Throw: case ReferenceHandling.References: return typeErrors; case ReferenceHandling.Structural: if (!IsCopyableCollectionType(type)) { return typeErrors.CreateIfNull(type) .Add(new NotCopyableCollection(type)); } break; default: throw new ArgumentOutOfRangeException(nameof(settings), settings.ReferenceHandling, "Unknown ReferenceHandling"); } return typeErrors; } internal static class Verify { internal static void CanCopyMemberValues<T>(T x, T y, MemberSettings settings) { var type = x?.GetType() ?? y?.GetType() ?? typeof(T); CanCopyMemberValues(type, settings, typeof(Copy).Name, settings.CopyMethodName()); } internal static void CanCopyMemberValues(Type type, MemberSettings settings, string className, string methodName) { GetOrCreateErrors(type, settings) .ThrowIfHasErrors(settings, className, methodName); } internal static void CanCopyRoot(Type type, MemberSettings settings) { if (settings.IsImmutable(type)) { throw new NotSupportedException("Cannot copy the members of an immutable object"); } if (typeof(IEnumerable).IsAssignableFrom(type) && !IsCopyableCollectionType(type)) { throw new NotSupportedException($"Can only copy the members of collections implementing {typeof(IList).Name} or {typeof(IDictionary).Name}"); } } internal static TypeErrors GetOrCreateErrors(Type type, MemberSettings settings, MemberPath path = null) { return settings.CopyErrors.GetOrAdd(type, t => CreateErrors(t, settings, path)); } private static TypeErrors CreateErrors(Type type, MemberSettings settings, MemberPath path) { if (settings.IsImmutable(type) || settings.TryGetCopyer(type, out _)) { return null; } var errors = VerifyCore(settings, type) .VerifyRecursive(type, settings, path, GetNodeErrors) .Finnish(); return errors; } private static ErrorBuilder.TypeErrorsBuilder VerifyCore(MemberSettings settings, Type type) { return ErrorBuilder.Start() .CheckRequiresReferenceHandling(type, settings, t => !settings.IsImmutable(t)) .CheckIsCopyableEnumerable(type, settings) .CheckIndexers(type, settings); } private static TypeErrors GetNodeErrors(MemberSettings settings, MemberPath path) { if (settings.ReferenceHandling == ReferenceHandling.References) { return null; } var type = path.LastNodeType; return GetOrCreateErrors(type, settings, path); } } } }
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* Copyright (c) 2015-2016, Schadin Alexey (schadin@gmail.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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace NppKate.Forms { partial class SnippetEdit { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SnippetEdit)); this.pTop = new System.Windows.Forms.Panel(); this.tbFileExt = new System.Windows.Forms.TextBox(); this.btnSnippet = new System.Windows.Forms.Button(); this.btnFileName = new System.Windows.Forms.Button(); this.btnUserName = new System.Windows.Forms.Button(); this.btnDate = new System.Windows.Forms.Button(); this.lShortName = new System.Windows.Forms.Label(); this.tbShortName = new System.Windows.Forms.TextBox(); this.lExt = new System.Windows.Forms.Label(); this.lCategory = new System.Windows.Forms.Label(); this.cbCategory = new System.Windows.Forms.ComboBox(); this.chbIsShowInMenu = new System.Windows.Forms.CheckBox(); this.lSnippet = new System.Windows.Forms.Label(); this.lName = new System.Windows.Forms.Label(); this.tbName = new System.Windows.Forms.TextBox(); this.pMiddle = new System.Windows.Forms.Panel(); this.tbSnippet = new System.Windows.Forms.TextBox(); this.pBottom = new System.Windows.Forms.Panel(); this.lblHelp = new System.Windows.Forms.Label(); this.bCancel = new System.Windows.Forms.Button(); this.bOk = new System.Windows.Forms.Button(); this.cmsSnippets = new System.Windows.Forms.ContextMenuStrip(this.components); this.pTop.SuspendLayout(); this.pMiddle.SuspendLayout(); this.pBottom.SuspendLayout(); this.SuspendLayout(); // // pTop // this.pTop.Controls.Add(this.tbFileExt); this.pTop.Controls.Add(this.btnSnippet); this.pTop.Controls.Add(this.btnFileName); this.pTop.Controls.Add(this.btnUserName); this.pTop.Controls.Add(this.btnDate); this.pTop.Controls.Add(this.lShortName); this.pTop.Controls.Add(this.tbShortName); this.pTop.Controls.Add(this.lExt); this.pTop.Controls.Add(this.lCategory); this.pTop.Controls.Add(this.cbCategory); this.pTop.Controls.Add(this.chbIsShowInMenu); this.pTop.Controls.Add(this.lSnippet); this.pTop.Controls.Add(this.lName); this.pTop.Controls.Add(this.tbName); this.pTop.Dock = System.Windows.Forms.DockStyle.Top; this.pTop.Location = new System.Drawing.Point(0, 0); this.pTop.Name = "pTop"; this.pTop.Size = new System.Drawing.Size(784, 81); this.pTop.TabIndex = 0; // // tbFileExt // this.tbFileExt.Location = new System.Drawing.Point(572, 28); this.tbFileExt.Name = "tbFileExt"; this.tbFileExt.Size = new System.Drawing.Size(70, 20); this.tbFileExt.TabIndex = 3; // // btnSnippet // this.btnSnippet.Location = new System.Drawing.Point(486, 54); this.btnSnippet.Name = "btnSnippet"; this.btnSnippet.Size = new System.Drawing.Size(80, 23); this.btnSnippet.TabIndex = 8; this.btnSnippet.Text = "$(SNIPPET)"; this.btnSnippet.UseVisualStyleBackColor = true; this.btnSnippet.Click += new System.EventHandler(this.btnSnippet_Click); // // btnFileName // this.btnFileName.Location = new System.Drawing.Point(387, 54); this.btnFileName.Name = "btnFileName"; this.btnFileName.Size = new System.Drawing.Size(93, 23); this.btnFileName.TabIndex = 7; this.btnFileName.Text = "$(FILENAME)"; this.btnFileName.UseVisualStyleBackColor = true; this.btnFileName.Click += new System.EventHandler(this.AutoParamInsert); // // btnUserName // this.btnUserName.Location = new System.Drawing.Point(291, 54); this.btnUserName.Name = "btnUserName"; this.btnUserName.Size = new System.Drawing.Size(90, 23); this.btnUserName.TabIndex = 6; this.btnUserName.Text = "$(USERNAME)"; this.btnUserName.UseVisualStyleBackColor = true; this.btnUserName.Click += new System.EventHandler(this.AutoParamInsert); // // btnDate // this.btnDate.Location = new System.Drawing.Point(228, 55); this.btnDate.Name = "btnDate"; this.btnDate.Size = new System.Drawing.Size(57, 23); this.btnDate.TabIndex = 5; this.btnDate.Text = "$(DATE)"; this.btnDate.UseVisualStyleBackColor = true; this.btnDate.Click += new System.EventHandler(this.AutoParamInsert); // // lShortName // this.lShortName.AutoSize = true; this.lShortName.Location = new System.Drawing.Point(225, 9); this.lShortName.Name = "lShortName"; this.lShortName.Size = new System.Drawing.Size(101, 13); this.lShortName.TabIndex = 9; this.lShortName.Text = "Snippet short name:"; // // tbShortName // this.tbShortName.Location = new System.Drawing.Point(228, 28); this.tbShortName.Name = "tbShortName"; this.tbShortName.Size = new System.Drawing.Size(179, 20); this.tbShortName.TabIndex = 1; this.tbShortName.Validating += new System.ComponentModel.CancelEventHandler(this.NameValidating); // // lExt // this.lExt.AutoSize = true; this.lExt.Location = new System.Drawing.Point(569, 9); this.lExt.Name = "lExt"; this.lExt.Size = new System.Drawing.Size(72, 13); this.lExt.TabIndex = 7; this.lExt.Text = "File extention:"; // // lCategory // this.lCategory.AutoSize = true; this.lCategory.Location = new System.Drawing.Point(410, 9); this.lCategory.Name = "lCategory"; this.lCategory.Size = new System.Drawing.Size(52, 13); this.lCategory.TabIndex = 6; this.lCategory.Text = "Category:"; // // cbCategory // this.cbCategory.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.cbCategory.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource; this.cbCategory.FormattingEnabled = true; this.cbCategory.Location = new System.Drawing.Point(413, 28); this.cbCategory.Name = "cbCategory"; this.cbCategory.Size = new System.Drawing.Size(153, 21); this.cbCategory.TabIndex = 2; // // chbIsShowInMenu // this.chbIsShowInMenu.AutoSize = true; this.chbIsShowInMenu.Location = new System.Drawing.Point(650, 29); this.chbIsShowInMenu.Name = "chbIsShowInMenu"; this.chbIsShowInMenu.Size = new System.Drawing.Size(93, 17); this.chbIsShowInMenu.TabIndex = 4; this.chbIsShowInMenu.Text = "Show in menu"; this.chbIsShowInMenu.UseVisualStyleBackColor = true; // // lSnippet // this.lSnippet.AutoSize = true; this.lSnippet.Location = new System.Drawing.Point(3, 64); this.lSnippet.Name = "lSnippet"; this.lSnippet.Size = new System.Drawing.Size(46, 13); this.lSnippet.TabIndex = 2; this.lSnippet.Text = "Snippet:"; // // lName // this.lName.AutoSize = true; this.lName.Location = new System.Drawing.Point(3, 9); this.lName.Name = "lName"; this.lName.Size = new System.Drawing.Size(75, 13); this.lName.TabIndex = 1; this.lName.Text = "Snippet name:"; // // tbName // this.tbName.Location = new System.Drawing.Point(6, 28); this.tbName.Name = "tbName"; this.tbName.Size = new System.Drawing.Size(216, 20); this.tbName.TabIndex = 0; this.tbName.Validating += new System.ComponentModel.CancelEventHandler(this.NameValidating); // // pMiddle // this.pMiddle.Controls.Add(this.tbSnippet); this.pMiddle.Dock = System.Windows.Forms.DockStyle.Fill; this.pMiddle.Location = new System.Drawing.Point(0, 81); this.pMiddle.Name = "pMiddle"; this.pMiddle.Size = new System.Drawing.Size(784, 455); this.pMiddle.TabIndex = 1; // // tbSnippet // this.tbSnippet.AcceptsReturn = true; this.tbSnippet.AcceptsTab = true; this.tbSnippet.Dock = System.Windows.Forms.DockStyle.Fill; this.tbSnippet.Font = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.tbSnippet.Location = new System.Drawing.Point(0, 0); this.tbSnippet.Multiline = true; this.tbSnippet.Name = "tbSnippet"; this.tbSnippet.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.tbSnippet.Size = new System.Drawing.Size(784, 455); this.tbSnippet.TabIndex = 1; // // pBottom // this.pBottom.Controls.Add(this.lblHelp); this.pBottom.Controls.Add(this.bCancel); this.pBottom.Controls.Add(this.bOk); this.pBottom.Dock = System.Windows.Forms.DockStyle.Bottom; this.pBottom.Location = new System.Drawing.Point(0, 536); this.pBottom.Name = "pBottom"; this.pBottom.Size = new System.Drawing.Size(784, 26); this.pBottom.TabIndex = 2; // // lblHelp // this.lblHelp.AutoSize = true; this.lblHelp.Location = new System.Drawing.Point(3, 7); this.lblHelp.Name = "lblHelp"; this.lblHelp.Size = new System.Drawing.Size(257, 13); this.lblHelp.TabIndex = 5; this.lblHelp.Text = "If you need characters \"{\" or \"}\" then use \"{{\" or \"}}\""; // // bCancel // this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.Dock = System.Windows.Forms.DockStyle.Right; this.bCancel.Image = global::NppKate.Properties.Resources.button_cancel_8865; this.bCancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCancel.Location = new System.Drawing.Point(634, 0); this.bCancel.Name = "bCancel"; this.bCancel.Size = new System.Drawing.Size(75, 26); this.bCancel.TabIndex = 4; this.bCancel.Text = "Cancel"; this.bCancel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.bCancel.UseVisualStyleBackColor = true; // // bOk // this.bOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.bOk.Dock = System.Windows.Forms.DockStyle.Right; this.bOk.Image = ((System.Drawing.Image)(resources.GetObject("bOk.Image"))); this.bOk.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bOk.Location = new System.Drawing.Point(709, 0); this.bOk.Name = "bOk"; this.bOk.Size = new System.Drawing.Size(75, 26); this.bOk.TabIndex = 3; this.bOk.Text = "OK"; this.bOk.UseVisualStyleBackColor = true; this.bOk.Click += new System.EventHandler(this.bOk_Click); // // cmsSnippets // this.cmsSnippets.Name = "cmsSnippets"; this.cmsSnippets.Size = new System.Drawing.Size(61, 4); this.cmsSnippets.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.cmsSnippets_ItemClicked); // // SnippetEdit // this.AcceptButton = this.bOk; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.bCancel; this.ClientSize = new System.Drawing.Size(784, 562); this.Controls.Add(this.pMiddle); this.Controls.Add(this.pBottom); this.Controls.Add(this.pTop); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(740, 300); this.Name = "SnippetEdit"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Snippet Editor"; this.VisibleChanged += new System.EventHandler(this.SnippetEdit_VisibleChanged); this.pTop.ResumeLayout(false); this.pTop.PerformLayout(); this.pMiddle.ResumeLayout(false); this.pMiddle.PerformLayout(); this.pBottom.ResumeLayout(false); this.pBottom.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel pTop; private System.Windows.Forms.TextBox tbName; private System.Windows.Forms.Panel pMiddle; private System.Windows.Forms.TextBox tbSnippet; private System.Windows.Forms.Panel pBottom; private System.Windows.Forms.Label lSnippet; private System.Windows.Forms.Label lName; private System.Windows.Forms.Button bCancel; private System.Windows.Forms.Button bOk; private System.Windows.Forms.CheckBox chbIsShowInMenu; private System.Windows.Forms.Label lExt; private System.Windows.Forms.Label lCategory; private System.Windows.Forms.ComboBox cbCategory; private System.Windows.Forms.Label lShortName; private System.Windows.Forms.TextBox tbShortName; private System.Windows.Forms.Label lblHelp; private System.Windows.Forms.Button btnFileName; private System.Windows.Forms.Button btnUserName; private System.Windows.Forms.Button btnDate; private System.Windows.Forms.Button btnSnippet; private System.Windows.Forms.ContextMenuStrip cmsSnippets; private System.Windows.Forms.TextBox tbFileExt; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Fabrikam.Module1.Uc1.Query.Services.WebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
namespace Easy.Common.Tests.Unit.Accessors { using System; using System.Diagnostics.CodeAnalysis; using NUnit.Framework; using Shouldly; [TestFixture] public sealed class ObjectAccessorTests { [Test] public void When_creating_object_accessor_with_default_flags() { var parent = new Parent(); ObjectAccessor parentAccessor = Accessor.Build(parent); parentAccessor.ShouldBeOfType<ObjectAccessor>(); parentAccessor.Type.ShouldBe(typeof(Parent)); parentAccessor.IgnoreCase.ShouldBe(false); parentAccessor.IncludesNonPublic.ShouldBe(false); parentAccessor.ShouldNotBeNull(); parentAccessor.Properties.ShouldNotBeNull(); parentAccessor.Properties.Count.ShouldBe(2); parentAccessor.Properties["Name"].PropertyType.ShouldBe(typeof(string)); parentAccessor.Properties["Age"].PropertyType.ShouldBe(typeof(int)); parentAccessor[parent, "Name"].ShouldBeNull(); parentAccessor[parent, "Name"] = "Foo"; parentAccessor[parent, "Name"].ShouldBe("Foo"); parentAccessor[parent, "Age"].ShouldBe(0); parentAccessor[parent, "Age"] = 10; parentAccessor[parent, "Age"].ShouldBe(10); var child = new Child(); ObjectAccessor childAccessor = Accessor.Build(child); childAccessor.ShouldBeOfType<ObjectAccessor>(); childAccessor.Type.ShouldBe(typeof(Child)); childAccessor.IgnoreCase.ShouldBe(false); childAccessor.IncludesNonPublic.ShouldBe(false); childAccessor.ShouldNotBeNull(); childAccessor.Properties.ShouldNotBeNull(); childAccessor.Properties.Count.ShouldBe(3); childAccessor.Properties["ChildName"].PropertyType.ShouldBe(typeof(string)); childAccessor.Properties["Name"].PropertyType.ShouldBe(typeof(string)); childAccessor.Properties["Age"].PropertyType.ShouldBe(typeof(int)); childAccessor[child, "ChildName"].ShouldBe("Bar"); childAccessor[child, "ChildName"] = "BarBar"; childAccessor[child, "ChildName"].ShouldBe("BarBar"); childAccessor[child, "Name"].ShouldBeNull(); childAccessor[child, "Name"] = "Foo"; childAccessor[child, "Name"].ShouldBe("Foo"); } [Test] public void When_creating_object_accessor_with_custom_flags() { var parent = new Parent(); ObjectAccessor parentAccessor = Accessor.Build(parent, true, true); parentAccessor.ShouldBeOfType<ObjectAccessor>(); parentAccessor.Type.ShouldBe(typeof(Parent)); parentAccessor.IgnoreCase.ShouldBe(true); parentAccessor.IncludesNonPublic.ShouldBe(true); parentAccessor.ShouldNotBeNull(); parentAccessor.Properties.ShouldNotBeNull(); parentAccessor.Properties.Count.ShouldBe(3); parentAccessor.Properties["Name"].PropertyType.ShouldBe(typeof(string)); parentAccessor.Properties["Age"].PropertyType.ShouldBe(typeof(int)); parentAccessor.Properties["Job"].PropertyType.ShouldBe(typeof(string)); parentAccessor[parent, "Name"].ShouldBeNull(); parentAccessor[parent, "Name"] = "Foo"; parentAccessor[parent, "Name"].ShouldBe("Foo"); parentAccessor[parent, "Age"].ShouldBe(0); parentAccessor[parent, "Age"] = 10; parentAccessor[parent, "Age"].ShouldBe(10); parentAccessor[parent, "Job"].ShouldBeNull(); parentAccessor[parent, "Job"] = "Clown"; parentAccessor[parent, "Job"].ShouldBe("Clown"); parentAccessor[parent, "NAME"].ShouldBe("Foo"); parentAccessor[parent, "name"] = "Foo Foo"; parentAccessor[parent, "naME"].ShouldBe("Foo Foo"); var child = new Child(); ObjectAccessor childAccessor = Accessor.Build(typeof(Child), true, true); childAccessor.ShouldBeOfType<ObjectAccessor>(); childAccessor.Type.ShouldBe(typeof(Child)); childAccessor.IgnoreCase.ShouldBe(true); childAccessor.IncludesNonPublic.ShouldBe(true); childAccessor.ShouldNotBeNull(); childAccessor.Properties.ShouldNotBeNull(); childAccessor.Properties.Count.ShouldBe(3); childAccessor.Properties["ChildName"].PropertyType.ShouldBe(typeof(string)); childAccessor.Properties["Name"].PropertyType.ShouldBe(typeof(string)); childAccessor.Properties["Age"].PropertyType.ShouldBe(typeof(int)); childAccessor[child, "ChildName"].ShouldBe("Bar"); childAccessor[child, "ChIldNAme"] = "BarBar"; childAccessor[child, "ChildName"].ShouldBe("BarBar"); childAccessor[child, "Name"].ShouldBeNull(); childAccessor[child, "Name"] = "Foo"; childAccessor[child, "Name"].ShouldBe("Foo"); } [Test] public void When_using_parent_accessor_to_access_child_properties() { var parent = new Parent(); ObjectAccessor parentAccessor = Accessor.Build(parent); parentAccessor.Type.ShouldBe(typeof(Parent)); parentAccessor.IgnoreCase.ShouldBe(false); parentAccessor.IncludesNonPublic.ShouldBe(false); var child = new Child(); Should.Throw<ArgumentException>(() => { var _ = parentAccessor[child, "ChildName"]; }) .Message.ShouldBe("Type: `Easy.Common.Tests.Unit.Accessors.ObjectAccessorTests+Child` does not have a property named: `ChildName` that supports reading."); Should.Throw<ArgumentException>(() => { parentAccessor[child, "ChildName"] = "foo"; }) .Message.ShouldBe("Type: `Easy.Common.Tests.Unit.Accessors.ObjectAccessorTests+Child` does not have a property named: `ChildName` that supports writing."); } [Test] public void When_using_child_accessor_to_access_parent_properties() { var child = new Child(); ObjectAccessor childAccessor = Accessor.Build(child); childAccessor.Type.ShouldBe(typeof(Child)); childAccessor.IgnoreCase.ShouldBe(false); childAccessor.IncludesNonPublic.ShouldBe(false); var parent = new Parent(); Should.Throw<NullReferenceException>(() => { var _ = childAccessor[parent, "Name"]; }); } [Test] public void When_setting_invalid_values() { var instance = new Parent(); var accessor = Accessor.Build(instance); accessor.Type.ShouldBe(typeof(Parent)); accessor.IgnoreCase.ShouldBe(false); accessor.IncludesNonPublic.ShouldBe(false); accessor[instance, "Name"] = 10; instance.Name.ShouldBeNull(); Should.Throw<InvalidCastException>(() => accessor[instance, "Age"] = "10"); } [Test] public void When_testing_special_cases() { var instance = new SpecialCase(); ObjectAccessor accessor = Accessor.Build(instance); accessor.Type.ShouldBe(typeof(SpecialCase)); accessor.IgnoreCase.ShouldBe(false); accessor.Properties.Count.ShouldBe(2); accessor.Properties.ShouldContain(x => x.Key == "GetterOnly"); accessor.Properties.ShouldContain(x => x.Key == "SetterOnly"); Should.Throw<ArgumentException>(() => { var _ = accessor[instance, "SetterOnly"]; }) .Message.ShouldBe("Type: `Easy.Common.Tests.Unit.Accessors.ObjectAccessorTests+SpecialCase` does not have a property named: `SetterOnly` that supports reading."); Should.Throw<ArgumentException>(() => accessor[instance, "GetterOnly"] = "bar") .Message.ShouldBe("Type: `Easy.Common.Tests.Unit.Accessors.ObjectAccessorTests+SpecialCase` does not have a property named: `GetterOnly` that supports writing."); accessor[instance, "SetterOnly"] = "Foo"; accessor[instance, "GetterOnly"].ShouldBe("Foo"); } [Test] public void When_reusing_object_accessor_on_different_instances_of_the_same_type() { var instanceOne = new Parent(); var instanceTwo = new Parent(); ObjectAccessor accessor = Accessor.Build(instanceOne); instanceOne.Name.ShouldBeNull(); instanceOne.Age.ShouldBe(0); accessor[instanceOne, "Name"] = "Foo1"; accessor[instanceOne, "Age"] = 1; accessor[instanceTwo, "Name"] = "Foo2"; accessor[instanceTwo, "Age"] = 2; instanceOne.Name.ShouldBe("Foo1"); instanceOne.Age.ShouldBe(1); instanceTwo.Name.ShouldBe("Foo2"); instanceTwo.Age.ShouldBe(2); } [SuppressMessage("ReSharper", "UnusedMember.Local")] private class Parent { public string Name { get; set; } public int Age { get; set; } private string Job { get; set; } public string GetJob() => Job; } [SuppressMessage("ReSharper", "UnusedMember.Local")] private sealed class Child : Parent { public string ChildName { get; set; } = "Bar"; } [SuppressMessage("ReSharper", "UnusedMember.Local")] private sealed class SpecialCase { // ReSharper disable once ConvertToAutoPropertyWithPrivateSetter public string GetterOnly => _stuff; private string _stuff; public string SetterOnly { set => _stuff = value; } } } }
// 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 gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; 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 GeneratedAccountBudgetServiceClientTest { [Category("Autogenerated")][Test] public void GetAccountBudgetRequestObject() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget response = client.GetAccountBudget(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountBudgetRequestObjectAsync() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudget>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget responseCallSettings = await client.GetAccountBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountBudget responseCancellationToken = await client.GetAccountBudgetAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAccountBudget() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget response = client.GetAccountBudget(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountBudgetAsync() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudget>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget responseCallSettings = await client.GetAccountBudgetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountBudget responseCancellationToken = await client.GetAccountBudgetAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAccountBudgetResourceNames() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget response = client.GetAccountBudget(request.ResourceNameAsAccountBudgetName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountBudgetResourceNamesAsync() { moq::Mock<AccountBudgetService.AccountBudgetServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetService.AccountBudgetServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetRequest request = new GetAccountBudgetRequest { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), }; gagvr::AccountBudget expectedResponse = new gagvr::AccountBudget { ResourceNameAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), Status = gagve::AccountBudgetStatusEnum.Types.AccountBudgetStatus.Cancelled, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, AdjustedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unspecified, PendingProposal = new gagvr::AccountBudget.Types.PendingAccountBudgetProposal(), Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, AdjustedSpendingLimitMicros = 5260592673487875057L, TotalAdjustmentsMicros = -1818058180873398375L, AmountServedMicros = -8683779131450697164L, PurchaseOrderNumber = "purchase_order_number7be7181f", Notes = "notes00b55843", }; mockGrpcClient.Setup(x => x.GetAccountBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudget>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetServiceClient client = new AccountBudgetServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudget responseCallSettings = await client.GetAccountBudgetAsync(request.ResourceNameAsAccountBudgetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountBudget responseCancellationToken = await client.GetAccountBudgetAsync(request.ResourceNameAsAccountBudgetName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI80; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Net.Pkcs11Interop.Tests.LowLevelAPI80 { /// <summary> /// Object attributes tests. /// </summary> [TestClass] public class _14_ObjectAttributeTest { /// <summary> /// Attribute with empty value test. /// </summary> [TestMethod] public void _01_EmptyAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); // Create attribute without the value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_CLASS); Assert.IsTrue(attr.type == (ulong)CKA.CKA_CLASS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with ulong value test. /// </summary> [TestMethod] public void _02_UintAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); ulong originalValue = Convert.ToUInt64(CKO.CKO_DATA); // Create attribute with ulong value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_CLASS, originalValue); Assert.IsTrue(attr.type == (ulong)CKA.CKA_CLASS); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(ulong)))); ulong recoveredValue = 0; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue == recoveredValue); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (ulong)CKA.CKA_CLASS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with bool value test. /// </summary> [TestMethod] public void _03_BoolAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); bool originalValue = true; // Create attribute with bool value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, originalValue); Assert.IsTrue(attr.type == (ulong)CKA.CKA_TOKEN); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == 1); bool recoveredValue = false; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue == recoveredValue); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (ulong)CKA.CKA_TOKEN); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with string value test. /// </summary> [TestMethod] public void _04_StringAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); string originalValue = "Hello world"; // Create attribute with string value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_LABEL, originalValue); Assert.IsTrue(attr.type == (ulong)CKA.CKA_LABEL); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == Convert.ToUInt64(originalValue.Length)); string recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue == recoveredValue); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (ulong)CKA.CKA_LABEL); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null string value attr = CkaUtils.CreateAttribute(CKA.CKA_LABEL, (string)null); Assert.IsTrue(attr.type == (ulong)CKA.CKA_LABEL); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with byte array value test. /// </summary> [TestMethod] public void _05_ByteArrayAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); byte[] originalValue = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; // Create attribute with byte array value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ID, originalValue); Assert.IsTrue(attr.type == (ulong)CKA.CKA_ID); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == Convert.ToUInt64(originalValue.Length)); byte[] recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(Convert.ToBase64String(originalValue) == Convert.ToBase64String(recoveredValue)); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (ulong)CKA.CKA_ID); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null byte array value attr = CkaUtils.CreateAttribute(CKA.CKA_ID, (byte[])null); Assert.IsTrue(attr.type == (ulong)CKA.CKA_ID); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with DateTime (CKA_DATE) value test. /// </summary> [TestMethod] public void _06_DateTimeAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); DateTime originalValue = new DateTime(2012, 1, 30, 0, 0, 0, DateTimeKind.Utc); // Create attribute with DateTime value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_START_DATE, originalValue); Assert.IsTrue(attr.type == (ulong)CKA.CKA_START_DATE); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == 8); DateTime? recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue == recoveredValue); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (ulong)CKA.CKA_START_DATE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with attribute array value test. /// </summary> [TestMethod] public void _07_AttributeArrayAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CK_ATTRIBUTE[] originalValue = new CK_ATTRIBUTE[2]; originalValue[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true); originalValue[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true); // Create attribute with attribute array value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue); Assert.IsTrue(attr.type == (ulong)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == Convert.ToUInt64((UnmanagedMemory.SizeOf(typeof(CK_ATTRIBUTE)) * originalValue.Length))); CK_ATTRIBUTE[] recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue.Length == recoveredValue.Length); for (int i = 0; i < recoveredValue.Length; i++) { Assert.IsTrue(originalValue[i].type == recoveredValue[i].type); Assert.IsTrue(originalValue[i].valueLen == recoveredValue[i].valueLen); bool originalBool = false; // Read the value of nested attribute CkaUtils.ConvertValue(ref originalValue[i], out originalBool); bool recoveredBool = true; // Read the value of nested attribute CkaUtils.ConvertValue(ref recoveredValue[i], out recoveredBool); Assert.IsTrue(originalBool == recoveredBool); // In this example there is the same pointer to unmanaged memory // in both originalValue and recoveredValue array therefore it // needs to be freed only once. Assert.IsTrue(originalValue[i].value == recoveredValue[i].value); // Free value of nested attributes UnmanagedMemory.Free(ref originalValue[i].value); originalValue[i].valueLen = 0; recoveredValue[i].value = IntPtr.Zero; recoveredValue[i].valueLen = 0; } // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (ulong)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null attribute array value attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, (CK_ATTRIBUTE[])null); Assert.IsTrue(attr.type == (ulong)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with empty attribute array value attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, new CK_ATTRIBUTE[0]); Assert.IsTrue(attr.type == (ulong)CKA.CKA_WRAP_TEMPLATE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with ulong array value test. /// </summary> [TestMethod] public void _08_UintArrayAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); ulong[] originalValue = new ulong[2]; originalValue[0] = 333333; originalValue[1] = 666666; // Create attribute with ulong array value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue); Assert.IsTrue(attr.type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == Convert.ToUInt64((UnmanagedMemory.SizeOf(typeof(ulong)) * originalValue.Length))); ulong[] recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue.Length == recoveredValue.Length); for (int i = 0; i < recoveredValue.Length; i++) { Assert.IsTrue(originalValue[i] == recoveredValue[i]); } // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null ulong array value attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, (ulong[])null); Assert.IsTrue(attr.type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with empty ulong array value attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, new ulong[0]); Assert.IsTrue(attr.type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Attribute with mechanism array value test. /// </summary> [TestMethod] public void _09_MechanismArrayAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKM[] originalValue = new CKM[2]; originalValue[0] = CKM.CKM_RSA_PKCS; originalValue[1] = CKM.CKM_AES_CBC; // Create attribute with mechanism array value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue); Assert.IsTrue(attr.type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == Convert.ToUInt64((UnmanagedMemory.SizeOf(typeof(ulong)) * originalValue.Length))); CKM[] recoveredValue = null; // Read the value of attribute CkaUtils.ConvertValue(ref attr, out recoveredValue); Assert.IsTrue(originalValue.Length == recoveredValue.Length); for (int i = 0; i < recoveredValue.Length; i++) { Assert.IsTrue(originalValue[i] == recoveredValue[i]); } // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with null mechanism array value attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, (CKM[])null); Assert.IsTrue(attr.type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Create attribute with empty mechanism array value attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, new CKM[0]); Assert.IsTrue(attr.type == (ulong)CKA.CKA_ALLOWED_MECHANISMS); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } /// <summary> /// Custom attribute with manually set value test. /// </summary> [TestMethod] public void _10_CustomAttributeTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); byte[] originalValue = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }; // Create attribute without the value CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_VALUE); Assert.IsTrue(attr.type == (ulong)CKA.CKA_VALUE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); // Allocate unmanaged memory for attribute value.. attr.value = UnmanagedMemory.Allocate(originalValue.Length); // ..then set the value of attribute.. UnmanagedMemory.Write(attr.value, originalValue); // ..and finally set the length of attribute value. attr.valueLen = Convert.ToUInt64(originalValue.Length); Assert.IsTrue(attr.type == (ulong)CKA.CKA_VALUE); Assert.IsTrue(attr.value != IntPtr.Zero); Assert.IsTrue(attr.valueLen == Convert.ToUInt64(originalValue.Length)); // Read the value of attribute byte[] recoveredValue = UnmanagedMemory.Read(attr.value, Convert.ToInt32(attr.valueLen)); Assert.IsTrue(Convert.ToBase64String(originalValue) == Convert.ToBase64String(recoveredValue)); // Free attribute value UnmanagedMemory.Free(ref attr.value); attr.valueLen = 0; Assert.IsTrue(attr.type == (ulong)CKA.CKA_VALUE); Assert.IsTrue(attr.value == IntPtr.Zero); Assert.IsTrue(attr.valueLen == 0); } } }
using DevExpress.Mvvm.ModuleInjection; using DevExpress.Mvvm.ModuleInjection.Native; using DevExpress.Mvvm.POCO; using NUnit.Framework; using System; using System.Linq; using System.Windows; using System.Windows.Controls; namespace DevExpress.Mvvm.UI.ModuleInjection.Tests { [TestFixture] public class LogicalSerializationTests : BaseWpfFixture { public class VMTest : ISupportState<VMTest> { public string Value { get; set; } void ISupportState<VMTest>.RestoreState(VMTest state) { Value = state.Value; } VMTest ISupportState<VMTest>.SaveState() { return this; } } public IModuleManager Manager { get { return ModuleManager.DefaultManager; } } public IModuleWindowManager WindowManager { get { return ModuleManager.DefaultWindowManager; } } protected override void SetUpCore() { base.SetUpCore(); InjectionTestHelper.SetUp(typeof(LogicalSerializationTests).Assembly); } protected override void TearDownCore() { InjectionTestHelper.TearDown(); base.TearDownCore(); } [Test] public void SerializeEmpty() { string logicalState = null; string visualState = null; LogicalInfo logicalInfo = null; VisualInfo visualInfo = null; Manager.Save(out logicalState, out visualState); logicalInfo = LogicalInfo.Deserialize(logicalState); visualInfo = VisualInfo.Deserialize(visualState); Assert.AreEqual(0, logicalInfo.Regions.Count()); Assert.AreEqual(0, visualInfo.Regions.Count()); Manager.Restore(null, null); Manager.Restore(string.Empty, string.Empty); Manager.Restore(logicalState, visualState); } [Test] public void SerializeEmpty2() { string logicalState = null; string visualState = null; LogicalInfo logicalInfo = null; VisualInfo visualInfo = null; Manager.Register("R", new Module("1", () => new object())); Manager.Save(out logicalState, out visualState); logicalInfo = LogicalInfo.Deserialize(logicalState); visualInfo = VisualInfo.Deserialize(visualState); Assert.AreEqual(0, logicalInfo.Regions.Count()); Assert.AreEqual(0, visualInfo.Regions.Count()); } [Test] public void SerializeEmpty3() { string logicalState = null; string visualState = null; LogicalInfo logicalInfo = null; VisualInfo visualInfo = null; Manager.Register("R", new Module("1", () => new object())); Manager.Inject("R", "1"); Manager.Save(out logicalState, out visualState); logicalInfo = LogicalInfo.Deserialize(logicalState); visualInfo = VisualInfo.Deserialize(visualState); Assert.AreEqual(1, logicalInfo.Regions.Count()); Assert.AreEqual(1, visualInfo.Regions.Count()); Assert.AreEqual(0, visualInfo.Regions[0].Items.Count); Assert.AreEqual("R", logicalInfo.Regions[0].RegionName); Assert.AreEqual(null, logicalInfo.Regions[0].SelectedViewModelKey); Assert.AreEqual(0, logicalInfo.Regions[0].Items.Count); } [Test] public void DeserializeState() { string logicalState = null; string visualState = null; VMTest vm = null; Manager.Register("R", new Module("1", () => vm = new VMTest() { Value = "Test" })); Manager.Inject("R", "1"); ContentControl c = new ContentControl(); c.BeginInit(); UIRegion.SetRegion(c, "R"); c.EndInit(); Manager.Save(out logicalState, out visualState); Manager.Restore(logicalState, visualState); Assert.AreNotEqual(vm, Manager.GetRegion("R").GetViewModel("1")); vm = (VMTest)Manager.GetRegion("R").GetViewModel("1"); Assert.AreEqual("Test", vm.Value); } [Test] public void DeserializeEvents() { string logicalState = null; string visualState = null; Manager.Register("R", new Module("1", () => new VMTest())); Manager.Register("R", new Module("2", () => new VMTest())); ContentControl c = new ContentControl(); UIRegion.SetRegion(c, "R"); Window.Content = c; Window.Show(); var serviceHelper = InjectionTestHelper.CreateServiceHelper(c, "R"); Manager.Inject("R", "1"); Manager.Inject("R", "2"); serviceHelper.AssertSelectionChanged(1); Assert.AreEqual("1", Manager.GetRegion("R").SelectedKey); Manager.Save(out logicalState, out visualState); Manager.Navigate("R", "2"); Assert.AreEqual("2", Manager.GetRegion("R").SelectedKey); serviceHelper.AssertSelectionChanged(2); Manager.Restore(logicalState, visualState); Assert.AreEqual("1", Manager.GetRegion("R").SelectedKey); serviceHelper.AssertSelectionChanged(4); serviceHelper.AssertViewModelRemoving(0); serviceHelper.AssertViewModelRemoved(2); } [Test] public void DisableEnable() { ContentControl c1 = new ContentControl(); ContentControl c2 = new ContentControl(); c1.BeginInit(); c1.EndInit(); c2.BeginInit(); c2.EndInit(); UIRegion.SetRegion(c1, "R1"); UIRegion.SetRegion(c2, "R2"); Manager.Register("R1", new Module("1", () => new VMTest())); Manager.Register("R1", new Module("2", () => new VMTest())); Manager.Register("R2", new Module("1", () => new VMTest())); Manager.Register("R2", new Module("2", () => new VMTest())); Manager.Inject("R1", "1"); Manager.Inject("R1", "2"); Manager.Inject("R2", "1"); Manager.Inject("R2", "2"); string logicalState = null; string visualState = null; Manager.Save(out logicalState, out visualState); var logicalInfo = LogicalInfo.Deserialize(logicalState); var visualInfo = VisualInfo.Deserialize(visualState); Assert.AreEqual(2, logicalInfo.Regions.Count()); Assert.AreEqual("R1", logicalInfo.Regions[0].RegionName); Assert.AreEqual("R2", logicalInfo.Regions[1].RegionName); Assert.AreEqual(2, logicalInfo.Regions[0].Items.Count()); Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count()); Manager.GetRegion("R1").LogicalSerializationMode = LogicalSerializationMode.Disabled; Manager.Save(out logicalState, out visualState); logicalInfo = LogicalInfo.Deserialize(logicalState); visualInfo = VisualInfo.Deserialize(visualState); Assert.AreEqual(2, logicalInfo.Regions.Count()); Assert.AreEqual("R1", logicalInfo.Regions[0].RegionName); Assert.AreEqual("R2", logicalInfo.Regions[1].RegionName); Assert.AreEqual(0, logicalInfo.Regions[0].Items.Count()); Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count()); Manager.GetRegion("R1").LogicalSerializationMode = LogicalSerializationMode.Enabled; Manager.Save(out logicalState, out visualState); logicalInfo = LogicalInfo.Deserialize(logicalState); visualInfo = VisualInfo.Deserialize(visualState); Assert.AreEqual(2, logicalInfo.Regions[0].Items.Count()); Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count()); Manager.GetRegion("R1").SetLogicalSerializationMode("1", LogicalSerializationMode.Disabled); Manager.Save(out logicalState, out visualState); logicalInfo = LogicalInfo.Deserialize(logicalState); visualInfo = VisualInfo.Deserialize(visualState); Assert.AreEqual(1, logicalInfo.Regions[0].Items.Count()); Assert.AreEqual("2", logicalInfo.Regions[0].Items[0].Key); Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count()); Manager.GetRegion("R1").LogicalSerializationMode = LogicalSerializationMode.Disabled; Manager.GetRegion("R1").SetLogicalSerializationMode("2", LogicalSerializationMode.Enabled); Manager.Save(out logicalState, out visualState); logicalInfo = LogicalInfo.Deserialize(logicalState); visualInfo = VisualInfo.Deserialize(visualState); Assert.AreEqual(1, logicalInfo.Regions[0].Items.Count()); Assert.AreEqual("2", logicalInfo.Regions[0].Items[0].Key); Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count()); Manager.GetRegion("R1").SetLogicalSerializationMode("1", null); Manager.GetRegion("R1").SetLogicalSerializationMode("2", null); Manager.Save(out logicalState, out visualState); logicalInfo = LogicalInfo.Deserialize(logicalState); visualInfo = VisualInfo.Deserialize(visualState); Assert.AreEqual(0, logicalInfo.Regions[0].Items.Count()); Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count()); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.MirrorSequences { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// A sample API that uses a petstore as an example to demonstrate /// features in the swagger-2.0 specification /// </summary> public partial class SequenceRequestResponseTest : ServiceClient<SequenceRequestResponseTest>, ISequenceRequestResponseTest { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SequenceRequestResponseTest(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SequenceRequestResponseTest(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SequenceRequestResponseTest(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SequenceRequestResponseTest(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new Uri("http://petstore.swagger.wordnik.com/api"); SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); } /// <summary> /// Creates a new pet in the store. Duplicates are allowed /// </summary> /// <param name='pets'> /// Pets to add to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorModelException"> /// 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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<Pet>>> AddPetWithHttpMessagesAsync(IList<Pet> pets, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (pets == null) { throw new ValidationException(ValidationRules.CannotBeNull, "pets"); } if (pets != null) { foreach (var element in pets) { if (element != null) { element.Validate(); } } } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("pets", pets); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "AddPet", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(pets != null) { _requestContent = SafeJsonConvert.SerializeObject(pets, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorModel _errorBody = SafeJsonConvert.DeserializeObject<ErrorModel>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<Pet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IList<Pet>>(_responseContent, this.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> /// Adds new pet stylesin the store. Duplicates are allowed /// </summary> /// <param name='petStyle'> /// Pet style to add to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<int?>>> AddPetStylesWithHttpMessagesAsync(IList<int?> petStyle, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (petStyle == null) { throw new ValidationException(ValidationRules.CannotBeNull, "petStyle"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("petStyle", petStyle); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "AddPetStyles", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(petStyle != null) { _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); IList<ErrorModel> _errorBody = SafeJsonConvert.DeserializeObject<IList<ErrorModel>>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IList<int?>>(_responseContent, this.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> /// Updates new pet stylesin the store. Duplicates are allowed /// </summary> /// <param name='petStyle'> /// Pet style to add to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<int?>>> UpdatePetStylesWithHttpMessagesAsync(IList<int?> petStyle, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (petStyle == null) { throw new ValidationException(ValidationRules.CannotBeNull, "petStyle"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("petStyle", petStyle); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UpdatePetStyles", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(petStyle != null) { _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); IList<ErrorModel> _errorBody = SafeJsonConvert.DeserializeObject<IList<ErrorModel>>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IList<int?>>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.IO; using SharpCompress.Common; using SharpCompress.Common.Rar.Headers; using SharpCompress.Compressor.PPMd.H; using SharpCompress.Compressor.Rar.decode; using SharpCompress.Compressor.Rar.PPM; using SharpCompress.Compressor.Rar.VM; namespace SharpCompress.Compressor.Rar { internal sealed class Unpack : Unpack20 { public bool FileExtracted { // Duplicate method // private boolean ReadEndOfBlock() throws IOException, RarException // { // int BitField = getbits(); // boolean NewTable, NewFile = false; // if ((BitField & 0x8000) != 0) { // NewTable = true; // addbits(1); // } else { // NewFile = true; // NewTable = (BitField & 0x4000) != 0; // addbits(2); // } // tablesRead = !NewTable; // return !(NewFile || NewTable && !readTables()); // } get { return fileExtracted; } } public long DestSize { get { return destUnpSize; } set { this.destUnpSize = value; this.fileExtracted = false; } } public bool Suspended { set { this.suspended = value; } } public int Char { get { if (inAddr > BitInput.MAX_SIZE - 30) { unpReadBuf(); } return (InBuf[inAddr++] & 0xff); } } public int PpmEscChar { get { return ppmEscChar; } set { this.ppmEscChar = value; } } //UPGRADE_NOTE: Final was removed from the declaration of 'ppm '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private ModelPPM ppm = new ModelPPM(); private int ppmEscChar; private RarVM rarVM = new RarVM(); /* Filters code, one entry per filter */ //UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'" private List<UnpackFilter> filters = new List<UnpackFilter>(); /* Filters stack, several entrances of same filter are possible */ //UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'" private List<UnpackFilter> prgStack = new List<UnpackFilter>(); /* * lengths of preceding blocks, one length per filter. Used to reduce size * required to write block length if lengths are repeating */ //UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'" private List<int> oldFilterLengths = new List<int>(); private int lastFilter; private bool tablesRead; //UPGRADE_NOTE: The initialization of 'unpOldTable' was moved to method 'InitBlock'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" private byte[] unpOldTable = new byte[Compress.HUFF_TABLE_SIZE]; private BlockTypes unpBlockType; //private bool externalWindow; private long writtenFileSize; private bool fileExtracted; private bool ppmError; private int prevLowDist; private int lowDistRepCount; public static int[] DBitLengthCounts = new int[] {4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 14, 0, 12}; private FileHeader fileHeader; public Unpack() { window = null; //externalWindow = false; suspended = false; unpAllBuf = false; unpSomeRead = false; } public void init(byte[] window) { if (window == null) { this.window = new byte[Compress.MAXWINSIZE]; } else { this.window = window; //externalWindow = true; } inAddr = 0; unpInitData(false); } public void doUnpack(FileHeader fileHeader, Stream readStream, Stream writeStream) { destUnpSize = fileHeader.UncompressedSize; this.fileHeader = fileHeader; base.writeStream = writeStream; base.readStream = readStream; bool solid = FlagUtility.HasFlag(fileHeader.FileFlags, FileFlags.SOLID); if (!solid) { init(null); } suspended = false; doUnpack(); } public void doUnpack() { bool solid = FlagUtility.HasFlag(fileHeader.FileFlags, FileFlags.SOLID); if (fileHeader.PackingMethod == 0x30) { unstoreFile(); return; } switch (fileHeader.RarVersion) { case 15: // rar 1.5 compression unpack15(solid); break; case 20: // rar 2.x compression case 26: // files larger than 2GB unpack20(solid); break; case 29: // rar 3.x compression case 36: // alternative hash unpack29(solid); break; } } private void unstoreFile() { byte[] buffer = new byte[0x10000]; while (true) { int code = readStream.Read(buffer, 0, (int) System.Math.Min(buffer.Length, destUnpSize)); if (code == 0 || code == -1) break; code = code < destUnpSize ? code : (int) destUnpSize; writeStream.Write(buffer, 0, code); if (destUnpSize >= 0) destUnpSize -= code; if (suspended) return; } } private void unpack29(bool solid) { int[] DDecode = new int[Compress.DC]; byte[] DBits = new byte[Compress.DC]; int Bits; if (DDecode[1] == 0) { int Dist = 0, BitLength = 0, Slot = 0; for (int I = 0; I < DBitLengthCounts.Length; I++, BitLength++) { int count = DBitLengthCounts[I]; for (int J = 0; J < count; J++, Slot++, Dist += (1 << BitLength)) { DDecode[Slot] = Dist; DBits[Slot] = (byte) BitLength; } } } fileExtracted = true; if (!suspended) { unpInitData(solid); if (!unpReadBuf()) { return; } if ((!solid || !tablesRead) && !readTables()) { return; } } if (ppmError) { return; } while (true) { unpPtr &= Compress.MAXWINMASK; if (inAddr > readBorder) { if (!unpReadBuf()) { break; } } // System.out.println(((wrPtr - unpPtr) & // Compress.MAXWINMASK)+":"+wrPtr+":"+unpPtr); if (((wrPtr - unpPtr) & Compress.MAXWINMASK) < 260 && wrPtr != unpPtr) { UnpWriteBuf(); if (destUnpSize <= 0) { return; } if (suspended) { fileExtracted = false; return; } } if (unpBlockType == BlockTypes.BLOCK_PPM) { int Ch = ppm.decodeChar(); if (Ch == -1) { ppmError = true; break; } if (Ch == ppmEscChar) { int NextCh = ppm.decodeChar(); if (NextCh == 0) { if (!readTables()) { break; } continue; } if (NextCh == 2 || NextCh == -1) { break; } if (NextCh == 3) { if (!readVMCodePPM()) { break; } continue; } if (NextCh == 4) { int Distance = 0, Length = 0; bool failed = false; for (int I = 0; I < 4 && !failed; I++) { int ch = ppm.decodeChar(); if (ch == -1) { failed = true; } else { if (I == 3) { // Bug fixed Length = ch & 0xff; } else { // Bug fixed Distance = (Distance << 8) + (ch & 0xff); } } } if (failed) { break; } copyString(Length + 32, Distance + 2); continue; } if (NextCh == 5) { int Length = ppm.decodeChar(); if (Length == -1) { break; } copyString(Length + 4, 1); continue; } } window[unpPtr++] = (byte) Ch; continue; } int Number = this.decodeNumber(LD); if (Number < 256) { window[unpPtr++] = (byte) Number; continue; } if (Number >= 271) { int Length = LDecode[Number -= 271] + 3; if ((Bits = LBits[Number]) > 0) { Length += Utility.URShift(GetBits(), (16 - Bits)); AddBits(Bits); } int DistNumber = this.decodeNumber(DD); int Distance = DDecode[DistNumber] + 1; if ((Bits = DBits[DistNumber]) > 0) { if (DistNumber > 9) { if (Bits > 4) { Distance += ((Utility.URShift(GetBits(), (20 - Bits))) << 4); AddBits(Bits - 4); } if (lowDistRepCount > 0) { lowDistRepCount--; Distance += prevLowDist; } else { int LowDist = this.decodeNumber(LDD); if (LowDist == 16) { lowDistRepCount = Compress.LOW_DIST_REP_COUNT - 1; Distance += prevLowDist; } else { Distance += LowDist; prevLowDist = LowDist; } } } else { Distance += Utility.URShift(GetBits(), (16 - Bits)); AddBits(Bits); } } if (Distance >= 0x2000) { Length++; if (Distance >= 0x40000L) { Length++; } } insertOldDist(Distance); insertLastMatch(Length, Distance); copyString(Length, Distance); continue; } if (Number == 256) { if (!readEndOfBlock()) { break; } continue; } if (Number == 257) { if (!readVMCode()) { break; } continue; } if (Number == 258) { if (lastLength != 0) { copyString(lastLength, lastDist); } continue; } if (Number < 263) { int DistNum = Number - 259; int Distance = oldDist[DistNum]; for (int I = DistNum; I > 0; I--) { oldDist[I] = oldDist[I - 1]; } oldDist[0] = Distance; int LengthNumber = this.decodeNumber(RD); int Length = LDecode[LengthNumber] + 2; if ((Bits = LBits[LengthNumber]) > 0) { Length += Utility.URShift(GetBits(), (16 - Bits)); AddBits(Bits); } insertLastMatch(Length, Distance); copyString(Length, Distance); continue; } if (Number < 272) { int Distance = SDDecode[Number -= 263] + 1; if ((Bits = SDBits[Number]) > 0) { Distance += Utility.URShift(GetBits(), (16 - Bits)); AddBits(Bits); } insertOldDist(Distance); insertLastMatch(2, Distance); copyString(2, Distance); continue; } } UnpWriteBuf(); } private void UnpWriteBuf() { int WrittenBorder = wrPtr; int WriteSize = (unpPtr - WrittenBorder) & Compress.MAXWINMASK; for (int I = 0; I < prgStack.Count; I++) { UnpackFilter flt = prgStack[I]; if (flt == null) { continue; } if (flt.NextWindow) { flt.NextWindow = false; // ->NextWindow=false; continue; } int BlockStart = flt.BlockStart; // ->BlockStart; int BlockLength = flt.BlockLength; // ->BlockLength; if (((BlockStart - WrittenBorder) & Compress.MAXWINMASK) < WriteSize) { if (WrittenBorder != BlockStart) { UnpWriteArea(WrittenBorder, BlockStart); WrittenBorder = BlockStart; WriteSize = (unpPtr - WrittenBorder) & Compress.MAXWINMASK; } if (BlockLength <= WriteSize) { int BlockEnd = (BlockStart + BlockLength) & Compress.MAXWINMASK; if (BlockStart < BlockEnd || BlockEnd == 0) { // VM.SetMemory(0,Window+BlockStart,BlockLength); rarVM.setMemory(0, window, BlockStart, BlockLength); } else { int FirstPartLength = Compress.MAXWINSIZE - BlockStart; // VM.SetMemory(0,Window+BlockStart,FirstPartLength); rarVM.setMemory(0, window, BlockStart, FirstPartLength); // VM.SetMemory(FirstPartLength,Window,BlockEnd); rarVM.setMemory(FirstPartLength, window, 0, BlockEnd); } VMPreparedProgram ParentPrg = filters[flt.ParentFilter].Program; VMPreparedProgram Prg = flt.Program; if (ParentPrg.GlobalData.Count > RarVM.VM_FIXEDGLOBALSIZE) { // copy global data from previous script execution if // any // Prg->GlobalData.Alloc(ParentPrg->GlobalData.Size()); // memcpy(&Prg->GlobalData[VM_FIXEDGLOBALSIZE],&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],ParentPrg->GlobalData.Size()-VM_FIXEDGLOBALSIZE); Prg.GlobalData.Clear(); for (int i = 0; i < ParentPrg.GlobalData.Count - RarVM.VM_FIXEDGLOBALSIZE; i++) { Prg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = ParentPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; } } ExecuteCode(Prg); if (Prg.GlobalData.Count > RarVM.VM_FIXEDGLOBALSIZE) { // save global data for next script execution if (ParentPrg.GlobalData.Count < Prg.GlobalData.Count) { //ParentPrg.GlobalData.Clear(); // ->GlobalData.Alloc(Prg->GlobalData.Size()); ParentPrg.GlobalData.SetSize(Prg.GlobalData.Count); } // memcpy(&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],&Prg->GlobalData[VM_FIXEDGLOBALSIZE],Prg->GlobalData.Size()-VM_FIXEDGLOBALSIZE); for (int i = 0; i < Prg.GlobalData.Count - RarVM.VM_FIXEDGLOBALSIZE; i++) { ParentPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = Prg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; } } else { ParentPrg.GlobalData.Clear(); } int FilteredDataOffset = Prg.FilteredDataOffset; int FilteredDataSize = Prg.FilteredDataSize; byte[] FilteredData = new byte[FilteredDataSize]; for (int i = 0; i < FilteredDataSize; i++) { FilteredData[i] = rarVM.Mem[FilteredDataOffset + i]; // Prg.GlobalData.get(FilteredDataOffset // + // i); } prgStack[I] = null; while (I + 1 < prgStack.Count) { UnpackFilter NextFilter = prgStack[I + 1]; if (NextFilter == null || NextFilter.BlockStart != BlockStart || NextFilter.BlockLength != FilteredDataSize || NextFilter.NextWindow) { break; } // apply several filters to same data block rarVM.setMemory(0, FilteredData, 0, FilteredDataSize); // .SetMemory(0,FilteredData,FilteredDataSize); VMPreparedProgram pPrg = filters[NextFilter.ParentFilter].Program; VMPreparedProgram NextPrg = NextFilter.Program; if (pPrg.GlobalData.Count > RarVM.VM_FIXEDGLOBALSIZE) { // copy global data from previous script execution // if any // NextPrg->GlobalData.Alloc(ParentPrg->GlobalData.Size()); NextPrg.GlobalData.SetSize(pPrg.GlobalData.Count); // memcpy(&NextPrg->GlobalData[VM_FIXEDGLOBALSIZE],&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],ParentPrg->GlobalData.Size()-VM_FIXEDGLOBALSIZE); for (int i = 0; i < pPrg.GlobalData.Count - RarVM.VM_FIXEDGLOBALSIZE; i++) { NextPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = pPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; } } ExecuteCode(NextPrg); if (NextPrg.GlobalData.Count > RarVM.VM_FIXEDGLOBALSIZE) { // save global data for next script execution if (pPrg.GlobalData.Count < NextPrg.GlobalData.Count) { pPrg.GlobalData.SetSize(NextPrg.GlobalData.Count); } // memcpy(&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],&NextPrg->GlobalData[VM_FIXEDGLOBALSIZE],NextPrg->GlobalData.Size()-VM_FIXEDGLOBALSIZE); for (int i = 0; i < NextPrg.GlobalData.Count - RarVM.VM_FIXEDGLOBALSIZE; i++) { pPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i] = NextPrg.GlobalData[RarVM.VM_FIXEDGLOBALSIZE + i]; } } else { pPrg.GlobalData.Clear(); } FilteredDataOffset = NextPrg.FilteredDataOffset; FilteredDataSize = NextPrg.FilteredDataSize; FilteredData = new byte[FilteredDataSize]; for (int i = 0; i < FilteredDataSize; i++) { FilteredData[i] = NextPrg.GlobalData[FilteredDataOffset + i]; } I++; prgStack[I] = null; } writeStream.Write(FilteredData, 0, FilteredDataSize); unpSomeRead = true; writtenFileSize += FilteredDataSize; destUnpSize -= FilteredDataSize; WrittenBorder = BlockEnd; WriteSize = (unpPtr - WrittenBorder) & Compress.MAXWINMASK; } else { for (int J = I; J < prgStack.Count; J++) { UnpackFilter filt = prgStack[J]; if (filt != null && filt.NextWindow) { filt.NextWindow = false; } } wrPtr = WrittenBorder; return; } } } UnpWriteArea(WrittenBorder, unpPtr); wrPtr = unpPtr; } private void UnpWriteArea(int startPtr, int endPtr) { if (endPtr != startPtr) { unpSomeRead = true; } if (endPtr < startPtr) { UnpWriteData(window, startPtr, -startPtr & Compress.MAXWINMASK); UnpWriteData(window, 0, endPtr); unpAllBuf = true; } else { UnpWriteData(window, startPtr, endPtr - startPtr); } } private void UnpWriteData(byte[] data, int offset, int size) { if (destUnpSize <= 0) { return; } int writeSize = size; if (writeSize > destUnpSize) { writeSize = (int) destUnpSize; } writeStream.Write(data, offset, writeSize); writtenFileSize += size; destUnpSize -= size; } private void insertOldDist(int distance) { oldDist[3] = oldDist[2]; oldDist[2] = oldDist[1]; oldDist[1] = oldDist[0]; oldDist[0] = distance; } private void insertLastMatch(int length, int distance) { lastDist = distance; lastLength = length; } private void copyString(int length, int distance) { // System.out.println("copyString(" + length + ", " + distance + ")"); int destPtr = unpPtr - distance; // System.out.println(unpPtr+":"+distance); if (destPtr >= 0 && destPtr < Compress.MAXWINSIZE - 260 && unpPtr < Compress.MAXWINSIZE - 260) { window[unpPtr++] = window[destPtr++]; while (--length > 0) window[unpPtr++] = window[destPtr++]; } else while (length-- != 0) { window[unpPtr] = window[destPtr++ & Compress.MAXWINMASK]; unpPtr = (unpPtr + 1) & Compress.MAXWINMASK; } } protected internal override void unpInitData(bool solid) { if (!solid) { tablesRead = false; Utility.Fill(oldDist, 0); // memset(oldDist,0,sizeof(OldDist)); oldDistPtr = 0; lastDist = 0; lastLength = 0; Utility.Fill(unpOldTable, (byte) 0); // memset(UnpOldTable,0,sizeof(UnpOldTable)); unpPtr = 0; wrPtr = 0; ppmEscChar = 2; initFilters(); } InitBitInput(); ppmError = false; writtenFileSize = 0; readTop = 0; readBorder = 0; unpInitData20(solid); } private void initFilters() { oldFilterLengths.Clear(); lastFilter = 0; filters.Clear(); prgStack.Clear(); } private bool readEndOfBlock() { int BitField = GetBits(); bool NewTable, NewFile = false; if ((BitField & 0x8000) != 0) { NewTable = true; AddBits(1); } else { NewFile = true; NewTable = (BitField & 0x4000) != 0 ? true : false; AddBits(2); } tablesRead = !NewTable; return !(NewFile || NewTable && !readTables()); } private bool readTables() { byte[] bitLength = new byte[Compress.BC]; byte[] table = new byte[Compress.HUFF_TABLE_SIZE]; if (inAddr > readTop - 25) { if (!unpReadBuf()) { return (false); } } AddBits((8 - inBit) & 7); long bitField = GetBits() & unchecked((int) 0xffFFffFF); if ((bitField & 0x8000) != 0) { unpBlockType = BlockTypes.BLOCK_PPM; return (ppm.decodeInit(this, ppmEscChar)); } unpBlockType = BlockTypes.BLOCK_LZ; prevLowDist = 0; lowDistRepCount = 0; if ((bitField & 0x4000) == 0) { Utility.Fill(unpOldTable, (byte) 0); // memset(UnpOldTable,0,sizeof(UnpOldTable)); } AddBits(2); for (int i = 0; i < Compress.BC; i++) { int length = (Utility.URShift(GetBits(), 12)) & 0xFF; AddBits(4); if (length == 15) { int zeroCount = (Utility.URShift(GetBits(), 12)) & 0xFF; AddBits(4); if (zeroCount == 0) { bitLength[i] = 15; } else { zeroCount += 2; while (zeroCount-- > 0 && i < bitLength.Length) { bitLength[i++] = 0; } i--; } } else { bitLength[i] = (byte) length; } } UnpackUtility.makeDecodeTables(bitLength, 0, BD, Compress.BC); int TableSize = Compress.HUFF_TABLE_SIZE; for (int i = 0; i < TableSize;) { if (inAddr > readTop - 5) { if (!unpReadBuf()) { return (false); } } int Number = this.decodeNumber(BD); if (Number < 16) { table[i] = (byte) ((Number + unpOldTable[i]) & 0xf); i++; } else if (Number < 18) { int N; if (Number == 16) { N = (Utility.URShift(GetBits(), 13)) + 3; AddBits(3); } else { N = (Utility.URShift(GetBits(), 9)) + 11; AddBits(7); } while (N-- > 0 && i < TableSize) { table[i] = table[i - 1]; i++; } } else { int N; if (Number == 18) { N = (Utility.URShift(GetBits(), 13)) + 3; AddBits(3); } else { N = (Utility.URShift(GetBits(), 9)) + 11; AddBits(7); } while (N-- > 0 && i < TableSize) { table[i++] = 0; } } } tablesRead = true; if (inAddr > readTop) { return (false); } UnpackUtility.makeDecodeTables(table, 0, LD, Compress.NC); UnpackUtility.makeDecodeTables(table, Compress.NC, DD, Compress.DC); UnpackUtility.makeDecodeTables(table, Compress.NC + Compress.DC, LDD, Compress.LDC); UnpackUtility.makeDecodeTables(table, Compress.NC + Compress.DC + Compress.LDC, RD, Compress.RC); // memcpy(unpOldTable,table,sizeof(unpOldTable)); Buffer.BlockCopy(table, 0, unpOldTable, 0, unpOldTable.Length); return (true); } private bool readVMCode() { int FirstByte = GetBits() >> 8; AddBits(8); int Length = (FirstByte & 7) + 1; if (Length == 7) { Length = (GetBits() >> 8) + 7; AddBits(8); } else if (Length == 8) { Length = GetBits(); AddBits(16); } //UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'" List<Byte> vmCode = new List<Byte>(); for (int I = 0; I < Length; I++) { if (inAddr >= readTop - 1 && !unpReadBuf() && I < Length - 1) { return (false); } vmCode.Add((byte) (GetBits() >> 8)); AddBits(8); } return (addVMCode(FirstByte, vmCode, Length)); } private bool readVMCodePPM() { int FirstByte = ppm.decodeChar(); if ((int) FirstByte == -1) { return (false); } int Length = (FirstByte & 7) + 1; if (Length == 7) { int B1 = ppm.decodeChar(); if (B1 == -1) { return (false); } Length = B1 + 7; } else if (Length == 8) { int B1 = ppm.decodeChar(); if (B1 == -1) { return (false); } int B2 = ppm.decodeChar(); if (B2 == -1) { return (false); } Length = B1*256 + B2; } //UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'" List<Byte> vmCode = new List<Byte>(); for (int I = 0; I < Length; I++) { int Ch = ppm.decodeChar(); if (Ch == -1) { return (false); } vmCode.Add((byte) Ch); // VMCode[I]=Ch; } return (addVMCode(FirstByte, vmCode, Length)); } private bool addVMCode(int firstByte, List<byte> vmCode, int length) { BitInput Inp = new BitInput(); Inp.InitBitInput(); // memcpy(Inp.InBuf,Code,Min(BitInput::MAX_SIZE,CodeSize)); for (int i = 0; i < Math.Min(BitInput.MAX_SIZE, vmCode.Count); i++) { Inp.InBuf[i] = vmCode[i]; } rarVM.init(); int FiltPos; if ((firstByte & 0x80) != 0) { FiltPos = RarVM.ReadData(Inp); if (FiltPos == 0) { initFilters(); } else { FiltPos--; } } else FiltPos = lastFilter; // use the same filter as last time if (FiltPos > filters.Count || FiltPos > oldFilterLengths.Count) { return (false); } lastFilter = FiltPos; bool NewFilter = (FiltPos == filters.Count); UnpackFilter StackFilter = new UnpackFilter(); // new filter for // PrgStack UnpackFilter Filter; if (NewFilter) // new filter code, never used before since VM reset { // too many different filters, corrupt archive if (FiltPos > 1024) { return (false); } // Filters[Filters.Size()-1]=Filter=new UnpackFilter; Filter = new UnpackFilter(); filters.Add(Filter); StackFilter.ParentFilter = filters.Count - 1; oldFilterLengths.Add(0); Filter.ExecCount = 0; } // filter was used in the past else { Filter = filters[FiltPos]; StackFilter.ParentFilter = FiltPos; Filter.ExecCount = Filter.ExecCount + 1; // ->ExecCount++; } prgStack.Add(StackFilter); StackFilter.ExecCount = Filter.ExecCount; // ->ExecCount; int BlockStart = RarVM.ReadData(Inp); if ((firstByte & 0x40) != 0) { BlockStart += 258; } StackFilter.BlockStart = ((BlockStart + unpPtr) & Compress.MAXWINMASK); if ((firstByte & 0x20) != 0) { StackFilter.BlockLength = RarVM.ReadData(Inp); } else { StackFilter.BlockLength = FiltPos < oldFilterLengths.Count ? oldFilterLengths[FiltPos] : 0; } StackFilter.NextWindow = (wrPtr != unpPtr) && ((wrPtr - unpPtr) & Compress.MAXWINMASK) <= BlockStart; // DebugLog("\nNextWindow: UnpPtr=%08x WrPtr=%08x // BlockStart=%08x",UnpPtr,WrPtr,BlockStart); oldFilterLengths[FiltPos] = StackFilter.BlockLength; // memset(StackFilter->Prg.InitR,0,sizeof(StackFilter->Prg.InitR)); Utility.Fill(StackFilter.Program.InitR, 0); StackFilter.Program.InitR[3] = RarVM.VM_GLOBALMEMADDR; // StackFilter->Prg.InitR[3]=VM_GLOBALMEMADDR; StackFilter.Program.InitR[4] = StackFilter.BlockLength; // StackFilter->Prg.InitR[4]=StackFilter->BlockLength; StackFilter.Program.InitR[5] = StackFilter.ExecCount; // StackFilter->Prg.InitR[5]=StackFilter->ExecCount; if ((firstByte & 0x10) != 0) // set registers to optional parameters // if any { int InitMask = Utility.URShift(Inp.GetBits(), 9); Inp.AddBits(7); for (int I = 0; I < 7; I++) { if ((InitMask & (1 << I)) != 0) { // StackFilter->Prg.InitR[I]=RarVM::ReadData(Inp); StackFilter.Program.InitR[I] = RarVM.ReadData(Inp); } } } if (NewFilter) { int VMCodeSize = RarVM.ReadData(Inp); if (VMCodeSize >= 0x10000 || VMCodeSize == 0) { return (false); } byte[] VMCode = new byte[VMCodeSize]; for (int I = 0; I < VMCodeSize; I++) { if (Inp.Overflow(3)) { return (false); } VMCode[I] = (byte) (Inp.GetBits() >> 8); Inp.AddBits(8); } // VM.Prepare(&VMCode[0],VMCodeSize,&Filter->Prg); rarVM.prepare(VMCode, VMCodeSize, Filter.Program); } StackFilter.Program.AltCommands = Filter.Program.Commands; // StackFilter->Prg.AltCmd=&Filter->Prg.Cmd[0]; StackFilter.Program.CommandCount = Filter.Program.CommandCount; // StackFilter->Prg.CmdCount=Filter->Prg.CmdCount; int StaticDataSize = Filter.Program.StaticData.Count; if (StaticDataSize > 0 && StaticDataSize < RarVM.VM_GLOBALMEMSIZE) { // read statically defined data contained in DB commands // StackFilter->Prg.StaticData.Add(StaticDataSize); StackFilter.Program.StaticData = Filter.Program.StaticData; // memcpy(&StackFilter->Prg.StaticData[0],&Filter->Prg.StaticData[0],StaticDataSize); } if (StackFilter.Program.GlobalData.Count < RarVM.VM_FIXEDGLOBALSIZE) { // StackFilter->Prg.GlobalData.Reset(); // StackFilter->Prg.GlobalData.Add(VM_FIXEDGLOBALSIZE); StackFilter.Program.GlobalData.Clear(); StackFilter.Program.GlobalData.SetSize(RarVM.VM_FIXEDGLOBALSIZE); } // byte *GlobalData=&StackFilter->Prg.GlobalData[0]; List<byte> globalData = StackFilter.Program.GlobalData; for (int I = 0; I < 7; I++) { rarVM.SetLowEndianValue(globalData, I*4, StackFilter.Program.InitR[I]); } // VM.SetLowEndianValue((uint // *)&GlobalData[0x1c],StackFilter->BlockLength); rarVM.SetLowEndianValue(globalData, 0x1c, StackFilter.BlockLength); // VM.SetLowEndianValue((uint *)&GlobalData[0x20],0); rarVM.SetLowEndianValue(globalData, 0x20, 0); rarVM.SetLowEndianValue(globalData, 0x24, 0); rarVM.SetLowEndianValue(globalData, 0x28, 0); // VM.SetLowEndianValue((uint // *)&GlobalData[0x2c],StackFilter->ExecCount); rarVM.SetLowEndianValue(globalData, 0x2c, StackFilter.ExecCount); // memset(&GlobalData[0x30],0,16); for (int i = 0; i < 16; i++) { globalData[0x30 + i] = 0x0; } if ((firstByte & 8) != 0) // put data block passed as parameter if any { if (Inp.Overflow(3)) { return (false); } int DataSize = RarVM.ReadData(Inp); if (DataSize > RarVM.VM_GLOBALMEMSIZE - RarVM.VM_FIXEDGLOBALSIZE) { return (false); } int CurSize = StackFilter.Program.GlobalData.Count; if (CurSize < DataSize + RarVM.VM_FIXEDGLOBALSIZE) { // StackFilter->Prg.GlobalData.Add(DataSize+VM_FIXEDGLOBALSIZE-CurSize); StackFilter.Program.GlobalData.SetSize(DataSize + RarVM.VM_FIXEDGLOBALSIZE - CurSize); } int offset = RarVM.VM_FIXEDGLOBALSIZE; globalData = StackFilter.Program.GlobalData; for (int I = 0; I < DataSize; I++) { if (Inp.Overflow(3)) { return (false); } globalData[offset + I] = (byte) (Utility.URShift(Inp.GetBits(), 8)); Inp.AddBits(8); } } return (true); } private void ExecuteCode(VMPreparedProgram Prg) { if (Prg.GlobalData.Count > 0) { // Prg->InitR[6]=int64to32(WrittenFileSize); Prg.InitR[6] = (int) (writtenFileSize); // rarVM.SetLowEndianValue((uint // *)&Prg->GlobalData[0x24],int64to32(WrittenFileSize)); rarVM.SetLowEndianValue(Prg.GlobalData, 0x24, (int) writtenFileSize); // rarVM.SetLowEndianValue((uint // *)&Prg->GlobalData[0x28],int64to32(WrittenFileSize>>32)); rarVM.SetLowEndianValue(Prg.GlobalData, 0x28, (int) (Utility.URShift(writtenFileSize, 32))); rarVM.execute(Prg); } } public void cleanUp() { if (ppm != null) { SubAllocator allocator = ppm.SubAlloc; if (allocator != null) { allocator.stopSubAllocator(); } } } } }
// TVGL Version building on System.Numerics at https://github.com/dotnet/runtime/tree/main/src/libraries/System.Private.CoreLib/src/System/Numerics // That version is licensed to the .NET Foundation under the MIT license. // See their LICENSE file for more information: https://github.com/dotnet/runtime/blob/main/LICENSE.TXT // TVGL Version changes to double precision and adds a few functions. using System; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; using MIConvexHull; namespace TVGL.Numerics // COMMENTEDCHANGE namespace System.Numerics { /// <summary> /// A structure encapsulating three single precision doubleing point values and provides hardware accelerated methods. /// </summary> public readonly partial struct Vector4 : IEquatable<Vector4>, IFormattable, IVertex3D, IVertex { /// <summary> /// The X component of the vector. /// </summary> public double X { get; } /// <summary> /// The Y component of the vector. /// </summary> public double Y { get; } /// <summary> /// The Z component of the vector. /// </summary> public double Z { get; } /// <summary> /// The W (weight or scale) component of the vector. /// </summary> public double W { get; } public double[] Position => new[] { X / W, Y / W, Z / W }; #region Constructors /// <summary> /// Constructs a Vector4 from the given Vector2 and a third value. /// </summary> /// <param name="value">The Vector to extract X and Y components from.</param> /// <param name="z">The Z component.</param> public Vector4(Vector2 value, double z) : this(value.X, value.Y, z) { } public Vector4(Vector4 value) : this(value.X, value.Y, value.Z, value.W) { } /// <summary> /// Constructs a vector with the given individual elements. /// </summary> /// <param name="x">The X component.</param> /// <param name="y">The Y component.</param> /// <param name="z">The Z component.</param> public Vector4(double x, double y, double z) { X = x; Y = y; Z = z; W = 1; } /// <summary> /// Constructs a vector with the given individual elements. /// </summary> /// <param name="x">The X component.</param> /// <param name="y">The Y component.</param> /// <param name="z">The Z component.</param> public Vector4(double x, double y, double z, double w) { X = x; Y = y; Z = z; W = w; } public Vector4(ReadOnlySpan<double> values) { if (values.Length < 3) { throw new ArgumentOutOfRangeException(); } X = values[0]; Y = values[1]; Z = values[2]; if (values.Length > 3) W = values[3]; else W = 1; } #endregion Constructors /// <summary>Gets a vector whose 4 elements are equal to zero.</summary> /// <value>A vector whose four elements are equal to zero (that is, it returns the vector <c>(0,0,0,0)</c>.</value> public static Vector4 Zero { get => default; } /// <summary>Gets the vector (1,0,0,0).</summary> /// <value>The vector <c>(1,0,0,0)</c>.</value> public static Vector4 UnitX { get => new Vector4(1.0, 0.0, 0.0, 0.0); } /// <summary>Gets the vector (0,1,0,0).</summary> /// <value>The vector <c>(0,1,0,0)</c>.</value> public static Vector4 UnitY { get => new Vector4(0.0, 1.0, 0.0, 0.0); } /// <summary>Gets the vector (0,0,1,0).</summary> /// <value>The vector <c>(0,0,1,0)</c>.</value> public static Vector4 UnitZ { get => new Vector4(0.0, 0.0, 1.0, 0.0); } /// <summary>Gets the vector (0,0,0,1).</summary> /// <value>The vector <c>(0,0,0,1)</c>.</value> public static Vector4 UnitW { get => new Vector4(0.0, 0.0, 0.0, 1.0); } /// <summary> /// Returns the vector (NaN, NaN, NaN, NaN). /// </summary> public static Vector4 Null => new Vector4(double.NaN, double.NaN, double.NaN, double.NaN); public bool IsNull() { return double.IsNaN(X) || double.IsNaN(Y) || double.IsNaN(Z) || double.IsNaN(W); } public double this[int index] { get { if (index == 0) return X; if (index == 1) return Y; if (index == 2) return Z; if (index == 3) return W; throw new ArgumentOutOfRangeException(); } } /// <summary>Adds two vectors together.</summary> /// <param name="left">The first vector to add.</param> /// <param name="right">The second vector to add.</param> /// <returns>The summed vector.</returns> /// <remarks>The <see cref="System.Numerics.Vector4.op_Addition" /> method defines the addition operation for <see cref="System.Numerics.Vector4" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator +(Vector4 left, Vector4 right) { return new Vector4( left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W ); } /// <summary>Divides the first vector by the second.</summary> /// <param name="left">The first vector.</param> /// <param name="right">The second vector.</param> /// <returns>The vector that results from dividing <paramref name="left" /> by <paramref name="right" />.</returns> /// <remarks>The <see cref="System.Numerics.Vector4.op_Division" /> method defines the division operation for <see cref="System.Numerics.Vector4" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator /(Vector4 left, Vector4 right) { return new Vector4( left.X / right.X, left.Y / right.Y, left.Z / right.Z, left.W / right.W ); } /// <summary>Divides the specified vector by a specified scalar value.</summary> /// <param name="value1">The vector.</param> /// <param name="value2">The scalar value.</param> /// <returns>The result of the division.</returns> /// <remarks>The <see cref="System.Numerics.Vector4.op_Division" /> method defines the division operation for <see cref="System.Numerics.Vector4" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator /(Vector4 value1, double value2) { return new Vector4(value1.X / value2, value1.Y / value2, value1.Z / value2, value1.W / value2); } /// <summary>Returns a value that indicates whether each pair of elements in two specified vectors is equal.</summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns><see langword="true" /> if <paramref name="left" /> and <paramref name="right" /> are equal; otherwise, <see langword="false" />.</returns> /// <remarks>Two <see cref="System.Numerics.Vector4" /> objects are equal if each element in <paramref name="left" /> is equal to the corresponding element in <paramref name="right" />.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector4 left, Vector4 right) { return (left.X == right.X) && (left.Y == right.Y) && (left.Z == right.Z) && (left.W == right.W); } /// <summary>Returns a value that indicates whether two specified vectors are not equal.</summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns><see langword="true" /> if <paramref name="left" /> and <paramref name="right" /> are not equal; otherwise, <see langword="false" />.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector4 left, Vector4 right) { return !(left == right); } /// <summary>Returns a new vector whose values are the product of each pair of elements in two specified vectors.</summary> /// <param name="left">The first vector.</param> /// <param name="right">The second vector.</param> /// <returns>The element-wise product vector.</returns> /// <remarks>The <see cref="System.Numerics.Vector4.op_Multiply" /> method defines the multiplication operation for <see cref="System.Numerics.Vector4" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(Vector4 left, Vector4 right) { return new Vector4( left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W ); } /// <summary>Multiplies the specified vector by the specified scalar value.</summary> /// <param name="left">The vector.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> /// <remarks>The <see cref="System.Numerics.Vector4.op_Multiply" /> method defines the multiplication operation for <see cref="System.Numerics.Vector4" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(Vector4 left, double right) { return right * left; } /// <summary>Multiplies the scalar value by the specified vector.</summary> /// <param name="left">The vector.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> /// <remarks>The <see cref="System.Numerics.Vector4.op_Multiply" /> method defines the multiplication operation for <see cref="System.Numerics.Vector4" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(double left, Vector4 right) { return new Vector4(left * right.X, left * right.Y, left * right.Z, left * right.W); } /// <summary>Subtracts the second vector from the first.</summary> /// <param name="left">The first vector.</param> /// <param name="right">The second vector.</param> /// <returns>The vector that results from subtracting <paramref name="right" /> from <paramref name="left" />.</returns> /// <remarks>The <see cref="System.Numerics.Vector4.op_Subtraction" /> method defines the subtraction operation for <see cref="System.Numerics.Vector4" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator -(Vector4 left, Vector4 right) { return new Vector4( left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W ); } /// <summary>Negates the specified vector.</summary> /// <param name="value">The vector to negate.</param> /// <returns>The negated vector.</returns> /// <remarks>The <see cref="System.Numerics.Vector4.op_UnaryNegation" /> method defines the unary negation operation for <see cref="System.Numerics.Vector4" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator -(Vector4 value) { return Zero - value; } /// <summary>Returns a vector whose elements are the absolute values of each of the specified vector's elements.</summary> /// <param name="value">A vector.</param> /// <returns>The absolute value vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Abs(Vector4 value) { return new Vector4( Math.Abs(value.X), Math.Abs(value.Y), Math.Abs(value.Z), Math.Abs(value.W) ); } /// <summary>Adds two vectors together.</summary> /// <param name="left">The first vector to add.</param> /// <param name="right">The second vector to add.</param> /// <returns>The summed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Add(Vector4 left, Vector4 right) { return left + right; } /// <summary>Restricts a vector between a minimum and a maximum value.</summary> /// <param name="value1">The vector to restrict.</param> /// <param name="min">The minimum value.</param> /// <param name="max">The maximum value.</param> /// <returns>The restricted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max) { // We must follow HLSL behavior in the case user specified min value is bigger than max value. return Min(Max(value1, min), max); } /// <summary>Computes the Euclidean distance between the two given points.</summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Distance(Vector4 value1, Vector4 value2) { double distanceSquared = DistanceSquared(value1, value2); return Math.Sqrt(distanceSquared); } /// <summary>Returns the Euclidean distance squared between two specified points.</summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double DistanceSquared(Vector4 value1, Vector4 value2) { Vector4 difference = value1 - value2; return Dot(difference, difference); } /// <summary>Divides the first vector by the second.</summary> /// <param name="left">The first vector.</param> /// <param name="right">The second vector.</param> /// <returns>The vector resulting from the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Divide(Vector4 left, Vector4 right) { return left / right; } /// <summary>Divides the specified vector by a specified scalar value.</summary> /// <param name="left">The vector.</param> /// <param name="divisor">The scalar value.</param> /// <returns>The vector that results from the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Divide(Vector4 left, double divisor) { return left / divisor; } /// <summary>Returns the dot product of two vectors.</summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The dot product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Dot(Vector4 vector1, Vector4 vector2) { return (vector1.X * vector2.X) + (vector1.Y * vector2.Y) + (vector1.Z * vector2.Z) + (vector1.W * vector2.W); } /// <summary> /// Computes the cross product of two vectors. Note that this is really /// the 3D cross product, but the W term that scales each vector is simply /// the product of the two weights. This makes correct geometric sense in 3D /// space. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The cross product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Cross(in Vector4 vector1, Vector4 vector2) { return new Vector4( vector1.Y * vector2.Z - vector1.Z * vector2.Y, vector1.Z * vector2.X - vector1.X * vector2.Z, vector1.X * vector2.Y - vector1.Y * vector2.X, vector1.W * vector2.W); } /// <summary>Performs a linear interpolation between two vectors based on the given weighting.</summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="amount">A value between 0 and 1 that indicates the weight of <paramref name="value2" />.</param> /// <returns>The interpolated vector.</returns> /// <remarks><format type="text/markdown"><![CDATA[ /// The behavior of this method changed in .NET 5.0. For more information, see [Behavior change for Vector2.Lerp and Vector4.Lerp](/dotnet/core/compatibility/3.1-5.0#behavior-change-for-vector2lerp-and-vector4lerp). /// ]]></format></remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Lerp(Vector4 value1, Vector4 value2, double amount) { return (value1 * (1.0 - amount)) + (value2 * amount); } /// <summary>Returns a vector whose elements are the maximum of each of the pairs of elements in two specified vectors.</summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The maximized vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Max(Vector4 value1, Vector4 value2) { return new Vector4( (value1.X > value2.X) ? value1.X : value2.X, (value1.Y > value2.Y) ? value1.Y : value2.Y, (value1.Z > value2.Z) ? value1.Z : value2.Z, (value1.W > value2.W) ? value1.W : value2.W ); } /// <summary>Returns a vector whose elements are the minimum of each of the pairs of elements in two specified vectors.</summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The minimized vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Min(Vector4 value1, Vector4 value2) { return new Vector4( (value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y, (value1.Z < value2.Z) ? value1.Z : value2.Z, (value1.W < value2.W) ? value1.W : value2.W ); } /// <summary>Returns a new vector whose values are the product of each pair of elements in two specified vectors.</summary> /// <param name="left">The first vector.</param> /// <param name="right">The second vector.</param> /// <returns>The element-wise product vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(Vector4 left, Vector4 right) { return left * right; } /// <summary>Multiplies a vector by a specified scalar.</summary> /// <param name="left">The vector to multiply.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(Vector4 left, double right) { return left * right; } /// <summary>Multiplies a scalar value by a specified vector.</summary> /// <param name="left">The scaled value.</param> /// <param name="right">The vector.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(double left, Vector4 right) { return left * right; } /// <summary>Negates a specified vector.</summary> /// <param name="value">The vector to negate.</param> /// <returns>The negated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Negate(Vector4 value) { return -value; } /// <summary>Returns a vector with the same direction as the specified vector, but with a length of one.</summary> /// <param name="vector">The vector to normalize.</param> /// <returns>The normalized vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Normalize(Vector4 vector) { return vector / vector.Length(); } /// <summary>Returns a vector whose elements are the square root of each of a specified vector's elements.</summary> /// <param name="value">A vector.</param> /// <returns>The square root vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 SquareRoot(Vector4 value) { return new Vector4( Math.Sqrt(value.X), Math.Sqrt(value.Y), Math.Sqrt(value.Z), Math.Sqrt(value.W) ); } /// <summary>Subtracts the second vector from the first.</summary> /// <param name="left">The first vector.</param> /// <param name="right">The second vector.</param> /// <returns>The difference vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Subtract(Vector4 left, Vector4 right) { return left - right; } /// <summary>Transforms a two-dimensional vector by a specified 4x4 matrix.</summary> /// <param name="position">The vector to transform.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector2 position, Matrix4x4 matrix) { return new Vector4( (position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + matrix.M43, (position.X * matrix.M14) + (position.Y * matrix.M24) + matrix.M44 ); } /// <summary>Transforms a two-dimensional vector by the specified Quaternion rotation value.</summary> /// <param name="value">The vector to rotate.</param> /// <param name="rotation">The rotation to apply.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector2 value, Quaternion rotation) { double x2 = rotation.X + rotation.X; double y2 = rotation.Y + rotation.Y; double z2 = rotation.Z + rotation.Z; double wx2 = rotation.W * x2; double wy2 = rotation.W * y2; double wz2 = rotation.W * z2; double xx2 = rotation.X * x2; double xy2 = rotation.X * y2; double xz2 = rotation.X * z2; double yy2 = rotation.Y * y2; double yz2 = rotation.Y * z2; double zz2 = rotation.Z * z2; return new Vector4( value.X * (1.0 - yy2 - zz2) + value.Y * (xy2 - wz2), value.X * (xy2 + wz2) + value.Y * (1.0 - xx2 - zz2), value.X * (xz2 - wy2) + value.Y * (yz2 + wx2), 1.0 ); } /// <summary>Transforms a three-dimensional vector by a specified 4x4 matrix.</summary> /// <param name="position">The vector to transform.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector3 position, Matrix4x4 matrix) { return new Vector4( (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43, (position.X * matrix.M14) + (position.Y * matrix.M24) + (position.Z * matrix.M34) + matrix.M44 ); } /// <summary>Transforms a three-dimensional vector by the specified Quaternion rotation value.</summary> /// <param name="value">The vector to rotate.</param> /// <param name="rotation">The rotation to apply.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector3 value, Quaternion rotation) { double x2 = rotation.X + rotation.X; double y2 = rotation.Y + rotation.Y; double z2 = rotation.Z + rotation.Z; double wx2 = rotation.W * x2; double wy2 = rotation.W * y2; double wz2 = rotation.W * z2; double xx2 = rotation.X * x2; double xy2 = rotation.X * y2; double xz2 = rotation.X * z2; double yy2 = rotation.Y * y2; double yz2 = rotation.Y * z2; double zz2 = rotation.Z * z2; return new Vector4( value.X * (1.0 - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2), value.X * (xy2 + wz2) + value.Y * (1.0 - xx2 - zz2) + value.Z * (yz2 - wx2), value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0 - xx2 - yy2), 1.0 ); } /// <summary>Transforms a four-dimensional vector by a specified 4x4 matrix.</summary> /// <param name="vector">The vector to transform.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector4 vector, Matrix4x4 matrix) { return new Vector4( (vector.X * matrix.M11) + (vector.Y * matrix.M21) + (vector.Z * matrix.M31) + (vector.W * matrix.M41), (vector.X * matrix.M12) + (vector.Y * matrix.M22) + (vector.Z * matrix.M32) + (vector.W * matrix.M42), (vector.X * matrix.M13) + (vector.Y * matrix.M23) + (vector.Z * matrix.M33) + (vector.W * matrix.M43), (vector.X * matrix.M14) + (vector.Y * matrix.M24) + (vector.Z * matrix.M34) + (vector.W * matrix.M44) ); } /// <summary>Transforms a four-dimensional vector by the specified Quaternion rotation value.</summary> /// <param name="value">The vector to rotate.</param> /// <param name="rotation">The rotation to apply.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector4 value, Quaternion rotation) { double x2 = rotation.X + rotation.X; double y2 = rotation.Y + rotation.Y; double z2 = rotation.Z + rotation.Z; double wx2 = rotation.W * x2; double wy2 = rotation.W * y2; double wz2 = rotation.W * z2; double xx2 = rotation.X * x2; double xy2 = rotation.X * y2; double xz2 = rotation.X * z2; double yy2 = rotation.Y * y2; double yz2 = rotation.Y * z2; double zz2 = rotation.Z * z2; return new Vector4( value.X * (1.0 - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2), value.X * (xy2 + wz2) + value.Y * (1.0 - xx2 - zz2) + value.Z * (yz2 - wx2), value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0 - xx2 - yy2), value.W); } /// <summary>Copies the elements of the vector to a specified array.</summary> /// <param name="array">The destination array.</param> /// <remarks><paramref name="array" /> must have at least four elements. The method copies the vector's elements starting at index 0.</remarks> /// <exception cref="System.NullReferenceException"><paramref name="array" /> is <see langword="null" />.</exception> /// <exception cref="System.ArgumentException">The number of elements in the current instance is greater than in the array.</exception> /// <exception cref="System.RankException"><paramref name="array" /> is multidimensional.</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly void CopyTo(double[] array) { CopyTo(array, 0); } /// <summary>Copies the elements of the vector to a specified array starting at a specified index position.</summary> /// <param name="array">The destination array.</param> /// <param name="index">The index at which to copy the first element of the vector.</param> /// <remarks><paramref name="array" /> must have a sufficient number of elements to accommodate the four vector elements. In other words, elements <paramref name="index" /> through <paramref name="index" /> + 3 must already exist in <paramref name="array" />.</remarks> /// <exception cref="System.NullReferenceException"><paramref name="array" /> is <see langword="null" />.</exception> /// <exception cref="System.ArgumentException">The number of elements in the current instance is greater than in the array.</exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="index" /> is less than zero. /// -or- /// <paramref name="index" /> is greater than or equal to the array length.</exception> /// <exception cref="System.RankException"><paramref name="array" /> is multidimensional.</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly void CopyTo(double[] array, int index) { if (array is null) throw new NullReferenceException(); if ((index < 0) || (index >= array.Length)) throw new ArgumentOutOfRangeException(); if ((array.Length - index) < 4) throw new ArgumentException("Destination is too short to accomodate the four cells of a Vector4"); array[index] = X; array[index + 1] = Y; array[index + 2] = Z; array[index + 3] = W; } /// <summary>Returns a value that indicates whether this instance and another vector are equal.</summary> /// <param name="other">The other vector.</param> /// <returns><see langword="true" /> if the two vectors are equal; otherwise, <see langword="false" />.</returns> /// <remarks>Two vectors are equal if their <see cref="System.Numerics.Vector4.X" />, <see cref="System.Numerics.Vector4.Y" />, <see cref="System.Numerics.Vector4.Z" />, and <see cref="System.Numerics.Vector4.W" /> elements are equal.</remarks> public readonly bool Equals(Vector4 other) { return this == other; } /// <summary>Returns a value that indicates whether this instance and a specified object are equal.</summary> /// <param name="obj">The object to compare with the current instance.</param> /// <returns><see langword="true" /> if the current instance and <paramref name="obj" /> are equal; otherwise, <see langword="false" />. If <paramref name="obj" /> is <see langword="null" />, the method returns <see langword="false" />.</returns> /// <remarks>The current instance and <paramref name="obj" /> are equal if <paramref name="obj" /> is a <see cref="System.Numerics.Vector4" /> object and their corresponding elements are equal.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals(object obj) { return (obj is Vector4 other) && Equals(other); } /// <summary>Returns the hash code for this instance.</summary> /// <returns>The hash code.</returns> public override readonly int GetHashCode() { return HashCode.Combine(X, Y, Z, W); } /// <summary>Returns the length of this vector object.</summary> /// <returns>The vector's length.</returns> /// <altmember cref="System.Numerics.Vector4.LengthSquared"/> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly double Length() { double lengthSquared = LengthSquared(); return Math.Sqrt(lengthSquared); } /// <summary>Returns the length of the vector squared.</summary> /// <returns>The vector's length squared.</returns> /// <remarks>This operation offers better performance than a call to the <see cref="System.Numerics.Vector4.Length" /> method.</remarks> /// <altmember cref="System.Numerics.Vector4.Length"/> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly double LengthSquared() { return Dot(this, this); } /// <summary>Returns the string representation of the current instance using default formatting.</summary> /// <returns>The string representation of the current instance.</returns> /// <remarks>This method returns a string in which each element of the vector is formatted using the "G" (general) format string and the formatting conventions of the current thread culture. The "&lt;" and "&gt;" characters are used to begin and end the string, and the current culture's <see cref="System.Globalization.NumberFormatInfo.NumberGroupSeparator" /> property followed by a space is used to separate each element.</remarks> public override readonly string ToString() { return ToString("G", CultureInfo.CurrentCulture); } /// <summary>Returns the string representation of the current instance using the specified format string to format individual elements.</summary> /// <param name="format">A standard or custom numeric format string that defines the format of individual elements.</param> /// <returns>The string representation of the current instance.</returns> /// <remarks>This method returns a string in which each element of the vector is formatted using <paramref name="format" /> and the current culture's formatting conventions. The "&lt;" and "&gt;" characters are used to begin and end the string, and the current culture's <see cref="System.Globalization.NumberFormatInfo.NumberGroupSeparator" /> property followed by a space is used to separate each element.</remarks> /// <related type="Article" href="/dotnet/standard/base-types/standard-numeric-format-strings">Standard Numeric Format Strings</related> /// <related type="Article" href="/dotnet/standard/base-types/custom-numeric-format-strings">Custom Numeric Format Strings</related> public readonly string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary>Returns the string representation of the current instance using the specified format string to format individual elements and the specified format provider to define culture-specific formatting.</summary> /// <param name="format">A standard or custom numeric format string that defines the format of individual elements.</param> /// <param name="formatProvider">A format provider that supplies culture-specific formatting information.</param> /// <returns>The string representation of the current instance.</returns> /// <remarks>This method returns a string in which each element of the vector is formatted using <paramref name="format" /> and <paramref name="formatProvider" />. The "&lt;" and "&gt;" characters are used to begin and end the string, and the format provider's <see cref="System.Globalization.NumberFormatInfo.NumberGroupSeparator" /> property followed by a space is used to separate each element.</remarks> /// <related type="Article" href="/dotnet/standard/base-types/standard-numeric-format-strings">Standard Numeric Format Strings</related> /// <related type="Article" href="/dotnet/standard/base-types/custom-numeric-format-strings">Custom Numeric Format Strings</related> public readonly string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; sb.Append('<'); sb.Append(X.ToString(format, formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(Y.ToString(format, formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(Z.ToString(format, formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(W.ToString(format, formatProvider)); sb.Append('>'); return sb.ToString(); } #region obvious matrix-vector multiplications /// <summary> /// Pre-multiplies the vector to the matrix. Here, the vector is treated /// as a single row, so the result is also a single-row vector. Each cell /// is a dot-product between the vector and the column of the matrix. /// This is the same as transforming by the matrix. /// </summary> /// <param name="position">The vector.</param> /// <param name="matrix">The matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(Vector4 rowVector, Matrix4x4 matrix) { return Multiply(rowVector, matrix); } /// <summary> /// Pre-multiplies the vector to the matrix. Here, the vector is treated /// as a single row, so the result is also a single-row vector. Each cell /// is a dot-product between the vector and the column of the matrix. /// This is the same as transforming by the matrix. /// </summary> /// <param name="rowVector">The vector.</param> /// <param name="matrix">The matrix.</param> /// <returns>The transformed vector.</returns> public static Vector4 Multiply(Vector4 rowVector, Matrix4x4 matrix) { return new Vector4( rowVector.X * matrix.M11 + rowVector.Y * matrix.M21 + rowVector.Z * matrix.M31 + rowVector.W * matrix.M41, rowVector.X * matrix.M12 + rowVector.Y * matrix.M22 + rowVector.Z * matrix.M32 + rowVector.W * matrix.M42, rowVector.X * matrix.M13 + rowVector.Y * matrix.M23 + rowVector.Z * matrix.M33 + rowVector.W * matrix.M43, rowVector.X * matrix.M14 + rowVector.Y * matrix.M24 + rowVector.Z * matrix.M34 + rowVector.W * matrix.M44); } /// <summary> /// Post-multiplies the vector to the matrix. Here, the vector is treated /// as a single column, so the result is also a single-column vector. Each cell /// is a dot-product between the vector and the row of the matrix. /// </summary> /// <param name="matrix">The Matrix value.</param> /// <param name="colVector">The vector.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(Matrix4x4 matrix, Vector4 colVector) { return Multiply(matrix, colVector); } /// <summary> /// Post-multiplies the vector to the matrix. Here, the vector is treated /// as a single column, so the result is also a single-column vector. Each cell /// is a dot-product between the vector and the row of the matrix. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The product matrix.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(Matrix4x4 matrix, Vector4 colVector) { return new Vector4( colVector.X * matrix.M11 + colVector.Y * matrix.M12 + colVector.Z * matrix.M13 + colVector.W * matrix.M14, colVector.X * matrix.M21 + colVector.Y * matrix.M22 + colVector.Z * matrix.M23 + colVector.W * matrix.M24, colVector.X * matrix.M31 + colVector.Y * matrix.M32 + colVector.Z * matrix.M33 + colVector.W * matrix.M34, colVector.X * matrix.M41 + colVector.Y * matrix.M42 + colVector.Z * matrix.M43 + colVector.W * matrix.M44); } /// <summary> /// Transforms a vector by the given matrix without the translation component. /// This is often used for transforming normals, however note that proper transformations /// of normal vectors requires that the input matrix be the transpose of the inverse of that matrix. /// </summary> /// <param name="rowVector">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 TransformNoTranslate(Vector4 rowVector, Matrix4x4 matrix) { return new Vector4( rowVector.X * matrix.M11 + rowVector.Y * matrix.M21 + rowVector.Z * matrix.M31 , rowVector.X * matrix.M12 + rowVector.Y * matrix.M22 + rowVector.Z * matrix.M32 , rowVector.X * matrix.M13 + rowVector.Y * matrix.M23 + rowVector.Z * matrix.M33, rowVector.X * matrix.M14 + rowVector.Y * matrix.M24 + rowVector.Z * matrix.M34 + rowVector.W * matrix.M44); } #endregion #region Solve Ax=b /// <summary> /// Solves for the value x in Ax=b. This is also represented as the /// backslash operation /// </summary> /// <param name="matrix">The matrix.</param> /// <param name="b">The b.</param> /// <returns>Vector3.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Solve(Matrix4x4 matrix, Vector4 b) { if (!Matrix4x4.Invert(matrix, out var invert)) return Vector4.Null; // Yes, this is a pretty silly method. Ideally, one would take apart // in an LU Decomposition way and it may be quicker than this. It not likely // true for 3x3 (or 2x2), but it just might be for 4x4 return invert * b; } #endregion } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2012LightDockPaneStrip : DockPaneStripBase { private class TabVS2012Light : Tab { public TabVS2012Light(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected internal override Tab CreateTab(IDockContent content) { return new TabVS2012Light(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 0;//16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 0; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 3; private const int _DocumentButtonGapBottom = 3; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 0;//3; private const int _DocumentTabGapLeft = 0;//3; private const int _DocumentTabGapRight = 0;//3; private const int _DocumentIconGapBottom = 2;//2; private const int _DocumentIconGapLeft = 0; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 6; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; private Rectangle _activeClose; private int _selectMenuMargin = 5; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height + DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } public int SelectMenuMargin { get { return _selectMenuMargin; } set { _selectMenuMargin = value; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2005AutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.ControlDark; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2012LightDockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected internal override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; DockPanelGradient gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; } else { gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient; } Color startColor = gradient.StartColor; Color endColor = gradient.EndColor; LinearGradientMode gradientMode = gradient.LinearGradientMode; DrawingRoutines.SafelyDrawLinearGradient(rect, startColor, endColor, gradientMode, e.Graphics); base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } protected internal override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2012Light tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; var tab = Tabs[index] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X; //+ rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; var tab = Tabs[m_startDisplayingTab] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X;// +rectTabStrip.Height / 2; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected internal override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); var tab = Tabs[index] as TabVS2012Light; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private const int TAB_CLOSE_BUTTON_WIDTH = 30; private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); int width; if (DockPane.DockPanel.ShowDocumentIcon) width = sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else width = sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; width += TAB_CLOSE_BUTTON_WIDTH; return width; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; rectTabStrip.Height += 1; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2012Light tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2012Light; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2012Light, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else { Color tabUnderLineColor; if (tabActive != null && DockPane.IsActiveDocumentPane) tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; else tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; g.DrawLine(new Pen(tabUnderLineColor, 4), rectTabStrip.Left, rectTabStrip.Bottom, rectTabStrip.Right, rectTabStrip.Bottom); } g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) { rectTab.Intersect(rectTabOnly); DrawTab(g, tabActive, rectTab); } } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2012Light, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2012Light tab = (TabVS2012Light)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; var tab = (TabVS2012Light)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2012Light tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); rect.Width--; if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); GraphicsPath.AddRectangle(rect); return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2012Light tab, Rectangle rect) { rect.Y += 1; Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); if (DockPane.ActiveContent == tab.Content && ((DockContent)tab.Content).IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillRectangle(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), rect); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color textColor; if (tab.Content == DockPane.MouseOverTab) textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; else textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } g.DrawLine(PenToolWindowTabBorder, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Height); if (rectTab.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2012Light tab, Rectangle rect) { if (tab.TabWidth == 0) return; var rectCloseButton = GetCloseButtonRect(rect); Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight - rectCloseButton.Width; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); Color activeColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color lostFocusColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; Color inactiveColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color mouseHoverColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor; Color activeText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; Color inactiveText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; Color lostFocusText = SystemColors.GrayText; if (DockPane.ActiveContent == tab.Content) { if (DockPane.IsActiveDocumentPane) { g.FillRectangle(new SolidBrush(activeColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.ActiveTab_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(lostFocusColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, lostFocusText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.LostFocusTabHover_Close : Resources.LostFocusTab_Close, rectCloseButton); } } else { if (tab.Content == DockPane.MouseOverTab) { g.FillRectangle(new SolidBrush(mouseHoverColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.InactiveTabHover_Close : Resources.ActiveTabHover_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(inactiveColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, inactiveText, DocumentTextFormat); } } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document) return; var indexHit = HitTest(); if (indexHit > -1) TabCloseButtonHit(indexHit); } private void TabCloseButtonHit(int index) { var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); if (closeButtonRect.IntersectsWith(mouseRect)) DockPane.CloseActiveContent(); } private Rectangle GetCloseButtonRect(Rectangle rectTab) { if (Appearance != Docking.DockPane.AppearanceStyle.Document) { return Rectangle.Empty; } const int gap = 3; const int imageSize = 15; return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap - 1, rectTab.Y + gap, imageSize, imageSize); } private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); foreach (TabVS2012Light tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { SelectMenu.Show(menu.Location); } else { var newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. newPoint.Y = button.Y - ButtonWindowList.Height; SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); } else { SelectMenu.Show(newPoint); } } } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = false; m_closeButtonVisible = false; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } protected internal override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } private Rectangle ActiveClose { get { return _activeClose; } } private bool SetActiveClose(Rectangle rectangle) { if (_activeClose == rectangle) return false; _activeClose = rectangle; return true; } private bool SetMouseOverTab(IDockContent content) { if (DockPane.MouseOverTab == content) return false; DockPane.MouseOverTab = content; return true; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); bool tabUpdate = false; bool buttonUpdate = false; if (index != -1) { var tab = Tabs[index] as TabVS2012Light; if (Appearance == DockPane.AppearanceStyle.ToolWindow || Appearance == DockPane.AppearanceStyle.Document) { tabUpdate = SetMouseOverTab(tab.Content == DockPane.ActiveContent ? null : tab.Content); } if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) ? closeButtonRect : Rectangle.Empty); } else { tabUpdate = SetMouseOverTab(null); buttonUpdate = SetActiveClose(Rectangle.Empty); } if (tabUpdate || buttonUpdate) Invalidate(); if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnMouseLeave(EventArgs e) { var tabUpdate = SetMouseOverTab(null); var buttonUpdate = SetActiveClose(Rectangle.Empty); if (tabUpdate || buttonUpdate) Invalidate(); base.OnMouseLeave(e); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
//////////////////////////////////////////////////////////////////////////////// // // @module IOS Native Plugin for Unity3D // @author Osipov Stanislav (Stan's Assets) // @support stans.assets@gmail.com // //////////////////////////////////////////////////////////////////////////////// using UnityEngine; using System.Collections; using System.Collections.Generic; #if (UNITY_IPHONE && !UNITY_EDITOR) || SA_DEBUG_MODE using System.Runtime.InteropServices; #endif public class iAdBanner : EventDispatcherBase { #if (UNITY_IPHONE && !UNITY_EDITOR) || SA_DEBUG_MODE [DllImport ("__Internal")] private static extern void _IADCreateBannerAd(int gravity, int id); [DllImport ("__Internal")] private static extern void _IADCreateBannerAdPos(int x, int y, int id); [DllImport ("__Internal")] private static extern void _IADShowAd(int id); [DllImport ("__Internal")] private static extern void _IADHideAd(int id); #endif private bool _IsLoaded = false; private bool _IsOnScreen = false; private bool firstLoad = true; private bool _ShowOnLoad = true; private int _id; private TextAnchor _anchor; public iAdBanner(TextAnchor anchor, int id) { _id = id; _anchor = anchor; #if (UNITY_IPHONE && !UNITY_EDITOR) || SA_DEBUG_MODE _IADCreateBannerAd(gravity, _id); #endif } public iAdBanner(int x, int y, int id) { _id = id; #if (UNITY_IPHONE && !UNITY_EDITOR) || SA_DEBUG_MODE _IADCreateBannerAdPos(x, y, _id); #endif } public void Hide() { if(!_IsOnScreen) { return; } _IsOnScreen = false; #if (UNITY_IPHONE && !UNITY_EDITOR) || SA_DEBUG_MODE _IADHideAd(_id); #endif } public void Show() { if(_IsOnScreen) { return; } _IsOnScreen = true; #if (UNITY_IPHONE && !UNITY_EDITOR) || SA_DEBUG_MODE _IADShowAd(_id); #endif } //-------------------------------------- // GET/SET //-------------------------------------- public int id { get { return _id; } } public bool IsLoaded { get { return _IsLoaded; } } public bool IsOnScreen { get { return _IsOnScreen; } } public bool ShowOnLoad { get { return _ShowOnLoad; } set { _ShowOnLoad = value; } } public TextAnchor anchor { get { return _anchor; } } public int gravity { get { switch(_anchor) { case TextAnchor.LowerCenter: return IOSGravity.BOTTOM | IOSGravity.CENTER; case TextAnchor.LowerLeft: return IOSGravity.BOTTOM | IOSGravity.LEFT; case TextAnchor.LowerRight: return IOSGravity.BOTTOM | IOSGravity.RIGHT; case TextAnchor.MiddleCenter: return IOSGravity.CENTER; case TextAnchor.MiddleLeft: return IOSGravity.CENTER | IOSGravity.LEFT; case TextAnchor.MiddleRight: return IOSGravity.CENTER | IOSGravity.RIGHT; case TextAnchor.UpperCenter: return IOSGravity.TOP | IOSGravity.CENTER; case TextAnchor.UpperLeft: return IOSGravity.TOP | IOSGravity.LEFT; case TextAnchor.UpperRight: return IOSGravity.TOP | IOSGravity.RIGHT; } return IOSGravity.TOP; } } public void didFailToReceiveAdWithError() { dispatch(iAdEvent.FAIL_TO_RECEIVE_AD); } public void bannerViewDidLoadAd() { _IsLoaded = true; if(ShowOnLoad && firstLoad) { Show(); firstLoad = false; } dispatch(iAdEvent.AD_LOADED); } public void bannerViewWillLoadAd(){ dispatch(iAdEvent.AD_VIEW_LOADED); } public void bannerViewActionDidFinish(){ dispatch(iAdEvent.AD_VIEW_ACTION_FINISHED); } public void bannerViewActionShouldBegin() { dispatch(iAdEvent.AD_VIEW_ACTION_BEGIN); } }
#region Copyright (c) 2007 Atif Aziz. All rights reserved. // // Copyright (c) 2007 Atif Aziz. All rights reserved. // http://www.raboof.com // // Portion Copyright (c) 2001 Douglas Crockford // http://www.crockford.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #endregion namespace MSBuild.Community.Tasks.JavaScript { #region Imports using System; using System.Diagnostics; using System.IO; using System.Runtime.Serialization; #endregion #region About JavaScriptCompressor (JSMin) /* JavaScriptCompressor is a C# port of jsmin.c that was originally written by Douglas Crockford. jsmin.c 04-Dec-2003 (c) 2001 Douglas Crockford http://www.crockford.com C# port written by Atif Aziz 12-Apr-2005 http://www.raboof.com The following documentation is a minimal adaption from the original found at: http://www.crockford.com/javascript/jsmin.html The documentation therefore still refers to JSMin, but equally applies to this C# port since the code implementation has not been changed or enhanced in any way. Some passages have been omitted since they don't apply. For example, the original documentation has a comment about character set. This does not apply to this port since JavaScriptCompressor works with TextReader and TextWriter from the Base Class Library (BCL). The character set responsibility is therefore pushed back to the user of this class. What JSMin Does --------------- JSMin is a filter that omits or modifies some characters. This does not change the behavior of the program that it is minifying. The result may be harder to debug. It will definitely be harder to read. JSMin first replaces carriage returns ('\r') with linefeeds ('\n'). It replaces all other control characters (including tab) with spaces. It replaces comments in the // form with linefeeds. It replaces comments with spaces. All runs of spaces are replaced with a single space. All runs of linefeeds are replaced with a single linefeed. It omits spaces except when a space is preceded or followed by a non-ASCII character or by an ASCII letter or digit, or by one of these characters: \ $ _ It is more conservative in omitting linefeeds, because linefeeds are sometimes treated as semicolons. A linefeed is not omitted if it precedes a non-ASCII character or an ASCII letter or digit or one of these characters: \ $ _ { [ ( + - and if it follows a non-ASCII character or an ASCII letter or digit or one of these characters: \ $ _ } ] ) + - " ' No other characters are omitted or modified. JSMin knows to not modify quoted strings and regular expression literals. JSMin does not obfuscate, but it does uglify. Before: // is.js // (c) 2001 Douglas Crockford // 2001 June 3 // is // The -is- object is used to identify the browser. Every browser edition // identifies itself, but there is no standard way of doing it, and some of // the identification is deceptive. This is because the authors of web // browsers are liars. For example, Microsoft's IE browsers claim to be // Mozilla 4. Netscape 6 claims to be version 5. var is = { ie: navigator.appName == 'Microsoft Internet Explorer', java: navigator.javaEnabled(), ns: navigator.appName == 'Netscape', ua: navigator.userAgent.toLowerCase(), version: parseFloat(navigator.appVersion.substr(21)) || parseFloat(navigator.appVersion), win: navigator.platform == 'Win32' } is.mac = is.ua.indexOf('mac') >= 0; if (is.ua.indexOf('opera') >= 0) { is.ie = is.ns = false; is.opera = true; } if (is.ua.indexOf('gecko') >= 0) { is.ie = is.ns = false; is.gecko = true; } After: var is={ie:navigator.appName=='MicrosoftInternetExplorer',java:navigator.javaEnabled(),ns:navigator.appName=='Netscape',ua:navigator.userAgent.toLowerCase(),version:parseFloat(navigator.appVersion.substr(21))||parseFloat(navigator.appVersion),win:navigator.platform=='Win32'} is.mac=is.ua.indexOf('mac')>=0;if(is.ua.indexOf('opera')>=0){is.ie=is.ns=false;is.opera=true;} if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;} Caution ------- Do not put raw control characters inside a quoted string. That is an extremely bad practice. Use \xhh notation instead. JSMin will replace control characters with spaces or linefeeds. Use parens with confusing sequences of + or -. For example, minification changes a + ++b into a+++b which is interpreted as a++ + b which is wrong. You can avoid this by using parens: a + (++b) JSLint (http://www.jslint.com/) checks for all of these problems. It is suggested that JSLint be used before using JSMin. Errors ------ JSMin can detect and produce three error messages: - Unterminated comment. - Unterminated string constant. - Unterminated regular expression. It ignores all other errors that may be present in your source program. */ #endregion internal sealed class JavaScriptCompressor { // // Public functions // public static string Compress(string source) { StringWriter writer = new StringWriter(); Compress(new StringReader(source), writer); return writer.ToString(); } public static void Compress(TextReader reader, TextWriter writer) { if (reader == null) throw new ArgumentNullException("reader"); if (writer == null) throw new ArgumentNullException("writer"); JavaScriptCompressor compressor = new JavaScriptCompressor(reader, writer); compressor.Compress(); } // // Private implementation // private int aa; private int bb; private int lookahead = eof; private TextReader reader = Console.In; private TextWriter writer = Console.Out; private const int eof = -1; private JavaScriptCompressor(TextReader reader, TextWriter writer) { Debug.Assert(reader != null); Debug.Assert(writer != null); this.reader = reader; this.writer = writer; } /* Compress -- Copy the input to the output, deleting the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. */ private void Compress() { aa = '\n'; Action(3); while (aa != eof) { switch (aa) { case ' ': if (IsAlphanum(bb)) { Action(1); } else { Action(2); } break; case '\n': switch (bb) { case '{': case '[': case '(': case '+': case '-': Action(1); break; case ' ': Action(3); break; default: if (IsAlphanum(bb)) { Action(1); } else { Action(2); } break; } break; default: switch (bb) { case ' ': if (IsAlphanum(aa)) { Action(1); break; } Action(3); break; case '\n': switch (aa) { case '}': case ']': case ')': case '+': case '-': case '"': case '\'': Action(1); break; default: if (IsAlphanum(aa)) { Action(1); } else { Action(3); } break; } break; default: Action(1); break; } break; } } } /* Get -- return the next character from stdin. Watch out for lookahead. If the character is a control character, translate it to a space or linefeed. */ private int Get() { int ch = lookahead; lookahead = eof; if (ch == eof) { ch = reader.Read(); } if (ch >= ' ' || ch == '\n' || ch == eof) { return ch; } if (ch == '\r') { return '\n'; } return ' '; } /* Peek -- get the next character without getting it. */ private int Peek() { lookahead = Get(); return lookahead; } /* Next -- get the next character, excluding comments. Peek() is used to see if a '/' is followed by a '/' or '*'. */ private int Next() { int ch = Get(); if (ch == '/') { switch (Peek()) { case '/': for (;; ) { ch = Get(); if (ch <= '\n') { return ch; } } case '*': Get(); for (;; ) { switch (Get()) { case '*': if (Peek() == '/') { Get(); return ' '; } break; case eof: throw new Exception("Unterminated comment."); } } default: return ch; } } return ch; } /* Action -- do something! What you do is determined by the argument: 1 Output A. Copy A to B. Get the next B. 2 Copy B to A. Get the next B. (Delete A). 3 Get the next B. (Delete B). Action treats a string as a single character. Wow! Action recognizes a regular expression if it is preceded by ( or , or =. */ private void Action(int d) { switch (d) { case 1: Write(aa); goto case 2; case 2: aa = bb; if (aa == '\'' || aa == '"') { for (;; ) { Write(aa); aa = Get(); if (aa == bb) { break; } if (aa <= '\n') { string message = string.Format("Unterminated string literal: '{0}'.", aa); throw new Exception(message); } if (aa == '\\') { Write(aa); aa = Get(); } } } goto case 3; case 3: bb = Next(); if (bb == '/' && (aa == '(' || aa == ',' || aa == '=')) { Write(aa); Write(bb); for (;; ) { aa = Get(); if (aa == '/') { break; } else if (aa == '\\') { Write(aa); aa = Get(); } else if (aa <= '\n') { throw new Exception("Unterminated Regular Expression literal."); } Write(aa); } bb = Next(); } break; } } private void Write(int ch) { writer.Write((char) ch); } /* IsAlphanum -- return true if the character is a letter, digit, underscore, dollar sign, or non-ASCII character. */ private static bool IsAlphanum(int ch) { return ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || ch == '_' || ch == '$' || ch == '\\' || ch > 126); } [ Serializable ] public class Exception : System.Exception { public Exception() {} public Exception(string message) : base(message) {} public Exception(string message, Exception innerException) : base(message, innerException) {} protected Exception(SerializationInfo info, StreamingContext context) : base(info, context) {} } } }
using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Windows; using InRule.Repository; namespace InRuleLabs.AuthoringExtensions.GenerateSDKCode.Features.Rendering { public class CodeTypeDeclarationEx { public HashSet<string> UsedNames = new HashSet<string>(); public CodeTypeDeclarationEx ParentClass { get; set; } public CodeTypeDeclaration InnerDeclaration { get; set; } public List<CodeTypeDeclarationEx> ChildClasses = new List<CodeTypeDeclarationEx>(); public bool IsDefFactory { get; set; } private CodeTypeDeclarationEx(CodeTypeDeclarationEx parentClass) { ParentClass = parentClass; } public CodeTypeDeclarationEx AddChildClass(object sourceDef, string name) { UsedNames.Add(name); var ret = new CodeTypeDeclarationEx(this); var innerTypeDeclaration = ret.SetInnerTypeDeclaration(this, sourceDef, name); var firstFactoryMember = this.ChildClasses.FirstOrDefault(c=>c.IsDefFactory); if (firstFactoryMember != null) { // Push the factory members to the end of the file var index = this.InnerDeclaration.Members.IndexOf(firstFactoryMember.InnerDeclaration); this.InnerDeclaration.Members.Insert(index, innerTypeDeclaration); } else { this.InnerDeclaration.Members.Add(innerTypeDeclaration); } ChildClasses.Add(ret); return ret; } private CodeTypeDeclaration SetInnerTypeDeclaration(CodeTypeDeclarationEx parent, object sourceDef, string name) { string typeName = name; if (sourceDef != null) { var defaultTypeName = sourceDef.GetType().Name + "_" + name; if (parent != null) { // This adds it to the parent used names list typeName = parent.GetSafeName(defaultTypeName, true); } } // This is the local used names list UsedNames.Add(typeName); var codeTypeDeclaration = CreateCodeTypeDeclarationInternal(typeName); codeTypeDeclaration.IsClass = true; codeTypeDeclaration.TypeAttributes = TypeAttributes.Public; this.InnerDeclaration = codeTypeDeclaration; return codeTypeDeclaration; } private static CodeTypeDeclaration CreateCodeTypeDeclarationInternal(string name) { return new CodeTypeDeclaration(name); } private string GetSafeName(string defaultName, bool addToUsedNamesList) { defaultName = defaultName.Replace("@", ""); defaultName = defaultName.Replace(".", "_"); defaultName = defaultName.Replace("+", "_"); var typeName = defaultName; if (this.HasTypeName(defaultName)) { int count = 0; typeName = defaultName + "_" + count; while (HasTypeName(typeName)) { count ++; typeName = defaultName + "_" + count; } } if (addToUsedNamesList) { UsedNames.Add(typeName); } return typeName; } private bool HasTypeName(string name) { if (UsedNames.Contains(name)) return true; //if (this.GetMemberTypes().Any(t => t.Name == typeName)) //{ // return true; //} //if (this.GetMemberMethods().Any(t => t.Name == typeName)) //{ // return true; //} if (this.ParentClass != null) { return this.ParentClass.HasTypeName(name); } return false; } public string Name { get { return this.InnerDeclaration.Name; } } public IEnumerable<CodeTypeMember> GetMembers() { foreach (CodeTypeMember member in this.InnerDeclaration.Members) { yield return member; } } public CodeMemberMethodEx AddFactoryMethod(CodeTypeReferenceEx returnType, string methodName, out CodeMethodVariableReferenceEx returnVariable) { var method = new CodeMemberMethodEx(this); returnVariable = new CodeMethodVariableReferenceEx(method, method.AddMethodVariable("newDef", returnType, returnType.ReferencedType.CallCodeConstructor())); method.Name = methodName; method.Attributes = MemberAttributes.Public | MemberAttributes.Static; method.ReturnType = returnType; method.IsSharedFactoryMethod = true; this.AddMethod(method); return method; } public void AddMethod(CodeMemberMethodEx method) { UsedNames.Add(method.Name); this.InnerDeclaration.Members.Add(method); } public bool ContainsMethod(string methodName) { return GetMembers().OfType<CodeMemberMethodEx>().Any(m => m.Name == methodName); } public bool ContainsChildClass(string className) { return GetMembers().OfType<CodeTypeDeclarationEx>().Any(m => m.Name == className); } public bool ContainsSharedFactoryMethod(string methodName, params CodeDefPropertyDescriptor[] properties) { if (GetMembers().OfType<CodeMemberMethodEx>().Any(m => m.Name == methodName && m.MatchesPropertyAssignments(properties))) { return true; } if (properties.Length > 0) { var matchByOverload = GetMembers().OfType<CodeMemberMethodEx>().Where(m => m.Name == methodName && m.MatchesPropertyAssignmentOverloads(properties)).FirstOrDefault(); if(matchByOverload != null) { if (MessageBox.Show("Warning: Duplicate Factory Method Overloads", "Method Overload Collision", MessageBoxButton.YesNo) == MessageBoxResult.No) { throw new Exception(); } } } return false; } public CodeMemberMethodEx AddCreateMethod(object sourceDef, bool justUseCreateForName = false) { var createMethod = new CodeMemberMethodEx(this); if (justUseCreateForName) { createMethod.Name = "Create"; } else { var methodSuffix = sourceDef.GetType().Name; if (sourceDef is RuleRepositoryDefBase) { var name = methodSuffix +"_" + ((RuleRepositoryDefBase) sourceDef).Name; methodSuffix = name; } // Used name is captured below createMethod.Name = GetSafeName("Create_" + methodSuffix, false); } createMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; createMethod.ReturnType = sourceDef.GetType().ToCodeTypeReference(); this.InnerDeclaration.Members.Add(createMethod); UsedNames.Add(createMethod.Name); return createMethod; } public static CodeTypeDeclarationEx CreateRoot(object sourceRuleAppDef) { string name = sourceRuleAppDef.GetType().Name; if (sourceRuleAppDef.IsInstanceOf<RuleApplicationDef>()) { name = "RuleAppGen_" + ((RuleApplicationDef) sourceRuleAppDef).Name; } var ret = new CodeTypeDeclarationEx(null); ret.SetInnerTypeDeclaration(null, sourceRuleAppDef, name); return ret; } public CodeTypeDeclarationEx GetDefFactory() { if (this.ParentClass != null) { return this.ParentClass.GetDefFactory(); } var defFactory = this.ChildClasses.FirstOrDefault(c => c.IsDefFactory); if (defFactory == null) { defFactory = this.AddChildClass(null, "DefFactory"); defFactory.IsDefFactory = true; } return defFactory; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CSharp; using Microsoft.VisualBasic; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Runtime.Serialization; namespace System.CodeDom.Compiler { public abstract class CodeDomProvider : Component { private static readonly Dictionary<string, CompilerInfo> s_compilerLanguages = new Dictionary<string, CompilerInfo>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, CompilerInfo> s_compilerExtensions = new Dictionary<string, CompilerInfo>(StringComparer.OrdinalIgnoreCase); private static readonly List<CompilerInfo> s_allCompilerInfo = new List<CompilerInfo>(); static CodeDomProvider() { // C# AddCompilerInfo(new CompilerInfo(new CompilerParameters() { WarningLevel = 4 }, typeof(CSharpCodeProvider).FullName) { _compilerLanguages = new string[] { "c#", "cs", "csharp" }, _compilerExtensions = new string[] { ".cs", "cs" } }); // VB AddCompilerInfo(new CompilerInfo(new CompilerParameters() { WarningLevel = 4 }, typeof(VBCodeProvider).FullName) { _compilerLanguages = new string[] { "vb", "vbs", "visualbasic", "vbscript" }, _compilerExtensions = new string[] { ".vb", "vb" } }); } private static void AddCompilerInfo(CompilerInfo compilerInfo) { foreach (string language in compilerInfo._compilerLanguages) { s_compilerLanguages[language] = compilerInfo; } foreach (string extension in compilerInfo._compilerExtensions) { s_compilerExtensions[extension] = compilerInfo; } s_allCompilerInfo.Add(compilerInfo); } public static CodeDomProvider CreateProvider(string language, System.Collections.Generic.IDictionary<string, string> providerOptions) { CompilerInfo compilerInfo = GetCompilerInfo(language); return compilerInfo.CreateProvider(providerOptions); } public static CodeDomProvider CreateProvider(string language) { CompilerInfo compilerInfo = GetCompilerInfo(language); return compilerInfo.CreateProvider(); } public static string GetLanguageFromExtension(string extension) { CompilerInfo compilerInfo = GetCompilerInfoForExtensionNoThrow(extension); if (compilerInfo == null) { throw new ConfigurationErrorsException(SR.CodeDomProvider_NotDefined); } return compilerInfo._compilerLanguages[0]; } public static bool IsDefinedLanguage(string language) => GetCompilerInfoForLanguageNoThrow(language) != null; public static bool IsDefinedExtension(string extension) => GetCompilerInfoForExtensionNoThrow(extension) != null; public static CompilerInfo GetCompilerInfo(string language) { CompilerInfo compilerInfo = GetCompilerInfoForLanguageNoThrow(language); if (compilerInfo == null) { throw new ConfigurationErrorsException(SR.CodeDomProvider_NotDefined); } return compilerInfo; } private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language) { if (language == null) { throw new ArgumentNullException(nameof(language)); } CompilerInfo value; s_compilerLanguages.TryGetValue(language.Trim(), out value); return value; } private static CompilerInfo GetCompilerInfoForExtensionNoThrow(string extension) { if (extension == null) { throw new ArgumentNullException(nameof(extension)); } CompilerInfo value; s_compilerExtensions.TryGetValue(extension.Trim(), out value); return value; } public static CompilerInfo[] GetAllCompilerInfo() => s_allCompilerInfo.ToArray(); public virtual string FileExtension => string.Empty; public virtual LanguageOptions LanguageOptions => LanguageOptions.None; [Obsolete("Callers should not use the ICodeGenerator interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")] public abstract ICodeGenerator CreateGenerator(); #pragma warning disable 618 // obsolete public virtual ICodeGenerator CreateGenerator(TextWriter output) => CreateGenerator(); public virtual ICodeGenerator CreateGenerator(string fileName) => CreateGenerator(); #pragma warning restore 618 [Obsolete("Callers should not use the ICodeCompiler interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")] public abstract ICodeCompiler CreateCompiler(); [Obsolete("Callers should not use the ICodeParser interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")] public virtual ICodeParser CreateParser() => null; public virtual TypeConverter GetConverter(Type type) => TypeDescriptor.GetConverter(type); public virtual CompilerResults CompileAssemblyFromDom(CompilerParameters options, params CodeCompileUnit[] compilationUnits) => CreateCompilerHelper().CompileAssemblyFromDomBatch(options, compilationUnits); public virtual CompilerResults CompileAssemblyFromFile(CompilerParameters options, params string[] fileNames) => CreateCompilerHelper().CompileAssemblyFromFileBatch(options, fileNames); public virtual CompilerResults CompileAssemblyFromSource(CompilerParameters options, params string[] sources) => CreateCompilerHelper().CompileAssemblyFromSourceBatch(options, sources); public virtual bool IsValidIdentifier(string value) => CreateGeneratorHelper().IsValidIdentifier(value); public virtual string CreateEscapedIdentifier(string value) => CreateGeneratorHelper().CreateEscapedIdentifier(value); public virtual string CreateValidIdentifier(string value) => CreateGeneratorHelper().CreateValidIdentifier(value); public virtual string GetTypeOutput(CodeTypeReference type) => CreateGeneratorHelper().GetTypeOutput(type); public virtual bool Supports(GeneratorSupport generatorSupport) => CreateGeneratorHelper().Supports(generatorSupport); public virtual void GenerateCodeFromExpression(CodeExpression expression, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromExpression(expression, writer, options); public virtual void GenerateCodeFromStatement(CodeStatement statement, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromStatement(statement, writer, options); public virtual void GenerateCodeFromNamespace(CodeNamespace codeNamespace, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromNamespace(codeNamespace, writer, options); public virtual void GenerateCodeFromCompileUnit(CodeCompileUnit compileUnit, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromCompileUnit(compileUnit, writer, options); public virtual void GenerateCodeFromType(CodeTypeDeclaration codeType, TextWriter writer, CodeGeneratorOptions options) => CreateGeneratorHelper().GenerateCodeFromType(codeType, writer, options); public virtual void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } public virtual CodeCompileUnit Parse(TextReader codeStream) => CreateParserHelper().Parse(codeStream); #pragma warning disable 0618 // obsolete private ICodeCompiler CreateCompilerHelper() { ICodeCompiler compiler = CreateCompiler(); if (compiler == null) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } return compiler; } private ICodeGenerator CreateGeneratorHelper() { ICodeGenerator generator = CreateGenerator(); if (generator == null) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } return generator; } private ICodeParser CreateParserHelper() { ICodeParser parser = CreateParser(); if (parser == null) { throw new NotImplementedException(SR.NotSupported_CodeDomAPI); } return parser; } #pragma warning restore 618 private sealed class ConfigurationErrorsException : SystemException { public ConfigurationErrorsException(string message) : base(message) { } public ConfigurationErrorsException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } }
using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Xml; using ICSharpCode.SharpZipLib.Zip; using MarkdownSharp; using NuGet; using Splat; namespace Squirrel { internal static class FrameworkTargetVersion { public static FrameworkName Net40 = new FrameworkName(".NETFramework,Version=v4.0"); public static FrameworkName Net45 = new FrameworkName(".NETFramework,Version=v4.5"); } public interface IReleasePackage { string InputPackageFile { get; } string ReleasePackageFile { get; } string SuggestedReleaseFileName { get; } string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null); } public static class VersionComparer { public static bool Matches(IVersionSpec versionSpec, SemanticVersion version) { if (versionSpec == null) return true; // I CAN'T DEAL WITH THIS bool minVersion; if (versionSpec.MinVersion == null) { minVersion = true; // no preconditon? LET'S DO IT } else if (versionSpec.IsMinInclusive) { minVersion = version >= versionSpec.MinVersion; } else { minVersion = version > versionSpec.MinVersion; } bool maxVersion; if (versionSpec.MaxVersion == null) { maxVersion = true; // no preconditon? LET'S DO IT } else if (versionSpec.IsMaxInclusive) { maxVersion = version <= versionSpec.MaxVersion; } else { maxVersion = version < versionSpec.MaxVersion; } return maxVersion && minVersion; } } public class ReleasePackage : IEnableLogger, IReleasePackage { IEnumerable<IPackage> localPackageCache; public ReleasePackage(string inputPackageFile, bool isReleasePackage = false) { InputPackageFile = inputPackageFile; if (isReleasePackage) { ReleasePackageFile = inputPackageFile; } } public string InputPackageFile { get; protected set; } public string ReleasePackageFile { get; protected set; } public string SuggestedReleaseFileName { get { var zp = new ZipPackage(InputPackageFile); return String.Format("{0}-{1}-full.nupkg", zp.Id, zp.Version); } } public Version Version { get { return InputPackageFile.ToVersion(); } } public string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null) { Contract.Requires(!String.IsNullOrEmpty(outputFile)); releaseNotesProcessor = releaseNotesProcessor ?? (x => (new Markdown()).Transform(x)); if (ReleasePackageFile != null) { return ReleasePackageFile; } var package = new ZipPackage(InputPackageFile); // we can tell from here what platform(s) the package targets // but given this is a simple package we only // ever expect one entry here (crash hard otherwise) var frameworks = package.GetSupportedFrameworks(); if (frameworks.Count() > 1) { var platforms = frameworks .Aggregate(new StringBuilder(), (sb, f) => sb.Append(f.ToString() + "; ")); throw new InvalidOperationException(String.Format( "The input package file {0} targets multiple platforms - {1} - and cannot be transformed into a release package.", InputPackageFile, platforms)); } else if (!frameworks.Any()) { throw new InvalidOperationException(String.Format( "The input package file {0} targets no platform and cannot be transformed into a release package.", InputPackageFile)); } var targetFramework = frameworks.Single(); // Recursively walk the dependency tree and extract all of the // dependent packages into the a temporary directory this.Log().Info("Creating release package: {0} => {1}", InputPackageFile, outputFile); var dependencies = findAllDependentPackages( package, new LocalPackageRepository(packagesRootDir), frameworkName: targetFramework); string tempPath = null; using (Utility.WithTempDirectory(out tempPath, null)) { var tempDir = new DirectoryInfo(tempPath); var fz = new FastZip(); fz.ExtractZip(InputPackageFile, tempPath, null); this.Log().Info("Extracting dependent packages: [{0}]", String.Join(",", dependencies.Select(x => x.Id))); extractDependentPackages(dependencies, tempDir, targetFramework); var specPath = tempDir.GetFiles("*.nuspec").First().FullName; this.Log().Info("Removing unnecessary data"); removeDependenciesFromPackageSpec(specPath); removeDeveloperDocumentation(tempDir); if (releaseNotesProcessor != null) { renderReleaseNotesMarkdown(specPath, releaseNotesProcessor); } addDeltaFilesToContentTypes(tempDir.FullName); if (contentsPostProcessHook != null) { contentsPostProcessHook(tempPath); } fz.CreateZip(outputFile, tempPath, true, null); ReleasePackageFile = outputFile; return ReleasePackageFile; } } void extractDependentPackages(IEnumerable<IPackage> dependencies, DirectoryInfo tempPath, FrameworkName framework) { dependencies.ForEach(pkg => { this.Log().Info("Scanning {0}", pkg.Id); pkg.GetLibFiles().ForEach(file => { var outPath = new FileInfo(Path.Combine(tempPath.FullName, file.Path)); if (!VersionUtility.IsCompatible(framework , new[] { file.TargetFramework })) { this.Log().Info("Ignoring {0} as the target framework is not compatible", outPath); return; } Directory.CreateDirectory(outPath.Directory.FullName); using (var of = File.Create(outPath.FullName)) { this.Log().Info("Writing {0} to {1}", file.Path, outPath); file.GetStream().CopyTo(of); } }); }); } void removeDeveloperDocumentation(DirectoryInfo expandedRepoPath) { expandedRepoPath.GetAllFilesRecursively() .Where(x => x.Name.EndsWith(".dll", true, CultureInfo.InvariantCulture)) .Select(x => new FileInfo(x.FullName.ToLowerInvariant().Replace(".dll", ".xml"))) .Where(x => x.Exists) .ForEach(x => x.Delete()); } void renderReleaseNotesMarkdown(string specPath, Func<string, string> releaseNotesProcessor) { var doc = new XmlDocument(); doc.Load(specPath); // XXX: This code looks full tart var metadata = doc.DocumentElement.ChildNodes .OfType<XmlElement>() .First(x => x.Name.ToLowerInvariant() == "metadata"); var releaseNotes = metadata.ChildNodes .OfType<XmlElement>() .FirstOrDefault(x => x.Name.ToLowerInvariant() == "releasenotes"); if (releaseNotes == null) { this.Log().Info("No release notes found in {0}", specPath); return; } releaseNotes.InnerText = String.Format("<![CDATA[\n" + "{0}\n" + "]]>", releaseNotesProcessor(releaseNotes.InnerText)); doc.Save(specPath); } void removeDependenciesFromPackageSpec(string specPath) { var xdoc = new XmlDocument(); xdoc.Load(specPath); var metadata = xdoc.DocumentElement.FirstChild; var dependenciesNode = metadata.ChildNodes.OfType<XmlElement>().FirstOrDefault(x => x.Name.ToLowerInvariant() == "dependencies"); if (dependenciesNode != null) { metadata.RemoveChild(dependenciesNode); } xdoc.Save(specPath); } internal IEnumerable<IPackage> findAllDependentPackages( IPackage package = null, IPackageRepository packageRepository = null, HashSet<string> packageCache = null, FrameworkName frameworkName = null) { package = package ?? new ZipPackage(InputPackageFile); packageCache = packageCache ?? new HashSet<string>(); var deps = package.DependencySets .Where(x => x.TargetFramework == null || x.TargetFramework == frameworkName) .SelectMany(x => x.Dependencies); return deps.SelectMany(dependency => { var ret = matchPackage(packageRepository, dependency.Id, dependency.VersionSpec); if (ret == null) { var message = String.Format("Couldn't find file for package in {1}: {0}", dependency.Id, packageRepository.Source); this.Log().Error(message); throw new Exception(message); } if (packageCache.Contains(ret.GetFullName())) { return Enumerable.Empty<IPackage>(); } packageCache.Add(ret.GetFullName()); return findAllDependentPackages(ret, packageRepository, packageCache, frameworkName).StartWith(ret).Distinct(y => y.GetFullName()); }).ToArray(); } IPackage matchPackage(IPackageRepository packageRepository, string id, IVersionSpec version) { return packageRepository.FindPackagesById(id).FirstOrDefault(x => VersionComparer.Matches(version, x.Version)); } static internal void addDeltaFilesToContentTypes(string rootDirectory) { var doc = new XmlDocument(); var path = Path.Combine(rootDirectory, "[Content_Types].xml"); doc.Load(path); ContentType.Merge(doc); using (var sw = new StreamWriter(path, false, Encoding.UTF8)) { doc.Save(sw); } } } public class ChecksumFailedException : Exception { public string Filename { get; set; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGenerator.Model; using Orleans.CodeGenerator.Utilities; using Microsoft.Extensions.Logging; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using ITypeSymbol = Microsoft.CodeAnalysis.ITypeSymbol; namespace Orleans.CodeGenerator.Generators { /// <summary> /// Code generator which generates serializers. /// Sample of generated serializer: /// [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "2.0.0.0"), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.SerializerAttribute(typeof(global::MyType))] /// internal sealed class OrleansCodeGenUnitTests_GrainInterfaces_MyTypeSerializer /// { /// private readonly global::System.Func&lt;global::MyType, global::System.Int32&gt; getField0; /// private readonly global::System.Action&lt;global::MyType, global::System.Int32&gt; setField0; /// public OrleansCodeGenUnitTests_GrainInterfaces_MyTypeSerializer(global::Orleans.Serialization.IFieldUtils fieldUtils) /// { /// [...] /// } /// [global::Orleans.CodeGeneration.CopierMethodAttribute] /// public global::System.Object DeepCopier(global::System.Object original, global::Orleans.Serialization.ICopyContext context) /// { /// [...] /// } /// [global::Orleans.CodeGeneration.SerializerMethodAttribute] /// public void Serializer(global::System.Object untypedInput, global::Orleans.Serialization.ISerializationContext context, global::System.Type expected) /// { /// [...] /// } /// [global::Orleans.CodeGeneration.DeserializerMethodAttribute] /// public global::System.Object Deserializer(global::System.Type expected, global::Orleans.Serialization.IDeserializationContext context) /// { /// [...] /// } ///} /// </summary> internal class SerializerGenerator { /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "Serializer"; private readonly CodeGeneratorOptions options; private readonly WellKnownTypes wellKnownTypes; public SerializerGenerator(CodeGeneratorOptions options, WellKnownTypes wellKnownTypes) { this.options = options; this.wellKnownTypes = wellKnownTypes; } private readonly ConcurrentDictionary<ITypeSymbol, bool> ShallowCopyableTypes = new ConcurrentDictionary<ITypeSymbol, bool>(); /// <summary> /// Returns the name of the generated class for the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>The name of the generated class for the provided type.</returns> internal string GetGeneratedClassName(INamedTypeSymbol type) { var parts = type.ToDisplayParts(SymbolDisplayFormat.FullyQualifiedFormat .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted) .WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.None) .WithGenericsOptions(SymbolDisplayGenericsOptions.None) .WithKindOptions(SymbolDisplayKindOptions.None) .WithLocalOptions(SymbolDisplayLocalOptions.None) .WithMemberOptions(SymbolDisplayMemberOptions.None) .WithParameterOptions(SymbolDisplayParameterOptions.None)); var b = new StringBuilder(); foreach (var part in parts) { // Add the class prefix after the type name. switch (part.Kind) { case SymbolDisplayPartKind.Punctuation: b.Append('_'); break; case SymbolDisplayPartKind.ClassName: case SymbolDisplayPartKind.InterfaceName: case SymbolDisplayPartKind.StructName: b.Append(part.ToString().TrimStart('@')); b.Append(ClassSuffix); break; default: b.Append(part.ToString().TrimStart('@')); break; } } return CodeGenerator.ToolName + b; } /// <summary> /// Generates the non serializer class for the provided grain types. /// </summary> internal (TypeDeclarationSyntax, TypeSyntax) GenerateClass(SemanticModel model, SerializerTypeDescription description, ILogger logger) { var className = GetGeneratedClassName(description.Target); var type = description.Target; var genericTypes = type.GetHierarchyTypeParameters().Select(_ => TypeParameter(_.ToString())).ToArray(); var attributes = new List<AttributeSyntax> { GeneratedCodeAttributeGenerator.GetGeneratedCodeAttributeSyntax(wellKnownTypes), Attribute(wellKnownTypes.ExcludeFromCodeCoverageAttribute.ToNameSyntax()), Attribute(wellKnownTypes.SerializerAttribute.ToNameSyntax()) .AddArgumentListArguments( AttributeArgument(TypeOfExpression(type.WithoutTypeParameters().ToTypeSyntax()))) }; var fields = GetFields(model, type, logger); var members = new List<MemberDeclarationSyntax>(GenerateFields(fields)) { GenerateConstructor(className, fields), GenerateDeepCopierMethod(type, fields, model), GenerateSerializerMethod(type, fields, model), GenerateDeserializerMethod(type, fields, model), }; var classDeclaration = ClassDeclaration(className) .AddModifiers(Token(SyntaxKind.InternalKeyword)) .AddModifiers(Token(SyntaxKind.SealedKeyword)) .AddAttributeLists(AttributeList().AddAttributes(attributes.ToArray())) .AddMembers(members.ToArray()) .AddConstraintClauses(type.GetTypeConstraintSyntax()); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } if (this.options.DebuggerStepThrough) { var debuggerStepThroughAttribute = Attribute(this.wellKnownTypes.DebuggerStepThroughAttribute.ToNameSyntax()); classDeclaration = classDeclaration.AddAttributeLists(AttributeList().AddAttributes(debuggerStepThroughAttribute)); } return (classDeclaration, ParseTypeName(type.GetParsableReplacementName(className))); } private MemberDeclarationSyntax GenerateConstructor(string className, List<FieldInfoMember> fields) { var body = new List<StatementSyntax>(); // Expressions for specifying binding flags. var bindingFlags = SymbolSyntaxExtensions.GetBindingFlagsParenthesizedExpressionSyntax( SyntaxKind.BitwiseOrExpression, BindingFlags.Instance, BindingFlags.NonPublic, BindingFlags.Public); var fieldUtils = IdentifierName("fieldUtils"); foreach (var field in fields) { // Get the field var fieldInfoField = IdentifierName(field.InfoFieldName); var fieldInfo = InvocationExpression(TypeOfExpression(field.Field.ContainingType.ToTypeSyntax()).Member("GetField")) .AddArgumentListArguments( Argument(field.Field.Name.ToLiteralExpression()), Argument(bindingFlags)); var fieldInfoVariable = VariableDeclarator(field.InfoFieldName).WithInitializer(EqualsValueClause(fieldInfo)); if (!field.IsGettableProperty || !field.IsSettableProperty) { body.Add(LocalDeclarationStatement( VariableDeclaration(wellKnownTypes.FieldInfo.ToTypeSyntax()).AddVariables(fieldInfoVariable))); } // Set the getter/setter of the field if (!field.IsGettableProperty) { var getterType = wellKnownTypes.Func_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var getterInvoke = CastExpression( getterType, InvocationExpression(fieldUtils.Member("GetGetter")).AddArgumentListArguments(Argument(fieldInfoField))); body.Add(ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(field.GetterFieldName), getterInvoke))); } if (!field.IsSettableProperty) { if (field.Field.ContainingType != null && field.Field.ContainingType.IsValueType) { var setterType = wellKnownTypes.ValueTypeSetter_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var getValueSetterInvoke = CastExpression( setterType, InvocationExpression(fieldUtils.Member("GetValueSetter")) .AddArgumentListArguments(Argument(fieldInfoField))); body.Add(ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(field.SetterFieldName), getValueSetterInvoke))); } else { var setterType = wellKnownTypes.Action_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var getReferenceSetterInvoke = CastExpression( setterType, InvocationExpression(fieldUtils.Member("GetReferenceSetter")) .AddArgumentListArguments(Argument(fieldInfoField))); body.Add(ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(field.SetterFieldName), getReferenceSetterInvoke))); } } } return ConstructorDeclaration(className) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters( Parameter(fieldUtils.Identifier).WithType(wellKnownTypes.IFieldUtils.ToTypeSyntax())) .AddBodyStatements(body.ToArray()); } /// <summary> /// Returns syntax for the deserializer method. /// </summary> private MemberDeclarationSyntax GenerateDeserializerMethod(INamedTypeSymbol type, List<FieldInfoMember> fields, SemanticModel model) { var contextParameter = IdentifierName("context"); var resultDeclaration = LocalDeclarationStatement( VariableDeclaration(type.ToTypeSyntax()) .AddVariables( VariableDeclarator("result") .WithInitializer(EqualsValueClause(GetObjectCreationExpressionSyntax(type, model))))); var resultVariable = IdentifierName("result"); var body = new List<StatementSyntax> {resultDeclaration}; // Value types cannot be referenced, only copied, so there is no need to box & record instances of value types. if (!type.IsValueType) { // Record the result for cyclic deserialization. var currentSerializationContext = contextParameter; body.Add( ExpressionStatement( InvocationExpression(currentSerializationContext.Member("RecordObject")) .AddArgumentListArguments(Argument(resultVariable)))); } // Deserialize all fields. foreach (var field in fields) { var deserialized = InvocationExpression(contextParameter.Member("DeserializeInner")) .AddArgumentListArguments( Argument(TypeOfExpression(field.Type))); body.Add( ExpressionStatement( field.GetSetter( resultVariable, CastExpression(field.Type, deserialized)))); } // If the type implements the internal IOnDeserialized lifecycle method, invoke it's method now. if (type.HasInterface(wellKnownTypes.IOnDeserialized)) { // C#: ((IOnDeserialized)result).OnDeserialized(context); var typedResult = ParenthesizedExpression(CastExpression(wellKnownTypes.IOnDeserialized.ToTypeSyntax(), resultVariable)); var invokeOnDeserialized = InvocationExpression(typedResult.Member("OnDeserialized")) .AddArgumentListArguments(Argument(contextParameter)); body.Add(ExpressionStatement(invokeOnDeserialized)); } body.Add(ReturnStatement(CastExpression(type.ToTypeSyntax(), resultVariable))); return MethodDeclaration(wellKnownTypes.Object.ToTypeSyntax(), "Deserializer") .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters( Parameter(Identifier("expected")).WithType(wellKnownTypes.Type.ToTypeSyntax()), Parameter(Identifier("context")).WithType(wellKnownTypes.IDeserializationContext.ToTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( AttributeList() .AddAttributes(Attribute(wellKnownTypes.DeserializerMethodAttribute.ToNameSyntax()))); } private MemberDeclarationSyntax GenerateSerializerMethod(INamedTypeSymbol type, List<FieldInfoMember> fields, SemanticModel model) { var contextParameter = IdentifierName("context"); var body = new List<StatementSyntax> { LocalDeclarationStatement( VariableDeclaration(type.ToTypeSyntax()) .AddVariables( VariableDeclarator("input") .WithInitializer( EqualsValueClause( CastExpression(type.ToTypeSyntax(), IdentifierName("untypedInput")))))) }; var inputExpression = IdentifierName("input"); // Serialize all members. foreach (var field in fields) { body.Add( ExpressionStatement( InvocationExpression(contextParameter.Member("SerializeInner")) .AddArgumentListArguments( Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)), Argument(TypeOfExpression(field.Type))))); } return MethodDeclaration(wellKnownTypes.Void.ToTypeSyntax(), "Serializer") .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters( Parameter(Identifier("untypedInput")).WithType(wellKnownTypes.Object.ToTypeSyntax()), Parameter(Identifier("context")).WithType(wellKnownTypes.ISerializationContext.ToTypeSyntax()), Parameter(Identifier("expected")).WithType(wellKnownTypes.Type.ToTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( AttributeList() .AddAttributes(Attribute(wellKnownTypes.SerializerMethodAttribute.ToNameSyntax()))); } /// <summary> /// Returns syntax for the deep copy method. /// </summary> private MemberDeclarationSyntax GenerateDeepCopierMethod(INamedTypeSymbol type, List<FieldInfoMember> fields, SemanticModel model) { var originalVariable = IdentifierName("original"); var inputVariable = IdentifierName("input"); var resultVariable = IdentifierName("result"); var body = new List<StatementSyntax>(); if (type.HasInterface(wellKnownTypes.ImmutableAttribute)) { // Immutable types do not require copying. var typeName = type.ToDisplayString(); var comment = Comment($"// No deep copy required since {typeName} is marked with the [Immutable] attribute."); body.Add(ReturnStatement(originalVariable).WithLeadingTrivia(comment)); } else { body.Add( LocalDeclarationStatement( VariableDeclaration(type.ToTypeSyntax()) .AddVariables( VariableDeclarator("input") .WithInitializer( EqualsValueClause( ParenthesizedExpression( CastExpression(type.ToTypeSyntax(), originalVariable))))))); body.Add( LocalDeclarationStatement( VariableDeclaration(type.ToTypeSyntax()) .AddVariables( VariableDeclarator("result") .WithInitializer(EqualsValueClause(GetObjectCreationExpressionSyntax(type, model)))))); // Record this serialization. var context = IdentifierName("context"); body.Add( ExpressionStatement( InvocationExpression(context.Member("RecordCopy")) .AddArgumentListArguments(Argument(originalVariable), Argument(resultVariable)))); // Copy all members from the input to the result. foreach (var field in fields) { body.Add(ExpressionStatement(field.GetSetter(resultVariable, field.GetGetter(inputVariable, context)))); } body.Add(ReturnStatement(resultVariable)); } return MethodDeclaration(wellKnownTypes.Object.ToTypeSyntax(), "DeepCopier") .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters( Parameter(Identifier("original")).WithType(wellKnownTypes.Object.ToTypeSyntax()), Parameter(Identifier("context")).WithType(wellKnownTypes.ICopyContext.ToTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( AttributeList().AddAttributes(Attribute(wellKnownTypes.CopierMethodAttribute.ToNameSyntax()))); } /// <summary> /// Returns syntax for the fields of the serializer class. /// </summary> private MemberDeclarationSyntax[] GenerateFields(List<FieldInfoMember> fields) { var result = new List<MemberDeclarationSyntax>(); // Add each field and initialize it. foreach (var field in fields) { // Declare the getter for this field. if (!field.IsGettableProperty) { var getterType = wellKnownTypes.Func_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var fieldGetterVariable = VariableDeclarator(field.GetterFieldName); result.Add( FieldDeclaration(VariableDeclaration(getterType).AddVariables(fieldGetterVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword))); } if (!field.IsSettableProperty) { if (field.Field.ContainingType != null && field.Field.ContainingType.IsValueType) { var setterType = wellKnownTypes.ValueTypeSetter_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var fieldSetterVariable = VariableDeclarator(field.SetterFieldName); result.Add( FieldDeclaration(VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword))); } else { var setterType = wellKnownTypes.Action_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax(); var fieldSetterVariable = VariableDeclarator(field.SetterFieldName); result.Add( FieldDeclaration(VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword))); } } } return result.ToArray(); } /// <summary> /// Returns syntax for initializing a new instance of the provided type. /// </summary> private ExpressionSyntax GetObjectCreationExpressionSyntax(INamedTypeSymbol type, SemanticModel model) { ExpressionSyntax result; if (type.IsValueType) { // Use the default value. result = DefaultExpression(type.ToTypeSyntax()); } else if (GetEmptyConstructor(type, model) != null) { // Use the default constructor. result = ObjectCreationExpression(type.ToTypeSyntax()).AddArgumentListArguments(); } else { // Create an unformatted object. result = CastExpression( type.ToTypeSyntax(), InvocationExpression(wellKnownTypes.FormatterServices.ToTypeSyntax().Member("GetUninitializedObject")) .AddArgumentListArguments( Argument(TypeOfExpression(type.ToTypeSyntax())))); } return result; } /// <summary> /// Return the default constructor on <paramref name="type"/> if found or null if not found. /// </summary> private IMethodSymbol GetEmptyConstructor(INamedTypeSymbol type, SemanticModel model) { return type.GetDeclaredInstanceMembers<IMethodSymbol>() .FirstOrDefault(method => method.MethodKind == MethodKind.Constructor && method.Parameters.Length == 0 && model.IsAccessible(0, method)); } /// <summary> /// Returns a sorted list of the fields of the provided type. /// </summary> private List<FieldInfoMember> GetFields(SemanticModel model, INamedTypeSymbol type, ILogger logger) { var result = new List<FieldInfoMember>(); foreach (var field in type.GetDeclaredInstanceMembers<IFieldSymbol>()) { if (ShouldSerializeField(field)) { result.Add(new FieldInfoMember(this, model, type, field, result.Count)); } } if (type.TypeKind == TypeKind.Class) { // Some reference assemblies are compiled without private fields. // Warn the user if they are inheriting from a type in one of these assemblies using a heuristic: // If the type inherits from a type in a reference assembly and there are no fields declared on those // base types, emit a warning. var hasUnsupportedRefAsmBase = false; var referenceAssemblyHasFields = false; var baseType = type.BaseType; while (baseType != null && !baseType.Equals(wellKnownTypes.Object) && !baseType.Equals(wellKnownTypes.Attribute)) { if (!hasUnsupportedRefAsmBase && baseType.ContainingAssembly.HasAttribute("ReferenceAssemblyAttribute") && !IsSupportedRefAsmType(baseType)) { hasUnsupportedRefAsmBase = true; } foreach (var field in baseType.GetDeclaredInstanceMembers<IFieldSymbol>()) { if (hasUnsupportedRefAsmBase) referenceAssemblyHasFields = true; if (ShouldSerializeField(field)) { result.Add(new FieldInfoMember(this, model, type, field, result.Count)); } } baseType = baseType.BaseType; } if (hasUnsupportedRefAsmBase && !referenceAssemblyHasFields) { var fileLocation = string.Empty; var declaration = type.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() as ClassDeclarationSyntax; if (declaration != null) { var location = declaration.Identifier.GetLocation(); if (location.IsInSource) { var pos = location.GetLineSpan(); fileLocation = string.Format( "{0}({1},{2},{3},{4}): ", pos.Path, pos.StartLinePosition.Line + 1, pos.StartLinePosition.Character + 1, pos.EndLinePosition.Line + 1, pos.EndLinePosition.Character + 1); } } logger.LogWarning( $"{fileLocation}warning ORL1001: Type {type} has a base type which belongs to a reference assembly." + " Serializer generation for this type may not include important base type fields."); } bool IsSupportedRefAsmType(INamedTypeSymbol t) { INamedTypeSymbol baseDefinition; if (t.IsGenericType && !t.IsUnboundGenericType) { baseDefinition = t.ConstructUnboundGenericType().OriginalDefinition; } else { baseDefinition = t.OriginalDefinition; } foreach (var refAsmType in wellKnownTypes.SupportedRefAsmBaseTypes) { if (baseDefinition.Equals(refAsmType)) return true; } return false; } } result.Sort(FieldInfoMember.Comparer.Instance); return result; } /// <summary> /// Returns <see langowrd="true"/> if the provided field should be serialized, <see langword="false"/> otherwise. /// </summary> public bool ShouldSerializeField(IFieldSymbol symbol) { if (symbol.IsStatic) return false; if (symbol.HasAttribute(wellKnownTypes.NonSerializedAttribute)) return false; ITypeSymbol fieldType = symbol.Type; if (fieldType.TypeKind == TypeKind.Pointer) return false; if (fieldType.TypeKind == TypeKind.Delegate) return false; if (wellKnownTypes.IntPtr.Equals(fieldType)) return false; if (wellKnownTypes.UIntPtr.Equals(fieldType)) return false; if (symbol.ContainingType.HasBaseType(wellKnownTypes.MarshalByRefObject)) return false; return true; } internal bool IsOrleansShallowCopyable(ITypeSymbol type) { var root = new HashSet<ITypeSymbol>(); return IsOrleansShallowCopyable(type, root); } internal bool IsOrleansShallowCopyable(ITypeSymbol type, HashSet<ITypeSymbol> examining) { switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_String: case SpecialType.System_DateTime: return true; } if (wellKnownTypes.TimeSpan.Equals(type) || wellKnownTypes.IPAddress.Equals(type) || wellKnownTypes.IPEndPoint.Equals(type) || wellKnownTypes.SiloAddress.Equals(type) || wellKnownTypes.GrainId.Equals(type) || wellKnownTypes.ActivationId.Equals(type) || wellKnownTypes.ActivationAddress.Equals(type) || wellKnownTypes.CorrelationId is WellKnownTypes.Some correlationIdType && correlationIdType.Value.Equals(type) || wellKnownTypes.CancellationToken.Equals(type)) return true; if (ShallowCopyableTypes.TryGetValue(type, out var result)) return result; if (type.HasAttribute(wellKnownTypes.ImmutableAttribute)) { return ShallowCopyableTypes[type] = true; } if (type.HasBaseType(wellKnownTypes.Exception)) { return ShallowCopyableTypes[type] = true; } if (!(type is INamedTypeSymbol namedType)) { return ShallowCopyableTypes[type] = false; } if (namedType.IsGenericType && wellKnownTypes.Immutable_1.Equals(namedType.ConstructedFrom)) { return ShallowCopyableTypes[type] = true; } if (type.TypeKind == TypeKind.Struct && !namedType.IsGenericType && !namedType.IsUnboundGenericType) { return ShallowCopyableTypes[type] = IsValueTypeFieldsShallowCopyable(type, examining); } return ShallowCopyableTypes[type] = false; } private bool IsValueTypeFieldsShallowCopyable(ITypeSymbol type, HashSet<ITypeSymbol> examining) { foreach (var field in type.GetInstanceMembers<IFieldSymbol>()) { if (field.IsStatic) continue; if (!(field.Type is INamedTypeSymbol fieldType)) { return false; } if (type.Equals(fieldType)) return false; if (!IsOrleansShallowCopyable(fieldType, examining)) return false; } return true; } /// <summary> /// Represents a field. /// </summary> private class FieldInfoMember { private readonly SerializerGenerator generator; private readonly SemanticModel model; private readonly WellKnownTypes wellKnownTypes; private readonly INamedTypeSymbol targetType; private IPropertySymbol property; /// <summary> /// The ordinal assigned to this field. /// </summary> private readonly int ordinal; public FieldInfoMember(SerializerGenerator generator, SemanticModel model, INamedTypeSymbol targetType, IFieldSymbol field, int ordinal) { this.generator = generator; this.wellKnownTypes = generator.wellKnownTypes; this.model = model; this.targetType = targetType; this.Field = field; this.ordinal = ordinal; } /// <summary> /// Gets the underlying <see cref="Field"/> instance. /// </summary> public IFieldSymbol Field { get; } /// <summary> /// Gets a usable representation of the field type. /// </summary> /// <remarks> /// If the field is of type 'dynamic', we represent it as 'object' because 'dynamic' cannot appear in typeof expressions. /// </remarks> public ITypeSymbol SafeType => this.Field.Type.TypeKind == TypeKind.Dynamic ? this.wellKnownTypes.Object : this.Field.Type; /// <summary> /// Gets the name of the field info field. /// </summary> public string InfoFieldName => "field" + this.ordinal; /// <summary> /// Gets the name of the getter field. /// </summary> public string GetterFieldName => "getField" + this.ordinal; /// <summary> /// Gets the name of the setter field. /// </summary> public string SetterFieldName => "setField" + this.ordinal; /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter. /// </summary> public bool IsGettableProperty => this.Property?.GetMethod != null && this.model.IsAccessible(0, this.Property.GetMethod) && !this.IsObsolete; /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter. /// </summary> public bool IsSettableProperty => this.Property?.SetMethod != null && this.model.IsAccessible(0, this.Property.SetMethod) && !this.IsObsolete; /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax Type => this.SafeType.ToTypeSyntax(); /// <summary> /// Gets the <see cref="Property"/> which this field is the backing property for, or /// <see langword="null" /> if this is not the backing field of an auto-property. /// </summary> private IPropertySymbol Property { get { if (this.property != null) { return this.property; } var propertyName = Regex.Match(this.Field.Name, "^<([^>]+)>.*$"); if (!propertyName.Success || this.Field.ContainingType == null) return null; var name = propertyName.Groups[1].Value; var candidates = this.targetType .GetInstanceMembers<IPropertySymbol>() .Where(p => string.Equals(name, p.Name, StringComparison.Ordinal) && !p.IsAbstract) .ToArray(); if (candidates.Length > 1) return null; if (!this.SafeType.Equals(candidates[0].Type)) return null; return this.property = candidates[0]; } } /// <summary> /// Gets a value indicating whether or not this field is obsolete. /// </summary> private bool IsObsolete => this.Field.HasAttribute(this.wellKnownTypes.ObsoleteAttribute) || this.Property != null && this.Property.HasAttribute(this.wellKnownTypes.ObsoleteAttribute); /// <summary> /// Returns syntax for retrieving the value of this field, deep copying it if necessary. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="serializationContextExpression">The expression used to retrieve the serialization context.</param> /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance, ExpressionSyntax serializationContextExpression = null, bool forceAvoidCopy = false) { // Retrieve the value of the field. var getValueExpression = this.GetValueExpression(instance); // Avoid deep-copying the field if possible. if (forceAvoidCopy || generator.IsOrleansShallowCopyable(this.SafeType)) { // Return the value without deep-copying it. return getValueExpression; } // Addressable arguments must be converted to references before passing. // IGrainObserver instances cannot be directly converted to references, therefore they are not included. ExpressionSyntax deepCopyValueExpression; if (this.SafeType.HasInterface(this.wellKnownTypes.IAddressable) && this.SafeType.TypeKind == TypeKind.Interface && !this.SafeType.HasInterface(this.wellKnownTypes.IGrainObserver)) { var getAsReference = getValueExpression.Member("AsReference".ToGenericName().AddTypeArgumentListArguments(this.Type)); // If the value is not a GrainReference, convert it to a strongly-typed GrainReference. // C#: (value == null || value is GrainReference) ? value : value.AsReference<TInterface>() deepCopyValueExpression = ConditionalExpression( ParenthesizedExpression( BinaryExpression( SyntaxKind.LogicalOrExpression, BinaryExpression( SyntaxKind.EqualsExpression, getValueExpression, LiteralExpression(SyntaxKind.NullLiteralExpression)), BinaryExpression( SyntaxKind.IsExpression, getValueExpression, this.wellKnownTypes.GrainReference.ToTypeSyntax()))), getValueExpression, InvocationExpression(getAsReference)); } else { deepCopyValueExpression = getValueExpression; } // Deep-copy the value. return CastExpression( this.Type, InvocationExpression(serializationContextExpression.Member("DeepCopyInner")) .AddArgumentListArguments( Argument(deepCopyValueExpression))); } /// <summary> /// Returns syntax for setting the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="value">Syntax for the new value.</param> /// <returns>Syntax for setting the value of this field.</returns> public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) { // If the field is the backing field for an accessible auto-property use the property directly. if (this.IsSettableProperty) { return AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, instance.Member(this.Property.Name), value); } var instanceArg = Argument(instance); if (this.Field.ContainingType != null && this.Field.ContainingType.IsValueType) { instanceArg = instanceArg.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)); } return InvocationExpression(IdentifierName(this.SetterFieldName)) .AddArgumentListArguments(instanceArg, Argument(value)); } /// <summary> /// Returns syntax for retrieving the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <returns>Syntax for retrieving the value of this field.</returns> private ExpressionSyntax GetValueExpression(ExpressionSyntax instance) { // If the field is the backing field for an accessible auto-property use the property directly. ExpressionSyntax result; if (this.IsGettableProperty) { result = instance.Member(this.Property.Name); } else { // Retrieve the field using the generated getter. result = InvocationExpression(IdentifierName(this.GetterFieldName)) .AddArgumentListArguments(Argument(instance)); } return result; } /// <summary> /// A comparer for <see cref="FieldInfoMember"/> which compares by name. /// </summary> public class Comparer : IComparer<FieldInfoMember> { /// <summary> /// Gets the singleton instance of this class. /// </summary> public static Comparer Instance { get; } = new Comparer(); public int Compare(FieldInfoMember x, FieldInfoMember y) { return string.Compare(x?.Field.Name, y?.Field.Name, StringComparison.Ordinal); } } } } }
// 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.Text; namespace System.Xml.Schema { /// <summary> /// This structure holds components of an Xsd Duration. It is used internally to support Xsd durations without loss /// of fidelity. XsdDuration structures are immutable once they've been created. /// </summary> internal struct XsdDuration { private int _years; private int _months; private int _days; private int _hours; private int _minutes; private int _seconds; private uint _nanoseconds; // High bit is used to indicate whether duration is negative private const uint NegativeBit = 0x80000000; private enum Parts { HasNone = 0, HasYears = 1, HasMonths = 2, HasDays = 4, HasHours = 8, HasMinutes = 16, HasSeconds = 32, } public enum DurationType { Duration, YearMonthDuration, DayTimeDuration, }; /// <summary> /// Construct an XsdDuration from component parts. /// </summary> public XsdDuration(bool isNegative, int years, int months, int days, int hours, int minutes, int seconds, int nanoseconds) { if (years < 0) throw new ArgumentOutOfRangeException(nameof(years)); if (months < 0) throw new ArgumentOutOfRangeException(nameof(months)); if (days < 0) throw new ArgumentOutOfRangeException(nameof(days)); if (hours < 0) throw new ArgumentOutOfRangeException(nameof(hours)); if (minutes < 0) throw new ArgumentOutOfRangeException(nameof(minutes)); if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); if (nanoseconds < 0 || nanoseconds > 999999999) throw new ArgumentOutOfRangeException(nameof(nanoseconds)); _years = years; _months = months; _days = days; _hours = hours; _minutes = minutes; _seconds = seconds; _nanoseconds = (uint)nanoseconds; if (isNegative) _nanoseconds |= NegativeBit; } /// <summary> /// Construct an XsdDuration from a TimeSpan value. /// </summary> public XsdDuration(TimeSpan timeSpan) : this(timeSpan, DurationType.Duration) { } /// <summary> /// Construct an XsdDuration from a TimeSpan value that represents an xsd:duration, an xdt:dayTimeDuration, or /// an xdt:yearMonthDuration. /// </summary> public XsdDuration(TimeSpan timeSpan, DurationType durationType) { long ticks = timeSpan.Ticks; ulong ticksPos; bool isNegative; if (ticks < 0) { // Note that (ulong) -Int64.MinValue = Int64.MaxValue + 1, which is what we want for that special case isNegative = true; ticksPos = (ulong)-ticks; } else { isNegative = false; ticksPos = (ulong)ticks; } if (durationType == DurationType.YearMonthDuration) { int years = (int)(ticksPos / ((ulong)TimeSpan.TicksPerDay * 365)); int months = (int)((ticksPos % ((ulong)TimeSpan.TicksPerDay * 365)) / ((ulong)TimeSpan.TicksPerDay * 30)); if (months == 12) { // If remaining days >= 360 and < 365, then round off to year years++; months = 0; } this = new XsdDuration(isNegative, years, months, 0, 0, 0, 0, 0); } else { Debug.Assert(durationType == DurationType.Duration || durationType == DurationType.DayTimeDuration); // Tick count is expressed in 100 nanosecond intervals _nanoseconds = (uint)(ticksPos % 10000000) * 100; if (isNegative) _nanoseconds |= NegativeBit; _years = 0; _months = 0; _days = (int)(ticksPos / (ulong)TimeSpan.TicksPerDay); _hours = (int)((ticksPos / (ulong)TimeSpan.TicksPerHour) % 24); _minutes = (int)((ticksPos / (ulong)TimeSpan.TicksPerMinute) % 60); _seconds = (int)((ticksPos / (ulong)TimeSpan.TicksPerSecond) % 60); } } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored with loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s) : this(s, DurationType.Duration) { } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored without loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s, DurationType durationType) { XsdDuration result; Exception exception = TryParse(s, durationType, out result); if (exception != null) { throw exception; } _years = result.Years; _months = result.Months; _days = result.Days; _hours = result.Hours; _minutes = result.Minutes; _seconds = result.Seconds; _nanoseconds = (uint)result.Nanoseconds; if (result.IsNegative) { _nanoseconds |= NegativeBit; } return; } /// <summary> /// Return true if this duration is negative. /// </summary> public bool IsNegative { get { return (_nanoseconds & NegativeBit) != 0; } } /// <summary> /// Return number of years in this duration (stored in 31 bits). /// </summary> public int Years { get { return _years; } } /// <summary> /// Return number of months in this duration (stored in 31 bits). /// </summary> public int Months { get { return _months; } } /// <summary> /// Return number of days in this duration (stored in 31 bits). /// </summary> public int Days { get { return _days; } } /// <summary> /// Return number of hours in this duration (stored in 31 bits). /// </summary> public int Hours { get { return _hours; } } /// <summary> /// Return number of minutes in this duration (stored in 31 bits). /// </summary> public int Minutes { get { return _minutes; } } /// <summary> /// Return number of seconds in this duration (stored in 31 bits). /// </summary> public int Seconds { get { return _seconds; } } /// <summary> /// Return number of nanoseconds in this duration. /// </summary> public int Nanoseconds { get { return (int)(_nanoseconds & ~NegativeBit); } } /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan() { return ToTimeSpan(DurationType.Duration); } /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan(DurationType durationType) { TimeSpan result; Exception exception = TryToTimeSpan(durationType, out result); if (exception != null) { throw exception; } return result; } internal Exception TryToTimeSpan(DurationType durationType, out TimeSpan result) { Exception exception = null; ulong ticks = 0; // Throw error if result cannot fit into a long try { checked { // Discard year and month parts if constructing TimeSpan for DayTimeDuration if (durationType != DurationType.DayTimeDuration) { ticks += ((ulong)_years + (ulong)_months / 12) * 365; ticks += ((ulong)_months % 12) * 30; } // Discard day and time parts if constructing TimeSpan for YearMonthDuration if (durationType != DurationType.YearMonthDuration) { ticks += (ulong)_days; ticks *= 24; ticks += (ulong)_hours; ticks *= 60; ticks += (ulong)_minutes; ticks *= 60; ticks += (ulong)_seconds; // Tick count interval is in 100 nanosecond intervals (7 digits) ticks *= (ulong)TimeSpan.TicksPerSecond; ticks += (ulong)Nanoseconds / 100; } else { // Multiply YearMonth duration by number of ticks per day ticks *= (ulong)TimeSpan.TicksPerDay; } if (IsNegative) { // Handle special case of Int64.MaxValue + 1 before negation, since it would otherwise overflow if (ticks == (ulong)Int64.MaxValue + 1) { result = new TimeSpan(Int64.MinValue); } else { result = new TimeSpan(-((long)ticks)); } } else { result = new TimeSpan((long)ticks); } return null; } } catch (OverflowException) { result = TimeSpan.MinValue; exception = new OverflowException(SR.Format(SR.XmlConvert_Overflow, durationType, "TimeSpan")); } return exception; } /// <summary> /// Return the string representation of this Xsd duration. /// </summary> public override string ToString() { return ToString(DurationType.Duration); } /// <summary> /// Return the string representation according to xsd:duration rules, xdt:dayTimeDuration rules, or /// xdt:yearMonthDuration rules. /// </summary> internal string ToString(DurationType durationType) { StringBuilder sb = new StringBuilder(20); int nanoseconds, digit, zeroIdx, len; if (IsNegative) sb.Append('-'); sb.Append('P'); if (durationType != DurationType.DayTimeDuration) { if (_years != 0) { sb.Append(XmlConvert.ToString(_years)); sb.Append('Y'); } if (_months != 0) { sb.Append(XmlConvert.ToString(_months)); sb.Append('M'); } } if (durationType != DurationType.YearMonthDuration) { if (_days != 0) { sb.Append(XmlConvert.ToString(_days)); sb.Append('D'); } if (_hours != 0 || _minutes != 0 || _seconds != 0 || Nanoseconds != 0) { sb.Append('T'); if (_hours != 0) { sb.Append(XmlConvert.ToString(_hours)); sb.Append('H'); } if (_minutes != 0) { sb.Append(XmlConvert.ToString(_minutes)); sb.Append('M'); } nanoseconds = Nanoseconds; if (_seconds != 0 || nanoseconds != 0) { sb.Append(XmlConvert.ToString(_seconds)); if (nanoseconds != 0) { sb.Append('.'); len = sb.Length; sb.Length += 9; zeroIdx = sb.Length - 1; for (int idx = zeroIdx; idx >= len; idx--) { digit = nanoseconds % 10; sb[idx] = (char)(digit + '0'); if (zeroIdx == idx && digit == 0) zeroIdx--; nanoseconds /= 10; } sb.Length = zeroIdx + 1; } sb.Append('S'); } } // Zero is represented as "PT0S" if (sb[sb.Length - 1] == 'P') sb.Append("T0S"); } else { // Zero is represented as "T0M" if (sb[sb.Length - 1] == 'P') sb.Append("0M"); } return sb.ToString(); } internal static Exception TryParse(string s, DurationType durationType, out XsdDuration result) { string errorCode; int length; int value, pos, numDigits; Parts parts = Parts.HasNone; result = new XsdDuration(); s = s.Trim(); length = s.Length; pos = 0; numDigits = 0; if (pos >= length) goto InvalidFormat; if (s[pos] == '-') { pos++; result._nanoseconds = NegativeBit; } else { result._nanoseconds = 0; } if (pos >= length) goto InvalidFormat; if (s[pos++] != 'P') goto InvalidFormat; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'Y') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasYears; result._years = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMonths; result._months = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'D') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasDays; result._days = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'T') { if (numDigits != 0) goto InvalidFormat; pos++; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'H') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasHours; result._hours = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMinutes; result._minutes = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == '.') { pos++; parts |= Parts.HasSeconds; result._seconds = value; errorCode = TryParseDigits(s, ref pos, true, out value, out numDigits); if (errorCode != null) goto Error; if (numDigits == 0) { //If there are no digits after the decimal point, assume 0 value = 0; } // Normalize to nanosecond intervals for (; numDigits > 9; numDigits--) value /= 10; for (; numDigits < 9; numDigits++) value *= 10; result._nanoseconds |= (uint)value; if (pos >= length) goto InvalidFormat; if (s[pos] != 'S') goto InvalidFormat; if (++pos == length) goto Done; } else if (s[pos] == 'S') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasSeconds; result._seconds = value; if (++pos == length) goto Done; } } // Duration cannot end with digits if (numDigits != 0) goto InvalidFormat; // No further characters are allowed if (pos != length) goto InvalidFormat; Done: // At least one part must be defined if (parts == Parts.HasNone) goto InvalidFormat; if (durationType == DurationType.DayTimeDuration) { if ((parts & (Parts.HasYears | Parts.HasMonths)) != 0) goto InvalidFormat; } else if (durationType == DurationType.YearMonthDuration) { if ((parts & ~(XsdDuration.Parts.HasYears | XsdDuration.Parts.HasMonths)) != 0) goto InvalidFormat; } return null; InvalidFormat: return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, durationType)); Error: return new OverflowException(SR.Format(SR.XmlConvert_Overflow, s, durationType)); } /// Helper method that constructs an integer from leading digits starting at s[offset]. "offset" is /// updated to contain an offset just beyond the last digit. The number of digits consumed is returned in /// cntDigits. The integer is returned (0 if no digits). If the digits cannot fit into an Int32: /// 1. If eatDigits is true, then additional digits will be silently discarded (don't count towards numDigits) /// 2. If eatDigits is false, an overflow exception is thrown private static string TryParseDigits(string s, ref int offset, bool eatDigits, out int result, out int numDigits) { int offsetStart = offset; int offsetEnd = s.Length; int digit; result = 0; numDigits = 0; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { digit = s[offset] - '0'; if (result > (Int32.MaxValue - digit) / 10) { if (!eatDigits) { return SR.XmlConvert_Overflow; } // Skip past any remaining digits numDigits = offset - offsetStart; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { offset++; } return null; } result = result * 10 + digit; offset++; } numDigits = offset - offsetStart; return null; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: IM.SwitchService.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 IM.SwitchService { /// <summary>Holder for reflection information generated from IM.SwitchService.proto</summary> public static partial class IMSwitchServiceReflection { #region Descriptor /// <summary>File descriptor for IM.SwitchService.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static IMSwitchServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZJTS5Td2l0Y2hTZXJ2aWNlLnByb3RvEhBJTS5Td2l0Y2hTZXJ2aWNlIk0K", "C0lNUDJQQ21kTXNnEhQKDGZyb21fdXNlcl9pZBgBIAEoBBISCgp0b191c2Vy", "X2lkGAIgASgEEhQKDGNtZF9tc2dfZGF0YRgDIAEoCUIiCh5jb20uYmx0LnRh", "bGsuY29tbW9uLmNvZGUucHJvdG9IA2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::IM.SwitchService.IMP2PCmdMsg), global::IM.SwitchService.IMP2PCmdMsg.Parser, new[]{ "FromUserId", "ToUserId", "CmdMsgData" }, null, null, null) })); } #endregion } #region Messages public sealed partial class IMP2PCmdMsg : pb::IMessage<IMP2PCmdMsg> { private static readonly pb::MessageParser<IMP2PCmdMsg> _parser = new pb::MessageParser<IMP2PCmdMsg>(() => new IMP2PCmdMsg()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<IMP2PCmdMsg> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::IM.SwitchService.IMSwitchServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public IMP2PCmdMsg() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public IMP2PCmdMsg(IMP2PCmdMsg other) : this() { fromUserId_ = other.fromUserId_; toUserId_ = other.toUserId_; cmdMsgData_ = other.cmdMsgData_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public IMP2PCmdMsg Clone() { return new IMP2PCmdMsg(this); } /// <summary>Field number for the "from_user_id" field.</summary> public const int FromUserIdFieldNumber = 1; private ulong fromUserId_; /// <summary> ///cmd id: 0x0601 /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong FromUserId { get { return fromUserId_; } set { fromUserId_ = value; } } /// <summary>Field number for the "to_user_id" field.</summary> public const int ToUserIdFieldNumber = 2; private ulong toUserId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong ToUserId { get { return toUserId_; } set { toUserId_ = value; } } /// <summary>Field number for the "cmd_msg_data" field.</summary> public const int CmdMsgDataFieldNumber = 3; private string cmdMsgData_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CmdMsgData { get { return cmdMsgData_; } set { cmdMsgData_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as IMP2PCmdMsg); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(IMP2PCmdMsg other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (FromUserId != other.FromUserId) return false; if (ToUserId != other.ToUserId) return false; if (CmdMsgData != other.CmdMsgData) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (FromUserId != 0UL) hash ^= FromUserId.GetHashCode(); if (ToUserId != 0UL) hash ^= ToUserId.GetHashCode(); if (CmdMsgData.Length != 0) hash ^= CmdMsgData.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (FromUserId != 0UL) { output.WriteRawTag(8); output.WriteUInt64(FromUserId); } if (ToUserId != 0UL) { output.WriteRawTag(16); output.WriteUInt64(ToUserId); } if (CmdMsgData.Length != 0) { output.WriteRawTag(26); output.WriteString(CmdMsgData); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (FromUserId != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(FromUserId); } if (ToUserId != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(ToUserId); } if (CmdMsgData.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CmdMsgData); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(IMP2PCmdMsg other) { if (other == null) { return; } if (other.FromUserId != 0UL) { FromUserId = other.FromUserId; } if (other.ToUserId != 0UL) { ToUserId = other.ToUserId; } if (other.CmdMsgData.Length != 0) { CmdMsgData = other.CmdMsgData; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { FromUserId = input.ReadUInt64(); break; } case 16: { ToUserId = input.ReadUInt64(); break; } case 26: { CmdMsgData = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using NetGore.IO; namespace NetGore { /// <summary> /// Provides helper methods for <see cref="Enum"/>s. /// </summary> /// <typeparam name="T">The Type of <see cref="Enum"/>.</typeparam> /// <exception cref="TypeInitializationException"><typeparamref name="T"/> is not an Enum.</exception> public static class EnumHelper<T> where T : struct, IComparable, IConvertible, IFormattable { // ReSharper disable StaticFieldInGenericType static readonly byte _bitsRequired; static readonly Func<int, T> _fromInt; static readonly int _maxValue; static readonly int _minValue; static readonly Func<T, int> _toInt; static readonly IEnumerable<T> _values; // ReSharper restore StaticFieldInGenericType /// <summary> /// Initializes the <see cref="EnumHelper{T}"/> class. /// </summary> /// <exception cref="MethodAccessException"><typeparamref name="T"/> is not an enum.</exception> static EnumHelper() { var supportedCastTypes = new Type[] { typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int) }; // Make sure we have an enum if (!typeof(T).IsEnum) throw CreateGenericTypeIsNotEnumException(); // Get the defined enum values _values = Enum.GetValues(typeof(T)).Cast<T>().ToCompact(); // Check if we have an underlying enum type that supports our ToInt/FromInt operations var underlyingType = Enum.GetUnderlyingType(typeof(T)); if (supportedCastTypes.Contains(underlyingType)) { // Create the funcs to cast to/from an int _toInt = CreateToInt(); _fromInt = CreateFromInt(); // Get all the defined values casted to int var valuesAsInt = _values.Select(_toInt); // Find the min and max values _minValue = valuesAsInt.Min(); _maxValue = valuesAsInt.Max(); Debug.Assert(_minValue <= _maxValue); // Find the difference between the min and max so we can cache how many bits are required for the range var diff = _maxValue - _minValue; Debug.Assert(diff >= 0); Debug.Assert(diff >= uint.MinValue); var bitsReq = BitOps.RequiredBits((uint)diff); Debug.Assert(bitsReq > 0); Debug.Assert(bitsReq < byte.MaxValue); _bitsRequired = (byte)bitsReq; } } /// <summary> /// Gets the number of bits required to write the enums values. /// </summary> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static int BitsRequired { get { if (!SupportsCastOperations) throw CastOperationsNotSupportedException(); return _bitsRequired; } } /// <summary> /// Gets the maximum defined enum value. /// </summary> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static int MaxValue { get { if (!SupportsCastOperations) throw CastOperationsNotSupportedException(); return _maxValue; } } /// <summary> /// Gets the minimum defined enum value. /// </summary> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static int MinValue { get { if (!SupportsCastOperations) throw CastOperationsNotSupportedException(); return _minValue; } } /// <summary> /// Gets if the cast operations of this class for the given type <typeparamref name="T"/> are supported. If false, /// some operations may not be available. Whether or not the operations are supported depends on the underlying /// type of the enum. /// </summary> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static bool SupportsCastOperations { get { return _toInt != null; } } /// <summary> /// Gets the defined values in the Enum. /// </summary> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static IEnumerable<T> Values { get { return _values; } } /// <summary> /// Creates an <see cref="MethodAccessException"/> to use for when accessing a method that requires casting to/from /// and int while <see cref="SupportsCastOperations"/> is false. /// </summary> /// <returns>An <see cref="MethodAccessException"/> to use for when accessing a method that requires casting to/from /// and int while <see cref="SupportsCastOperations"/> is false.</returns> static MethodAccessException CastOperationsNotSupportedException() { return new MethodAccessException("Methods that require casting the enum value to or from an Int32 are not" + " supported by this enum type since the underlying value type is not supported."); } /// <summary> /// Creates a Func to convert an int to <typeparamref name="T"/>. /// </summary> /// <returns>A Func to convert an int to <typeparamref name="T"/>.</returns> static Func<int, T> CreateFromInt() { var value = Expression.Parameter(typeof(int), "value"); var valueCast = Expression.Convert(value, typeof(T)); var lambda = Expression.Lambda<Func<int, T>>(valueCast, value); return lambda.Compile(); } /// <summary> /// Creates a <see cref="MethodAccessException"/> to use for when <typeparamref name="T"/> is not an enum. /// </summary> /// <returns>A <see cref="MethodAccessException"/> to use for when <typeparamref name="T"/> is not an enum.</returns> static MethodAccessException CreateGenericTypeIsNotEnumException() { const string errmsg = "Type parameter T ({0}) must be an Enum."; return new MethodAccessException(string.Format(errmsg, typeof(T))); } /// <summary> /// Creates a Func to convert <typeparamref name="T"/> to an int. /// </summary> /// <returns>A Func to convert <typeparamref name="T"/> to an int.</returns> static Func<T, int> CreateToInt() { var value = Expression.Parameter(typeof(T), "value"); var valueCast = Expression.Convert(value, typeof(int)); var lambda = Expression.Lambda<Func<T, int>>(valueCast, value); return lambda.Compile(); } /// <summary> /// Casts an int to type <typeparamref name="T"/>. /// </summary> /// <param name="value">The int value.</param> /// <returns>The <paramref name="value"/> casted to type <typeparamref name="T"/>.</returns> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T FromInt(int value) { if (!SupportsCastOperations) throw CastOperationsNotSupportedException(); return _fromInt(value); } /// <summary> /// Gets the Enum of the given type from its name. /// </summary> /// <typeparam name="T">The Type of <see cref="Enum"/>.</typeparam> /// <param name="value">The name of the <see cref="Enum"/> value.</param> /// <returns>The parsed enum.</returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> /// <exception cref="ArgumentException"><typeparamref name="T"/> is not an <see cref="Enum"/> -or- /// <paramref name="value"/> is an valid enum name -or- /// <paramref name="value"/> is a name, but not one of the named constants defined for the enumeration.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T FromName(string value) { return (T)Enum.Parse(typeof(T), value); } /// <summary> /// Gets a Func that will cast an int to <typeparamref name="T"/>. /// </summary> /// <returns>A Func that will cast an int to <typeparamref name="T"/>.</returns> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static Func<int, T> GetFromIntFunc() { if (!SupportsCastOperations) throw CastOperationsNotSupportedException(); return _fromInt; } /// <summary> /// Gets a Func that will cast <typeparamref name="T"/> to an int. /// </summary> /// <returns>A Func that will cast <typeparamref name="T"/> to an int.</returns> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static Func<T, int> GetToIntFunc() { if (!SupportsCastOperations) throw CastOperationsNotSupportedException(); return _toInt; } /// <summary> /// Returns an indication whether a constant with a specified value exists in the Enum of type /// <typeparamref name="T"/>. /// </summary> /// <param name="value">The value.</param> /// <returns>True if the <paramref name="value"/> exists in the Enum of type /// <typeparamref name="T"/>; otherwise false.</returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static bool IsDefined(T value) { return Enum.IsDefined(typeof(T), value); } /// <summary> /// Converts the string representation of the name or numeric value of one or more enumerated /// constants to an equivalent enumerated object. /// </summary> /// <param name="value">A string containing the name or value to convert.</param> /// <returns>The enum value parsed from <paramref name="value"/>.</returns> /// <exception cref="ArgumentException"><paramref name="value"/> is not equal to the name of any of /// the defined enum values.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T Parse(string value) { return (T)Enum.Parse(typeof(T), value); } /// <summary> /// Converts the string representation of the name or numeric value of one or more enumerated /// constants to an equivalent enumerated object. /// </summary> /// <typeparam name="T">The Type of Enum.</typeparam> /// <param name="value">A string containing the name or value to convert.</param> /// <param name="ignoreCase">If true, ignore case; otherwise, regard case.</param> /// <returns>The enum value parsed from <paramref name="value"/>.</returns> /// <exception cref="ArgumentException"><paramref name="value"/> is not equal to the name of any of /// the defined enum values.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T Parse(string value, bool ignoreCase) { return (T)Enum.Parse(typeof(T), value, ignoreCase); } /// <summary> /// Reads the Enum value using the name of the Enum instead of the underlying integer value. /// </summary> /// <param name="bitStream">The BitStream to read the value from.</param> /// <returns>The value read from the <paramref name="bitStream"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T ReadName(BitStream bitStream) { var str = bitStream.ReadString(); var value = FromName(str); return value; } /// <summary> /// Reads the Enum value using the underlying integer value of the Enum instead of the name. /// </summary> /// <param name="reader">The IValueReader to read the value from.</param> /// <param name="name">The name of the value to read.</param> /// <returns>The value read from the <paramref name="reader"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T ReadName(IValueReader reader, string name) { var str = reader.ReadString(name); var value = FromName(str); return value; } /// <summary> /// Reads a value of type <typeparamref name="T"/> from a <see cref="BitStream"/>. /// </summary> /// <param name="bitStream">The <see cref="BitStream"/> to read from.</param> /// <returns>The value read from the <see cref="bitStream"/>.</returns> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T ReadValue(BitStream bitStream) { var v = (int)(bitStream.ReadUInt(_bitsRequired) + _minValue); return FromInt(v); } /// <summary> /// Reads a value of type <typeparamref name="T"/> from a <see cref="IValueReader"/>. /// </summary> /// <param name="reader">The <see cref="IValueReader"/> to read from.</param> /// <param name="name">Unique name of the value to read.</param> /// <returns>The value read from the <paramref name="reader"/>.</returns> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T ReadValue(IValueReader reader, string name) { var v = (int)(reader.ReadUInt(name, _bitsRequired) + _minValue); return FromInt(v); } /// <summary> /// Casts a value of type <typeparamref name="T"/> to an int. /// </summary> /// <param name="value">The value.</param> /// <returns>The <paramref name="value"/> casted to an int.</returns> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static int ToInt(T value) { if (!SupportsCastOperations) throw CastOperationsNotSupportedException(); return _toInt(value); } /// <summary> /// Gets the name of the <paramref name="value"/>. /// </summary> /// <typeparam name="T">The Type of <see cref="Enum"/>.</typeparam> /// <param name="value">The enum value.</param> /// <returns>The string name of the <paramref name="value"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static string ToName(T value) { return value.ToString(); } /// <summary> /// Converts the string representation of the name or numeric value of one or more enumerated /// constants to an equivalent enumerated object. /// </summary> /// <typeparam name="T">The Type of Enum.</typeparam> /// <param name="value">A string containing the name or value to convert.</param> /// <param name="outValue">When this method returns true, contains the parsed enum value.</param> /// <returns>The enum value parsed from <paramref name="value"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static bool TryParse(string value, out T outValue) { try { outValue = (T)Enum.Parse(typeof(T), value); } catch (ArgumentException) { outValue = default(T); return false; } return true; } /// <summary> /// Converts the string representation of the name or numeric value of one or more enumerated /// constants to an equivalent enumerated object. /// </summary> /// <typeparam name="T">The Type of Enum.</typeparam> /// <param name="value">A string containing the name or value to convert.</param> /// <param name="ignoreCase">If true, ignore case; otherwise, regard case.</param> /// <param name="outValue">When this method returns true, contains the parsed enum value.</param> /// <returns>The enum value parsed from <paramref name="value"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static bool TryParse(string value, bool ignoreCase, out T outValue) { try { outValue = (T)Enum.Parse(typeof(T), value, ignoreCase); } catch (ArgumentException) { outValue = default(T); return false; } return true; } /// <summary> /// Writes the Enum value using the name of the Enum instead of the underlying integer value. /// </summary> /// <param name="bitStream">The BitStream to write the value to.</param> /// <param name="value">The value to write.</param> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static void WriteName(BitStream bitStream, T value) { var str = ToName(value); bitStream.Write(str); } /// <summary> /// Writes the Enum value using the underlying integer value of the Enum instead of the name. /// </summary> /// <param name="writer">The IValueWriter to write the value to.</param> /// <param name="name">The name of the value to write.</param> /// <param name="value">The value to write.</param> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static void WriteName(IValueWriter writer, string name, T value) { var str = ToName(value); writer.Write(name, str); } /// <summary> /// Writes a value of type <typeparamref name="T"/> to a <see cref="BitStream"/>. /// </summary> /// <param name="bitStream">The <see cref="BitStream"/> to write to.</param> /// <param name="value">The value to write.</param> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static void WriteValue(BitStream bitStream, T value) { var signedV = ToInt(value) - _minValue; Debug.Assert(signedV >= uint.MinValue); var v = (uint)signedV; bitStream.Write(v, _bitsRequired); } /// <summary> /// Writes a value of type <typeparamref name="T"/> to a <see cref="IValueWriter"/>. /// </summary> /// <param name="writer">The <see cref="IValueWriter"/> to write to.</param> /// <param name="name">Unique name of the <paramref name="value"/> that will be used to distinguish it /// from other values when reading.</param> /// <param name="value">The value to write.</param> /// <exception cref="MethodAccessException"><see cref="SupportsCastOperations"/> is false.</exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static void WriteValue(IValueWriter writer, string name, T value) { var signedV = ToInt(value) - _minValue; Debug.Assert(signedV >= uint.MinValue); var v = (uint)signedV; writer.Write(name, v, _bitsRequired); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ComEventsSink ** ** Purpose: part of ComEventHelpers APIs which allow binding ** managed delegates to COM's connection point based events. ** ** Date: April 2008 **/ namespace System.Runtime.InteropServices { using System; using System.Diagnostics; // see code:ComEventsHelper#ComEventsArchitecture [System.Security.SecurityCritical] internal class ComEventsSink : NativeMethods.IDispatch, ICustomQueryInterface { #region private fields private Guid _iidSourceItf; private ComTypes.IConnectionPoint _connectionPoint; private int _cookie; private ComEventsMethod _methods; private ComEventsSink _next; #endregion #region ctor internal ComEventsSink(object rcw, Guid iid) { _iidSourceItf = iid; this.Advise(rcw); } #endregion #region static members internal static ComEventsSink Find(ComEventsSink sinks, ref Guid iid) { ComEventsSink sink = sinks; while (sink != null && sink._iidSourceItf != iid) { sink = sink._next; } return sink; } internal static ComEventsSink Add(ComEventsSink sinks, ComEventsSink sink) { sink._next = sinks; return sink; } [System.Security.SecurityCritical] internal static ComEventsSink RemoveAll(ComEventsSink sinks) { while (sinks != null) { sinks.Unadvise(); sinks = sinks._next; } return null; } [System.Security.SecurityCritical] internal static ComEventsSink Remove(ComEventsSink sinks, ComEventsSink sink) { BCLDebug.Assert(sinks != null, "removing event sink from empty sinks collection"); BCLDebug.Assert(sink != null, "specify event sink is null"); if (sink == sinks) { sinks = sinks._next; } else { ComEventsSink current = sinks; while (current != null && current._next != sink) current = current._next; if (current != null) { current._next = sink._next; } } sink.Unadvise(); return sinks; } #endregion #region public methods public ComEventsMethod RemoveMethod(ComEventsMethod method) { _methods = ComEventsMethod.Remove(_methods, method); return _methods; } public ComEventsMethod FindMethod(int dispid) { return ComEventsMethod.Find(_methods, dispid); } public ComEventsMethod AddMethod(int dispid) { ComEventsMethod method = new ComEventsMethod(dispid); _methods = ComEventsMethod.Add(_methods, method); return method; } #endregion #region IDispatch Members [System.Security.SecurityCritical] void NativeMethods.IDispatch.GetTypeInfoCount(out uint pctinfo) { pctinfo = 0; } [System.Security.SecurityCritical] void NativeMethods.IDispatch.GetTypeInfo(uint iTInfo, int lcid, out IntPtr info) { throw new NotImplementedException(); } [System.Security.SecurityCritical] void NativeMethods.IDispatch.GetIDsOfNames(ref Guid iid, string[] names, uint cNames, int lcid, int[] rgDispId) { throw new NotImplementedException(); } private const VarEnum VT_BYREF_VARIANT = VarEnum.VT_BYREF | VarEnum.VT_VARIANT; private const VarEnum VT_TYPEMASK = (VarEnum) 0x0fff; private const VarEnum VT_BYREF_TYPEMASK = VT_TYPEMASK | VarEnum.VT_BYREF; private static unsafe Variant *GetVariant(Variant *pSrc) { if (pSrc->VariantType == VT_BYREF_VARIANT) { // For VB6 compatibility reasons, if the VARIANT is a VT_BYREF | VT_VARIANT that // contains another VARIANT with VT_BYREF | VT_VARIANT, then we need to extract the // inner VARIANT and use it instead of the outer one. Note that if the inner VARIANT // is VT_BYREF | VT_VARIANT | VT_ARRAY, it will pass the below test too. Variant *pByRefVariant = (Variant *)pSrc->AsByRefVariant; if ((pByRefVariant->VariantType & VT_BYREF_TYPEMASK) == VT_BYREF_VARIANT) return (Variant *)pByRefVariant; } return pSrc; } [System.Security.SecurityCritical] unsafe void NativeMethods.IDispatch.Invoke( int dispid, ref Guid riid, int lcid, ComTypes.INVOKEKIND wFlags, ref ComTypes.DISPPARAMS pDispParams, IntPtr pvarResult, IntPtr pExcepInfo, IntPtr puArgErr) { ComEventsMethod method = FindMethod(dispid); if (method == null) return; // notice the unsafe pointers we are using. This is to avoid unnecessary // arguments marshalling. see code:ComEventsHelper#ComEventsArgsMarshalling object [] args = new object[pDispParams.cArgs]; int [] byrefsMap = new int[pDispParams.cArgs]; bool [] usedArgs = new bool[pDispParams.cArgs]; Variant* pvars = (Variant*)pDispParams.rgvarg; int* pNamedArgs = (int*)pDispParams.rgdispidNamedArgs; // copy the named args (positional) as specified int i; int pos; for (i = 0; i < pDispParams.cNamedArgs; i++) { pos = pNamedArgs[i]; Variant* pvar = GetVariant(&pvars[i]); args[pos] = pvar->ToObject(); usedArgs[pos] = true; if (pvar->IsByRef) { byrefsMap[pos] = i; } else { byrefsMap[pos] = -1; } } // copy the rest of the arguments in the reverse order pos = 0; for (; i < pDispParams.cArgs; i++) { // find the next unassigned argument while (usedArgs[pos]) { ++pos; } Variant* pvar = GetVariant(&pvars[pDispParams.cArgs - 1 - i]); args[pos] = pvar->ToObject(); if (pvar->IsByRef) byrefsMap[pos] = pDispParams.cArgs - 1 - i; else byrefsMap[pos] = -1; pos++; } // Do the actual delegate invocation object result; result = method.Invoke(args); // convert result to VARIANT if (pvarResult != IntPtr.Zero) { Marshal.GetNativeVariantForObject(result, pvarResult); } // Now we need to marshal all the byrefs back for (i = 0; i < pDispParams.cArgs; i++) { int idxToPos = byrefsMap[i]; if (idxToPos == -1) continue; GetVariant(&pvars[idxToPos])->CopyFromIndirect(args[i]); } } #endregion static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}"); [System.Security.SecurityCritical] CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) { ppv = IntPtr.Zero; if (iid == this._iidSourceItf || iid == typeof(NativeMethods.IDispatch).GUID) { ppv = Marshal.GetComInterfaceForObject(this, typeof(NativeMethods.IDispatch), CustomQueryInterfaceMode.Ignore); return CustomQueryInterfaceResult.Handled; } else if (iid == IID_IManagedObject) { return CustomQueryInterfaceResult.Failed; } return CustomQueryInterfaceResult.NotHandled; } #region private methods private void Advise(object rcw) { BCLDebug.Assert(_connectionPoint == null, "comevent sink is already advised"); ComTypes.IConnectionPointContainer cpc = (ComTypes.IConnectionPointContainer)rcw; ComTypes.IConnectionPoint cp; cpc.FindConnectionPoint(ref _iidSourceItf, out cp); object sinkObject = this; cp.Advise(sinkObject, out _cookie); _connectionPoint = cp; } [System.Security.SecurityCritical] private void Unadvise() { BCLDebug.Assert(_connectionPoint != null, "can not unadvise from empty connection point"); try { _connectionPoint.Unadvise(_cookie); Marshal.ReleaseComObject(_connectionPoint); } catch (System.Exception) { // swallow all exceptions on unadvise // the host may not be available at this point } finally { _connectionPoint = null; } } #endregion }; }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // 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.Data.Common; using System.Collections; using Xunit; namespace System.Data.Tests { public class DataTableReaderTest { private DataTable _dt; public DataTableReaderTest() { _dt = new DataTable("test"); _dt.Columns.Add("id", typeof(int)); _dt.Columns.Add("name", typeof(string)); _dt.PrimaryKey = new DataColumn[] { _dt.Columns["id"] }; _dt.Rows.Add(new object[] { 1, "mono 1" }); _dt.Rows.Add(new object[] { 2, "mono 2" }); _dt.Rows.Add(new object[] { 3, "mono 3" }); _dt.AcceptChanges(); } #region Positive Tests [Fact] public void CtorTest() { _dt.Rows[1].Delete(); DataTableReader reader = new DataTableReader(_dt); try { int i = 0; while (reader.Read()) i++; reader.Close(); Assert.Equal(2, i); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void RowInAccessibleTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); reader.Read(); // 2nd row _dt.Rows[1].Delete(); string value = reader[1].ToString(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void IgnoreDeletedRowsDynamicTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row _dt.Rows[1].Delete(); reader.Read(); // it should be 3rd row string value = reader[0].ToString(); Assert.Equal("3", value); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void SeeTheModifiedTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row _dt.Rows[1]["name"] = "mono changed"; reader.Read(); string value = reader[1].ToString(); Assert.Equal("mono changed", value); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void SchemaTest() { DataTable another = new DataTable("another"); another.Columns.Add("x", typeof(string)); another.Rows.Add(new object[] { "test 1" }); another.Rows.Add(new object[] { "test 2" }); another.Rows.Add(new object[] { "test 3" }); DataTableReader reader = new DataTableReader(new DataTable[] { _dt, another }); try { DataTable schema = reader.GetSchemaTable(); Assert.Equal(_dt.Columns.Count, schema.Rows.Count); Assert.Equal(_dt.Columns[1].DataType.ToString(), schema.Rows[1]["DataType"].ToString()); reader.NextResult(); //schema should change here schema = reader.GetSchemaTable(); Assert.Equal(another.Columns.Count, schema.Rows.Count); Assert.Equal(another.Columns[0].DataType.ToString(), schema.Rows[0]["DataType"].ToString()); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void MultipleResultSetsTest() { DataTable dt1 = new DataTable("test2"); dt1.Columns.Add("x", typeof(string)); dt1.Rows.Add(new object[] { "test" }); dt1.Rows.Add(new object[] { "test1" }); dt1.AcceptChanges(); DataTable[] collection = new DataTable[] { _dt, dt1 }; DataTableReader reader = new DataTableReader(collection); try { int i = 0; do { while (reader.Read()) i++; } while (reader.NextResult()); Assert.Equal(5, i); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void GetTest() { _dt.Columns.Add("nullint", typeof(int)); _dt.Rows[0]["nullint"] = 333; DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); int ordinal = reader.GetOrdinal("nullint"); // Get by name Assert.Equal(1, (int)reader["id"]); Assert.Equal(333, reader.GetInt32(ordinal)); Assert.Equal("Int32", reader.GetDataTypeName(ordinal)); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void CloseTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { int i = 0; while (reader.Read() && i < 1) i++; reader.Close(); reader.Read(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void GetOrdinalTest() { DataTableReader reader = new DataTableReader(_dt); try { Assert.Equal(1, reader.GetOrdinal("name")); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } #endregion // Positive Tests #region Negative Tests [Fact] public void NoRowsTest() { _dt.Rows.Clear(); _dt.AcceptChanges(); DataTableReader reader = new DataTableReader(_dt); try { Assert.False(reader.Read()); Assert.False(reader.NextResult()); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void NoTablesTest() { AssertExtensions.Throws<ArgumentException>(null, () => { DataTableReader reader = new DataTableReader(new DataTable[] { }); try { reader.Read(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void ReadAfterClosedTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); reader.Close(); reader.Read(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void AccessAfterClosedTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); reader.Close(); int i = (int)reader[0]; i++; // to suppress warning } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void AccessBeforeReadTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { int i = (int)reader[0]; i++; // to suppress warning } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void InvalidIndexTest() { Assert.Throws<ArgumentOutOfRangeException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); int i = (int)reader[90]; // kidding, ;-) i++; // to suppress warning } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void DontSeeTheEarlierRowsTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row // insert a row at position 0 DataRow r = _dt.NewRow(); r[0] = 0; r[1] = "adhi bagavan"; _dt.Rows.InsertAt(r, 0); Assert.Equal(2, reader.GetInt32(0)); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void AddBeforePointTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row DataRow r = _dt.NewRow(); r[0] = 0; r[1] = "adhi bagavan"; _dt.Rows.InsertAt(r, 0); _dt.Rows.Add(new object[] { 4, "mono 4" }); // should not affect the counter Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void AddAtPointTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row DataRow r = _dt.NewRow(); r[0] = 0; r[1] = "same point"; _dt.Rows.InsertAt(r, 1); _dt.Rows.Add(new object[] { 4, "mono 4" }); // should not affect the counter Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void DeletePreviousAndAcceptChangesTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row _dt.Rows[0].Delete(); _dt.AcceptChanges(); Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void DeleteCurrentAndAcceptChangesTest2() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row _dt.Rows[1].Delete(); // delete row, where reader points to _dt.AcceptChanges(); // accept the action Assert.Equal(1, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void DeleteFirstCurrentAndAcceptChangesTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row _dt.Rows[0].Delete(); // delete row, where reader points to _dt.AcceptChanges(); // accept the action Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void DeleteLastAndAcceptChangesTest2() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row reader.Read(); // third row _dt.Rows[2].Delete(); // delete row, where reader points to _dt.AcceptChanges(); // accept the action Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void ClearTest() { DataTableReader reader = null; try { reader = new DataTableReader(_dt); reader.Read(); // first row reader.Read(); // second row _dt.Clear(); try { int i = (int)reader[0]; i++; // suppress warning Assert.False(true); } catch (RowNotInTableException) { } // clear and add test reader.Close(); reader = new DataTableReader(_dt); reader.Read(); // first row reader.Read(); // second row _dt.Clear(); _dt.Rows.Add(new object[] { 8, "mono 8" }); _dt.AcceptChanges(); bool success = reader.Read(); Assert.False(success); // clear when reader is not read yet reader.Close(); reader = new DataTableReader(_dt); _dt.Clear(); _dt.Rows.Add(new object[] { 8, "mono 8" }); _dt.AcceptChanges(); success = reader.Read(); Assert.True(success); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void MultipleDeleteTest() { _dt.Rows.Add(new object[] { 4, "mono 4" }); _dt.Rows.Add(new object[] { 5, "mono 5" }); _dt.Rows.Add(new object[] { 6, "mono 6" }); _dt.Rows.Add(new object[] { 7, "mono 7" }); _dt.Rows.Add(new object[] { 8, "mono 8" }); _dt.AcceptChanges(); DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); reader.Read(); reader.Read(); reader.Read(); _dt.Rows[3].Delete(); _dt.Rows[1].Delete(); _dt.Rows[2].Delete(); _dt.Rows[0].Delete(); _dt.Rows[6].Delete(); _dt.AcceptChanges(); Assert.Equal(5, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } #endregion // Negative Tests [Fact] public void TestSchemaTable() { var ds = new DataSet(); DataTable testTable = new DataTable("TestTable1"); DataTable testTable1 = new DataTable(); testTable.Namespace = "TableNamespace"; testTable1.Columns.Add("col1", typeof(int)); testTable1.Columns.Add("col2", typeof(int)); ds.Tables.Add(testTable); ds.Tables.Add(testTable1); //create a col for standard datatype testTable.Columns.Add("col_string"); testTable.Columns.Add("col_string_fixed"); testTable.Columns["col_string_fixed"].MaxLength = 10; testTable.Columns.Add("col_int", typeof(int)); testTable.Columns.Add("col_decimal", typeof(decimal)); testTable.Columns.Add("col_datetime", typeof(DateTime)); testTable.Columns.Add("col_float", typeof(float)); // Check for col constraints/properties testTable.Columns.Add("col_readonly").ReadOnly = true; testTable.Columns.Add("col_autoincrement", typeof(long)).AutoIncrement = true; testTable.Columns["col_autoincrement"].AutoIncrementStep = 5; testTable.Columns["col_autoincrement"].AutoIncrementSeed = 10; testTable.Columns.Add("col_pk"); testTable.PrimaryKey = new DataColumn[] { testTable.Columns["col_pk"] }; testTable.Columns.Add("col_unique"); testTable.Columns["col_unique"].Unique = true; testTable.Columns.Add("col_defaultvalue"); testTable.Columns["col_defaultvalue"].DefaultValue = "DefaultValue"; testTable.Columns.Add("col_expression_local", typeof(int)); testTable.Columns["col_expression_local"].Expression = "col_int*5"; ds.Relations.Add("rel", new DataColumn[] { testTable1.Columns["col1"] }, new DataColumn[] { testTable.Columns["col_int"] }, false); testTable.Columns.Add("col_expression_ext"); testTable.Columns["col_expression_ext"].Expression = "parent.col2"; testTable.Columns.Add("col_namespace"); testTable.Columns["col_namespace"].Namespace = "ColumnNamespace"; testTable.Columns.Add("col_mapping"); testTable.Columns["col_mapping"].ColumnMapping = MappingType.Attribute; DataTable schemaTable = testTable.CreateDataReader().GetSchemaTable(); Assert.Equal(25, schemaTable.Columns.Count); Assert.Equal(testTable.Columns.Count, schemaTable.Rows.Count); //True for all rows for (int i = 0; i < schemaTable.Rows.Count; ++i) { Assert.Equal(testTable.TableName, schemaTable.Rows[i]["BaseTableName"]); Assert.Equal(ds.DataSetName, schemaTable.Rows[i]["BaseCatalogName"]); Assert.Equal(DBNull.Value, schemaTable.Rows[i]["BaseSchemaName"]); Assert.Equal(schemaTable.Rows[i]["BaseColumnName"], schemaTable.Rows[i]["ColumnName"]); Assert.False((bool)schemaTable.Rows[i]["IsRowVersion"]); } Assert.Equal("col_string", schemaTable.Rows[0]["ColumnName"]); Assert.Equal(typeof(string), schemaTable.Rows[0]["DataType"]); Assert.Equal(-1, schemaTable.Rows[0]["ColumnSize"]); Assert.Equal(0, schemaTable.Rows[0]["ColumnOrdinal"]); // ms.net contradicts documented behavior Assert.False((bool)schemaTable.Rows[0]["IsLong"]); Assert.Equal("col_string_fixed", schemaTable.Rows[1]["ColumnName"]); Assert.Equal(typeof(string), schemaTable.Rows[1]["DataType"]); Assert.Equal(10, schemaTable.Rows[1]["ColumnSize"]); Assert.Equal(1, schemaTable.Rows[1]["ColumnOrdinal"]); Assert.False((bool)schemaTable.Rows[1]["IsLong"]); Assert.Equal("col_int", schemaTable.Rows[2]["ColumnName"]); Assert.Equal(typeof(int), schemaTable.Rows[2]["DataType"]); Assert.Equal(DBNull.Value, schemaTable.Rows[2]["NumericPrecision"]); Assert.Equal(DBNull.Value, schemaTable.Rows[2]["NumericScale"]); Assert.Equal(-1, schemaTable.Rows[2]["ColumnSize"]); Assert.Equal(2, schemaTable.Rows[2]["ColumnOrdinal"]); Assert.Equal("col_decimal", schemaTable.Rows[3]["ColumnName"]); Assert.Equal(typeof(decimal), schemaTable.Rows[3]["DataType"]); // When are the Precision and Scale Values set ? Assert.Equal(DBNull.Value, schemaTable.Rows[3]["NumericPrecision"]); Assert.Equal(DBNull.Value, schemaTable.Rows[3]["NumericScale"]); Assert.Equal(-1, schemaTable.Rows[3]["ColumnSize"]); Assert.Equal(3, schemaTable.Rows[3]["ColumnOrdinal"]); Assert.Equal("col_datetime", schemaTable.Rows[4]["ColumnName"]); Assert.Equal(typeof(DateTime), schemaTable.Rows[4]["DataType"]); Assert.Equal(4, schemaTable.Rows[4]["ColumnOrdinal"]); Assert.Equal("col_float", schemaTable.Rows[5]["ColumnName"]); Assert.Equal(typeof(float), schemaTable.Rows[5]["DataType"]); Assert.Equal(5, schemaTable.Rows[5]["ColumnOrdinal"]); Assert.Equal(DBNull.Value, schemaTable.Rows[5]["NumericPrecision"]); Assert.Equal(DBNull.Value, schemaTable.Rows[5]["NumericScale"]); Assert.Equal(-1, schemaTable.Rows[5]["ColumnSize"]); Assert.Equal("col_readonly", schemaTable.Rows[6]["ColumnName"]); Assert.True((bool)schemaTable.Rows[6]["IsReadOnly"]); Assert.Equal("col_autoincrement", schemaTable.Rows[7]["ColumnName"]); Assert.True((bool)schemaTable.Rows[7]["IsAutoIncrement"]); Assert.Equal(10L, schemaTable.Rows[7]["AutoIncrementSeed"]); Assert.Equal(5L, schemaTable.Rows[7]["AutoIncrementStep"]); Assert.False((bool)schemaTable.Rows[7]["IsReadOnly"]); Assert.Equal("col_pk", schemaTable.Rows[8]["ColumnName"]); Assert.True((bool)schemaTable.Rows[8]["IsKey"]); Assert.True((bool)schemaTable.Rows[8]["IsUnique"]); Assert.Equal("col_unique", schemaTable.Rows[9]["ColumnName"]); Assert.True((bool)schemaTable.Rows[9]["IsUnique"]); Assert.Equal("col_defaultvalue", schemaTable.Rows[10]["ColumnName"]); Assert.Equal("DefaultValue", schemaTable.Rows[10]["DefaultValue"]); Assert.Equal("col_expression_local", schemaTable.Rows[11]["ColumnName"]); Assert.Equal("col_int*5", schemaTable.Rows[11]["Expression"]); Assert.True((bool)schemaTable.Rows[11]["IsReadOnly"]); // if expression depends on a external col, then set Expression as null.. Assert.Equal("col_expression_ext", schemaTable.Rows[12]["ColumnName"]); Assert.Equal(DBNull.Value, schemaTable.Rows[12]["Expression"]); Assert.True((bool)schemaTable.Rows[12]["IsReadOnly"]); Assert.Equal("col_namespace", schemaTable.Rows[13]["ColumnName"]); Assert.Equal("TableNamespace", schemaTable.Rows[13]["BaseTableNamespace"]); Assert.Equal("TableNamespace", schemaTable.Rows[12]["BaseColumnNamespace"]); Assert.Equal("ColumnNamespace", schemaTable.Rows[13]["BaseColumnNamespace"]); Assert.Equal("col_mapping", schemaTable.Rows[14]["ColumnName"]); Assert.Equal(MappingType.Element, (MappingType)schemaTable.Rows[13]["ColumnMapping"]); Assert.Equal(MappingType.Attribute, (MappingType)schemaTable.Rows[14]["ColumnMapping"]); } [Fact] public void TestExceptionIfSchemaChanges() { DataTable table = new DataTable(); table.Columns.Add("col1"); DataTableReader rdr = table.CreateDataReader(); Assert.Equal(1, rdr.GetSchemaTable().Rows.Count); table.Columns[0].ColumnName = "newcol1"; try { rdr.GetSchemaTable(); Assert.False(true); } catch (InvalidOperationException) { // Never premise English. //Assert.Equal ("Schema of current DataTable '" + table.TableName + // "' in DataTableReader has changed, DataTableReader is invalid.", e.Message, "#1"); } rdr = table.CreateDataReader(); rdr.GetSchemaTable(); //no exception table.Columns.Add("col2"); try { rdr.GetSchemaTable(); Assert.False(true); } catch (InvalidOperationException) { // Never premise English. //Assert.Equal ("Schema of current DataTable '" + table.TableName + // "' in DataTableReader has changed, DataTableReader is invalid.", e.Message, "#1"); } } [Fact] public void EnumeratorTest() { DataTable table = new DataTable(); table.Columns.Add("col1", typeof(int)); table.Rows.Add(new object[] { 0 }); table.Rows.Add(new object[] { 1 }); DataTableReader rdr = table.CreateDataReader(); IEnumerator enmr = rdr.GetEnumerator(); table.Rows.Add(new object[] { 2 }); table.Rows.RemoveAt(0); //Test if the Enumerator is stable int i = 1; while (enmr.MoveNext()) { DbDataRecord rec = (DbDataRecord)enmr.Current; Assert.Equal(i, rec.GetInt32(0)); i++; } } [Fact] public void GetCharsTest() { _dt.Columns.Add("col2", typeof(char[])); _dt.Rows.Clear(); _dt.Rows.Add(new object[] { 1, "string", "string".ToCharArray() }); _dt.Rows.Add(new object[] { 2, "string1", null }); DataTableReader rdr = _dt.CreateDataReader(); rdr.Read(); try { rdr.GetChars(1, 0, null, 0, 10); Assert.False(true); } catch (InvalidCastException e) { // Never premise English. //Assert.Equal ("Unable to cast object of type 'System.String'" + // " to type 'System.Char[]'.", e.Message, "#1"); } char[] char_arr = null; long len = 0; len = rdr.GetChars(2, 0, null, 0, 0); Assert.Equal(6, len); char_arr = new char[len]; len = rdr.GetChars(2, 0, char_arr, 0, 0); Assert.Equal(0, len); len = rdr.GetChars(2, 0, null, 0, 0); char_arr = new char[len + 2]; len = rdr.GetChars(2, 0, char_arr, 2, 100); Assert.Equal(6, len); char[] val = (char[])rdr.GetValue(2); for (int i = 0; i < len; ++i) Assert.Equal(val[i], char_arr[i + 2]); } [Fact] public void GetProviderSpecificTests() { DataTableReader rdr = _dt.CreateDataReader(); while (rdr.Read()) { object[] values = new object[rdr.FieldCount]; object[] pvalues = new object[rdr.FieldCount]; rdr.GetValues(values); rdr.GetProviderSpecificValues(pvalues); for (int i = 0; i < rdr.FieldCount; ++i) { Assert.Equal(values[i], pvalues[i]); Assert.Equal(rdr.GetValue(i), rdr.GetProviderSpecificValue(i)); Assert.Equal(rdr.GetFieldType(i), rdr.GetProviderSpecificFieldType(i)); } } } [Fact] public void GetNameTest() { DataTableReader rdr = _dt.CreateDataReader(); for (int i = 0; i < _dt.Columns.Count; ++i) Assert.Equal(_dt.Columns[i].ColumnName, rdr.GetName(i)); } } }
#pragma warning disable 162,108,618 using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; using UnityEngine; namespace Game { public class World : MonoBehaviour { public static int frame; void Update() { Update(Time.deltaTime, this); frame++; } public bool JustEntered = true; public void Start() { SelectedCubeToDestroy = (new Nothing<Cube>()); Cubes = ( Enumerable.Empty<Cube>()).ToList<Cube>(); } public List<Cube> Cubes; public Option<Cube> SelectedCubeToDestroy; public System.Single count_down1; public Cube ___selected_element40; System.DateTime init_time = System.DateTime.Now; public void Update(float dt, World world) { var t = System.DateTime.Now; for (int x0 = 0; x0 < Cubes.Count; x0++) { Cubes[x0].Update(dt, world); } this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); this.Rule4(dt, world); } int s0 = -1; public void Rule0(float dt, World world) { switch (s0) { case -1: if (!(UnityEngine.Input.GetKeyDown(KeyCode.P))) { s0 = -1; return; } else { goto case 0; } case 0: Cubes = new Cons<Cube>(new Cube(Color.white), (Cubes)).ToList<Cube>(); s0 = -1; return; default: return; } } int s1 = -1; public void Rule1(float dt, World world) { if (s1 > 0 && UnityEngine.Input.GetKeyDown(KeyCode.Q)) s1 = -1; else if (s1 > 1 && UnityEngine.Input.GetKeyDown(KeyCode.S)) s1 = -1; switch (s1) { case -1: if (!(((UnityEngine.Input.GetKeyDown(KeyCode.Q)) || (UnityEngine.Input.GetKeyDown(KeyCode.S))))) { s1 = -1; return; } else { goto case 0; } case 0: if (UnityEngine.Input.GetKeyDown(KeyCode.Q)) { goto case 2; } else { if (UnityEngine.Input.GetKeyDown(KeyCode.S)) { goto case 3; } else { s1 = 0; return; } } case 2: UnityEngine.Debug.Log("Hello"); Cubes = Cubes; s1 = -1; return; case 3: if (!(true)) { s1 = -1; return; } else { goto case 7; } case 7: Cubes = new Cons<Cube>(new Cube(Color.white), (Cubes)).ToList<Cube>(); s1 = 8; return; case 8: count_down1 = 1f; goto case 9; case 9: if (((count_down1) > (0f))) { count_down1 = ((count_down1) - (dt)); s1 = 9; return; } else { s1 = 3; return; } default: return; } } int s2 = -1; public void Rule2(float dt, World world) { switch (s2) { case -1: Cubes = ( (Cubes).Select(__ContextSymbol1 => new { ___c20 = __ContextSymbol1 }) .Where(__ContextSymbol2 => !(__ContextSymbol2.___c20.Destroyed)) .Select(__ContextSymbol3 => __ContextSymbol3.___c20) .ToList<Cube>()).ToList<Cube>(); s2 = -1; return; default: return; } } int s3 = -1; public void Rule3(float dt, World world) { switch (s3) { case -1: if (!(((SelectedCubeToDestroy.IsSome) && (SelectedCubeToDestroy.Value.Destroyed)))) { s3 = -1; return; } else { goto case 0; } case 0: SelectedCubeToDestroy = (new Nothing<Cube>()); s3 = -1; return; default: return; } } int s4 = -1; public void Rule4(float dt, World world) { switch (s4) { case -1: if (!(((UnityEngine.Input.GetKeyDown(KeyCode.R)) && (((Cubes.Count) > (0)))))) { s4 = -1; return; } else { goto case 1; } case 1: ___selected_element40 = (Cubes)[UnityEngine.Random.Range(0, Cubes.Count)]; SelectedCubeToDestroy = (new Just<Cube>(___selected_element40)); s4 = -1; return; default: return; } } } public class Cube { public int frame; public bool JustEntered = true; private UnityEngine.Color color; public int ID; public Cube(UnityEngine.Color color) { JustEntered = false; frame = World.frame; UnityCube ___cube00; ___cube00 = UnityCube.Instantiate(color); System.Single ___dist00; ___dist00 = 3f; List<UnityEngine.Vector3> ___checkpoints00; ___checkpoints00 = ( (new Cons<UnityEngine.Vector3>(new UnityEngine.Vector3((___cube00.Position.x) + (___dist00), ___cube00.Position.y, ___cube00.Position.z), (new Cons<UnityEngine.Vector3>(new UnityEngine.Vector3((___cube00.Position.x) + (___dist00), (___cube00.Position.y) + (___dist00), ___cube00.Position.z), (new Cons<UnityEngine.Vector3>(new UnityEngine.Vector3(___cube00.Position.x, (___cube00.Position.y) + (___dist00), ___cube00.Position.z), (new Cons<UnityEngine.Vector3>(___cube00.Position, (new Empty<UnityEngine.Vector3>()).ToList<UnityEngine.Vector3>())).ToList<UnityEngine.Vector3>())).ToList<UnityEngine.Vector3>())).ToList<UnityEngine.Vector3>())).ToList<UnityEngine.Vector3>()).ToList<UnityEngine.Vector3>(); Velocity = Vector3.zero; UnityCube = ___cube00; Factor = 2f; Checkpoints = ___checkpoints00; } public List<UnityEngine.Vector3> Checkpoints; public UnityEngine.Color Color { set { UnityCube.Color = value; } } public System.Boolean Destroyed { get { return UnityCube.Destroyed; } set { UnityCube.Destroyed = value; } } public System.Single Factor; public UnityEngine.Vector3 Position { get { return UnityCube.Position; } set { UnityCube.Position = value; } } public UnityEngine.Vector3 Scale { get { return UnityCube.Scale; } set { UnityCube.Scale = value; } } public UnityCube UnityCube; public UnityEngine.Vector3 Velocity; public System.Boolean enabled { get { return UnityCube.enabled; } set { UnityCube.enabled = value; } } public UnityEngine.GameObject gameObject { get { return UnityCube.gameObject; } } public UnityEngine.HideFlags hideFlags { get { return UnityCube.hideFlags; } set { UnityCube.hideFlags = value; } } public System.Boolean isActiveAndEnabled { get { return UnityCube.isActiveAndEnabled; } } public System.String name { get { return UnityCube.name; } set { UnityCube.name = value; } } public System.String tag { get { return UnityCube.tag; } set { UnityCube.tag = value; } } public UnityEngine.Transform transform { get { return UnityCube.transform; } } public System.Boolean useGUILayout { get { return UnityCube.useGUILayout; } set { UnityCube.useGUILayout = value; } } public UnityEngine.Vector3 ___c11; public System.Int32 counter21; public UnityEngine.Vector3 ___dir010; public System.Single count_down2; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); } int s0 = -1; public void Rule0(float dt, World world) { switch (s0) { case -1: Position = ((Position) + (((Velocity) * (dt)))); s0 = -1; return; default: return; } } int s1 = -1; public void Rule1(float dt, World world) { switch (s1) { case -1: counter21 = -1; if ((((Checkpoints).Count) == (0))) { goto case 0; } else { ___c11 = (Checkpoints)[0]; goto case 2; } case 2: counter21 = ((counter21) + (1)); if ((((((Checkpoints).Count) == (counter21))) || (((counter21) > ((Checkpoints).Count))))) { goto case 0; } else { ___c11 = (Checkpoints)[counter21]; goto case 3; } case 3: ___dir010 = ((___c11) - (Position)); Position = Position; Velocity = ___dir010.normalized; Destroyed = Destroyed; s1 = 7; return; case 7: if (!(((0f) > (UnityEngine.Vector3.Dot(___dir010, (___c11) - (Position)))))) { s1 = 7; return; } else { goto case 6; } case 6: Position = ___c11; Velocity = Vector3.zero; Destroyed = Destroyed; s1 = 4; return; case 4: count_down2 = 1f; goto case 5; case 5: if (((count_down2) > (0f))) { count_down2 = ((count_down2) - (dt)); s1 = 5; return; } else { s1 = 2; return; } case 0: Position = Position; Velocity = Velocity; Destroyed = true; s1 = -1; return; default: return; } } int s2 = -1; public void Rule2(float dt, World world) { switch (s2) { case -1: if (!(((world.SelectedCubeToDestroy.IsSome) && (((world.SelectedCubeToDestroy.Value) == (this)))))) { s2 = -1; return; } else { goto case 1; } case 1: if (!(((Factor) > (0f)))) { goto case 0; } else { goto case 2; } case 2: Scale = ((Scale) + (((Vector3.one) * (dt)))); Factor = ((Factor) - (dt)); Destroyed = Destroyed; s2 = 1; return; case 0: Scale = Scale; Factor = Factor; Destroyed = true; s2 = -1; return; default: return; } } } }
// 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 Rotorz.Games.Collections { /// <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.Instance.Container); DefaultListControl.FooterButtonStyle = new GUIStyle(ReorderableListStyles.Instance.FooterButton); DefaultListControl.ItemButtonStyle = new GUIStyle(ReorderableListStyles.Instance.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> /// </example> /// <param name="title">Content for title control.</param> public static void Title(GUIContent title) { Rect position = GUILayoutUtility.GetRect(title, ReorderableListStyles.Instance.Title); Title(position, title); GUILayout.Space(-1); } /// <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> /// </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.Instance.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 } }
using System; using System.Collections.Generic; using NinthChevron.Data; using NinthChevron.Data.Entity; using NinthChevron.Helpers; using NinthChevron.ComponentModel.DataAnnotations; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.HumanResourcesSchema; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.PersonSchema; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.ProductionSchema; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.SalesSchema; namespace NinthChevron.Data.SqlServer.Test.AdventureWorks2012.PurchasingSchema { [Table("ProductVendor", "Purchasing", "AdventureWorks2012")] public partial class ProductVendor : Entity<ProductVendor> { static ProductVendor() { Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation Join<UnitMeasure>(t => t.UnitMeasureCodeUnitMeasure, (t, f) => t.UnitMeasureCode == f.UnitMeasureCode); // Relation Join<Vendor>(t => t.BusinessEntityVendor, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)] public int BusinessEntityID { get; set; } [NotifyPropertyChanged, Column("AverageLeadTime", true, false, false)] public int AverageLeadTime { get; set; } [NotifyPropertyChanged, Column("StandardPrice", true, false, false)] public object StandardPrice { get; set; } [NotifyPropertyChanged, Column("LastReceiptCost", true, false, true)] public object LastReceiptCost { get; set; } [NotifyPropertyChanged, Column("LastReceiptDate", false, false, true)] public System.Nullable<System.DateTime> LastReceiptDate { get; set; } [NotifyPropertyChanged, Column("MinOrderQty", true, false, false)] public int MinOrderQty { get; set; } [NotifyPropertyChanged, Column("MaxOrderQty", true, false, false)] public int MaxOrderQty { get; set; } [NotifyPropertyChanged, Column("OnOrderQty", true, false, true)] public System.Nullable<int> OnOrderQty { get; set; } [NotifyPropertyChanged, Column("UnitMeasureCode", true, false, false)] public string UnitMeasureCode { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } [InnerJoinColumn] public UnitMeasure UnitMeasureCodeUnitMeasure { get; set; } [InnerJoinColumn] public Vendor BusinessEntityVendor { get; set; } } [Table("PurchaseOrderDetail", "Purchasing", "AdventureWorks2012")] public partial class PurchaseOrderDetail : Entity<PurchaseOrderDetail> { static PurchaseOrderDetail() { Join<Product>(t => t.ProductProduct, (t, f) => t.ProductID == f.ProductID); // Relation Join<PurchaseOrderHeader>(t => t.PurchaseOrderPurchaseOrderHeader, (t, f) => t.PurchaseOrderID == f.PurchaseOrderID); // Relation } [NotifyPropertyChanged, Column("PurchaseOrderID", true, false, false)] public int PurchaseOrderID { get; set; } [NotifyPropertyChanged, Column("PurchaseOrderDetailID", true, true, false)] public int PurchaseOrderDetailID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("DueDate", false, false, false)] public System.DateTime DueDate { get; set; } [NotifyPropertyChanged, Column("OrderQty", true, false, false)] public short OrderQty { get; set; } [NotifyPropertyChanged, Column("ProductID", true, false, false)] public int ProductID { get; set; } [NotifyPropertyChanged, Column("UnitPrice", true, false, false)] public object UnitPrice { get; set; } [NotifyPropertyChanged, Column("LineTotal", false, false, false)] public object LineTotal { get; set; } [NotifyPropertyChanged, Column("ReceivedQty", true, false, false)] public decimal ReceivedQty { get; set; } [NotifyPropertyChanged, Column("RejectedQty", true, false, false)] public decimal RejectedQty { get; set; } [NotifyPropertyChanged, Column("StockedQty", false, false, false)] public decimal StockedQty { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Product ProductProduct { get; set; } [InnerJoinColumn] public PurchaseOrderHeader PurchaseOrderPurchaseOrderHeader { get; set; } } [Table("PurchaseOrderHeader", "Purchasing", "AdventureWorks2012")] public partial class PurchaseOrderHeader : Entity<PurchaseOrderHeader> { static PurchaseOrderHeader() { Join<Employee>(t => t.EmployeeEmployee, (t, f) => t.EmployeeID == f.BusinessEntityID); // Relation Join<PurchaseOrderDetail>(t => t.PurchaseOrderPurchaseOrderDetail, (t, f) => t.PurchaseOrderID == f.PurchaseOrderID); // Reverse Relation Join<ShipMethod>(t => t.ShipMethodShipMethod, (t, f) => t.ShipMethodID == f.ShipMethodID); // Relation Join<Vendor>(t => t.VendorVendor, (t, f) => t.VendorID == f.BusinessEntityID); // Relation } [NotifyPropertyChanged, Column("PurchaseOrderID", true, true, false)] public int PurchaseOrderID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("RevisionNumber", false, false, false)] public byte RevisionNumber { get; set; } [NotifyPropertyChanged, Column("Status", true, false, false)] public byte Status { get; set; } [NotifyPropertyChanged, Column("EmployeeID", true, false, false)] public int EmployeeID { get; set; } [NotifyPropertyChanged, Column("VendorID", true, false, false)] public int VendorID { get; set; } [NotifyPropertyChanged, Column("ShipMethodID", true, false, false)] public int ShipMethodID { get; set; } [NotifyPropertyChanged, Column("OrderDate", true, false, false)] public System.DateTime OrderDate { get; set; } [NotifyPropertyChanged, Column("ShipDate", true, false, true)] public System.Nullable<System.DateTime> ShipDate { get; set; } [NotifyPropertyChanged, Column("SubTotal", true, false, false)] public object SubTotal { get; set; } [NotifyPropertyChanged, Column("TaxAmt", true, false, false)] public object TaxAmt { get; set; } [NotifyPropertyChanged, Column("Freight", true, false, false)] public object Freight { get; set; } [NotifyPropertyChanged, Column("TotalDue", false, false, false)] public object TotalDue { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Employee EmployeeEmployee { get; set; } [InnerJoinColumn] public PurchaseOrderDetail PurchaseOrderPurchaseOrderDetail { get; set; } [InnerJoinColumn] public ShipMethod ShipMethodShipMethod { get; set; } [InnerJoinColumn] public Vendor VendorVendor { get; set; } } [Table("ShipMethod", "Purchasing", "AdventureWorks2012")] public partial class ShipMethod : Entity<ShipMethod> { static ShipMethod() { Join<PurchaseOrderHeader>(t => t.ShipMethodPurchaseOrderHeader, (t, f) => t.ShipMethodID == f.ShipMethodID); // Reverse Relation Join<SalesOrderHeader>(t => t.ShipMethodSalesOrderHeader, (t, f) => t.ShipMethodID == f.ShipMethodID); // Reverse Relation } [NotifyPropertyChanged, Column("ShipMethodID", true, true, false)] public int ShipMethodID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("ShipBase", true, false, false)] public object ShipBase { get; set; } [NotifyPropertyChanged, Column("ShipRate", true, false, false)] public object ShipRate { get; set; } [NotifyPropertyChanged, Column("rowguid", false, false, false)] public System.Guid Rowguid { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public PurchaseOrderHeader ShipMethodPurchaseOrderHeader { get; set; } [InnerJoinColumn] public SalesOrderHeader ShipMethodSalesOrderHeader { get; set; } } [Table("Vendor", "Purchasing", "AdventureWorks2012")] public partial class Vendor : Entity<Vendor> { static Vendor() { Join<BusinessEntity>(t => t.BusinessEntityBusinessEntity, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation Join<PurchaseOrderHeader>(t => t.VendorPurchaseOrderHeader, (t, f) => t.BusinessEntityID == f.VendorID); // Reverse Relation Join<ProductVendor>(t => t.BusinessEntityProductVendor, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Reverse Relation } [NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)] public int BusinessEntityID { get; set; } [NotifyPropertyChanged, Column("AccountNumber", false, false, false)] public string AccountNumber { get; set; } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("CreditRating", true, false, false)] public byte CreditRating { get; set; } [NotifyPropertyChanged, Column("PreferredVendorStatus", false, false, false)] public bool PreferredVendorStatus { get; set; } [NotifyPropertyChanged, Column("ActiveFlag", false, false, false)] public bool ActiveFlag { get; set; } [NotifyPropertyChanged, Column("PurchasingWebServiceURL", false, false, true)] public string PurchasingWebServiceURL { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public BusinessEntity BusinessEntityBusinessEntity { get; set; } [InnerJoinColumn] public PurchaseOrderHeader VendorPurchaseOrderHeader { get; set; } [InnerJoinColumn] public ProductVendor BusinessEntityProductVendor { get; set; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Data; namespace OpenSim.Data.MySQL { public class MySQLEstateStore : IEstateDataStore { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string m_waitTimeoutSelect = "select @@wait_timeout"; private string m_connectionString; private long m_waitTimeout; private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond; // private long m_lastConnectionUse; private FieldInfo[] m_Fields; private Dictionary<string, FieldInfo> m_FieldMap = new Dictionary<string, FieldInfo>(); protected virtual Assembly Assembly { get { return GetType().Assembly; } } public MySQLEstateStore() { } public MySQLEstateStore(string connectionString) { Initialise(connectionString); } public void Initialise(string connectionString) { m_connectionString = connectionString; try { m_log.Info("[REGION DB]: MySql - connecting: " + Util.GetDisplayConnectionString(m_connectionString)); } catch (Exception e) { m_log.Debug("Exception: password not found in connection string\n" + e.ToString()); } GetWaitTimeout(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "EstateStore"); m.Update(); Type t = typeof(EstateSettings); m_Fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo f in m_Fields) { if (f.Name.Substring(0, 2) == "m_") m_FieldMap[f.Name.Substring(2)] = f; } } } private string[] FieldList { get { return new List<string>(m_FieldMap.Keys).ToArray(); } } protected void GetWaitTimeout() { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon)) { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { m_waitTimeout = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; } } } // m_lastConnectionUse = DateTime.Now.Ticks; m_log.DebugFormat( "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond); } } public EstateSettings LoadEstateSettings(UUID regionID, bool create) { string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = ?RegionID"; using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = sql; cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); return DoLoad(cmd, regionID, create); } } public EstateSettings CreateNewEstate() { EstateSettings es = new EstateSettings(); es.OnSave += StoreEstateSettings; DoCreate(es); LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); return es; } private EstateSettings DoLoad(MySqlCommand cmd, UUID regionID, bool create) { EstateSettings es = new EstateSettings(); es.OnSave += StoreEstateSettings; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); cmd.Connection = dbcon; bool found = false; using (IDataReader r = cmd.ExecuteReader()) { if (r.Read()) { found = true; foreach (string name in FieldList) { if (m_FieldMap[name].FieldType == typeof(bool)) { m_FieldMap[name].SetValue(es, Convert.ToInt32(r[name]) != 0); } else if (m_FieldMap[name].FieldType == typeof(UUID)) { m_FieldMap[name].SetValue(es, DBGuid.FromDB(r[name])); } else { m_FieldMap[name].SetValue(es, r[name]); } } } } if (!found && create) { DoCreate(es); LinkRegion(regionID, (int)es.EstateID); } } LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); return es; } private void DoCreate(EstateSettings es) { // Migration case List<string> names = new List<string>(FieldList); names.Remove("EstateID"); string sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd2 = dbcon.CreateCommand()) { cmd2.CommandText = sql; cmd2.Parameters.Clear(); foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd2.Parameters.AddWithValue("?" + name, "1"); else cmd2.Parameters.AddWithValue("?" + name, "0"); } else { cmd2.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd2.ExecuteNonQuery(); cmd2.CommandText = "select LAST_INSERT_ID() as id"; cmd2.Parameters.Clear(); using (IDataReader r = cmd2.ExecuteReader()) { r.Read(); es.EstateID = Convert.ToUInt32(r["id"]); } es.Save(); } } } public void StoreEstateSettings(EstateSettings es) { string sql = "replace into estate_settings (" + String.Join(",", FieldList) + ") values ( ?" + String.Join(", ?", FieldList) + ")"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd.Parameters.AddWithValue("?" + name, "1"); else cmd.Parameters.AddWithValue("?" + name, "0"); } else { cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd.ExecuteNonQuery(); } } SaveBanList(es); SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); } private void LoadBanList(EstateSettings es) { es.ClearBans(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { EstateBan eb = new EstateBan(); UUID uuid = new UUID(); UUID.TryParse(r["bannedUUID"].ToString(), out uuid); eb.BannedUserID = uuid; eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0"; es.AddBan(eb); } } } } } private void SaveBanList(EstateSettings es) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )"; foreach (EstateBan b in es.EstateBans) { cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } void SaveUUIDList(uint EstateID, string table, UUID[] data) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )"; foreach (UUID uuid in data) { cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.Parameters.AddWithValue("?uuid", uuid.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } UUID[] LoadUUIDList(uint EstateID, string table) { List<UUID> uuids = new List<UUID>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { // EstateBan eb = new EstateBan(); uuids.Add(DBGuid.FromDB(r["uuid"])); } } } } return uuids.ToArray(); } public EstateSettings LoadEstateSettings(int estateID) { using (MySqlCommand cmd = new MySqlCommand()) { string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_settings where EstateID = ?EstateID"; cmd.CommandText = sql; cmd.Parameters.AddWithValue("?EstateID", estateID); return DoLoad(cmd, UUID.Zero, false); } } public List<EstateSettings> LoadEstateSettingsAll() { List<EstateSettings> allEstateSettings = new List<EstateSettings>(); List<int> allEstateIds = GetEstatesAll(); foreach (int estateId in allEstateIds) allEstateSettings.Add(LoadEstateSettings(estateId)); return allEstateSettings; } public List<int> GetEstatesAll() { List<int> result = new List<int>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select estateID from estate_settings"; using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } dbcon.Close(); } return result; } public List<int> GetEstates(string search) { List<int> result = new List<int>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select estateID from estate_settings where EstateName = ?EstateName"; cmd.Parameters.AddWithValue("?EstateName", search); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } dbcon.Close(); } return result; } public List<int> GetEstatesByOwner(UUID ownerID) { List<int> result = new List<int>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select estateID from estate_settings where EstateOwner = ?EstateOwner"; cmd.Parameters.AddWithValue("?EstateOwner", ownerID); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } dbcon.Close(); } return result; } public bool LinkRegion(UUID regionID, int estateID) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); MySqlTransaction transaction = dbcon.BeginTransaction(); try { // Delete any existing association of this region with an estate. using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.Transaction = transaction; cmd.CommandText = "delete from estate_map where RegionID = ?RegionID"; cmd.Parameters.AddWithValue("?RegionID", regionID); cmd.ExecuteNonQuery(); } using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.Transaction = transaction; cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)"; cmd.Parameters.AddWithValue("?RegionID", regionID); cmd.Parameters.AddWithValue("?EstateID", estateID); int ret = cmd.ExecuteNonQuery(); if (ret != 0) transaction.Commit(); else transaction.Rollback(); dbcon.Close(); return (ret != 0); } } catch (MySqlException ex) { m_log.Error("[REGION DB]: LinkRegion failed: " + ex.Message); transaction.Rollback(); } dbcon.Close(); } return false; } public List<UUID> GetRegions(int estateID) { List<UUID> result = new List<UUID>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); try { using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select RegionID from estate_map where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", estateID.ToString()); using (IDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) result.Add(DBGuid.FromDB(reader["RegionID"])); reader.Close(); } } } catch (Exception e) { m_log.Error("[REGION DB]: Error reading estate map. " + e.ToString()); return result; } dbcon.Close(); } return result; } public bool DeleteEstate(int estateID) { return false; } } }
using System; using UnityEngine; using UnityEngine.UI; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { public GameObject enemy; public Slider healthSlider; [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; //Brandon's Variables public static float health = 100f; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { this.healthSlider.value = health; RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; gunController (); } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void gunController() { if (Input.GetMouseButtonDown (0)) { EnemyController.underFire = true; } } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
// // RadioConnection.cs // // Authors: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Web; using System.Threading; using Hyena; using Hyena.Json; using Mono.Unix; using Media.Playlists.Xspf; namespace Lastfm { public class ConnectionStateChangedArgs : EventArgs { public ConnectionState State; public ConnectionStateChangedArgs (ConnectionState state) { State = state; } } public enum ConnectionState { Disconnected, NoAccount, NoNetwork, InvalidAccount, NotAuthorized, Connecting, Connected }; // Error codes returned by the API methods public enum StationError { None = 0, NotUsed = 1, InvalidService, InvalidMethod, AuthenticationFailed, InvalidFormat, InvalidParameters, InvalidResource, TokenFailure, InvalidSessionKey, InvalidApiKey, ServiceOffline, SubscriptionError, InvalidSignature, TokenNotAuthorized, ExpiredToken, SubscriptionRequired = 18, NotEnoughContent = 20, NotEnoughMembers, NotEnoughFans, NotEnoughNeighbours, Unknown // not an official code, just the fall back } public class RadioConnection { public delegate void StateChangedHandler (RadioConnection connection, ConnectionStateChangedArgs args); public event StateChangedHandler StateChanged; private ConnectionState state; private string info_message; private bool network_connected = false; public string InfoMessage { get { return info_message; } } public ConnectionState State { get { return state; } private set { if (value == state) return; state = value; Log.Debug (String.Format ("Last.fm State Changed to {0}", state), null); StateChangedHandler handler = StateChanged; if (handler != null) { handler (this, new ConnectionStateChangedArgs (state)); } } } public bool Connected { get { return state == ConnectionState.Connected; } } private string station; public string Station { get { return station; } } internal RadioConnection () { Initialize (); State = ConnectionState.Disconnected; LastfmCore.Account.Updated += HandleAccountUpdated; } public void Dispose () { LastfmCore.Account.Updated -= HandleAccountUpdated; } public void Connect () { if (State == ConnectionState.Connecting || State == ConnectionState.Connected) return; if (String.IsNullOrEmpty (LastfmCore.Account.UserName)) { State = ConnectionState.NoAccount; return; } if (String.IsNullOrEmpty (LastfmCore.Account.SessionKey)) { State = ConnectionState.NotAuthorized; return; } if (!network_connected) { State = ConnectionState.NoNetwork; return; } // Otherwise, we're good and consider ourselves connected State = ConnectionState.Connected; } public bool Love (string artist, string title) { return PostTrackRequest ("love", artist, title); } public bool Ban (string artist, string title) { return PostTrackRequest ("ban", artist, title); } public StationError ChangeStationTo (string station) { lock (this) { if (Station == station) return StationError.None; try { LastfmRequest radio_tune = new LastfmRequest ("radio.tune", RequestType.Write, ResponseFormat.Json); radio_tune.AddParameter ("station", station); radio_tune.Send (); StationError error = radio_tune.GetError (); if (error != StationError.None) { return error; } this.station = station; return StationError.None; } catch (Exception e) { Log.Exception (e); return StationError.Unknown; } } } public Playlist LoadPlaylistFor (string station) { lock (this) { if (station != Station) return null; Playlist pl = new Playlist (); Stream stream = null; LastfmRequest radio_playlist = new LastfmRequest ("radio.getPlaylist", RequestType.AuthenticatedRead, ResponseFormat.Raw); try { radio_playlist.Send (); stream = radio_playlist.GetResponseStream (); pl.Load (stream); Log.Debug (String.Format ("Adding {0} Tracks to Last.fm Station {1}", pl.TrackCount, station), null); } catch (System.Net.WebException e) { Log.Warning ("Error Loading Last.fm Station", e.Message, false); return null; } catch (Exception e) { string body = null; try { using (StreamReader strm = new StreamReader (stream)) { body = strm.ReadToEnd (); } } catch {} Log.Warning ( "Error loading station", String.Format ("Exception:\n{0}\n\nResponse:\n{1}", e.ToString (), body ?? "Unable to get response"), false ); return null; } return pl; } } // Private methods private void Initialize () { station = info_message = null; } private void HandleAccountUpdated (object o, EventArgs args) { State = ConnectionState.Disconnected; Connect (); } public void UpdateNetworkState (bool connected) { network_connected = connected; if (connected) { if (State == ConnectionState.NoNetwork) { Connect (); } } else { if (State == ConnectionState.Connected) { Initialize (); State = ConnectionState.NoNetwork; } } } // Translated error message strings public static string ErrorMessageFor (StationError error) { switch (error) { case StationError.InvalidService: case StationError.InvalidMethod: return Catalog.GetString ("This service does not exist."); case StationError.AuthenticationFailed: case StationError.SubscriptionError: case StationError.SubscriptionRequired: return Catalog.GetString ("This station is only available to subscribers."); case StationError.InvalidFormat: return Catalog.GetString ("This station is not available."); case StationError.InvalidParameters: return Catalog.GetString ("The request is missing a required parameter."); case StationError.InvalidResource: return Catalog.GetString ("The specified resource is invalid."); case StationError.TokenFailure: return Catalog.GetString ("Server error, please try again later."); case StationError.InvalidSessionKey: return Catalog.GetString ("Invalid authentication information, please re-authenticate."); case StationError.InvalidApiKey: return Catalog.GetString ("The API key used by this application is invalid."); case StationError.ServiceOffline: return Catalog.GetString ("The streaming system is offline for maintenance, please try again later."); case StationError.InvalidSignature: return Catalog.GetString ("The method signature is invalid."); case StationError.TokenNotAuthorized: case StationError.ExpiredToken: return Catalog.GetString ("You need to allow Banshee to access your Last.fm account."); case StationError.NotEnoughContent: return Catalog.GetString ("There is not enough content to play this station."); case StationError.NotEnoughMembers: return Catalog.GetString ("This group does not have enough members for radio."); case StationError.NotEnoughFans: return Catalog.GetString ("This artist does not have enough fans for radio."); case StationError.NotEnoughNeighbours: return Catalog.GetString ("There are not enough neighbours for this station."); case StationError.Unknown: return Catalog.GetString ("There was an unknown error."); } return String.Empty; } public static string MessageFor (ConnectionState state) { switch (state) { case ConnectionState.Disconnected: return Catalog.GetString ("Not connected to Last.fm."); case ConnectionState.NoAccount: return Catalog.GetString ("Account details are needed before you can connect to Last.fm"); case ConnectionState.NoNetwork: return Catalog.GetString ("No network connection detected."); case ConnectionState.InvalidAccount: return Catalog.GetString ("Last.fm username is invalid."); case ConnectionState.NotAuthorized: return Catalog.GetString ("You need to allow Banshee to access your Last.fm account."); case ConnectionState.Connecting: return Catalog.GetString ("Connecting to Last.fm."); case ConnectionState.Connected: return Catalog.GetString ("Connected to Last.fm."); } return String.Empty; } private bool PostTrackRequest (string method, string artist, string title) { if (State != ConnectionState.Connected) return false; // track.love and track.ban do not return JSON LastfmRequest track_request = new LastfmRequest (String.Concat ("track.", method), RequestType.Write, ResponseFormat.Raw); track_request.AddParameter ("track", title); track_request.AddParameter ("artist", artist); track_request.Send (); return (track_request.GetError () == StationError.None); } } }
// 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! namespace Google.Cloud.AutoML.V1.Snippets { using Google.LongRunning; using System.Collections.Generic; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedPredictionServiceClientSnippets { /// <summary>Snippet for Predict</summary> public void PredictRequestObject() { // Snippet: Predict(PredictRequest, CallSettings) // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) PredictRequest request = new PredictRequest { ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"), Payload = new ExamplePayload(), Params = { { "", "" }, }, }; // Make the request PredictResponse response = predictionServiceClient.Predict(request); // End snippet } /// <summary>Snippet for PredictAsync</summary> public async Task PredictRequestObjectAsync() { // Snippet: PredictAsync(PredictRequest, CallSettings) // Additional: PredictAsync(PredictRequest, CancellationToken) // Create client PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync(); // Initialize request argument(s) PredictRequest request = new PredictRequest { ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"), Payload = new ExamplePayload(), Params = { { "", "" }, }, }; // Make the request PredictResponse response = await predictionServiceClient.PredictAsync(request); // End snippet } /// <summary>Snippet for Predict</summary> public void Predict() { // Snippet: Predict(string, ExamplePayload, IDictionary<string,string>, CallSettings) // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]"; ExamplePayload payload = new ExamplePayload(); IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, }; // Make the request PredictResponse response = predictionServiceClient.Predict(name, payload, @params); // End snippet } /// <summary>Snippet for PredictAsync</summary> public async Task PredictAsync() { // Snippet: PredictAsync(string, ExamplePayload, IDictionary<string,string>, CallSettings) // Additional: PredictAsync(string, ExamplePayload, IDictionary<string,string>, CancellationToken) // Create client PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]"; ExamplePayload payload = new ExamplePayload(); IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, }; // Make the request PredictResponse response = await predictionServiceClient.PredictAsync(name, payload, @params); // End snippet } /// <summary>Snippet for Predict</summary> public void PredictResourceNames() { // Snippet: Predict(ModelName, ExamplePayload, IDictionary<string,string>, CallSettings) // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) ModelName name = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"); ExamplePayload payload = new ExamplePayload(); IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, }; // Make the request PredictResponse response = predictionServiceClient.Predict(name, payload, @params); // End snippet } /// <summary>Snippet for PredictAsync</summary> public async Task PredictResourceNamesAsync() { // Snippet: PredictAsync(ModelName, ExamplePayload, IDictionary<string,string>, CallSettings) // Additional: PredictAsync(ModelName, ExamplePayload, IDictionary<string,string>, CancellationToken) // Create client PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync(); // Initialize request argument(s) ModelName name = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"); ExamplePayload payload = new ExamplePayload(); IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, }; // Make the request PredictResponse response = await predictionServiceClient.PredictAsync(name, payload, @params); // End snippet } /// <summary>Snippet for BatchPredict</summary> public void BatchPredictRequestObject() { // Snippet: BatchPredict(BatchPredictRequest, CallSettings) // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) BatchPredictRequest request = new BatchPredictRequest { ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"), InputConfig = new BatchPredictInputConfig(), OutputConfig = new BatchPredictOutputConfig(), Params = { { "", "" }, }, }; // Make the request Operation<BatchPredictResult, OperationMetadata> response = predictionServiceClient.BatchPredict(request); // Poll until the returned long-running operation is complete Operation<BatchPredictResult, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result BatchPredictResult result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchPredictResult, OperationMetadata> retrievedResponse = predictionServiceClient.PollOnceBatchPredict(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchPredictResult retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchPredictAsync</summary> public async Task BatchPredictRequestObjectAsync() { // Snippet: BatchPredictAsync(BatchPredictRequest, CallSettings) // Additional: BatchPredictAsync(BatchPredictRequest, CancellationToken) // Create client PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync(); // Initialize request argument(s) BatchPredictRequest request = new BatchPredictRequest { ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"), InputConfig = new BatchPredictInputConfig(), OutputConfig = new BatchPredictOutputConfig(), Params = { { "", "" }, }, }; // Make the request Operation<BatchPredictResult, OperationMetadata> response = await predictionServiceClient.BatchPredictAsync(request); // Poll until the returned long-running operation is complete Operation<BatchPredictResult, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result BatchPredictResult result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchPredictResult, OperationMetadata> retrievedResponse = await predictionServiceClient.PollOnceBatchPredictAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchPredictResult retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchPredict</summary> public void BatchPredict() { // Snippet: BatchPredict(string, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CallSettings) // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]"; BatchPredictInputConfig inputConfig = new BatchPredictInputConfig(); BatchPredictOutputConfig outputConfig = new BatchPredictOutputConfig(); IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, }; // Make the request Operation<BatchPredictResult, OperationMetadata> response = predictionServiceClient.BatchPredict(name, inputConfig, outputConfig, @params); // Poll until the returned long-running operation is complete Operation<BatchPredictResult, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result BatchPredictResult result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchPredictResult, OperationMetadata> retrievedResponse = predictionServiceClient.PollOnceBatchPredict(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchPredictResult retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchPredictAsync</summary> public async Task BatchPredictAsync() { // Snippet: BatchPredictAsync(string, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CallSettings) // Additional: BatchPredictAsync(string, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CancellationToken) // Create client PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]"; BatchPredictInputConfig inputConfig = new BatchPredictInputConfig(); BatchPredictOutputConfig outputConfig = new BatchPredictOutputConfig(); IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, }; // Make the request Operation<BatchPredictResult, OperationMetadata> response = await predictionServiceClient.BatchPredictAsync(name, inputConfig, outputConfig, @params); // Poll until the returned long-running operation is complete Operation<BatchPredictResult, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result BatchPredictResult result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchPredictResult, OperationMetadata> retrievedResponse = await predictionServiceClient.PollOnceBatchPredictAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchPredictResult retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchPredict</summary> public void BatchPredictResourceNames() { // Snippet: BatchPredict(ModelName, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CallSettings) // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) ModelName name = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"); BatchPredictInputConfig inputConfig = new BatchPredictInputConfig(); BatchPredictOutputConfig outputConfig = new BatchPredictOutputConfig(); IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, }; // Make the request Operation<BatchPredictResult, OperationMetadata> response = predictionServiceClient.BatchPredict(name, inputConfig, outputConfig, @params); // Poll until the returned long-running operation is complete Operation<BatchPredictResult, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result BatchPredictResult result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchPredictResult, OperationMetadata> retrievedResponse = predictionServiceClient.PollOnceBatchPredict(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchPredictResult retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchPredictAsync</summary> public async Task BatchPredictResourceNamesAsync() { // Snippet: BatchPredictAsync(ModelName, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CallSettings) // Additional: BatchPredictAsync(ModelName, BatchPredictInputConfig, BatchPredictOutputConfig, IDictionary<string,string>, CancellationToken) // Create client PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync(); // Initialize request argument(s) ModelName name = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"); BatchPredictInputConfig inputConfig = new BatchPredictInputConfig(); BatchPredictOutputConfig outputConfig = new BatchPredictOutputConfig(); IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, }; // Make the request Operation<BatchPredictResult, OperationMetadata> response = await predictionServiceClient.BatchPredictAsync(name, inputConfig, outputConfig, @params); // Poll until the returned long-running operation is complete Operation<BatchPredictResult, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result BatchPredictResult result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchPredictResult, OperationMetadata> retrievedResponse = await predictionServiceClient.PollOnceBatchPredictAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchPredictResult retrievedResult = retrievedResponse.Result; } // End snippet } } }
//----------------------------------------------------------------------- // <copyright file="ModelClass" company="LoginRadius"> // Created by LoginRadius Development Team // Copyright 2019 LoginRadius Inc. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using Newtonsoft.Json; using LoginRadiusSDK.V2.Models.ResponseModels.UserProfile.Objects; namespace LoginRadiusSDK.V2.Models.ResponseModels.UserProfile { /// <summary> /// Response containing Definition for Complete SocialUserProfile data /// </summary> public class SocialUserProfile { /// <summary> /// About value that need to be inserted /// </summary> [JsonProperty(PropertyName = "About")] public string About {get;set;} /// <summary> /// Array of objects,String represents address of user /// </summary> [JsonProperty(PropertyName = "Addresses")] public List<Address> Addresses {get;set;} /// <summary> /// User's Age /// </summary> [JsonProperty(PropertyName = "Age")] public string Age {get;set;} /// <summary> /// user's age range. /// </summary> [JsonProperty(PropertyName = "AgeRange")] public AgeRange AgeRange {get;set;} /// <summary> /// Organization a person is assosciated with /// </summary> [JsonProperty(PropertyName = "Associations")] public string Associations {get;set;} /// <summary> /// Array of Objects,String represents Id, Name and Issuer /// </summary> [JsonProperty(PropertyName = "Awards")] public List<Awards> Awards {get;set;} /// <summary> /// User's Badges. /// </summary> [JsonProperty(PropertyName = "Badges")] public List<Badges> Badges {get;set;} /// <summary> /// user's birthdate /// </summary> [JsonProperty(PropertyName = "BirthDate")] public string BirthDate {get;set;} /// <summary> /// boards count /// </summary> [JsonProperty(PropertyName = "BoardsCount")] public int? BoardsCount {get;set;} /// <summary> /// Array of Objects,String represents Id,Name,Category,CreatedDate /// </summary> [JsonProperty(PropertyName = "Books")] public List<Books> Books {get;set;} /// <summary> /// Array of Objects,string represents Id,Name,Authority Number,StartDate,EndDate /// </summary> [JsonProperty(PropertyName = "Certifications")] public List<Certifications> Certifications {get;set;} /// <summary> /// user's city /// </summary> [JsonProperty(PropertyName = "City")] public string City {get;set;} /// <summary> /// users company name /// </summary> [JsonProperty(PropertyName = "Company")] public string Company {get;set;} /// <summary> /// Country of the user /// </summary> [JsonProperty(PropertyName = "Country")] public Country Country {get;set;} /// <summary> /// users course information /// </summary> [JsonProperty(PropertyName = "Courses")] public List<Courses> Courses {get;set;} /// <summary> /// URL of the photo that need to be inserted /// </summary> [JsonProperty(PropertyName = "CoverPhoto")] public string CoverPhoto {get;set;} /// <summary> /// created /// </summary> [JsonProperty(PropertyName = "Created")] public string Created {get;set;} /// <summary> /// Date of Creation of Profile /// </summary> [JsonProperty(PropertyName = "CreatedDate")] public DateTime? CreatedDate {get;set;} /// <summary> /// Currency /// </summary> [JsonProperty(PropertyName = "Currency")] public string Currency {get;set;} /// <summary> /// Array of Objects,String represents id ,Text ,Source and CreatedDate /// </summary> [JsonProperty(PropertyName = "CurrentStatus")] public List<CurrentStatus> CurrentStatus {get;set;} /// <summary> /// Array of Objects,which represents the educations record /// </summary> [JsonProperty(PropertyName = "Educations")] public List<Education> Educations {get;set;} /// <summary> /// user's email /// </summary> [JsonProperty(PropertyName = "Email")] public List<Email> Email {get;set;} /// <summary> /// user's family /// </summary> [JsonProperty(PropertyName = "Family")] public List<Family> Family {get;set;} /// <summary> /// URL of the favicon that need to be inserted /// </summary> [JsonProperty(PropertyName = "Favicon")] public string Favicon {get;set;} /// <summary> /// Array of Objects,strings represents Id ,Name ,Type /// </summary> [JsonProperty(PropertyName = "FavoriteThings")] public List<FavoriteThings> FavoriteThings {get;set;} /// <summary> /// first login /// </summary> [JsonProperty(PropertyName = "FirstLogin")] public bool? FirstLogin {get;set;} /// <summary> /// user's first name /// </summary> [JsonProperty(PropertyName = "FirstName")] public string FirstName {get;set;} /// <summary> /// user's followers count /// </summary> [JsonProperty(PropertyName = "FollowersCount")] public int? FollowersCount {get;set;} /// <summary> /// users friends count /// </summary> [JsonProperty(PropertyName = "FriendsCount")] public int? FriendsCount {get;set;} /// <summary> /// Users complete name /// </summary> [JsonProperty(PropertyName = "FullName")] public string FullName {get;set;} /// <summary> /// Array of Objects,string represents Id,Name,Category,CreatedDate /// </summary> [JsonProperty(PropertyName = "Games")] public List<Games> Games {get;set;} /// <summary> /// user's gender /// </summary> [JsonProperty(PropertyName = "Gender")] public string Gender {get;set;} /// <summary> /// Git Repository URL /// </summary> [JsonProperty(PropertyName = "GistsUrl")] public string GistsUrl {get;set;} /// <summary> /// URL of image that need to be inserted /// </summary> [JsonProperty(PropertyName = "GravatarImageUrl")] public string GravatarImageUrl {get;set;} /// <summary> /// boolean type value, default value is true /// </summary> [JsonProperty(PropertyName = "Hireable")] public bool? Hireable {get;set;} /// <summary> /// user's home town name /// </summary> [JsonProperty(PropertyName = "HomeTown")] public string HomeTown {get;set;} /// <summary> /// Awards lists from the social provider /// </summary> [JsonProperty(PropertyName = "Honors")] public string Honors {get;set;} /// <summary> /// URL of the Image that need to be inserted /// </summary> [JsonProperty(PropertyName = "HttpsImageUrl")] public string HttpsImageUrl {get;set;} /// <summary> /// ID of the User /// </summary> [JsonProperty(PropertyName = "ID")] public string ID {get;set;} /// <summary> /// Array of objects, String represents account type and account name. /// </summary> [JsonProperty(PropertyName = "IMAccounts")] public List<IMAccount> IMAccounts {get;set;} /// <summary> /// image URL should be absolute and has HTTPS domain /// </summary> [JsonProperty(PropertyName = "ImageUrl")] public string ImageUrl {get;set;} /// <summary> /// Industry name /// </summary> [JsonProperty(PropertyName = "Industry")] public string Industry {get;set;} /// <summary> /// Array of Objects,string represents Id and Name /// </summary> [JsonProperty(PropertyName = "InspirationalPeople")] public List<InspirationalPeople> InspirationalPeople {get;set;} /// <summary> /// array of string represents interest /// </summary> [JsonProperty(PropertyName = "InterestedIn")] public List<string> InterestedIn {get;set;} /// <summary> /// Array of objects, string shows InterestedType and InterestedName /// </summary> [JsonProperty(PropertyName = "Interests")] public List<Interests> Interests {get;set;} /// <summary> /// boolean type value, default is true /// </summary> [JsonProperty(PropertyName = "IsGeoEnabled")] public string IsGeoEnabled {get;set;} /// <summary> /// boolean type value, default is true /// </summary> [JsonProperty(PropertyName = "IsProtected")] public bool? IsProtected {get;set;} /// <summary> /// Array of Objects,Strings,boolean,object represents IsApplied,ApplyTimestamp,IsSaved,SavedTimestamp,Job /// </summary> [JsonProperty(PropertyName = "JobBookmarks")] public List<JobBookmarks> JobBookmarks {get;set;} /// <summary> /// Object, string represents KloutId and double represents Score /// </summary> [JsonProperty(PropertyName = "KloutScore")] public KloutProfile KloutScore {get;set;} /// <summary> /// language known by user's /// </summary> [JsonProperty(PropertyName = "Language")] public string Language {get;set;} /// <summary> /// language known by user's /// </summary> [JsonProperty(PropertyName = "Languages")] public List<Languages> Languages {get;set;} /// <summary> /// last login date /// </summary> [JsonProperty(PropertyName = "LastLoginDate")] public DateTime? LastLoginDate {get;set;} /// <summary> /// user's last name /// </summary> [JsonProperty(PropertyName = "LastName")] public string LastName {get;set;} /// <summary> /// likes count /// </summary> [JsonProperty(PropertyName = "LikesCount")] public int? LikesCount {get;set;} /// <summary> /// Local City of the user /// </summary> [JsonProperty(PropertyName = "LocalCity")] public string LocalCity {get;set;} /// <summary> /// Local country of the user /// </summary> [JsonProperty(PropertyName = "LocalCountry")] public string LocalCountry {get;set;} /// <summary> /// Local language of the user /// </summary> [JsonProperty(PropertyName = "LocalLanguage")] public string LocalLanguage {get;set;} /// <summary> /// LR user id /// </summary> [JsonProperty(PropertyName = "LRUserID")] public string LRUserID {get;set;} /// <summary> /// Main address of the user /// </summary> [JsonProperty(PropertyName = "MainAddress")] public string MainAddress {get;set;} /// <summary> /// Array of Objects,String represents Url,UrlName /// </summary> [JsonProperty(PropertyName = "MemberUrlResources")] public List<Memberurlresources> MemberUrlResources {get;set;} /// <summary> /// user's middle name /// </summary> [JsonProperty(PropertyName = "MiddleName")] public string MiddleName {get;set;} /// <summary> /// profile updated date /// </summary> [JsonProperty(PropertyName = "ModifiedDate")] public DateTime? ModifiedDate {get;set;} /// <summary> /// Array of Objects,strings represents Id,Name,Category,CreatedDate /// </summary> [JsonProperty(PropertyName = "Movies")] public List<Movies> Movies {get;set;} /// <summary> /// Array of Objects, strings represents Id,Name,FirstName,LastName,Birthday,Hometown,Link,Gender /// </summary> [JsonProperty(PropertyName = "MutualFriends")] public List<MutualFriends> MutualFriends {get;set;} /// <summary> /// Nick name of the user /// </summary> [JsonProperty(PropertyName = "NickName")] public string NickName {get;set;} /// <summary> /// Count for the user profile recommended /// </summary> [JsonProperty(PropertyName = "NumRecommenders")] public int? NumRecommenders {get;set;} /// <summary> /// Patents Registered /// </summary> [JsonProperty(PropertyName = "Patents")] public List<Patents> Patents {get;set;} /// <summary> /// Users Phone Number /// </summary> [JsonProperty(PropertyName = "PhoneNumbers")] public List<Phone> PhoneNumbers {get;set;} /// <summary> /// count of pins /// </summary> [JsonProperty(PropertyName = "PinsCount")] public int? PinsCount {get;set;} /// <summary> /// Array of Objects,strings Name and boolean IsPrimary /// </summary> [JsonProperty(PropertyName = "PlacesLived")] public List<PlacesLived> PlacesLived {get;set;} /// <summary> /// List of Political interest /// </summary> [JsonProperty(PropertyName = "Political")] public string Political {get;set;} /// <summary> /// Array of Objects,which represents the PositionSummary,StartDate,EndDate,IsCurrent,Company,Location /// </summary> [JsonProperty(PropertyName = "Positions")] public List<ProfessionalPosition> Positions {get;set;} /// <summary> /// Prefix for FirstName /// </summary> [JsonProperty(PropertyName = "Prefix")] public string Prefix {get;set;} /// <summary> /// previous ids /// </summary> [JsonProperty(PropertyName = "PreviousUids")] public List<string> PreviousUids {get;set;} /// <summary> /// user private Repository Urls /// </summary> [JsonProperty(PropertyName = "PrivateGists")] public int? PrivateGists {get;set;} /// <summary> /// This field provide by linkedin.contain our linkedin profile headline /// </summary> [JsonProperty(PropertyName = "ProfessionalHeadline")] public string ProfessionalHeadline {get;set;} /// <summary> /// ProfileCity value that need to be inserted /// </summary> [JsonProperty(PropertyName = "ProfileCity")] public string ProfileCity {get;set;} /// <summary> /// ProfileCountry value that need to be inserted /// </summary> [JsonProperty(PropertyName = "ProfileCountry")] public string ProfileCountry {get;set;} /// <summary> /// ProfileImageUrls that need to be inserted /// </summary> [JsonProperty(PropertyName = "ProfileImageUrls")] public Dictionary<string,string> ProfileImageUrls {get;set;} /// <summary> /// profile updated date /// </summary> [JsonProperty(PropertyName = "ProfileModifiedDate")] public DateTime? ProfileModifiedDate {get;set;} /// <summary> /// ProfileName value field that need to be inserted /// </summary> [JsonProperty(PropertyName = "ProfileName")] public string ProfileName {get;set;} /// <summary> /// User profile url like facebook profile Url /// </summary> [JsonProperty(PropertyName = "ProfileUrl")] public string ProfileUrl {get;set;} /// <summary> /// Array of Objects,string represents Id,Name,Summary With StartDate,EndDate,IsCurrent /// </summary> [JsonProperty(PropertyName = "Projects")] public List<Projects> Projects {get;set;} /// <summary> /// Name of the provider /// </summary> [JsonProperty(PropertyName = "Provider")] public string Provider {get;set;} /// <summary> /// Object,string represents AccessToken,TokenSecret /// </summary> [JsonProperty(PropertyName = "ProviderAccessCredential")] public ProviderAccessCredential ProviderAccessCredential {get;set;} /// <summary> /// Array of Objects,string represents Id,Title,Publisher,Authors,Date,Url,Summary /// </summary> [JsonProperty(PropertyName = "Publications")] public List<Publications> Publications {get;set;} /// <summary> /// gist is a Git repository, which means that it can be forked and cloned. /// </summary> [JsonProperty(PropertyName = "PublicGists")] public int? PublicGists {get;set;} /// <summary> /// user public Repository Urls /// </summary> [JsonProperty(PropertyName = "PublicRepository")] public string PublicRepository {get;set;} /// <summary> /// Quota /// </summary> [JsonProperty(PropertyName = "Quota")] public string Quota {get;set;} /// <summary> /// quote /// </summary> [JsonProperty(PropertyName = "Quote")] public string Quote {get;set;} /// <summary> /// Array of Objects,string represents Id,RecommendationType,RecommendationText,Recommender /// </summary> [JsonProperty(PropertyName = "RecommendationsReceived")] public List<RecommendationsReceived> RecommendationsReceived {get;set;} /// <summary> /// Array of Objects,String represents Id,FirstName,LastName /// </summary> [JsonProperty(PropertyName = "RelatedProfileViews")] public List<RelatedProfileViews> RelatedProfileViews {get;set;} /// <summary> /// user's relationship status /// </summary> [JsonProperty(PropertyName = "RelationshipStatus")] public string RelationshipStatus {get;set;} /// <summary> /// String shows users religion /// </summary> [JsonProperty(PropertyName = "Religion")] public string Religion {get;set;} /// <summary> /// Repository URL /// </summary> [JsonProperty(PropertyName = "RepositoryUrl")] public string RepositoryUrl {get;set;} /// <summary> /// Signup date /// </summary> [JsonProperty(PropertyName = "SignupDate")] public DateTime? SignupDate {get;set;} /// <summary> /// Array of objects, String represents ID and Name /// </summary> [JsonProperty(PropertyName = "Skills")] public List<Skills> Skills {get;set;} /// <summary> /// Array of objects, String represents ID and Name /// </summary> [JsonProperty(PropertyName = "Sports")] public List<Sports> Sports {get;set;} /// <summary> /// Git users bookmark repositories /// </summary> [JsonProperty(PropertyName = "StarredUrl")] public string StarredUrl {get;set;} /// <summary> /// State of the user /// </summary> [JsonProperty(PropertyName = "State")] public string State {get;set;} /// <summary> /// Object,string represents Name,Space,PrivateRepos,Collaborators /// </summary> [JsonProperty(PropertyName = "Subscription")] public GitHubPlan Subscription {get;set;} /// <summary> /// Suffix for the User. /// </summary> [JsonProperty(PropertyName = "Suffix")] public string Suffix {get;set;} /// <summary> /// Object,array of objects represents CompaniestoFollow,IndustriestoFollow,NewssourcetoFollow,PeopletoFollow /// </summary> [JsonProperty(PropertyName = "Suggestions")] public Suggestions Suggestions {get;set;} /// <summary> /// Tagline that need to be inserted /// </summary> [JsonProperty(PropertyName = "TagLine")] public string TagLine {get;set;} /// <summary> /// Array of Objects,string represents Id,Name,Category,CreatedDate /// </summary> [JsonProperty(PropertyName = "TeleVisionShow")] public List<Television> TeleVisionShow {get;set;} /// <summary> /// URL for the Thumbnail /// </summary> [JsonProperty(PropertyName = "ThumbnailImageUrl")] public string ThumbnailImageUrl {get;set;} /// <summary> /// The Current Time Zone. /// </summary> [JsonProperty(PropertyName = "TimeZone")] public string TimeZone {get;set;} /// <summary> /// Total Private repository /// </summary> [JsonProperty(PropertyName = "TotalPrivateRepository")] public int? TotalPrivateRepository {get;set;} /// <summary> /// Count of Total status /// </summary> [JsonProperty(PropertyName = "TotalStatusesCount")] public int? TotalStatusesCount {get;set;} /// <summary> /// updated date /// </summary> [JsonProperty(PropertyName = "UpdatedTime")] public string UpdatedTime {get;set;} /// <summary> /// verified /// </summary> [JsonProperty(PropertyName = "Verified")] public string Verified {get;set;} /// <summary> /// Array of Objects,string represents Id,Role,Organization,Cause /// </summary> [JsonProperty(PropertyName = "Volunteer")] public List<Volunteer> Volunteer {get;set;} /// <summary> /// Twitter, Facebook ProfileUrls /// </summary> [JsonProperty(PropertyName = "WebProfiles")] public Dictionary<string,string> WebProfiles {get;set;} /// <summary> /// Personal Website a User has /// </summary> [JsonProperty(PropertyName = "Website")] public string Website {get;set;} } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcfav = Google.Cloud.Firestore.Admin.V1; using sys = System; namespace Google.Cloud.Firestore.Admin.V1 { /// <summary>Resource name for the <c>Database</c> resource.</summary> public sealed partial class DatabaseName : gax::IResourceName, sys::IEquatable<DatabaseName> { /// <summary>The possible contents of <see cref="DatabaseName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/databases/{database}</c>.</summary> ProjectDatabase = 1, } private static gax::PathTemplate s_projectDatabase = new gax::PathTemplate("projects/{project}/databases/{database}"); /// <summary>Creates a <see cref="DatabaseName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="DatabaseName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static DatabaseName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new DatabaseName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="DatabaseName"/> with the pattern <c>projects/{project}/databases/{database}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="DatabaseName"/> constructed from the provided ids.</returns> public static DatabaseName FromProjectDatabase(string projectId, string databaseId) => new DatabaseName(ResourceNameType.ProjectDatabase, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), databaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(databaseId, nameof(databaseId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="DatabaseName"/> with pattern /// <c>projects/{project}/databases/{database}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DatabaseName"/> with pattern /// <c>projects/{project}/databases/{database}</c>. /// </returns> public static string Format(string projectId, string databaseId) => FormatProjectDatabase(projectId, databaseId); /// <summary> /// Formats the IDs into the string representation of this <see cref="DatabaseName"/> with pattern /// <c>projects/{project}/databases/{database}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DatabaseName"/> with pattern /// <c>projects/{project}/databases/{database}</c>. /// </returns> public static string FormatProjectDatabase(string projectId, string databaseId) => s_projectDatabase.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(databaseId, nameof(databaseId))); /// <summary>Parses the given resource name string into a new <see cref="DatabaseName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/databases/{database}</c></description></item> /// </list> /// </remarks> /// <param name="databaseName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="DatabaseName"/> if successful.</returns> public static DatabaseName Parse(string databaseName) => Parse(databaseName, false); /// <summary> /// Parses the given resource name string into a new <see cref="DatabaseName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/databases/{database}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="databaseName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="DatabaseName"/> if successful.</returns> public static DatabaseName Parse(string databaseName, bool allowUnparsed) => TryParse(databaseName, allowUnparsed, out DatabaseName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DatabaseName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/databases/{database}</c></description></item> /// </list> /// </remarks> /// <param name="databaseName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="DatabaseName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string databaseName, out DatabaseName result) => TryParse(databaseName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DatabaseName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/databases/{database}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="databaseName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="DatabaseName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string databaseName, bool allowUnparsed, out DatabaseName result) { gax::GaxPreconditions.CheckNotNull(databaseName, nameof(databaseName)); gax::TemplatedResourceName resourceName; if (s_projectDatabase.TryParseName(databaseName, out resourceName)) { result = FromProjectDatabase(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(databaseName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private DatabaseName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string databaseId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; DatabaseId = databaseId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="DatabaseName"/> class from the component parts of pattern /// <c>projects/{project}/databases/{database}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param> public DatabaseName(string projectId, string databaseId) : this(ResourceNameType.ProjectDatabase, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), databaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(databaseId, nameof(databaseId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Database</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DatabaseId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectDatabase: return s_projectDatabase.Expand(ProjectId, DatabaseId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as DatabaseName); /// <inheritdoc/> public bool Equals(DatabaseName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(DatabaseName a, DatabaseName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(DatabaseName a, DatabaseName b) => !(a == b); } /// <summary>Resource name for the <c>CollectionGroup</c> resource.</summary> public sealed partial class CollectionGroupName : gax::IResourceName, sys::IEquatable<CollectionGroupName> { /// <summary>The possible contents of <see cref="CollectionGroupName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/databases/{database}/collectionGroups/{collection}</c> /// . /// </summary> ProjectDatabaseCollection = 1, } private static gax::PathTemplate s_projectDatabaseCollection = new gax::PathTemplate("projects/{project}/databases/{database}/collectionGroups/{collection}"); /// <summary>Creates a <see cref="CollectionGroupName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CollectionGroupName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CollectionGroupName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CollectionGroupName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CollectionGroupName"/> with the pattern /// <c>projects/{project}/databases/{database}/collectionGroups/{collection}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="collectionId">The <c>Collection</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CollectionGroupName"/> constructed from the provided ids.</returns> public static CollectionGroupName FromProjectDatabaseCollection(string projectId, string databaseId, string collectionId) => new CollectionGroupName(ResourceNameType.ProjectDatabaseCollection, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), databaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(databaseId, nameof(databaseId)), collectionId: gax::GaxPreconditions.CheckNotNullOrEmpty(collectionId, nameof(collectionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CollectionGroupName"/> with pattern /// <c>projects/{project}/databases/{database}/collectionGroups/{collection}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="collectionId">The <c>Collection</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CollectionGroupName"/> with pattern /// <c>projects/{project}/databases/{database}/collectionGroups/{collection}</c>. /// </returns> public static string Format(string projectId, string databaseId, string collectionId) => FormatProjectDatabaseCollection(projectId, databaseId, collectionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CollectionGroupName"/> with pattern /// <c>projects/{project}/databases/{database}/collectionGroups/{collection}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="collectionId">The <c>Collection</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CollectionGroupName"/> with pattern /// <c>projects/{project}/databases/{database}/collectionGroups/{collection}</c>. /// </returns> public static string FormatProjectDatabaseCollection(string projectId, string databaseId, string collectionId) => s_projectDatabaseCollection.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(databaseId, nameof(databaseId)), gax::GaxPreconditions.CheckNotNullOrEmpty(collectionId, nameof(collectionId))); /// <summary> /// Parses the given resource name string into a new <see cref="CollectionGroupName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/databases/{database}/collectionGroups/{collection}</c></description> /// </item> /// </list> /// </remarks> /// <param name="collectionGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CollectionGroupName"/> if successful.</returns> public static CollectionGroupName Parse(string collectionGroupName) => Parse(collectionGroupName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CollectionGroupName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/databases/{database}/collectionGroups/{collection}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="collectionGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CollectionGroupName"/> if successful.</returns> public static CollectionGroupName Parse(string collectionGroupName, bool allowUnparsed) => TryParse(collectionGroupName, allowUnparsed, out CollectionGroupName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CollectionGroupName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/databases/{database}/collectionGroups/{collection}</c></description> /// </item> /// </list> /// </remarks> /// <param name="collectionGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CollectionGroupName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string collectionGroupName, out CollectionGroupName result) => TryParse(collectionGroupName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CollectionGroupName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/databases/{database}/collectionGroups/{collection}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="collectionGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CollectionGroupName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string collectionGroupName, bool allowUnparsed, out CollectionGroupName result) { gax::GaxPreconditions.CheckNotNull(collectionGroupName, nameof(collectionGroupName)); gax::TemplatedResourceName resourceName; if (s_projectDatabaseCollection.TryParseName(collectionGroupName, out resourceName)) { result = FromProjectDatabaseCollection(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(collectionGroupName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CollectionGroupName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string collectionId = null, string databaseId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; CollectionId = collectionId; DatabaseId = databaseId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="CollectionGroupName"/> class from the component parts of pattern /// <c>projects/{project}/databases/{database}/collectionGroups/{collection}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="databaseId">The <c>Database</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="collectionId">The <c>Collection</c> ID. Must not be <c>null</c> or empty.</param> public CollectionGroupName(string projectId, string databaseId, string collectionId) : this(ResourceNameType.ProjectDatabaseCollection, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), databaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(databaseId, nameof(databaseId)), collectionId: gax::GaxPreconditions.CheckNotNullOrEmpty(collectionId, nameof(collectionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Collection</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CollectionId { get; } /// <summary> /// The <c>Database</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DatabaseId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectDatabaseCollection: return s_projectDatabaseCollection.Expand(ProjectId, DatabaseId, CollectionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CollectionGroupName); /// <inheritdoc/> public bool Equals(CollectionGroupName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CollectionGroupName a, CollectionGroupName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CollectionGroupName a, CollectionGroupName b) => !(a == b); } public partial class CreateIndexRequest { /// <summary> /// <see cref="CollectionGroupName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public CollectionGroupName ParentAsCollectionGroupName { get => string.IsNullOrEmpty(Parent) ? null : CollectionGroupName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListIndexesRequest { /// <summary> /// <see cref="CollectionGroupName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public CollectionGroupName ParentAsCollectionGroupName { get => string.IsNullOrEmpty(Parent) ? null : CollectionGroupName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetIndexRequest { /// <summary> /// <see cref="gcfav::IndexName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfav::IndexName IndexName { get => string.IsNullOrEmpty(Name) ? null : gcfav::IndexName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteIndexRequest { /// <summary> /// <see cref="gcfav::IndexName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfav::IndexName IndexName { get => string.IsNullOrEmpty(Name) ? null : gcfav::IndexName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetFieldRequest { /// <summary> /// <see cref="gcfav::FieldName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfav::FieldName FieldName { get => string.IsNullOrEmpty(Name) ? null : gcfav::FieldName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListFieldsRequest { /// <summary> /// <see cref="CollectionGroupName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public CollectionGroupName ParentAsCollectionGroupName { get => string.IsNullOrEmpty(Parent) ? null : CollectionGroupName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ExportDocumentsRequest { /// <summary> /// <see cref="gcfav::DatabaseName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfav::DatabaseName DatabaseName { get => string.IsNullOrEmpty(Name) ? null : gcfav::DatabaseName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ImportDocumentsRequest { /// <summary> /// <see cref="gcfav::DatabaseName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfav::DatabaseName DatabaseName { get => string.IsNullOrEmpty(Name) ? null : gcfav::DatabaseName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Windows; using System.Xml; using NLog.Common; using NLog.Filters; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; /// <summary> /// A class for configuring NLog through an XML configuration file /// (App.config style or App.nlog style). /// </summary> public class XmlLoggingConfiguration : LoggingConfiguration { private readonly ConfigurationItemFactory configurationItemFactory = ConfigurationItemFactory.Default; private readonly Dictionary<string, bool> visitedFile = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, string> variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private string originalFileName; /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> public XmlLoggingConfiguration(string fileName) { using (XmlReader reader = XmlReader.Create(fileName)) { this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(string fileName, bool ignoreErrors) { using (XmlReader reader = XmlReader.Create(fileName)) { this.Initialize(reader, fileName, ignoreErrors); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> public XmlLoggingConfiguration(XmlReader reader, string fileName) { this.Initialize(reader, fileName, false); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors) { this.Initialize(reader, fileName, ignoreErrors); } #if !SILVERLIGHT /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> /// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, ignoreErrors); } } #endif #if !NET_CF && !SILVERLIGHT /// <summary> /// Gets the default <see cref="LoggingConfiguration" /> object by parsing /// the application configuration file (<c>app.exe.config</c>). /// </summary> public static LoggingConfiguration AppConfig { get { object o = System.Configuration.ConfigurationManager.GetSection("nlog"); return o as LoggingConfiguration; } } #endif /// <summary> /// Gets or sets a value indicating whether the configuration files /// should be watched for changes and reloaded automatically when changed. /// </summary> public bool AutoReload { get; set; } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// This is the list of configuration files processed. /// If the <c>autoReload</c> attribute is not set it returns empty collection. /// </summary> public override IEnumerable<string> FileNamesToWatch { get { if (this.AutoReload) { return this.visitedFile.Keys; } return new string[0]; } } /// <summary> /// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object. /// </summary> /// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns> public override LoggingConfiguration Reload() { return new XmlLoggingConfiguration(this.originalFileName); } private static bool IsTargetElement(string name) { return name.Equals("target", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target", StringComparison.OrdinalIgnoreCase); } private static bool IsTargetRefElement(string name) { return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase); } private static string CleanWhitespace(string s) { s = s.Replace(" ", string.Empty); // get rid of the whitespace return s; } private static string StripOptionalNamespacePrefix(string attributeValue) { if (attributeValue == null) { return null; } int p = attributeValue.IndexOf(':'); if (p < 0) { return attributeValue; } return attributeValue.Substring(p + 1); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")] private static Target WrapWithAsyncTargetWrapper(Target target) { var asyncTargetWrapper = new AsyncTargetWrapper(); asyncTargetWrapper.WrappedTarget = target; asyncTargetWrapper.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name); target = asyncTargetWrapper; return target; } /// <summary> /// Initializes the configuration. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> private void Initialize(XmlReader reader, string fileName, bool ignoreErrors) { try { reader.MoveToContent(); var content = new NLogXmlElement(reader); if (fileName != null) { InternalLogger.Info("Configuring from an XML element in {0}...", fileName); #if SILVERLIGHT string key = fileName; #else string key = Path.GetFullPath(fileName); #endif this.visitedFile[key] = true; this.originalFileName = fileName; this.ParseTopLevel(content, Path.GetDirectoryName(fileName)); } else { this.ParseTopLevel(content, null); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error {0}...", exception); if (!ignoreErrors) { throw new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception); } } } private void ConfigureFromFile(string fileName) { #if SILVERLIGHT // file names are relative to XAP string key = fileName; #else string key = Path.GetFullPath(fileName); #endif if (this.visitedFile.ContainsKey(key)) { return; } this.visitedFile[key] = true; this.ParseTopLevel(new NLogXmlElement(fileName), Path.GetDirectoryName(fileName)); } private void ParseTopLevel(NLogXmlElement content, string baseDirectory) { content.AssertName("nlog", "configuration"); switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "CONFIGURATION": this.ParseConfigurationElement(content, baseDirectory); break; case "NLOG": this.ParseNLogElement(content, baseDirectory); break; } } private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory) { InternalLogger.Trace("ParseConfigurationElement"); configurationElement.AssertName("configuration"); foreach (var el in configurationElement.Elements("nlog")) { this.ParseNLogElement(el, baseDirectory); } } private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory) { InternalLogger.Trace("ParseNLogElement"); nlogElement.AssertName("nlog"); this.AutoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", false); LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions); InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole); #if !NET_CF InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError); #endif InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile); InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name)); LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name)); foreach (var el in nlogElement.Children) { switch (el.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "EXTENSIONS": this.ParseExtensionsElement(el, baseDirectory); break; case "INCLUDE": this.ParseIncludeElement(el, baseDirectory); break; case "APPENDERS": case "TARGETS": this.ParseTargetsElement(el); break; case "VARIABLE": this.ParseVariableElement(el); break; case "RULES": this.ParseRulesElement(el, this.LoggingRules); break; default: InternalLogger.Warn("Skipping unknown node: {0}", el.LocalName); break; } } } private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection) { InternalLogger.Trace("ParseRulesElement"); rulesElement.AssertName("rules"); foreach (var loggerElement in rulesElement.Elements("logger")) { this.ParseLoggerElement(loggerElement, rulesCollection); } } private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection) { loggerElement.AssertName("logger"); var rule = new LoggingRule(); string namePattern = loggerElement.GetOptionalAttribute("name", "*"); string appendTo = loggerElement.GetOptionalAttribute("appendTo", null); if (appendTo == null) { appendTo = loggerElement.GetOptionalAttribute("writeTo", null); } rule.LoggerNamePattern = namePattern; if (appendTo != null) { foreach (string t in appendTo.Split(',')) { string targetName = t.Trim(); Target target = FindTargetByName(targetName); if (target != null) { rule.Targets.Add(target); } else { throw new NLogConfigurationException("Target " + targetName + " not found."); } } } rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false); string levelString; if (loggerElement.AttributeValues.TryGetValue("level", out levelString)) { LogLevel level = LogLevel.FromString(levelString); rule.EnableLoggingForLevel(level); } else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString)) { levelString = CleanWhitespace(levelString); string[] tokens = levelString.Split(','); foreach (string s in tokens) { if (!string.IsNullOrEmpty(s)) { LogLevel level = LogLevel.FromString(s); rule.EnableLoggingForLevel(level); } } } else { int minLevel = 0; int maxLevel = LogLevel.MaxLevel.Ordinal; string minLevelString; string maxLevelString; if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString)) { minLevel = LogLevel.FromString(minLevelString).Ordinal; } if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString)) { maxLevel = LogLevel.FromString(maxLevelString).Ordinal; } for (int i = minLevel; i <= maxLevel; ++i) { rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i)); } } foreach (var child in loggerElement.Children) { switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "FILTERS": this.ParseFilters(rule, child); break; case "LOGGER": this.ParseLoggerElement(child, rule.ChildRules); break; } } rulesCollection.Add(rule); } private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement) { filtersElement.AssertName("filters"); foreach (var filterElement in filtersElement.Children) { string name = filterElement.LocalName; Filter filter = this.configurationItemFactory.Filters.CreateInstance(name); this.ConfigureObjectFromAttributes(filter, filterElement, false); rule.Filters.Add(filter); } } private void ParseVariableElement(NLogXmlElement variableElement) { variableElement.AssertName("variable"); string name = variableElement.GetRequiredAttribute("name"); string value = this.ExpandVariables(variableElement.GetRequiredAttribute("value")); this.variables[name] = value; } private void ParseTargetsElement(NLogXmlElement targetsElement) { targetsElement.AssertName("targets", "appenders"); bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false); NLogXmlElement defaultWrapperElement = null; var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>(); foreach (var targetElement in targetsElement.Children) { string name = targetElement.LocalName; string type = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null)); switch (name.ToUpper(CultureInfo.InvariantCulture)) { case "DEFAULT-WRAPPER": defaultWrapperElement = targetElement; break; case "DEFAULT-TARGET-PARAMETERS": if (type == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } typeNameToDefaultTargetParameters[type] = targetElement; break; case "TARGET": case "APPENDER": case "WRAPPER": case "WRAPPER-TARGET": case "COMPOUND-TARGET": if (type == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); NLogXmlElement defaults; if (typeNameToDefaultTargetParameters.TryGetValue(type, out defaults)) { this.ParseTargetElement(newTarget, defaults); } this.ParseTargetElement(newTarget, targetElement); if (asyncWrap) { newTarget = WrapWithAsyncTargetWrapper(newTarget); } if (defaultWrapperElement != null) { newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement); } InternalLogger.Info("Adding target {0}", newTarget); AddTarget(newTarget.Name, newTarget); break; } } } private void ParseTargetElement(Target target, NLogXmlElement targetElement) { var compound = target as CompoundTargetBase; var wrapper = target as WrapperTargetBase; this.ConfigureObjectFromAttributes(target, targetElement, true); foreach (var childElement in targetElement.Children) { string name = childElement.LocalName; if (compound != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } compound.Targets.Add(newTarget); continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } compound.Targets.Add(newTarget); } continue; } } if (wrapper != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } wrapper.WrappedTarget = newTarget; continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } if (wrapper.WrappedTarget != null) { throw new NLogConfigurationException("Wrapped target already defined."); } wrapper.WrappedTarget = newTarget; } continue; } } this.SetPropertyFromElement(target, childElement); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")] private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory) { extensionsElement.AssertName("extensions"); foreach (var addElement in extensionsElement.Elements("add")) { string prefix = addElement.GetOptionalAttribute("prefix", null); if (prefix != null) { prefix = prefix + "."; } string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null)); if (type != null) { this.configurationItemFactory.RegisterType(Type.GetType(type, true), prefix); } #if !WINDOWS_PHONE string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null); if (assemblyFile != null) { try { #if SILVERLIGHT var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else string fullFileName = Path.Combine(baseDirectory, assemblyFile); InternalLogger.Info("Loading assembly file: {0}", fullFileName); Assembly asm = Assembly.LoadFrom(fullFileName); #endif this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception); } } continue; } string assemblyName = addElement.GetOptionalAttribute("assembly", null); if (assemblyName != null) { try { InternalLogger.Info("Loading assembly name: {0}", assemblyName); #if SILVERLIGHT var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else Assembly asm = Assembly.Load(assemblyName); #endif this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception); } } continue; } #endif } } private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory) { includeElement.AssertName("include"); string newFileName = includeElement.GetRequiredAttribute("file"); try { newFileName = this.ExpandVariables(newFileName); newFileName = SimpleLayout.Evaluate(newFileName); if (baseDirectory != null) { newFileName = Path.Combine(baseDirectory, newFileName); } #if SILVERLIGHT newFileName = newFileName.Replace("\\", "/"); if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null) #else if (File.Exists(newFileName)) #endif { InternalLogger.Debug("Including file '{0}'", newFileName); this.ConfigureFromFile(newFileName); } else { throw new FileNotFoundException("Included file not found: " + newFileName); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error when including '{0}' {1}", newFileName, exception); if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false)) { return; } throw new NLogConfigurationException("Error when including: " + newFileName, exception); } } private void SetPropertyFromElement(object o, NLogXmlElement element) { if (this.AddArrayItemFromElement(o, element)) { return; } if (this.SetLayoutFromElement(o, element)) { return; } PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandVariables(element.Value), this.configurationItemFactory); } private bool AddArrayItemFromElement(object o, NLogXmlElement element) { string name = element.LocalName; PropertyInfo propInfo; if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo)) { return false; } Type elementType = PropertyHelper.GetArrayItemType(propInfo); if (elementType != null) { IList propertyValue = (IList)propInfo.GetValue(o, null); object arrayItem = FactoryHelper.CreateInstance(elementType); this.ConfigureObjectFromAttributes(arrayItem, element, true); this.ConfigureObjectFromElement(arrayItem, element); propertyValue.Add(arrayItem); return true; } return false; } private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType) { foreach (var kvp in element.AttributeValues) { string childName = kvp.Key; string childValue = kvp.Value; if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase)) { continue; } PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandVariables(childValue), this.configurationItemFactory); } } private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement) { PropertyInfo targetPropertyInfo; string name = layoutElement.LocalName; // if property exists if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo)) { // and is a Layout if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType)) { string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null)); // and 'type' attribute has been specified if (layoutTypeName != null) { // configure it from current element Layout layout = this.configurationItemFactory.Layouts.CreateInstance(this.ExpandVariables(layoutTypeName)); this.ConfigureObjectFromAttributes(layout, layoutElement, true); this.ConfigureObjectFromElement(layout, layoutElement); targetPropertyInfo.SetValue(o, layout, null); return true; } } } return false; } private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element) { foreach (var child in element.Children) { this.SetPropertyFromElement(targetObject, child); } } private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters) { string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type")); Target wrapperTargetInstance = this.configurationItemFactory.Targets.CreateInstance(wrapperType); WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper."); } this.ParseTargetElement(wrapperTargetInstance, defaultParameters); while (wtb.WrappedTarget != null) { wtb = wtb.WrappedTarget as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper."); } } wtb.WrappedTarget = t; wrapperTargetInstance.Name = t.Name; t.Name = t.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name); return wrapperTargetInstance; } private string ExpandVariables(string input) { string output = input; // TODO - make this case-insensitive, will probably require a different approach foreach (var kvp in this.variables) { output = output.Replace("${" + kvp.Key + "}", kvp.Value); } return output; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using IronPython.Runtime; using Microsoft.Scripting; [assembly: PythonModule("errno", typeof(IronPython.Modules.PythonErrorNumber))] namespace IronPython.Modules { public static class PythonErrorNumber { public const string __doc__ = "Provides a list of common error numbers. These numbers are frequently reported in various exceptions."; [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { PythonDictionary errorcode = new PythonDictionary(); errorcode[E2BIG] = "E2BIG"; errorcode[EACCES] = "EACCES"; errorcode[EADDRINUSE] = "EADDRINUSE"; errorcode[EADDRNOTAVAIL] = "EADDRNOTAVAIL"; errorcode[EAFNOSUPPORT] = "EAFNOSUPPORT"; errorcode[EAGAIN] = "EAGAIN"; errorcode[EALREADY] = "EALREADY"; errorcode[EBADF] = "EBADF"; errorcode[EBUSY] = "EBUSY"; errorcode[ECHILD] = "ECHILD"; errorcode[ECONNABORTED] = "ECONNABORTED"; errorcode[ECONNREFUSED] = "ECONNREFUSED"; errorcode[ECONNRESET] = "ECONNRESET"; errorcode[EDEADLK] = "EDEADLK"; errorcode[EDEADLOCK] = "EDEADLOCK"; errorcode[EDESTADDRREQ] = "EDESTADDRREQ"; errorcode[EDOM] = "EDOM"; errorcode[EDQUOT] = "EDQUOT"; errorcode[EEXIST] = "EEXIST"; errorcode[EFAULT] = "EFAULT"; errorcode[EFBIG] = "EFBIG"; errorcode[EHOSTDOWN] = "EHOSTDOWN"; errorcode[EHOSTUNREACH] = "EHOSTUNREACH"; errorcode[EILSEQ] = "EILSEQ"; errorcode[EINPROGRESS] = "EINPROGRESS"; errorcode[EINTR] = "EINTR"; errorcode[EINVAL] = "EINVAL"; errorcode[EIO] = "EIO"; errorcode[EISCONN] = "EISCONN"; errorcode[EISDIR] = "EISDIR"; errorcode[ELOOP] = "ELOOP"; errorcode[EMFILE] = "EMFILE"; errorcode[EMLINK] = "EMLINK"; errorcode[EMSGSIZE] = "EMSGSIZE"; errorcode[ENAMETOOLONG] = "ENAMETOOLONG"; errorcode[ENETDOWN] = "ENETDOWN"; errorcode[ENETRESET] = "ENETRESET"; errorcode[ENETUNREACH] = "ENETUNREACH"; errorcode[ENFILE] = "ENFILE"; errorcode[ENOBUFS] = "ENOBUFS"; errorcode[ENODEV] = "ENODEV"; errorcode[ENOENT] = "ENOENT"; errorcode[ENOEXEC] = "ENOEXEC"; errorcode[ENOLCK] = "ENOLCK"; errorcode[ENOMEM] = "ENOMEM"; errorcode[ENOPROTOOPT] = "ENOPROTOOPT"; errorcode[ENOSPC] = "ENOSPC"; errorcode[ENOSYS] = "ENOSYS"; errorcode[ENOTCONN] = "ENOTCONN"; errorcode[ENOTDIR] = "ENOTDIR"; errorcode[ENOTEMPTY] = "ENOTEMPTY"; errorcode[ENOTSOCK] = "ENOTSOCK"; errorcode[ENOTTY] = "ENOTTY"; errorcode[ENXIO] = "ENXIO"; errorcode[EOPNOTSUPP] = "EOPNOTSUPP"; errorcode[EPERM] = "EPERM"; errorcode[EPFNOSUPPORT] = "EPFNOSUPPORT"; errorcode[EPIPE] = "EPIPE"; errorcode[EPROTONOSUPPORT] = "EPROTONOSUPPORT"; errorcode[EPROTOTYPE] = "EPROTOTYPE"; errorcode[ERANGE] = "ERANGE"; errorcode[EREMOTE] = "EREMOTE"; errorcode[EROFS] = "EROFS"; errorcode[ESHUTDOWN] = "ESHUTDOWN"; errorcode[ESOCKTNOSUPPORT] = "ESOCKTNOSUPPORT"; errorcode[ESPIPE] = "ESPIPE"; errorcode[ESRCH] = "ESRCH"; errorcode[ESTALE] = "ESTALE"; errorcode[ETIMEDOUT] = "ETIMEDOUT"; errorcode[ETOOMANYREFS] = "ETOOMANYREFS"; errorcode[EUSERS] = "EUSERS"; errorcode[EWOULDBLOCK] = "EWOULDBLOCK"; errorcode[EXDEV] = "EXDEV"; errorcode[WSABASEERR] = "WSABASEERR"; errorcode[WSAEACCES] = "WSAEACCES"; errorcode[WSAEADDRINUSE] = "WSAEADDRINUSE"; errorcode[WSAEADDRNOTAVAIL] = "WSAEADDRNOTAVAIL"; errorcode[WSAEAFNOSUPPORT] = "WSAEAFNOSUPPORT"; errorcode[WSAEALREADY] = "WSAEALREADY"; errorcode[WSAEBADF] = "WSAEBADF"; errorcode[WSAECONNABORTED] = "WSAECONNABORTED"; errorcode[WSAECONNREFUSED] = "WSAECONNREFUSED"; errorcode[WSAECONNRESET] = "WSAECONNRESET"; errorcode[WSAEDESTADDRREQ] = "WSAEDESTADDRREQ"; errorcode[WSAEDISCON] = "WSAEDISCON"; errorcode[WSAEDQUOT] = "WSAEDQUOT"; errorcode[WSAEFAULT] = "WSAEFAULT"; errorcode[WSAEHOSTDOWN] = "WSAEHOSTDOWN"; errorcode[WSAEHOSTUNREACH] = "WSAEHOSTUNREACH"; errorcode[WSAEINPROGRESS] = "WSAEINPROGRESS"; errorcode[WSAEINTR] = "WSAEINTR"; errorcode[WSAEINVAL] = "WSAEINVAL"; errorcode[WSAEISCONN] = "WSAEISCONN"; errorcode[WSAELOOP] = "WSAELOOP"; errorcode[WSAEMFILE] = "WSAEMFILE"; errorcode[WSAEMSGSIZE] = "WSAEMSGSIZE"; errorcode[WSAENAMETOOLONG] = "WSAENAMETOOLONG"; errorcode[WSAENETDOWN] = "WSAENETDOWN"; errorcode[WSAENETRESET] = "WSAENETRESET"; errorcode[WSAENETUNREACH] = "WSAENETUNREACH"; errorcode[WSAENOBUFS] = "WSAENOBUFS"; errorcode[WSAENOPROTOOPT] = "WSAENOPROTOOPT"; errorcode[WSAENOTCONN] = "WSAENOTCONN"; errorcode[WSAENOTEMPTY] = "WSAENOTEMPTY"; errorcode[WSAENOTSOCK] = "WSAENOTSOCK"; errorcode[WSAEOPNOTSUPP] = "WSAEOPNOTSUPP"; errorcode[WSAEPFNOSUPPORT] = "WSAEPFNOSUPPORT"; errorcode[WSAEPROCLIM] = "WSAEPROCLIM"; errorcode[WSAEPROTONOSUPPORT] = "WSAEPROTONOSUPPORT"; errorcode[WSAEPROTOTYPE] = "WSAEPROTOTYPE"; errorcode[WSAEREMOTE] = "WSAEREMOTE"; errorcode[WSAESHUTDOWN] = "WSAESHUTDOWN"; errorcode[WSAESOCKTNOSUPPORT] = "WSAESOCKTNOSUPPORT"; errorcode[WSAESTALE] = "WSAESTALE"; errorcode[WSAETIMEDOUT] = "WSAETIMEDOUT"; errorcode[WSAETOOMANYREFS] = "WSAETOOMANYREFS"; errorcode[WSAEUSERS] = "WSAEUSERS"; errorcode[WSAEWOULDBLOCK] = "WSAEWOULDBLOCK"; errorcode[WSANOTINITIALISED] = "WSANOTINITIALISED"; errorcode[WSASYSNOTREADY] = "WSASYSNOTREADY"; errorcode[WSAVERNOTSUPPORTED] = "WSAVERNOTSUPPORTED"; dict["errorcode"] = errorcode; } public const int E2BIG = 7; public const int EACCES = 13; public const int EADDRINUSE = 10048; public const int EADDRNOTAVAIL = 10049; public const int EAFNOSUPPORT = 10047; public const int EAGAIN = 11; public const int EALREADY = 10037; public const int EBADF = 9; public const int EBUSY = 16; public const int ECHILD = 10; public const int ECONNABORTED = 10053; public const int ECONNREFUSED = 10061; public const int ECONNRESET = 10054; public const int EDEADLK = 36; public const int EDEADLOCK = 36; public const int EDESTADDRREQ = 10039; public const int EDOM = 33; public const int EDQUOT = 10069; public const int EEXIST = 17; public const int EFAULT = 14; public const int EFBIG = 27; public const int EHOSTDOWN = 10064; public const int EHOSTUNREACH = 10065; public const int EILSEQ = 42; public const int EINPROGRESS = 10036; public const int EINTR = 4; public const int EINVAL = 22; public const int EIO = 5; public const int EISCONN = 10056; public const int EISDIR = 21; public const int ELOOP = 10062; public const int EMFILE = 24; public const int EMLINK = 31; public const int EMSGSIZE = 10040; public const int ENAMETOOLONG = 38; public const int ENETDOWN = 10050; public const int ENETRESET = 10052; public const int ENETUNREACH = 10051; public const int ENFILE = 23; public const int ENOBUFS = 10055; public const int ENODEV = 19; public const int ENOENT = 2; public const int ENOEXEC = 8; public const int ENOLCK = 39; public const int ENOMEM = 12; public const int ENOPROTOOPT = 10042; public const int ENOSPC = 28; public const int ENOSYS = 40; public const int ENOTCONN = 10057; public const int ENOTDIR = 20; public const int ENOTEMPTY = 41; public const int ENOTSOCK = 10038; public const int ENOTTY = 25; public const int ENXIO = 6; public const int EOPNOTSUPP = 10045; public const int EPERM = 1; public const int EPFNOSUPPORT = 10046; public const int EPIPE = 32; public const int EPROTONOSUPPORT = 10043; public const int EPROTOTYPE = 10041; public const int ERANGE = 34; public const int EREMOTE = 10071; public const int EROFS = 30; public const int ESHUTDOWN = 10058; public const int ESOCKTNOSUPPORT = 10044; public const int ESPIPE = 29; public const int ESRCH = 3; public const int ESTALE = 10070; public const int ETIMEDOUT = 10060; public const int ETOOMANYREFS = 10059; public const int EUSERS = 10068; public const int EWOULDBLOCK = 10035; public const int EXDEV = 18; public const int WSABASEERR = 10000; public const int WSAEACCES = 10013; public const int WSAEADDRINUSE = 10048; public const int WSAEADDRNOTAVAIL = 10049; public const int WSAEAFNOSUPPORT = 10047; public const int WSAEALREADY = 10037; public const int WSAEBADF = 10009; public const int WSAECONNABORTED = 10053; public const int WSAECONNREFUSED = 10061; public const int WSAECONNRESET = 10054; public const int WSAEDESTADDRREQ = 10039; public const int WSAEDISCON = 10101; public const int WSAEDQUOT = 10069; public const int WSAEFAULT = 10014; public const int WSAEHOSTDOWN = 10064; public const int WSAEHOSTUNREACH = 10065; public const int WSAEINPROGRESS = 10036; public const int WSAEINTR = 10004; public const int WSAEINVAL = 10022; public const int WSAEISCONN = 10056; public const int WSAELOOP = 10062; public const int WSAEMFILE = 10024; public const int WSAEMSGSIZE = 10040; public const int WSAENAMETOOLONG = 10063; public const int WSAENETDOWN = 10050; public const int WSAENETRESET = 10052; public const int WSAENETUNREACH = 10051; public const int WSAENOBUFS = 10055; public const int WSAENOPROTOOPT = 10042; public const int WSAENOTCONN = 10057; public const int WSAENOTEMPTY = 10066; public const int WSAENOTSOCK = 10038; public const int WSAEOPNOTSUPP = 10045; public const int WSAEPFNOSUPPORT = 10046; public const int WSAEPROCLIM = 10067; public const int WSAEPROTONOSUPPORT = 10043; public const int WSAEPROTOTYPE = 10041; public const int WSAEREMOTE = 10071; public const int WSAESHUTDOWN = 10058; public const int WSAESOCKTNOSUPPORT = 10044; public const int WSAESTALE = 10070; public const int WSAETIMEDOUT = 10060; public const int WSAETOOMANYREFS = 10059; public const int WSAEUSERS = 10068; public const int WSAEWOULDBLOCK = 10035; public const int WSANOTINITIALISED = 10093; public const int WSASYSNOTREADY = 10091; public const int WSAVERNOTSUPPORTED = 10092; } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// An adult entertainment establishment. /// </summary> public class AdultEntertainment_Core : TypeCore, IEntertainmentBusiness { public AdultEntertainment_Core() { this._TypeId = 11; this._Id = "AdultEntertainment"; this._Schema_Org_Url = "http://schema.org/AdultEntertainment"; string label = ""; GetLabel(out label, "AdultEntertainment", typeof(AdultEntertainment_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,96}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{96}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.IO; using System.Collections; using System.Text; using RdlEngine.Resources; namespace fyiReporting.RDL { /// <summary> /// A simple Lexer that is used by Parser. /// </summary> internal class Lexer { private TokenList tokens; private CharReader reader; /// <summary> /// Initializes a new instance of the Lexer class with the specified /// expression syntax to lex. /// </summary> /// <param name="expr">An expression to lex.</param> internal Lexer(string expr) : this(new StringReader(expr)) { // use this } /// <summary> /// Initializes a new instance of the Lexer class with the specified /// TextReader to lex. /// </summary> /// <param name="source">A TextReader to lex.</param> internal Lexer(TextReader source) { // token queue tokens = new TokenList(); // read the file contents reader = new CharReader(source); } /// <summary> /// Breaks the input stream onto the tokens list and returns it. /// </summary> /// <returns>The tokens list.</returns> internal TokenList Lex() { Token token = GetNextToken(); while(true) { if(token != null) tokens.Add(token); else { tokens.Add(new Token(null, reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.EOF)); return tokens; } token = GetNextToken(); } } private Token GetNextToken() { while(!reader.EndOfInput()) { char ch = reader.GetNext(); // skipping whitespaces if(Char.IsWhiteSpace(ch)) { continue; } switch(ch) { case '=': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.EQUAL); case '+': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.PLUS); case '-': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.MINUS); case '(': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.LPAREN); case ')': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.RPAREN); case ',': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.COMMA); case '^': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.EXP); case '%': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.MODULUS); case '!': if (reader.Peek() == '=') { reader.GetNext(); // go past the equal return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.NOTEQUAL); } else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.NOT); case '&': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.PLUSSTRING); case '|': if (reader.Peek() == '|') { reader.GetNext(); // go past the '|' return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.OR); } break; case '>': if (reader.Peek() == '=') { reader.GetNext(); // go past the equal return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.GREATERTHANOREQUAL); } else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.GREATERTHAN); case '/': if (reader.Peek() == '*') { // beginning of a comment of form /* a comment */ reader.GetNext(); // go past the '*' ReadComment(); continue; } else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.FORWARDSLASH); case '<': if (reader.Peek() == '=') { reader.GetNext(); // go past the equal return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.LESSTHANOREQUAL); } else if (reader.Peek() == '>') { reader.GetNext(); // go past the > return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.NOTEQUAL); } else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.LESSTHAN); case '*': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.STAR); case '"': case '\'': return ReadQuoted(ch); case '{': return ReadIdentifier(ch, 4); default: break; } // end of swith if (Char.IsDigit(ch)) return ReadNumber(ch); else if (ch == '.') { char tc = reader.Peek(); if (Char.IsDigit(tc)) return ReadNumber(ch); return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.DOT); } else if (Char.IsLetter(ch) || ch == '_') return ReadIdentifier(ch); else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.OTHER); } return null; } // Reads a decimal number with optional exponentiation private Token ReadNumber(char ch) { const char separator = '.'; // maybe CurrentCulture.NumberFormat.NumberDecimalSeparator ??? TODO int startLine = reader.Line; int startCol = reader.Column; bool bDecimal = ch == separator ? true : false; bool bDecimalType=false; // found d or D in number bool bFloat=false; // found e or E in number char cPeek; string number = ch.ToString(); while(!reader.EndOfInput() ) { cPeek = reader.Peek(); if (Char.IsWhiteSpace(cPeek)) break; if (Char.IsDigit(cPeek)) number += reader.GetNext(); else if ((cPeek == 'd' || cPeek == 'D') && !bFloat) { reader.GetNext(); // skip the 'd' bDecimalType = true; break; } else if ((cPeek == 'e' || cPeek == 'E') && !bFloat) { number += reader.GetNext(); // add the 'e' cPeek = reader.Peek(); if (cPeek == '-' || cPeek == '+') // +/- after e is optional assumes + number += reader.GetNext(); bFloat = true; if (Char.IsDigit(reader.Peek())) continue; throw new ParserException(Strings.Lexer_ErrorP_InvalidNumberConstant); } else if (!bDecimal && !bFloat && cPeek == separator) // can't already be decimal or float { bDecimal = true; number += reader.GetNext(); } else break; // another character } if (number.CompareTo(separator.ToString()) == 0) throw new ParserException(string.Format(Strings.Lexer_Error_SeparatorMustFollowedNumber, separator)); TokenTypes t; if (bDecimalType) t = TokenTypes.NUMBER; else if (bFloat || bDecimal) t = TokenTypes.DOUBLE; else t = TokenTypes.INTEGER; return new Token(number, startLine, startCol, reader.Line, reader.Column, t); } // Reads an identifier: // Must consist of letters, digits, "_". "!", "." are allowed // but have special meaning that is disambiguated later private Token ReadIdentifier(char ch) { return ReadIdentifier(ch, 1); } // Reads an identifier: // Must consist of letters, digits, "_". "!", "." are allowed // but have special meaning that is disambiguated later // Josh: 6:21:10 overloaded to allow for setting initial state. private Token ReadIdentifier(char ch, int initialState) { int startLine = reader.Line; int startCol = reader.Column; char cPeek; StringBuilder identifier = new StringBuilder(30); // initial capacity 30 characters identifier.Append(ch.ToString()); int state = initialState; // state=1 means accept letter,digit,'.','!','_' // state=2 means accept whitespace ends with '.' or '!' // state=3 means accept letter to start new qualifier while (!reader.EndOfInput()) { cPeek = reader.Peek(); if (state == 1) { if (Char.IsLetterOrDigit(cPeek) || cPeek == '.' || cPeek == '!' || cPeek == '_') identifier.Append(reader.GetNext()); else if (Char.IsWhiteSpace(cPeek)) { reader.GetNext(); // skip space if (identifier[identifier.Length - 1] == '.' || identifier[identifier.Length - 1] == '!') state = 3; // need to have an identfier next else state = 2; // need to get '.' or '!' next } else break; } else if (state == 2) { // state must equal 2 if (cPeek == '.' || cPeek == '!') { state = 3; identifier.Append(reader.GetNext()); } else if (Char.IsWhiteSpace(cPeek)) reader.GetNext(); else break; } else if (state == 3) { // state must equal 3 if (Char.IsLetter(cPeek) || cPeek == '_') { state = 1; identifier.Append(reader.GetNext()); } else if (Char.IsWhiteSpace(cPeek)) { reader.GetNext(); } else break; } else if (state == 4) { // state must equal 4 Josh: 6:21:10 added state 4 for field/param shortcuts if (Char.IsLetterOrDigit(cPeek) || cPeek == '@' || cPeek == '?' || cPeek == '_' || cPeek == '}' || cPeek == '!') identifier.Append(reader.GetNext()); if (cPeek == '}') break; else if (Char.IsWhiteSpace(cPeek)) { reader.GetNext(); // skip space } } } string key = identifier.ToString().ToLower(); if (key == "and" || key == "andalso") // technically 'and' and 'andalso' mean different things; but we treat the same return new Token(identifier.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.AND); else if (key == "or" || key == "orelse") // technically 'or' and 'orelse' mean different things; but we treat the same return new Token(identifier.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.OR); else if (key == "not") return new Token(identifier.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.NOT); else if (key == "mod") return new Token(identifier.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.MODULUS); //Shortcut identifier if (state == 4) { if (identifier[identifier.Length - 1] != '}') identifier.Append('}'); identifier = new StringBuilder(ParseShortcut(identifier.ToString())); } // normal identifier return new Token(identifier.ToString(), startLine, startCol, reader.Line, reader.Column, TokenTypes.IDENTIFIER); } // Quoted string like " asdf " or ' asdf ' private Token ReadQuoted(char ch) { char qChar = ch; int startLine = reader.Line; int startCol = reader.Column; StringBuilder quoted = new StringBuilder(); while(!reader.EndOfInput()) { ch = reader.GetNext(); if (ch == '\\') { char pChar = reader.Peek(); if (pChar == qChar) ch = reader.GetNext(); // got one skip escape char else if (pChar == 'n') { ch = '\n'; reader.GetNext(); // skip the character } else if (pChar == 'r') { ch = '\r'; reader.GetNext(); // skip the character } else if (pChar == '\\') { ch = '\\'; reader.GetNext(); } } else if (ch == qChar) { if (reader.Peek() == ch) // did user double the quote? ch = reader.GetNext(); // yes, we just append one character else return new Token(quoted.ToString(), startLine, startCol, reader.Line, reader.Column, TokenTypes.QUOTE); } quoted.Append(ch); } throw new ParserException(Strings.Lexer_ErrorP_UnterminatedString); } // Comment string like /* this is a comment */ private void ReadComment() { char ch; while(!reader.EndOfInput()) { ch = reader.GetNext(); if (ch == '*' && reader.Peek() == '/') { reader.GetNext(); // skip past the '/' return; } } throw new ParserException(Strings.Lexer_Error_UnterminatedComment); } // fields, parameters, and globals // Shortcuts for fields, parameters, globals private string ParseShortcut(string identifier) { if (identifier.StartsWith("{?")) { identifier = identifier.Replace("{?", "Parameters!"); identifier = identifier.Replace("}", ".Value"); } else if (identifier.StartsWith("{@")) { identifier = identifier.Replace("{@", "Globals!"); identifier = identifier.Replace("}", ""); } else if (identifier.StartsWith("{!")) { identifier = identifier.Replace("{!", "User!"); identifier = identifier.Replace("}", ""); } else if (identifier.StartsWith("{")) { identifier = identifier.Replace("{", "Fields!"); identifier = identifier.Replace("}", ".Value"); } return identifier; } // // Handles case of "<", "<=", and "<! ... xml string !> // private Token ReadXML(char ch) // { // int startLine = reader.Line; // int startCol = reader.Column; // // if (reader.EndOfInput()) // return new Token(ch.ToString(), startLine, startCol, startLine, startCol, TokenTypes.LESSTHAN); // ch = reader.GetNext(); // if (ch == '=') // return new Token("<=", startLine, startCol, reader.Line, reader.Column, TokenTypes.LESSTHANOREQUAL); // if (ch != '!') // If it's not '!' then it's not XML // { // reader.UnGet(); // put back the character // return new Token("<", startLine, startCol, reader.Line, reader.Column, TokenTypes.LESSTHAN); // } // // string xml = ""; // intialize our string // // while(!reader.EndOfInput()) // { // ch = reader.GetNext(); // // if(ch == '!') // check for end of XML denoted by "!>" // { // if (!reader.EndOfInput() && reader.Peek() == '>') // { // reader.GetNext(); // pull the '>' off the input // return new Token(xml, startLine, startCol, reader.Line, reader.Column, TokenTypes.XML); // } // } // // xml += ch.ToString(); // } // throw new ParserException("Unterminated XML clause!"); // } } }