context
stringlengths
2.52k
185k
gt
stringclasses
1 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.Text; using System.Diagnostics; using System.Runtime.InteropServices; using CryptographicException = System.Security.Cryptography.CryptographicException; using SafeBCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeBCryptKeyHandle; using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle; using X509KeyUsageFlags = System.Security.Cryptography.X509Certificates.X509KeyUsageFlags; using SafeNCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle; using Internal.Cryptography; using Internal.Cryptography.Pal.Native; using Microsoft.Win32.SafeHandles; internal static partial class Interop { public static partial class crypt32 { [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CryptQueryObject( CertQueryObjectType dwObjectType, void* pvObject, ExpectedContentTypeFlags dwExpectedContentTypeFlags, ExpectedFormatTypeFlags dwExpectedFormatTypeFlags, int dwFlags, // reserved - always pass 0 out CertEncodingType pdwMsgAndCertEncodingType, out ContentType pdwContentType, out FormatType pdwFormatType, out SafeCertStoreHandle phCertStore, out SafeCryptMsgHandle phMsg, out SafeCertContextHandle ppvContext ); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CryptQueryObject( CertQueryObjectType dwObjectType, void* pvObject, ExpectedContentTypeFlags dwExpectedContentTypeFlags, ExpectedFormatTypeFlags dwExpectedFormatTypeFlags, int dwFlags, // reserved - always pass 0 IntPtr pdwMsgAndCertEncodingType, out ContentType pdwContentType, IntPtr pdwFormatType, IntPtr phCertStore, IntPtr phMsg, IntPtr ppvContext ); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CryptQueryObject( CertQueryObjectType dwObjectType, void* pvObject, ExpectedContentTypeFlags dwExpectedContentTypeFlags, ExpectedFormatTypeFlags dwExpectedFormatTypeFlags, int dwFlags, // reserved - always pass 0 IntPtr pdwMsgAndCertEncodingType, out ContentType pdwContentType, IntPtr pdwFormatType, out SafeCertStoreHandle phCertStore, IntPtr phMsg, IntPtr ppvContext ); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] byte[] pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] out CRYPTOAPI_BLOB pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] out IntPtr pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetCertificateContextProperty")] public static extern bool CertGetCertificateContextPropertyString(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] StringBuilder pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPTOAPI_BLOB* pvData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPT_KEY_PROV_INFO* pvData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] SafeNCryptKeyHandle keyHandle); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")] public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStringType pvTypePara, [Out] StringBuilder pszNameString, int cchNameString); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeCertContextHandle CertDuplicateCertificateContext(IntPtr pCertContext); [DllImport(Libraries.Crypt32, SetLastError = true)] public static extern SafeX509ChainHandle CertDuplicateCertificateChain(IntPtr pChainContext); [DllImport(Libraries.Crypt32, SetLastError = true)] internal static extern SafeCertStoreHandle CertDuplicateStore(IntPtr hCertStore); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertDuplicateCertificateContext")] public static extern SafeCertContextHandleWithKeyContainerDeletion CertDuplicateCertificateContextWithKeyContainerDeletion(IntPtr pCertContext); public static SafeCertStoreHandle CertOpenStore(CertStoreProvider lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, string pvPara) { return CertOpenStore((IntPtr)lpszStoreProvider, dwMsgAndCertEncodingType, hCryptProv, dwFlags, pvPara); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern SafeCertStoreHandle CertOpenStore(IntPtr lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pvPara); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertAddCertificateContextToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertAddCertificateLinkToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext); /// <summary> /// A less error-prone wrapper for CertEnumCertificatesInStore(). /// /// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with /// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle /// and returns "false" to indicate the end of the store has been reached. /// </summary> public static bool CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, ref SafeCertContextHandle pCertContext) { unsafe { CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect(); pCertContext = CertEnumCertificatesInStore(hCertStore, pPrevCertContext); return !pCertContext.IsInvalid; } } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern unsafe SafeCertContextHandle CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, CERT_CONTEXT* pPrevCertContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern SafeCertStoreHandle PFXImportCertStore([In] ref CRYPTOAPI_BLOB pPFX, SafePasswordHandle password, PfxCertStoreFlags dwFlags); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, byte* pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, out int pvData, [In, Out] ref int pcbData); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertSerializeCertificateStoreElement(SafeCertContextHandle pCertContext, int dwFlags, [Out] byte[] pbElement, [In, Out] ref int pcbElement); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool PFXExportCertStore(SafeCertStoreHandle hStore, [In, Out] ref CRYPTOAPI_BLOB pPFX, SafePasswordHandle szPassword, PFXExportFlags dwFlags); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertNameToStrW")] public static extern int CertNameToStr(CertEncodingType dwCertEncodingType, [In] ref CRYPTOAPI_BLOB pName, CertNameStrTypeAndFlags dwStrType, StringBuilder psz, int csz); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertStrToNameW")] public static extern bool CertStrToName(CertEncodingType dwCertEncodingType, string pszX500, CertNameStrTypeAndFlags dwStrType, IntPtr pvReserved, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded, IntPtr ppszError); public static bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, FormatObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, StringBuilder pbFormat, ref int pcbFormat) { return CryptFormatObject(dwCertEncodingType, dwFormatType, dwFormatStrType, pFormatStruct, (IntPtr)lpszStructType, pbEncoded, cbEncoded, pbFormat, ref pcbFormat); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool CryptFormatObject(CertEncodingType dwCertEncodingType, FormatObjectType dwFormatType, FormatObjectStringType dwFormatStrType, IntPtr pFormatStruct, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, [Out] StringBuilder pbFormat, [In, Out] ref int pcbFormat); public static bool CryptDecodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, byte[] pvStructInfo, ref int pcbStructInfo) { return CryptDecodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool CryptDecodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] byte[] pvStructInfo, [In, Out] ref int pcbStructInfo); public static unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, void* pvStructInfo, ref int pcbStructInfo) { return CryptDecodeObjectPointer(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")] private static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")] public static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo); public static unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[] pbEncoded, ref int pcbEncoded) { return CryptEncodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pvStructInfo, pbEncoded, ref pcbEncoded); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded); public static unsafe byte[] EncodeObject(CryptDecodeObjectStructType lpszStructType, void* decoded) { int cb = 0; if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb)) throw Marshal.GetLastWin32Error().ToCryptographicException(); byte[] encoded = new byte[cb]; if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return encoded; } public static unsafe byte[] EncodeObject(string lpszStructType, void* decoded) { int cb = 0; if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb)) throw Marshal.GetLastWin32Error().ToCryptographicException(); byte[] encoded = new byte[cb]; if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return encoded; } public static unsafe bool CertGetCertificateChain(ChainEngine hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext) { return CertGetCertificateChain((IntPtr)hChainEngine, pCertContext, pTime, hStore, ref pChainPara, dwFlags, pvReserved, out ppChainContext); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern unsafe bool CertGetCertificateChain(IntPtr hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CryptHashPublicKeyInfo(IntPtr hCryptProv, int algId, int dwFlags, CertEncodingType dwCertEncodingType, [In] ref CERT_PUBLIC_KEY_INFO pInfo, [Out] byte[] pbComputedHash, [In, Out] ref int pcbComputedHash); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")] public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStrTypeAndFlags pvPara, [Out] StringBuilder pszNameString, int cchNameString); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertSaveStore(SafeCertStoreHandle hCertStore, CertEncodingType dwMsgAndCertEncodingType, CertStoreSaveAs dwSaveAs, CertStoreSaveTo dwSaveTo, ref CRYPTOAPI_BLOB pvSaveToPara, int dwFlags); /// <summary> /// A less error-prone wrapper for CertEnumCertificatesInStore(). /// /// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with /// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle /// and returns "false" to indicate the end of the store has been reached. /// </summary> public static unsafe bool CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertFindType dwFindType, void* pvFindPara, ref SafeCertContextHandle pCertContext) { CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect(); pCertContext = CertFindCertificateInStore(hCertStore, CertEncodingType.All, CertFindFlags.None, dwFindType, pvFindPara, pPrevCertContext); return !pCertContext.IsInvalid; } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern unsafe SafeCertContextHandle CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertEncodingType dwCertEncodingType, CertFindFlags dwFindFlags, CertFindType dwFindType, void* pvFindPara, CERT_CONTEXT* pPrevCertContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe int CertVerifyTimeValidity([In] ref FILETIME pTimeToVerify, [In] CERT_INFO* pCertInfo); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe CERT_EXTENSION* CertFindExtension([MarshalAs(UnmanagedType.LPStr)] string pszObjId, int cExtensions, CERT_EXTENSION* rgExtensions); // Note: It's somewhat unusual to use an API enum as a parameter type to a P/Invoke but in this case, X509KeyUsageFlags was intentionally designed as bit-wise // identical to the wincrypt CERT_*_USAGE values. [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CertGetIntendedKeyUsage(CertEncodingType dwCertEncodingType, CERT_INFO* pCertInfo, out X509KeyUsageFlags pbKeyUsage, int cbKeyUsage); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CertGetValidUsages(int cCerts, [In] ref SafeCertContextHandle rghCerts, out int cNumOIDs, [Out] void* rghOIDs, [In, Out] ref int pcbOIDs); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertControlStore(SafeCertStoreHandle hCertStore, CertControlStoreFlags dwFlags, CertControlStoreType dwControlType, IntPtr pvCtrlPara); // Note: CertDeleteCertificateFromStore always calls CertFreeCertificateContext on pCertContext, even if an error is encountered. [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CertDeleteCertificateFromStore(CERT_CONTEXT* pCertContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void CertFreeCertificateChain(IntPtr pChainContext); public static bool CertVerifyCertificateChainPolicy(ChainPolicy pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus) { return CertVerifyCertificateChainPolicy((IntPtr)pszPolicyOID, pChainContext, ref pPolicyPara, ref pPolicyStatus); } [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool CertVerifyCertificateChainPolicy(IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, [In] ref CERT_CHAIN_POLICY_PARA pPolicyPara, [In, Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertFreeCertificateContext(IntPtr pCertContext); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags); [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CryptMsgClose(IntPtr hCryptMsg); #if !uap [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern unsafe bool CryptImportPublicKeyInfoEx2(CertEncodingType dwCertEncodingType, CERT_PUBLIC_KEY_INFO* pInfo, int dwFlags, void* pvAuxInfo, out SafeBCryptKeyHandle phKey); #endif [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert, CryptAcquireFlags dwFlags, IntPtr pvParameters, out SafeNCryptKeyHandle phCryptProvOrNCryptKey, out int pdwKeySpec, out bool pfCallerFreeProvOrNCryptKey); } }
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A pool in the Azure Batch service. /// </summary> public partial class CloudPool : ITransportObjectProvider<Models.PoolAddParameter>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<Common.AllocationState?> AllocationStateProperty; public readonly PropertyAccessor<DateTime?> AllocationStateTransitionTimeProperty; public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty; public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty; public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty; public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty; public readonly PropertyAccessor<string> AutoScaleFormulaProperty; public readonly PropertyAccessor<AutoScaleRun> AutoScaleRunProperty; public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty; public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty; public readonly PropertyAccessor<DateTime?> CreationTimeProperty; public readonly PropertyAccessor<int?> CurrentDedicatedComputeNodesProperty; public readonly PropertyAccessor<int?> CurrentLowPriorityComputeNodesProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<string> ETagProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty; public readonly PropertyAccessor<DateTime?> LastModifiedProperty; public readonly PropertyAccessor<int?> MaxTasksPerComputeNodeProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty; public readonly PropertyAccessor<IReadOnlyList<ResizeError>> ResizeErrorsProperty; public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty; public readonly PropertyAccessor<StartTask> StartTaskProperty; public readonly PropertyAccessor<Common.PoolState?> StateProperty; public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty; public readonly PropertyAccessor<PoolStatistics> StatisticsProperty; public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty; public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty; public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty; public readonly PropertyAccessor<string> UrlProperty; public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty; public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty; public readonly PropertyAccessor<string> VirtualMachineSizeProperty; public PropertyContainer() : base(BindingState.Unbound) { this.AllocationStateProperty = this.CreatePropertyAccessor<Common.AllocationState?>(nameof(AllocationState), BindingAccess.None); this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(AllocationStateTransitionTime), BindingAccess.None); this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write); this.AutoScaleRunProperty = this.CreatePropertyAccessor<AutoScaleRun>(nameof(AutoScaleRun), BindingAccess.None); this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None); this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentDedicatedComputeNodes), BindingAccess.None); this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentLowPriorityComputeNodes), BindingAccess.None); this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None); this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write); this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None); this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor<int?>(nameof(MaxTasksPerComputeNode), BindingAccess.Read | BindingAccess.Write); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write); this.ResizeErrorsProperty = this.CreatePropertyAccessor<IReadOnlyList<ResizeError>>(nameof(ResizeErrors), BindingAccess.None); this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write); this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>(nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor<Common.PoolState?>(nameof(State), BindingAccess.None); this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None); this.StatisticsProperty = this.CreatePropertyAccessor<PoolStatistics>(nameof(Statistics), BindingAccess.None); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write); this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None); this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.CloudPool protocolObject) : base(BindingState.Bound) { this.AllocationStateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.AllocationState, Common.AllocationState>(protocolObject.AllocationState), nameof(AllocationState), BindingAccess.Read); this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.AllocationStateTransitionTime, nameof(AllocationStateTransitionTime), BindingAccess.Read); this.ApplicationLicensesProperty = this.CreatePropertyAccessor( UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o), nameof(ApplicationLicenses), BindingAccess.Read); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor( ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences), nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableAutoScale, nameof(AutoScaleEnabled), BindingAccess.Read); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleEvaluationInterval, nameof(AutoScaleEvaluationInterval), BindingAccess.Read); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleFormula, nameof(AutoScaleFormula), BindingAccess.Read); this.AutoScaleRunProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AutoScaleRun, o => new AutoScaleRun(o).Freeze()), nameof(AutoScaleRun), BindingAccess.Read); this.CertificateReferencesProperty = this.CreatePropertyAccessor( CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences), nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o).Freeze()), nameof(CloudServiceConfiguration), BindingAccess.Read); this.CreationTimeProperty = this.CreatePropertyAccessor( protocolObject.CreationTime, nameof(CreationTime), BindingAccess.Read); this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.CurrentDedicatedNodes, nameof(CurrentDedicatedComputeNodes), BindingAccess.Read); this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.CurrentLowPriorityNodes, nameof(CurrentLowPriorityComputeNodes), BindingAccess.Read); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, nameof(DisplayName), BindingAccess.Read); this.ETagProperty = this.CreatePropertyAccessor( protocolObject.ETag, nameof(ETag), BindingAccess.Read); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, nameof(Id), BindingAccess.Read); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableInterNodeCommunication, nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read); this.LastModifiedProperty = this.CreatePropertyAccessor( protocolObject.LastModified, nameof(LastModified), BindingAccess.Read); this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor( protocolObject.MaxTasksPerNode, nameof(MaxTasksPerComputeNode), BindingAccess.Read); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()), nameof(NetworkConfiguration), BindingAccess.Read); this.ResizeErrorsProperty = this.CreatePropertyAccessor( ResizeError.ConvertFromProtocolCollectionReadOnly(protocolObject.ResizeErrors), nameof(ResizeErrors), BindingAccess.Read); this.ResizeTimeoutProperty = this.CreatePropertyAccessor( protocolObject.ResizeTimeout, nameof(ResizeTimeout), BindingAccess.Read); this.StartTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)), nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.PoolState, Common.PoolState>(protocolObject.State), nameof(State), BindingAccess.Read); this.StateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.StateTransitionTime, nameof(StateTransitionTime), BindingAccess.Read); this.StatisticsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new PoolStatistics(o).Freeze()), nameof(Statistics), BindingAccess.Read); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetDedicatedNodes, nameof(TargetDedicatedComputeNodes), BindingAccess.Read); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetLowPriorityNodes, nameof(TargetLowPriorityComputeNodes), BindingAccess.Read); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o).Freeze()), nameof(TaskSchedulingPolicy), BindingAccess.Read); this.UrlProperty = this.CreatePropertyAccessor( protocolObject.Url, nameof(Url), BindingAccess.Read); this.UserAccountsProperty = this.CreatePropertyAccessor( UserAccount.ConvertFromProtocolCollectionAndFreeze(protocolObject.UserAccounts), nameof(UserAccounts), BindingAccess.Read); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o).Freeze()), nameof(VirtualMachineConfiguration), BindingAccess.Read); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor( protocolObject.VmSize, nameof(VirtualMachineSize), BindingAccess.Read); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CloudPool"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> internal CloudPool( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } internal CloudPool( BatchClient parentBatchClient, Models.CloudPool protocolObject, IEnumerable<BatchClientBehavior> baseBehaviors) { this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="CloudPool"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region CloudPool /// <summary> /// Gets an <see cref="Common.AllocationState"/> which indicates what node allocation activity is occurring on the /// pool. /// </summary> public Common.AllocationState? AllocationState { get { return this.propertyContainer.AllocationStateProperty.Value; } } /// <summary> /// Gets the time at which the pool entered its current <see cref="AllocationState"/>. /// </summary> public DateTime? AllocationStateTransitionTime { get { return this.propertyContainer.AllocationStateTransitionTimeProperty.Value; } } /// <summary> /// Gets or sets the list of application licenses the Batch service will make available on each compute node in the /// pool. /// </summary> /// <remarks> /// <para>The list of application licenses must be a subset of available Batch service application licenses.</para><para>The /// permitted licenses available on the pool are 'maya', 'vray', '3dsmax', 'arnold'. An additional charge applies /// for each application license added to the pool.</para> /// </remarks> public IList<string> ApplicationLicenses { get { return this.propertyContainer.ApplicationLicensesProperty.Value; } set { this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value); } } /// <summary> /// Gets or sets a list of application packages to be installed on each compute node in the pool. /// </summary> public IList<ApplicationPackageReference> ApplicationPackageReferences { get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; } set { this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets whether the pool size should automatically adjust according to the <see cref="AutoScaleFormula"/>. /// </summary> /// <remarks> /// <para>If true, the <see cref="AutoScaleFormula"/> property is required, the pool automatically resizes according /// to the formula, and <see cref="TargetDedicatedComputeNodes"/> and <see cref="TargetLowPriorityComputeNodes"/> /// must be null.</para> <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/> /// properties is required.</para><para>The default value is false.</para> /// </remarks> public bool? AutoScaleEnabled { get { return this.propertyContainer.AutoScaleEnabledProperty.Value; } set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; } } /// <summary> /// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>. /// </summary> /// <remarks> /// The default value is 15 minutes. The minimum allowed value is 5 minutes. /// </remarks> public TimeSpan? AutoScaleEvaluationInterval { get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; } set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; } } /// <summary> /// Gets or sets a formula for the desired number of compute nodes in the pool. /// </summary> /// <remarks> /// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/. /// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled /// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid, /// an exception is thrown when you try to commit the <see cref="CloudPool"/>.</para> /// </remarks> public string AutoScaleFormula { get { return this.propertyContainer.AutoScaleFormulaProperty.Value; } set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; } } /// <summary> /// Gets the results and errors from the last execution of the <see cref="AutoScaleFormula"/>. /// </summary> public AutoScaleRun AutoScaleRun { get { return this.propertyContainer.AutoScaleRunProperty.Value; } } /// <summary> /// Gets or sets a list of certificates to be installed on each compute node in the pool. /// </summary> public IList<CertificateReference> CertificateReferences { get { return this.propertyContainer.CertificateReferencesProperty.Value; } set { this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool. /// </summary> public CloudServiceConfiguration CloudServiceConfiguration { get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; } set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; } } /// <summary> /// Gets the creation time for the pool. /// </summary> public DateTime? CreationTime { get { return this.propertyContainer.CreationTimeProperty.Value; } } /// <summary> /// Gets the number of dedicated compute nodes currently in the pool. /// </summary> public int? CurrentDedicatedComputeNodes { get { return this.propertyContainer.CurrentDedicatedComputeNodesProperty.Value; } } /// <summary> /// Gets the number of low-priority compute nodes currently in the pool. /// </summary> /// <remarks> /// Low-priority compute nodes which have been preempted are included in this count. /// </remarks> public int? CurrentLowPriorityComputeNodes { get { return this.propertyContainer.CurrentLowPriorityComputeNodesProperty.Value; } } /// <summary> /// Gets or sets the display name of the pool. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets the ETag for the pool. /// </summary> public string ETag { get { return this.propertyContainer.ETagProperty.Value; } } /// <summary> /// Gets or sets the id of the pool. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets whether the pool permits direct communication between its compute nodes. /// </summary> /// <remarks> /// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes /// of the pool. This may result in the pool not reaching its desired size. /// </remarks> public bool? InterComputeNodeCommunicationEnabled { get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; } set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; } } /// <summary> /// Gets the last modified time of the pool. /// </summary> public DateTime? LastModified { get { return this.propertyContainer.LastModifiedProperty.Value; } } /// <summary> /// Gets or sets the maximum number of tasks that can run concurrently on a single compute node in the pool. /// </summary> /// <remarks> /// The default value is 1. The maximum value of this setting depends on the size of the compute nodes in the pool /// (the <see cref="VirtualMachineSize"/> property). /// </remarks> public int? MaxTasksPerComputeNode { get { return this.propertyContainer.MaxTasksPerComputeNodeProperty.Value; } set { this.propertyContainer.MaxTasksPerComputeNodeProperty.Value = value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the pool as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the network configuration of the pool. /// </summary> public NetworkConfiguration NetworkConfiguration { get { return this.propertyContainer.NetworkConfigurationProperty.Value; } set { this.propertyContainer.NetworkConfigurationProperty.Value = value; } } /// <summary> /// Gets a list of errors encountered while performing the last resize on the <see cref="CloudPool"/>. Errors are /// returned only when the Batch service encountered an error while resizing the pool, and when the pool's <see cref="CloudPool.AllocationState"/> /// is <see cref="Common.AllocationState.Steady">Steady</see>. /// </summary> public IReadOnlyList<ResizeError> ResizeErrors { get { return this.propertyContainer.ResizeErrorsProperty.Value; } } /// <summary> /// Gets or sets the timeout for allocation of compute nodes to the pool. /// </summary> public TimeSpan? ResizeTimeout { get { return this.propertyContainer.ResizeTimeoutProperty.Value; } set { this.propertyContainer.ResizeTimeoutProperty.Value = value; } } /// <summary> /// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to /// the pool or when the node is restarted. /// </summary> public StartTask StartTask { get { return this.propertyContainer.StartTaskProperty.Value; } set { this.propertyContainer.StartTaskProperty.Value = value; } } /// <summary> /// Gets the current state of the pool. /// </summary> public Common.PoolState? State { get { return this.propertyContainer.StateProperty.Value; } } /// <summary> /// Gets the time at which the pool entered its current state. /// </summary> public DateTime? StateTransitionTime { get { return this.propertyContainer.StateTransitionTimeProperty.Value; } } /// <summary> /// Gets the resource usage statistics for the pool. /// </summary> /// <remarks> /// This property is populated only if the <see cref="CloudPool"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/> /// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch /// service performs periodic roll-up of statistics. The typical delay is about 30 minutes. /// </remarks> public PoolStatistics Statistics { get { return this.propertyContainer.StatisticsProperty.Value; } } /// <summary> /// Gets or sets the desired number of dedicated compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property /// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false. /// If not specified, the default is 0. /// </remarks> public int? TargetDedicatedComputeNodes { get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; } set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets the desired number of low-priority compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/> /// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default /// is 0. /// </remarks> public int? TargetLowPriorityComputeNodes { get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; } set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets how tasks are distributed among compute nodes in the pool. /// </summary> public TaskSchedulingPolicy TaskSchedulingPolicy { get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; } set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; } } /// <summary> /// Gets the URL of the pool. /// </summary> public string Url { get { return this.propertyContainer.UrlProperty.Value; } } /// <summary> /// Gets or sets the list of user accounts to be created on each node in the pool. /// </summary> public IList<UserAccount> UserAccounts { get { return this.propertyContainer.UserAccountsProperty.Value; } set { this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool. /// </summary> public VirtualMachineConfiguration VirtualMachineConfiguration { get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; } set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size. /// </summary> /// <remarks> /// <para>For information about available sizes of virtual machines in pools, see Choose a VM size for compute nodes /// in an Azure Batch pool (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes).</para> /// </remarks> public string VirtualMachineSize { get { return this.propertyContainer.VirtualMachineSizeProperty.Value; } set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; } } #endregion // CloudPool #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.PoolAddParameter ITransportObjectProvider<Models.PoolAddParameter>.GetTransportObject() { Models.PoolAddParameter result = new Models.PoolAddParameter() { ApplicationLicenses = this.ApplicationLicenses, ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences), EnableAutoScale = this.AutoScaleEnabled, AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval, AutoScaleFormula = this.AutoScaleFormula, CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences), CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, Id = this.Id, EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled, MaxTasksPerNode = this.MaxTasksPerComputeNode, Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()), ResizeTimeout = this.ResizeTimeout, StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()), TargetDedicatedNodes = this.TargetDedicatedComputeNodes, TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes, TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()), UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts), VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()), VmSize = this.VirtualMachineSize, }; return result; } #endregion // Internal/private methods } }
/* * 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.Runtime.Remoting.Lifetime; using System.Threading; using System.Reflection; using System.Collections; using System.Collections.Generic; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass : MarshalByRefObject { public IOSSL_Api m_OSSL_Functions; public void ApiTypeOSSL(IScriptApi api) { if (!(api is IOSSL_Api)) return; m_OSSL_Functions = (IOSSL_Api)api; Prim = new OSSLPrim(this); } public void osSetRegionWaterHeight(double height) { m_OSSL_Functions.osSetRegionWaterHeight(height); } public void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour) { m_OSSL_Functions.osSetRegionSunSettings(useEstateSun, sunFixed, sunHour); } public void osSetEstateSunSettings(bool sunFixed, double sunHour) { m_OSSL_Functions.osSetEstateSunSettings(sunFixed, sunHour); } public double osGetCurrentSunHour() { return m_OSSL_Functions.osGetCurrentSunHour(); } public double osSunGetParam(string param) { return m_OSSL_Functions.osSunGetParam(param); } public void osSunSetParam(string param, double value) { m_OSSL_Functions.osSunSetParam(param, value); } public string osWindActiveModelPluginName() { return m_OSSL_Functions.osWindActiveModelPluginName(); } // Not yet plugged in as available OSSL functions, so commented out // void osWindParamSet(string plugin, string param, float value) // { // m_OSSL_Functions.osWindParamSet(plugin, param, value); // } // // float osWindParamGet(string plugin, string param) // { // return m_OSSL_Functions.osWindParamGet(plugin, param); // } public double osList2Double(LSL_Types.list src, int index) { return m_OSSL_Functions.osList2Double(src, index); } public string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams, int timer) { return m_OSSL_Functions.osSetDynamicTextureURL(dynamicID, contentType, url, extraParams, timer); } public string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams, int timer) { return m_OSSL_Functions.osSetDynamicTextureData(dynamicID, contentType, data, extraParams, timer); } public string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams, int timer, int alpha) { return m_OSSL_Functions.osSetDynamicTextureURLBlend(dynamicID, contentType, url, extraParams, timer, alpha); } public string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams, int timer, int alpha) { return m_OSSL_Functions.osSetDynamicTextureDataBlend(dynamicID, contentType, data, extraParams, timer, alpha); } public string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams, bool blend, int disp, int timer, int alpha, int face) { return m_OSSL_Functions.osSetDynamicTextureURLBlendFace(dynamicID, contentType, url, extraParams, blend, disp, timer, alpha, face); } public string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams, bool blend, int disp, int timer, int alpha, int face) { return m_OSSL_Functions.osSetDynamicTextureDataBlendFace(dynamicID, contentType, data, extraParams, blend, disp, timer, alpha, face); } public LSL_Float osTerrainGetHeight(int x, int y) { return m_OSSL_Functions.osTerrainGetHeight(x, y); } public LSL_Integer osTerrainSetHeight(int x, int y, double val) { return m_OSSL_Functions.osTerrainSetHeight(x, y, val); } public void osTerrainFlush() { m_OSSL_Functions.osTerrainFlush(); } public int osRegionRestart(double seconds) { return m_OSSL_Functions.osRegionRestart(seconds); } public void osRegionNotice(string msg) { m_OSSL_Functions.osRegionNotice(msg); } public bool osConsoleCommand(string Command) { return m_OSSL_Functions.osConsoleCommand(Command); } public void osSetParcelMediaURL(string url) { m_OSSL_Functions.osSetParcelMediaURL(url); } public void osSetParcelSIPAddress(string SIPAddress) { m_OSSL_Functions.osSetParcelSIPAddress(SIPAddress); } public void osSetPrimFloatOnWater(int floatYN) { m_OSSL_Functions.osSetPrimFloatOnWater(floatYN); } // Teleport Functions public void osTeleportAgent(string agent, string regionName, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, regionName, position, lookat); } public void osTeleportAgent(string agent, int regionX, int regionY, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, regionX, regionY, position, lookat); } public void osTeleportAgent(string agent, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, position, lookat); } // Avatar info functions public string osGetAgentIP(string agent) { return m_OSSL_Functions.osGetAgentIP(agent); } public LSL_List osGetAgents() { return m_OSSL_Functions.osGetAgents(); } // Animation Functions public void osAvatarPlayAnimation(string avatar, string animation) { m_OSSL_Functions.osAvatarPlayAnimation(avatar, animation); } public void osAvatarStopAnimation(string avatar, string animation) { m_OSSL_Functions.osAvatarStopAnimation(avatar, animation); } //Texture Draw functions public string osMovePen(string drawList, int x, int y) { return m_OSSL_Functions.osMovePen(drawList, x, y); } public string osDrawLine(string drawList, int startX, int startY, int endX, int endY) { return m_OSSL_Functions.osDrawLine(drawList, startX, startY, endX, endY); } public string osDrawLine(string drawList, int endX, int endY) { return m_OSSL_Functions.osDrawLine(drawList, endX, endY); } public string osDrawText(string drawList, string text) { return m_OSSL_Functions.osDrawText(drawList, text); } public string osDrawEllipse(string drawList, int width, int height) { return m_OSSL_Functions.osDrawEllipse(drawList, width, height); } public string osDrawRectangle(string drawList, int width, int height) { return m_OSSL_Functions.osDrawRectangle(drawList, width, height); } public string osDrawFilledRectangle(string drawList, int width, int height) { return m_OSSL_Functions.osDrawFilledRectangle(drawList, width, height); } public string osDrawPolygon(string drawList, LSL_List x, LSL_List y) { return m_OSSL_Functions.osDrawPolygon(drawList, x, y); } public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y) { return m_OSSL_Functions.osDrawFilledPolygon(drawList, x, y); } public string osSetFontSize(string drawList, int fontSize) { return m_OSSL_Functions.osSetFontSize(drawList, fontSize); } public string osSetFontName(string drawList, string fontName) { return m_OSSL_Functions.osSetFontName(drawList, fontName); } public string osSetPenSize(string drawList, int penSize) { return m_OSSL_Functions.osSetPenSize(drawList, penSize); } public string osSetPenCap(string drawList, string direction, string type) { return m_OSSL_Functions.osSetPenCap(drawList, direction, type); } public string osSetPenColour(string drawList, string colour) { return m_OSSL_Functions.osSetPenColour(drawList, colour); } public string osDrawImage(string drawList, int width, int height, string imageUrl) { return m_OSSL_Functions.osDrawImage(drawList, width, height, imageUrl); } public vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize) { return m_OSSL_Functions.osGetDrawStringSize(contentType, text, fontName, fontSize); } public void osSetStateEvents(int events) { m_OSSL_Functions.osSetStateEvents(events); } public string osGetScriptEngineName() { return m_OSSL_Functions.osGetScriptEngineName(); } public string osGetSimulatorVersion() { return m_OSSL_Functions.osGetSimulatorVersion(); } public Hashtable osParseJSON(string JSON) { return m_OSSL_Functions.osParseJSON(JSON); } public void osMessageObject(key objectUUID,string message) { m_OSSL_Functions.osMessageObject(objectUUID,message); } public void osMakeNotecard(string notecardName, LSL_Types.list contents) { m_OSSL_Functions.osMakeNotecard(notecardName, contents); } public string osGetNotecardLine(string name, int line) { return m_OSSL_Functions.osGetNotecardLine(name, line); } public string osGetNotecard(string name) { return m_OSSL_Functions.osGetNotecard(name); } public int osGetNumberOfNotecardLines(string name) { return m_OSSL_Functions.osGetNumberOfNotecardLines(name); } public string osAvatarName2Key(string firstname, string lastname) { return m_OSSL_Functions.osAvatarName2Key(firstname, lastname); } public string osKey2Name(string id) { return m_OSSL_Functions.osKey2Name(id); } public string osGetGridNick() { return m_OSSL_Functions.osGetGridNick(); } public string osGetGridName() { return m_OSSL_Functions.osGetGridName(); } public string osGetGridLoginURI() { return m_OSSL_Functions.osGetGridLoginURI(); } public LSL_String osFormatString(string str, LSL_List strings) { return m_OSSL_Functions.osFormatString(str, strings); } public LSL_List osMatchString(string src, string pattern, int start) { return m_OSSL_Functions.osMatchString(src, pattern, start); } // Information about data loaded into the region public string osLoadedCreationDate() { return m_OSSL_Functions.osLoadedCreationDate(); } public string osLoadedCreationTime() { return m_OSSL_Functions.osLoadedCreationTime(); } public string osLoadedCreationID() { return m_OSSL_Functions.osLoadedCreationID(); } public LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules) { return m_OSSL_Functions.osGetLinkPrimitiveParams(linknumber, rules); } public key osNpcCreate(string user, string name, vector position, key cloneFrom) { return m_OSSL_Functions.osNpcCreate(user, name, position, cloneFrom); } public void osNpcMoveTo(key npc, vector position) { m_OSSL_Functions.osNpcMoveTo(npc, position); } public void osNpcSay(key npc, string message) { m_OSSL_Functions.osNpcSay(npc, message); } public void osNpcRemove(key npc) { m_OSSL_Functions.osNpcRemove(npc); } public OSSLPrim Prim; [Serializable] public class OSSLPrim { internal ScriptBaseClass OSSL; public OSSLPrim(ScriptBaseClass bc) { OSSL = bc; Position = new OSSLPrim_Position(this); Rotation = new OSSLPrim_Rotation(this); } public OSSLPrim_Position Position; public OSSLPrim_Rotation Rotation; private TextStruct _text; public TextStruct Text { get { return _text; } set { _text = value; OSSL.llSetText(_text.Text, _text.color, _text.alpha); } } [Serializable] public struct TextStruct { public string Text; public LSL_Types.Vector3 color; public double alpha; } } [Serializable] public class OSSLPrim_Position { private OSSLPrim prim; private LSL_Types.Vector3 Position; public OSSLPrim_Position(OSSLPrim _prim) { prim = _prim; } private void Load() { Position = prim.OSSL.llGetPos(); } private void Save() { if (Position.x > ((int)Constants.RegionSize - 1)) Position.x = ((int)Constants.RegionSize - 1); if (Position.x < 0) Position.x = 0; if (Position.y > ((int)Constants.RegionSize - 1)) Position.y = ((int)Constants.RegionSize - 1); if (Position.y < 0) Position.y = 0; if (Position.z > 768) Position.z = 768; if (Position.z < 0) Position.z = 0; prim.OSSL.llSetPos(Position); } public double x { get { Load(); return Position.x; } set { Load(); Position.x = value; Save(); } } public double y { get { Load(); return Position.y; } set { Load(); Position.y = value; Save(); } } public double z { get { Load(); return Position.z; } set { Load(); Position.z = value; Save(); } } } [Serializable] public class OSSLPrim_Rotation { private OSSLPrim prim; private LSL_Types.Quaternion Rotation; public OSSLPrim_Rotation(OSSLPrim _prim) { prim = _prim; } private void Load() { Rotation = prim.OSSL.llGetRot(); } private void Save() { prim.OSSL.llSetRot(Rotation); } public double x { get { Load(); return Rotation.x; } set { Load(); Rotation.x = value; Save(); } } public double y { get { Load(); return Rotation.y; } set { Load(); Rotation.y = value; Save(); } } public double z { get { Load(); return Rotation.z; } set { Load(); Rotation.z = value; Save(); } } public double s { get { Load(); return Rotation.s; } set { Load(); Rotation.s = value; Save(); } } } public key osGetMapTexture() { return m_OSSL_Functions.osGetMapTexture(); } public key osGetRegionMapTexture(string regionName) { return m_OSSL_Functions.osGetRegionMapTexture(regionName); } public LSL_List osGetRegionStats() { return m_OSSL_Functions.osGetRegionStats(); } /// <summary> /// Returns the amount of memory in use by the Simulator Daemon. /// Amount in bytes - if >= 4GB, returns 4GB. (LSL is not 64-bit aware) /// </summary> /// <returns></returns> public LSL_Integer osGetSimulatorMemory() { return m_OSSL_Functions.osGetSimulatorMemory(); } public void osKickAvatar(string FirstName,string SurName,string alert) { m_OSSL_Functions.osKickAvatar(FirstName, SurName, alert); } public void osSetSpeed(string UUID, float SpeedModifier) { m_OSSL_Functions.osSetSpeed(UUID, SpeedModifier); } public void osCauseDamage(string avatar, double damage) { m_OSSL_Functions.osCauseDamage(avatar, damage); } public void osCauseHealing(string avatar, double healing) { m_OSSL_Functions.osCauseHealing(avatar, healing); } } }
//--------------------------------------------------------------------------- // // File: HtmlSchema.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Static information about HTML structure // //--------------------------------------------------------------------------- namespace MarkupConverter { using System.Diagnostics; using System.Collections; /// <summary> /// HtmlSchema class /// maintains static information about HTML structure /// can be used by HtmlParser to check conditions under which an element starts or ends, etc. /// </summary> internal class HtmlSchema { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// static constructor, initializes the ArrayLists /// that hold the elements in various sub-components of the schema /// e.g _htmlEmptyElements, etc. /// </summary> static HtmlSchema() { // initializes the list of all html elements InitializeInlineElements(); InitializeBlockElements(); InitializeOtherOpenableElements(); // initialize empty elements list InitializeEmptyElements(); // initialize list of elements closing on the outer element end InitializeElementsClosingOnParentElementEnd(); // initalize list of elements that close when a new element starts InitializeElementsClosingOnNewElementStart(); // Initialize character entities InitializeHtmlCharacterEntities(); } #endregion Constructors; // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// returns true when xmlElementName corresponds to empty element /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool IsEmptyElement(string xmlElementName) { // convert to lowercase before we check // because element names are not case sensitive return _htmlEmptyElements.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if xmlElementName represents a block formattinng element. /// It used in an algorithm of transferring inline elements over block elements /// in HtmlParser /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsBlockElement(string xmlElementName) { return _htmlBlockElements.Contains(xmlElementName); } /// <summary> /// returns true if the xmlElementName represents an inline formatting element /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsInlineElement(string xmlElementName) { return _htmlInlineElements.Contains(xmlElementName); } /// <summary> /// It is a list of known html elements which we /// want to allow to produce bt HTML parser, /// but don'tt want to act as inline, block or no-scope. /// Presence in this list will allow to open /// elements during html parsing, and adding the /// to a tree produced by html parser. /// </summary> internal static bool IsKnownOpenableElement(string xmlElementName) { return _htmlOtherOpenableElements.Contains(xmlElementName); } /// <summary> /// returns true when xmlElementName closes when the outer element closes /// this is true of elements with optional start tags /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool ClosesOnParentElementEnd(string xmlElementName) { // convert to lowercase when testing return _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if the current element closes when the new element, whose name has just been read, starts /// </summary> /// <param name="currentElementName"> /// string representing current element name /// </param> /// <param name="elementName"></param> /// string representing name of the next element that will start internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName) { Debug.Assert(currentElementName == currentElementName.ToLower()); switch (currentElementName) { case "colgroup": return _htmlElementsClosingColgroup.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dd": return _htmlElementsClosingDD.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dt": return _htmlElementsClosingDT.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "li": return _htmlElementsClosingLI.Contains(nextElementName); case "p": return HtmlSchema.IsBlockElement(nextElementName); case "tbody": return _htmlElementsClosingTbody.Contains(nextElementName); case "tfoot": return _htmlElementsClosingTfoot.Contains(nextElementName); case "thead": return _htmlElementsClosingThead.Contains(nextElementName); case "tr": return _htmlElementsClosingTR.Contains(nextElementName); case "td": return _htmlElementsClosingTD.Contains(nextElementName); case "th": return _htmlElementsClosingTH.Contains(nextElementName); } return false; } /// <summary> /// returns true if the string passed as argument is an Html entity name /// </summary> /// <param name="entityName"> /// string to be tested for Html entity name /// </param> internal static bool IsEntity(string entityName) { // we do not convert entity strings to lowercase because these names are case-sensitive if (_htmlCharacterEntities.Contains(entityName)) { return true; } else { return false; } } /// <summary> /// returns the character represented by the entity name string which is passed as an argument, if the string is an entity name /// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise /// </summary> /// <param name="entityName"> /// string representing entity name whose character value is desired /// </param> internal static char EntityCharacterValue(string entityName) { if (_htmlCharacterEntities.Contains(entityName)) { return (char) _htmlCharacterEntities[entityName]; } else { return (char)0; } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties #endregion Internal Indexers // --------------------------------------------------------------------- // // Private Methods // // --------------------------------------------------------------------- #region Private Methods private static void InitializeInlineElements() { _htmlInlineElements = new ArrayList(); _htmlInlineElements.Add("a"); _htmlInlineElements.Add("abbr"); _htmlInlineElements.Add("acronym"); _htmlInlineElements.Add("address"); _htmlInlineElements.Add("b"); _htmlInlineElements.Add("bdo"); // ??? _htmlInlineElements.Add("big"); _htmlInlineElements.Add("button"); _htmlInlineElements.Add("code"); _htmlInlineElements.Add("del"); // deleted text _htmlInlineElements.Add("dfn"); _htmlInlineElements.Add("em"); _htmlInlineElements.Add("font"); _htmlInlineElements.Add("i"); _htmlInlineElements.Add("ins"); // inserted text _htmlInlineElements.Add("kbd"); // text to entered by a user _htmlInlineElements.Add("label"); _htmlInlineElements.Add("legend"); // ??? _htmlInlineElements.Add("q"); // short inline quotation _htmlInlineElements.Add("s"); // strike-through text style _htmlInlineElements.Add("samp"); // Specifies a code sample _htmlInlineElements.Add("small"); _htmlInlineElements.Add("span"); _htmlInlineElements.Add("strike"); _htmlInlineElements.Add("strong"); _htmlInlineElements.Add("sub"); _htmlInlineElements.Add("sup"); _htmlInlineElements.Add("u"); _htmlInlineElements.Add("var"); // indicates an instance of a program variable } private static void InitializeBlockElements() { _htmlBlockElements = new ArrayList(); _htmlBlockElements.Add("blockquote"); _htmlBlockElements.Add("body"); _htmlBlockElements.Add("caption"); _htmlBlockElements.Add("center"); _htmlBlockElements.Add("cite"); _htmlBlockElements.Add("dd"); _htmlBlockElements.Add("dir"); // treat as UL element _htmlBlockElements.Add("div"); _htmlBlockElements.Add("dl"); _htmlBlockElements.Add("dt"); _htmlBlockElements.Add("form"); // Not a block according to XHTML spec _htmlBlockElements.Add("h1"); _htmlBlockElements.Add("h2"); _htmlBlockElements.Add("h3"); _htmlBlockElements.Add("h4"); _htmlBlockElements.Add("h5"); _htmlBlockElements.Add("h6"); _htmlBlockElements.Add("html"); _htmlBlockElements.Add("li"); _htmlBlockElements.Add("menu"); // treat as UL element _htmlBlockElements.Add("ol"); _htmlBlockElements.Add("p"); _htmlBlockElements.Add("pre"); // Renders text in a fixed-width font _htmlBlockElements.Add("table"); _htmlBlockElements.Add("tbody"); _htmlBlockElements.Add("td"); _htmlBlockElements.Add("textarea"); _htmlBlockElements.Add("tfoot"); _htmlBlockElements.Add("th"); _htmlBlockElements.Add("thead"); _htmlBlockElements.Add("tr"); _htmlBlockElements.Add("tt"); _htmlBlockElements.Add("ul"); } /// <summary> /// initializes _htmlEmptyElements with empty elements in HTML 4 spec at /// http://www.w3.org/TR/REC-html40/index/elements.html /// </summary> private static void InitializeEmptyElements() { // Build a list of empty (no-scope) elements // (element not requiring closing tags, and not accepting any content) _htmlEmptyElements = new ArrayList(); _htmlEmptyElements.Add("area"); _htmlEmptyElements.Add("base"); _htmlEmptyElements.Add("basefont"); _htmlEmptyElements.Add("br"); _htmlEmptyElements.Add("col"); _htmlEmptyElements.Add("frame"); _htmlEmptyElements.Add("hr"); _htmlEmptyElements.Add("img"); _htmlEmptyElements.Add("input"); _htmlEmptyElements.Add("isindex"); _htmlEmptyElements.Add("link"); _htmlEmptyElements.Add("meta"); _htmlEmptyElements.Add("param"); } private static void InitializeOtherOpenableElements() { // It is a list of known html elements which we // want to allow to produce bt HTML parser, // but don'tt want to act as inline, block or no-scope. // Presence in this list will allow to open // elements during html parsing, and adding the // to a tree produced by html parser. _htmlOtherOpenableElements = new ArrayList(); _htmlOtherOpenableElements.Add("applet"); _htmlOtherOpenableElements.Add("base"); _htmlOtherOpenableElements.Add("basefont"); _htmlOtherOpenableElements.Add("colgroup"); _htmlOtherOpenableElements.Add("fieldset"); //_htmlOtherOpenableElements.Add("form"); --> treated as block _htmlOtherOpenableElements.Add("frameset"); _htmlOtherOpenableElements.Add("head"); _htmlOtherOpenableElements.Add("iframe"); _htmlOtherOpenableElements.Add("map"); _htmlOtherOpenableElements.Add("noframes"); _htmlOtherOpenableElements.Add("noscript"); _htmlOtherOpenableElements.Add("object"); _htmlOtherOpenableElements.Add("optgroup"); _htmlOtherOpenableElements.Add("option"); _htmlOtherOpenableElements.Add("script"); _htmlOtherOpenableElements.Add("select"); _htmlOtherOpenableElements.Add("style"); _htmlOtherOpenableElements.Add("title"); } /// <summary> /// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are optional /// we assume that for any element for which closing tags are optional, the element closes when it's outer element /// (in which it is nested) does /// </summary> private static void InitializeElementsClosingOnParentElementEnd() { _htmlElementsClosingOnParentElementEnd = new ArrayList(); _htmlElementsClosingOnParentElementEnd.Add("body"); _htmlElementsClosingOnParentElementEnd.Add("colgroup"); _htmlElementsClosingOnParentElementEnd.Add("dd"); _htmlElementsClosingOnParentElementEnd.Add("dt"); _htmlElementsClosingOnParentElementEnd.Add("head"); _htmlElementsClosingOnParentElementEnd.Add("html"); _htmlElementsClosingOnParentElementEnd.Add("li"); _htmlElementsClosingOnParentElementEnd.Add("p"); _htmlElementsClosingOnParentElementEnd.Add("tbody"); _htmlElementsClosingOnParentElementEnd.Add("td"); _htmlElementsClosingOnParentElementEnd.Add("tfoot"); _htmlElementsClosingOnParentElementEnd.Add("thead"); _htmlElementsClosingOnParentElementEnd.Add("th"); _htmlElementsClosingOnParentElementEnd.Add("tr"); } private static void InitializeElementsClosingOnNewElementStart() { _htmlElementsClosingColgroup = new ArrayList(); _htmlElementsClosingColgroup.Add("colgroup"); _htmlElementsClosingColgroup.Add("tr"); _htmlElementsClosingColgroup.Add("thead"); _htmlElementsClosingColgroup.Add("tfoot"); _htmlElementsClosingColgroup.Add("tbody"); _htmlElementsClosingDD = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); // TODO: dd may end in other cases as well - if a new "p" starts, etc. // TODO: these are the basic "legal" cases but there may be more recovery _htmlElementsClosingDT = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); // TODO: dd may end in other cases as well - if a new "p" starts, etc. // TODO: these are the basic "legal" cases but there may be more recovery _htmlElementsClosingLI = new ArrayList(); _htmlElementsClosingLI.Add("li"); // TODO: more complex recovery _htmlElementsClosingTbody = new ArrayList(); _htmlElementsClosingTbody.Add("tbody"); _htmlElementsClosingTbody.Add("thead"); _htmlElementsClosingTbody.Add("tfoot"); // TODO: more complex recovery _htmlElementsClosingTR = new ArrayList(); // NOTE: tr should not really close on a new thead // because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional // and thead can't come after tbody // however, if we do encounter this, it's probably best to end the row and ignore the thead or treat // it as part of the table _htmlElementsClosingTR.Add("thead"); _htmlElementsClosingTR.Add("tfoot"); _htmlElementsClosingTR.Add("tbody"); _htmlElementsClosingTR.Add("tr"); // TODO: more complex recovery _htmlElementsClosingTD = new ArrayList(); _htmlElementsClosingTD.Add("td"); _htmlElementsClosingTD.Add("th"); _htmlElementsClosingTD.Add("tr"); _htmlElementsClosingTD.Add("tbody"); _htmlElementsClosingTD.Add("tfoot"); _htmlElementsClosingTD.Add("thead"); // TODO: more complex recovery _htmlElementsClosingTH = new ArrayList(); _htmlElementsClosingTH.Add("td"); _htmlElementsClosingTH.Add("th"); _htmlElementsClosingTH.Add("tr"); _htmlElementsClosingTH.Add("tbody"); _htmlElementsClosingTH.Add("tfoot"); _htmlElementsClosingTH.Add("thead"); // TODO: more complex recovery _htmlElementsClosingThead = new ArrayList(); _htmlElementsClosingThead.Add("tbody"); _htmlElementsClosingThead.Add("tfoot"); // TODO: more complex recovery _htmlElementsClosingTfoot = new ArrayList(); _htmlElementsClosingTfoot.Add("tbody"); // although thead comes before tfoot, we add it because if it is found the tfoot should close // and some recovery processing be done on the thead _htmlElementsClosingTfoot.Add("thead"); // TODO: more complex recovery } /// <summary> /// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names /// </summary> private static void InitializeHtmlCharacterEntities() { _htmlCharacterEntities = new Hashtable(); _htmlCharacterEntities["Aacute"] = (char)193; _htmlCharacterEntities["aacute"] = (char)225; _htmlCharacterEntities["Acirc"] = (char)194; _htmlCharacterEntities["acirc"] = (char)226; _htmlCharacterEntities["acute"] = (char)180; _htmlCharacterEntities["AElig"] = (char)198; _htmlCharacterEntities["aelig"] = (char)230; _htmlCharacterEntities["Agrave"] = (char)192; _htmlCharacterEntities["agrave"] = (char)224; _htmlCharacterEntities["alefsym"] = (char)8501; _htmlCharacterEntities["Alpha"] = (char)913; _htmlCharacterEntities["alpha"] = (char)945; _htmlCharacterEntities["amp"] = (char)38; _htmlCharacterEntities["and"] = (char)8743; _htmlCharacterEntities["ang"] = (char)8736; _htmlCharacterEntities["Aring"] = (char)197; _htmlCharacterEntities["aring"] = (char)229; _htmlCharacterEntities["asymp"] = (char)8776; _htmlCharacterEntities["Atilde"] = (char)195; _htmlCharacterEntities["atilde"] = (char)227; _htmlCharacterEntities["Auml"] = (char)196; _htmlCharacterEntities["auml"] = (char)228; _htmlCharacterEntities["bdquo"] = (char)8222; _htmlCharacterEntities["Beta"] = (char)914; _htmlCharacterEntities["beta"] = (char)946; _htmlCharacterEntities["brvbar"] = (char)166; _htmlCharacterEntities["bull"] = (char)8226; _htmlCharacterEntities["cap"] = (char)8745; _htmlCharacterEntities["Ccedil"] = (char)199; _htmlCharacterEntities["ccedil"] = (char)231; _htmlCharacterEntities["cent"] = (char)162; _htmlCharacterEntities["Chi"] = (char)935; _htmlCharacterEntities["chi"] = (char)967; _htmlCharacterEntities["circ"] = (char)710; _htmlCharacterEntities["clubs"] = (char)9827; _htmlCharacterEntities["cong"] = (char)8773; _htmlCharacterEntities["copy"] = (char)169; _htmlCharacterEntities["crarr"] = (char)8629; _htmlCharacterEntities["cup"] = (char)8746; _htmlCharacterEntities["curren"] = (char)164; _htmlCharacterEntities["dagger"] = (char)8224; _htmlCharacterEntities["Dagger"] = (char)8225; _htmlCharacterEntities["darr"] = (char)8595; _htmlCharacterEntities["dArr"] = (char)8659; _htmlCharacterEntities["deg"] = (char)176; _htmlCharacterEntities["Delta"] = (char)916; _htmlCharacterEntities["delta"] = (char)948; _htmlCharacterEntities["diams"] = (char)9830; _htmlCharacterEntities["divide"] = (char)247; _htmlCharacterEntities["Eacute"] = (char)201; _htmlCharacterEntities["eacute"] = (char)233; _htmlCharacterEntities["Ecirc"] = (char)202; _htmlCharacterEntities["ecirc"] = (char)234; _htmlCharacterEntities["Egrave"] = (char)200; _htmlCharacterEntities["egrave"] = (char)232; _htmlCharacterEntities["empty"] = (char)8709; _htmlCharacterEntities["emsp"] = (char)8195; _htmlCharacterEntities["ensp"] = (char)8194; _htmlCharacterEntities["Epsilon"] = (char)917; _htmlCharacterEntities["epsilon"] = (char)949; _htmlCharacterEntities["equiv"] = (char)8801; _htmlCharacterEntities["Eta"] = (char)919; _htmlCharacterEntities["eta"] = (char)951; _htmlCharacterEntities["ETH"] = (char)208; _htmlCharacterEntities["eth"] = (char)240; _htmlCharacterEntities["Euml"] = (char)203; _htmlCharacterEntities["euml"] = (char)235; _htmlCharacterEntities["euro"] = (char)8364; _htmlCharacterEntities["exist"] = (char)8707; _htmlCharacterEntities["fnof"] = (char)402; _htmlCharacterEntities["forall"] = (char)8704; _htmlCharacterEntities["frac12"] = (char)189; _htmlCharacterEntities["frac14"] = (char)188; _htmlCharacterEntities["frac34"] = (char)190; _htmlCharacterEntities["frasl"] = (char)8260; _htmlCharacterEntities["Gamma"] = (char)915; _htmlCharacterEntities["gamma"] = (char)947; _htmlCharacterEntities["ge"] = (char)8805; _htmlCharacterEntities["gt"] = (char)62; _htmlCharacterEntities["harr"] = (char)8596; _htmlCharacterEntities["hArr"] = (char)8660; _htmlCharacterEntities["hearts"] = (char)9829; _htmlCharacterEntities["hellip"] = (char)8230; _htmlCharacterEntities["Iacute"] = (char)205; _htmlCharacterEntities["iacute"] = (char)237; _htmlCharacterEntities["Icirc"] = (char)206; _htmlCharacterEntities["icirc"] = (char)238; _htmlCharacterEntities["iexcl"] = (char)161; _htmlCharacterEntities["Igrave"] = (char)204; _htmlCharacterEntities["igrave"] = (char)236; _htmlCharacterEntities["image"] = (char)8465; _htmlCharacterEntities["infin"] = (char)8734; _htmlCharacterEntities["int"] = (char)8747; _htmlCharacterEntities["Iota"] = (char)921; _htmlCharacterEntities["iota"] = (char)953; _htmlCharacterEntities["iquest"] = (char)191; _htmlCharacterEntities["isin"] = (char)8712; _htmlCharacterEntities["Iuml"] = (char)207; _htmlCharacterEntities["iuml"] = (char)239; _htmlCharacterEntities["Kappa"] = (char)922; _htmlCharacterEntities["kappa"] = (char)954; _htmlCharacterEntities["Lambda"] = (char)923; _htmlCharacterEntities["lambda"] = (char)955; _htmlCharacterEntities["lang"] = (char)9001; _htmlCharacterEntities["laquo"] = (char)171; _htmlCharacterEntities["larr"] = (char)8592; _htmlCharacterEntities["lArr"] = (char)8656; _htmlCharacterEntities["lceil"] = (char)8968; _htmlCharacterEntities["ldquo"] = (char)8220; _htmlCharacterEntities["le"] = (char)8804; _htmlCharacterEntities["lfloor"] = (char)8970; _htmlCharacterEntities["lowast"] = (char)8727; _htmlCharacterEntities["loz"] = (char)9674; _htmlCharacterEntities["lrm"] = (char)8206; _htmlCharacterEntities["lsaquo"] = (char)8249; _htmlCharacterEntities["lsquo"] = (char)8216; _htmlCharacterEntities["lt"] = (char)60; _htmlCharacterEntities["macr"] = (char)175; _htmlCharacterEntities["mdash"] = (char)8212; _htmlCharacterEntities["micro"] = (char)181; _htmlCharacterEntities["middot"] = (char)183; _htmlCharacterEntities["minus"] = (char)8722; _htmlCharacterEntities["Mu"] = (char)924; _htmlCharacterEntities["mu"] = (char)956; _htmlCharacterEntities["nabla"] = (char)8711; _htmlCharacterEntities["nbsp"] = (char)160; _htmlCharacterEntities["ndash"] = (char)8211; _htmlCharacterEntities["ne"] = (char)8800; _htmlCharacterEntities["ni"] = (char)8715; _htmlCharacterEntities["not"] = (char)172; _htmlCharacterEntities["notin"] = (char)8713; _htmlCharacterEntities["nsub"] = (char)8836; _htmlCharacterEntities["Ntilde"] = (char)209; _htmlCharacterEntities["ntilde"] = (char)241; _htmlCharacterEntities["Nu"] = (char)925; _htmlCharacterEntities["nu"] = (char)957; _htmlCharacterEntities["Oacute"] = (char)211; _htmlCharacterEntities["ocirc"] = (char)244; _htmlCharacterEntities["OElig"] = (char)338; _htmlCharacterEntities["oelig"] = (char)339; _htmlCharacterEntities["Ograve"] = (char)210; _htmlCharacterEntities["ograve"] = (char)242; _htmlCharacterEntities["oline"] = (char)8254; _htmlCharacterEntities["Omega"] = (char)937; _htmlCharacterEntities["omega"] = (char)969; _htmlCharacterEntities["Omicron"] = (char)927; _htmlCharacterEntities["omicron"] = (char)959; _htmlCharacterEntities["oplus"] = (char)8853; _htmlCharacterEntities["or"] = (char)8744; _htmlCharacterEntities["ordf"] = (char)170; _htmlCharacterEntities["ordm"] = (char)186; _htmlCharacterEntities["Oslash"] = (char)216; _htmlCharacterEntities["oslash"] = (char)248; _htmlCharacterEntities["Otilde"] = (char)213; _htmlCharacterEntities["otilde"] = (char)245; _htmlCharacterEntities["otimes"] = (char)8855; _htmlCharacterEntities["Ouml"] = (char)214; _htmlCharacterEntities["ouml"] = (char)246; _htmlCharacterEntities["para"] = (char)182; _htmlCharacterEntities["part"] = (char)8706; _htmlCharacterEntities["permil"] = (char)8240; _htmlCharacterEntities["perp"] = (char)8869; _htmlCharacterEntities["Phi"] = (char)934; _htmlCharacterEntities["phi"] = (char)966; _htmlCharacterEntities["pi"] = (char)960; _htmlCharacterEntities["piv"] = (char)982; _htmlCharacterEntities["plusmn"] = (char)177; _htmlCharacterEntities["pound"] = (char)163; _htmlCharacterEntities["prime"] = (char)8242; _htmlCharacterEntities["Prime"] = (char)8243; _htmlCharacterEntities["prod"] = (char)8719; _htmlCharacterEntities["prop"] = (char)8733; _htmlCharacterEntities["Psi"] = (char)936; _htmlCharacterEntities["psi"] = (char)968; _htmlCharacterEntities["quot"] = (char)34; _htmlCharacterEntities["radic"] = (char)8730; _htmlCharacterEntities["rang"] = (char)9002; _htmlCharacterEntities["raquo"] = (char)187; _htmlCharacterEntities["rarr"] = (char)8594; _htmlCharacterEntities["rArr"] = (char)8658; _htmlCharacterEntities["rceil"] = (char)8969; _htmlCharacterEntities["rdquo"] = (char)8221; _htmlCharacterEntities["real"] = (char)8476; _htmlCharacterEntities["reg"] = (char)174; _htmlCharacterEntities["rfloor"] = (char)8971; _htmlCharacterEntities["Rho"] = (char)929; _htmlCharacterEntities["rho"] = (char)961; _htmlCharacterEntities["rlm"] = (char)8207; _htmlCharacterEntities["rsaquo"] = (char)8250; _htmlCharacterEntities["rsquo"] = (char)8217; _htmlCharacterEntities["sbquo"] = (char)8218; _htmlCharacterEntities["Scaron"] = (char)352; _htmlCharacterEntities["scaron"] = (char)353; _htmlCharacterEntities["sdot"] = (char)8901; _htmlCharacterEntities["sect"] = (char)167; _htmlCharacterEntities["shy"] = (char)173; _htmlCharacterEntities["Sigma"] = (char)931; _htmlCharacterEntities["sigma"] = (char)963; _htmlCharacterEntities["sigmaf"] = (char)962; _htmlCharacterEntities["sim"] = (char)8764; _htmlCharacterEntities["spades"] = (char)9824; _htmlCharacterEntities["sub"] = (char)8834; _htmlCharacterEntities["sube"] = (char)8838; _htmlCharacterEntities["sum"] = (char)8721; _htmlCharacterEntities["sup"] = (char)8835; _htmlCharacterEntities["sup1"] = (char)185; _htmlCharacterEntities["sup2"] = (char)178; _htmlCharacterEntities["sup3"] = (char)179; _htmlCharacterEntities["supe"] = (char)8839; _htmlCharacterEntities["szlig"] = (char)223; _htmlCharacterEntities["Tau"] = (char)932; _htmlCharacterEntities["tau"] = (char)964; _htmlCharacterEntities["there4"] = (char)8756; _htmlCharacterEntities["Theta"] = (char)920; _htmlCharacterEntities["theta"] = (char)952; _htmlCharacterEntities["thetasym"] = (char)977; _htmlCharacterEntities["thinsp"] = (char)8201; _htmlCharacterEntities["THORN"] = (char)222; _htmlCharacterEntities["thorn"] = (char)254; _htmlCharacterEntities["tilde"] = (char)732; _htmlCharacterEntities["times"] = (char)215; _htmlCharacterEntities["trade"] = (char)8482; _htmlCharacterEntities["Uacute"] = (char)218; _htmlCharacterEntities["uacute"] = (char)250; _htmlCharacterEntities["uarr"] = (char)8593; _htmlCharacterEntities["uArr"] = (char)8657; _htmlCharacterEntities["Ucirc"] = (char)219; _htmlCharacterEntities["ucirc"] = (char)251; _htmlCharacterEntities["Ugrave"] = (char)217; _htmlCharacterEntities["ugrave"] = (char)249; _htmlCharacterEntities["uml"] = (char)168; _htmlCharacterEntities["upsih"] = (char)978; _htmlCharacterEntities["Upsilon"] = (char)933; _htmlCharacterEntities["upsilon"] = (char)965; _htmlCharacterEntities["Uuml"] = (char)220; _htmlCharacterEntities["uuml"] = (char)252; _htmlCharacterEntities["weierp"] = (char)8472; _htmlCharacterEntities["Xi"] = (char)926; _htmlCharacterEntities["xi"] = (char)958; _htmlCharacterEntities["Yacute"] = (char)221; _htmlCharacterEntities["yacute"] = (char)253; _htmlCharacterEntities["yen"] = (char)165; _htmlCharacterEntities["Yuml"] = (char)376; _htmlCharacterEntities["yuml"] = (char)255; _htmlCharacterEntities["Zeta"] = (char)918; _htmlCharacterEntities["zeta"] = (char)950; _htmlCharacterEntities["zwj"] = (char)8205; _htmlCharacterEntities["zwnj"] = (char)8204; } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // html element names // this is an array list now, but we may want to make it a hashtable later for better performance private static ArrayList _htmlInlineElements; private static ArrayList _htmlBlockElements; private static ArrayList _htmlOtherOpenableElements; // list of html empty element names private static ArrayList _htmlEmptyElements; // names of html elements for which closing tags are optional, and close when the outer nested element closes private static ArrayList _htmlElementsClosingOnParentElementEnd; // names of elements that close certain optional closing tag elements when they start // names of elements closing the colgroup element private static ArrayList _htmlElementsClosingColgroup; // names of elements closing the dd element private static ArrayList _htmlElementsClosingDD; // names of elements closing the dt element private static ArrayList _htmlElementsClosingDT; // names of elements closing the li element private static ArrayList _htmlElementsClosingLI; // names of elements closing the tbody element private static ArrayList _htmlElementsClosingTbody; // names of elements closing the td element private static ArrayList _htmlElementsClosingTD; // names of elements closing the tfoot element private static ArrayList _htmlElementsClosingTfoot; // names of elements closing the thead element private static ArrayList _htmlElementsClosingThead; // names of elements closing the th element private static ArrayList _htmlElementsClosingTH; // names of elements closing the tr element private static ArrayList _htmlElementsClosingTR; // html character entities hashtable private static Hashtable _htmlCharacterEntities; #endregion Private Fields } }
using Pid = System.UInt32; using IPage = Core.PgHdr; using Core.IO; using System; using System.Diagnostics; using System.Text; namespace Core { public partial class Backup : IBackup { public Context DestCtx; // Destination database handle public Btree Dest; // Destination b-tree file public uint DestSchema; // Original schema cookie in destination public bool DestLocked; // True once a write-transaction is open on pDest public Pid NextId; // Page number of the next source page to copy public Context SrcCtx; // Source database handle public Btree Src; // Source b-tree file public RC RC_; // Backup process error code // These two variables are set by every call to backup_step(). They are read by calls to backup_remaining() and backup_pagecount(). public Pid Remaining; // Number of pages left to copy */ public Pid Pagecount; // Total number of pages to copy */ public bool IsAttached; // True once backup has been registered with pager public Backup Next; // Next backup associated with source pager static Btree FindBtree(Context errorCtx, Context ctx, string dbName) { int i = Parse.FindDbName(ctx, dbName); if (i == 1) { RC rc = 0; Parse parse = new Parse(); if (parse == null) { DataEx.Error(errorCtx, RC.NOMEM, "out of memory"); rc = RC.NOMEM; } else { parse.Ctx = ctx; if (parse.OpenTempDatabase() != 0) { DataEx.Error(errorCtx, parse.RC, "%s", parse.ErrMsg); rc = RC.ERROR; } C._tagfree(errorCtx, ref parse.ErrMsg); } if (rc != 0) return null; } if (i < 0) { DataEx.Error(errorCtx, RC.ERROR, "unknown database %s", dbName); return null; } return ctx.DBs[i].Bt; } static RC SetDestPgsz(Backup p) { RC rc = p.Dest.SetPageSize(p.Src.GetPageSize(), -1, false); return rc; } public static Backup Init(Context destCtx, string destDbName, Context srcCtx, string srcDbName) { // Lock the source database handle. The destination database handle is not locked in this routine, but it is locked in // sqlite3_backup_step(). The user is required to ensure that no other thread accesses the destination handle for the duration // of the backup operation. Any attempt to use the destination database connection while a backup is in progress may cause // a malfunction or a deadlock. MutexEx.Enter(srcCtx.Mutex); MutexEx.Enter(destCtx.Mutex); Backup p; if (srcCtx == destCtx) { DataEx.Error(destCtx, RC.ERROR, "source and destination must be distinct"); p = null; } else { // Allocate space for a new sqlite3_backup object... EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a // call to sqlite3_backup_init() and is destroyed by a call to sqlite3_backup_finish(). p = new Backup(); if (p == null) DataEx.Error(destCtx, RC.NOMEM, null); } // If the allocation succeeded, populate the new object. if (p != null) { p.Src = FindBtree(destCtx, srcCtx, srcDbName); p.Dest = FindBtree(destCtx, destCtx, destDbName); p.DestCtx = destCtx; p.SrcCtx = srcCtx; p.NextId = 1; p.IsAttached = false; if (p.Src == null || p.Dest == null || SetDestPgsz(p) == RC.NOMEM) { // One (or both) of the named databases did not exist or an OOM error was hit. The error has already been written into the // pDestDb handle. All that is left to do here is free the sqlite3_backup structure. //C._free(ref p); p = null; } } if (p != null) p.Src.Backups++; MutexEx.Leave(destCtx.Mutex); MutexEx.Leave(srcCtx.Mutex); return p; } static bool IsFatalError(RC rc) { return (rc != RC.OK && rc != RC.BUSY && C._ALWAYS(rc != RC.LOCKED)); } static RC BackupOnePage(Backup p, Pid srcPg, byte[] srcData, bool update) { Pager destPager = p.Dest.get_Pager(); int srcPgsz = p.Src.GetPageSize(); int destPgsz = p.Dest.GetPageSize(); int copy = Math.Min(srcPgsz, destPgsz); long end = (long)srcPg * (long)srcPgsz; RC rc = RC.OK; Debug.Assert(p.Src.GetReserveNoMutex() >= 0); Debug.Assert(p.DestLocked); Debug.Assert(!IsFatalError(p.RC_)); Debug.Assert(srcPg != Btree.PENDING_BYTE_PAGE(p.Src.Bt)); Debug.Assert(srcData != null); // Catch the case where the destination is an in-memory database and the page sizes of the source and destination differ. if (srcPgsz != destPgsz && destPager.get_MemoryDB) rc = RC.READONLY; #if HAS_CODEC int srcReserve = p.Src.GetReserveNoMutex(); int destReserve = p.Dest.GetReserve(); // Backup is not possible if the page size of the destination is changing and a codec is in use. if (srcPgsz != destPgsz && Pager.GetCodec(destPager) != null) rc = RC.READONLY; // Backup is not possible if the number of bytes of reserve space differ between source and destination. If there is a difference, try to // fix the destination to agree with the source. If that is not possible, then the backup cannot proceed. if (srcReserve != destReserve) { uint newPgsz = (uint)srcPgsz; rc = destPager.SetPageSize(ref newPgsz, srcReserve); if (rc == RC.OK && newPgsz != srcPgsz) rc = RC.READONLY; } #endif // This loop runs once for each destination page spanned by the source page. For each iteration, variable iOff is set to the byte offset // of the destination page. for (long off = end - (long)srcPgsz; rc == RC.OK && off < end; off += destPgsz) { IPage destPg = null; uint dest = (uint)(off / destPgsz) + 1; if (dest == Btree.PENDING_BYTE_PAGE(p.Dest.Bt)) continue; if ((rc = destPager.Acquire(dest, ref destPg, false)) == RC.OK && (rc = Pager.Write(destPg)) == RC.OK) { byte[] destData = Pager.GetData(destPg); // Copy the data from the source page into the destination page. Then clear the Btree layer MemPage.isInit flag. Both this module // and the pager code use this trick (clearing the first byte of the page 'extra' space to invalidate the Btree layers // cached parse of the page). MemPage.isInit is marked "MUST BE FIRST" for this purpose. Buffer.BlockCopy(srcData, (int)(off % srcPgsz), destData, (int)(off % destPgsz), copy); Pager.GetExtra(destPg).IsInit = false; } Pager.Unref(destPg); } return rc; } static RC BackupTruncateFile(VFile file, int size) { long current; RC rc = file.get_FileSize(out current); if (rc == RC.OK && current > size) rc = file.Truncate(size); return rc; } static void AttachBackupObject(Backup p) { Debug.Assert(p.Src.HoldsMutex()); Backup pp = (Backup)p.Src.get_Pager().Backup; p.Next = pp; p.Src.get_Pager().Backup = p; p.IsAttached = true; } public RC Step(int pages) { MutexEx.Enter(SrcCtx.Mutex); Src.Enter(); if (DestCtx != null) MutexEx.Enter(DestCtx.Mutex); RC rc = RC_; if (!IsFatalError(rc)) { Pager srcPager = Src.get_Pager(); // Source pager Pager destPager = Dest.get_Pager(); // Dest pager Pid srcPage = 0; // Size of source db in pages bool closeTrans = false; // True if src db requires unlocking // If the source pager is currently in a write-transaction, return SQLITE_BUSY immediately. rc = (DestCtx != null && Src.Bt.InTransaction == TRANS.WRITE ? RC.BUSY : RC.OK); // Lock the destination database, if it is not locked already. if (rc == RC.OK && !DestLocked && (rc = Dest.BeginTrans(2)) == RC.OK) { DestLocked = true; Dest.GetMeta(Btree.META.SCHEMA_VERSION, ref DestSchema); } // If there is no open read-transaction on the source database, open one now. If a transaction is opened here, then it will be closed // before this function exits. if (rc == RC.OK && !Src.IsInReadTrans()) { rc = Src.BeginTrans(0); closeTrans = true; } // Do not allow backup if the destination database is in WAL mode and the page sizes are different between source and destination int pgszSrc = Src.GetPageSize(); // Source page size int pgszDest = Dest.GetPageSize(); // Destination page size IPager.JOURNALMODE destMode = Dest.get_Pager().GetJournalMode(); // Destination journal mode if (rc == RC.OK && destMode == IPager.JOURNALMODE.WAL && pgszSrc != pgszDest) rc = RC.READONLY; // Now that there is a read-lock on the source database, query the source pager for the number of pages in the database. srcPage = Src.LastPage(); Debug.Assert(srcPage >= 0); for (int ii = 0; (pages < 0 || ii < pages) && NextId <= (Pid)srcPage && rc == 0; ii++) { Pid srcPg = NextId; // Source page number if (srcPg != Btree.PENDING_BYTE_PAGE(Src.Bt)) { IPage srcPgAsObj = null; // Source page object rc = srcPager.Acquire(srcPg, ref srcPgAsObj, false); if (rc == RC.OK) { rc = BackupOnePage(p, srcPg, Pager.GetData(srcPgAsObj), false); Pager.Unref(srcPgAsObj); } } NextId++; } if (rc == RC.OK) { Pagecount = srcPage; Remaining = (srcPage + 1 - NextId); if (NextId > srcPage) rc = RC.DONE; else if (!IsAttached) AttachBackupObject(p); } // Update the schema version field in the destination database. This is to make sure that the schema-version really does change in // the case where the source and destination databases have the same schema version. if (rc == RC.DONE) { if (srcPage == null) { rc = Dest.NewDb(); srcPage = 1; } if (rc == RC.OK || rc == RC.DONE) rc = Dest.UpdateMeta(Btree.META.SCHEMA_VERSION, DestSchema + 1); if (rc == RC.OK) { if (DestCtx != null) DataEx.ResetAllSchemasOfConnection(DestCtx); if (destMode == IPager.JOURNALMODE.WAL) rc = Dest.SetVersion(2); } if (rc == RC.OK) { // Set nDestTruncate to the final number of pages in the destination database. The complication here is that the destination page // size may be different to the source page size. // // If the source page size is smaller than the destination page size, round up. In this case the call to sqlite3OsTruncate() below will // fix the size of the file. However it is important to call sqlite3PagerTruncateImage() here so that any pages in the // destination file that lie beyond the nDestTruncate page mark are journalled by PagerCommitPhaseOne() before they are destroyed // by the file truncation. Debug.Assert(pgszSrc == Src.GetPageSize()); Debug.Assert(pgszDest == Dest.GetPageSize()); Pid destTruncate; if (pgszSrc < pgszDest) { int ratio = pgszDest / pgszSrc; destTruncate = (Pid)((srcPage + ratio - 1) / ratio); if (destTruncate == Btree.PENDING_BYTE_PAGE(Dest.Bt)) destTruncate--; } else destTruncate = (Pid)(srcPage * (pgszSrc / pgszDest)); Debug.Assert(destTruncate > 0); if (pgszSrc < pgszDest) { // If the source page-size is smaller than the destination page-size, two extra things may need to happen: // // * The destination may need to be truncated, and // // * Data stored on the pages immediately following the pending-byte page in the source database may need to be // copied into the destination database. int size = (int)(pgszSrc * srcPage); VFile file = destPager.get_File(); Debug.Assert(file != null); Debug.Assert((long)destTruncate * (long)pgszDest >= size || (destTruncate == (int)(Btree.PENDING_BYTE_PAGE(Dest.Bt) - 1) && size >= VFile.PENDING_BYTE && size <= VFile.PENDING_BYTE + pgszDest)); // This block ensures that all data required to recreate the original database has been stored in the journal for pDestPager and the // journal synced to disk. So at this point we may safely modify the database file in any way, knowing that if a power failure // occurs, the original database will be reconstructed from the journal file. uint dstPage; destPager.Pages(out dstPage); for (Pid pg = destTruncate; rc == RC.OK && pg <= (Pid)dstPage; pg++) { if (pg != Btree.PENDING_BYTE_PAGE(Dest.Bt)) { IPage pgAsObj; rc = destPager.Acquire(pg, ref pgAsObj, false); if (rc == RC.OK) { rc = Pager.Write(pgAsObj); Pager.Unref(pgAsObj); } } } if (rc == RC.OK) rc = destPager.CommitPhaseOne(null, true); // Write the extra pages and truncate the database file as required. long end = Math.Min(VFile.PENDING_BYTE + pgszDest, size); for (long off = VFile.PENDING_BYTE + pgszSrc; rc == RC.OK && off < end; off += pgszSrc) { Pid srcPg = (Pid)((off / pgszSrc) + 1); PgHdr srcPgAsObj = null; rc = srcPager.Acquire(srcPg, ref srcPgAsObj, false); if (rc == RC.OK) { byte[] data = Pager.GetData(srcPgAsObj); rc = file.Write(data, pgszSrc, off); } Pager.Unref(srcPgAsObj); } if (rc == RC.OK) rc = BackupTruncateFile(file, (int)size); // Sync the database file to disk. if (rc == RC.OK) rc = destPager.Sync(); } else { destPager.TruncateImage(destTruncate); rc = destPager.CommitPhaseOne(null, false); } // Finish committing the transaction to the destination database. if (rc == RC.OK && (rc = Dest.CommitPhaseTwo(false)) == RC.OK) rc = RC.DONE; } } // If bCloseTrans is true, then this function opened a read transaction on the source database. Close the read transaction here. There is // no need to check the return values of the btree methods here, as "committing" a read-only transaction cannot fail. if (closeTrans) { #if !DEBUG || COVERAGE_TEST RC rc2 = Src.CommitPhaseOne(null); rc2 |= Src.CommitPhaseTwo(false); Debug.Assert(rc2 == RC.OK); #else Src.CommitPhaseOne(null); Src.CommitPhaseTwo(false); #endif } if (rc == RC.IOERR_NOMEM) rc = RC.NOMEM; RC_ = rc; } if (DestCtx != null) MutexEx.Leave(DestCtx.Mutex); Src.Leave(); MutexEx.Leave(SrcCtx.Mutex); return rc; } public static RC Finish(Backup p) { // Enter the mutexes if (p == null) return RC.OK; Context srcCtx = p.SrcCtx; // Source database connection MutexEx.Enter(srcCtx.Mutex); p.Src.Enter(); if (p.DestCtx != null) MutexEx.Enter(p.DestCtx.Mutex); // Detach this backup from the source pager. if (p.DestCtx != null) p.Src.Backups--; if (p.IsAttached) { Backup pp = (Backup)p.Src.get_Pager().Backup; while (pp != p) pp = (pp).Next; p.Src.get_Pager().Backup = p.Next; } // If a transaction is still open on the Btree, roll it back. p.Dest.Rollback(RC.OK); // Set the error code of the destination database handle. RC rc = (p.RC_ == RC.DONE ? RC.OK : p.RC_); DataEx.Error(p.DestCtx, rc, null); // Exit the mutexes and free the backup context structure. if (p.DestCtx != null) DataEx.LeaveMutexAndCloseZombie(p.DestCtx.Mutex); p.Src.Leave(); //// EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a call to sqlite3_backup_init() and is destroyed by a call to sqlite3_backup_finish(). //if (p.DestCtx != null) // C._free(ref p); DataEx.LeaveMutexAndCloseZombie(mutex); return rc; } //public static int Remaining(Backup p) //{ // return (int)p.Remaining; //} //public static int Pagecount(Backup p) //{ // return (int)p.Pagecount; } public static void Update(Backup backup, Pid page, byte[] data) { for (Backup p = backup; p != null; p = p.Next) { Debug.Assert(MutexEx.Held(p.Src.Bt.Mutex)); if (!IsFatalError(p.RC_) && page < p.NextId) { // The backup process p has already copied page iPage. But now it has been modified by a transaction on the source pager. Copy // the new data into the backup. Debug.Assert(p.DestCtx != null); MutexEx.Enter(p.DestCtx.Mutex); RC rc = BackupOnePage(p, page, data, true); MutexEx.Leave(p.DestCtx.Mutex); Debug.Assert(rc != RC.BUSY && rc != RC.LOCKED); if (rc != RC.OK) p.RC_ = rc; } } } public static void Restart(Backup backup) { for (Backup p = backup; p != null; p = p.Next) { Debug.Assert(MutexEx.Held(p.Src.Bt.Mutex)); p.NextId = 1; } } #if !OMIT_VACUUM public static RC BtreeCopyFile(Btree to, Btree from) { to.Enter(); from.Enter(); Debug.Assert(to.IsInTrans()); RC rc; VFile fd = to.get_Pager().get_File(); // File descriptor for database pTo if (true) //fd->Methods) { long bytes = from.GetPageSize() * (long)from.LastPage(); rc = fd.FileControl(VFile.FCNTL.OVERWRITE, ref bytes); if (rc == RC.NOTFOUND) rc = RC.OK; if (rc != RC.OK) goto copy_finished; } // Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set to 0. This is used by the implementations of sqlite3_backup_step() // and sqlite3_backup_finish() to detect that they are being called from this function, not directly by the user. Backup b = new Backup(); b.SrcCtx = (Context)from.Ctx; b.Src = from; b.Dest = to; b.NextId = 1; // 0x7FFFFFFF is the hard limit for the number of pages in a database file. By passing this as the number of pages to copy to // sqlite3_backup_step(), we can guarantee that the copy finishes within a single call (unless an error occurs). The assert() statement // checks this assumption - (p->rc) should be set to either SQLITE_DONE or an error code. b.Step(0x7FFFFFFF); Debug.Assert(b.RC_ != RC.OK); rc = Finish(b); if (rc == RC.OK) to.Bt.BtsFlags &= ~Btree.BTS.PAGESIZE_FIXED; else b.Dest.get_Pager().ClearCache(); Debug.Assert(!to.IsInTrans()); copy_finished: from.Leave(); to.Leave(); return rc; } #endif } }
// <copyright file="DivergenceStopCriterionTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 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 MathNet.Numerics.LinearAlgebra.Solvers; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Solvers.StopCriterion { /// <summary> /// Divergence stop criterion test. /// </summary> [TestFixture, Category("LASolver")] public sealed class DivergenceStopCriterionTest { /// <summary> /// Create with negative maximum increase throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void CreateWithNegativeMaximumIncreaseThrowsArgumentOutOfRangeException() { Assert.That(() => new DivergenceStopCriterion<float>(-0.1), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Create with illegal minimum iterations throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void CreateWithIllegalMinimumIterationsThrowsArgumentOutOfRangeException() { Assert.That(() => new DivergenceStopCriterion<float>(minimumIterations: 2), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can create stop criterion. /// </summary> [Test] public void Create() { var criterion = new DivergenceStopCriterion<float>(0.1, 3); Assert.IsNotNull(criterion, "There should be a criterion"); Assert.AreEqual(0.1, criterion.MaximumRelativeIncrease, "Incorrect maximum"); Assert.AreEqual(3, criterion.MinimumNumberOfIterations, "Incorrect iteration count"); } /// <summary> /// Determine status with illegal iteration number throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void DetermineStatusWithIllegalIterationNumberThrowsArgumentOutOfRangeException() { var criterion = new DivergenceStopCriterion<float>(0.5, 15); Assert.That(() => criterion.DetermineStatus( -1, Vector<float>.Build.Dense(3, 4), Vector<float>.Build.Dense(3, 5), Vector<float>.Build.Dense(3, 6)), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can determine status with too few iterations. /// </summary> [Test] public void DetermineStatusWithTooFewIterations() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<float>(Increase, Iterations); // Add residuals. We should not diverge because we'll have to few iterations for (var i = 0; i < Iterations - 1; i++) { var status = criterion.DetermineStatus( i, new DenseVector(new[] { 1.0f }), new DenseVector(new[] { 1.0f }), new DenseVector(new[] { (i + 1)*(Increase + 0.1f) })); Assert.AreEqual(IterationStatus.Continue, status, "Status check fail."); } } /// <summary> /// Can determine status with no divergence. /// </summary> [Test] public void DetermineStatusWithNoDivergence() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<float>(Increase, Iterations); // Add residuals. We should not diverge because we won't have enough increase for (var i = 0; i < Iterations*2; i++) { var status = criterion.DetermineStatus( i, new DenseVector(new[] { 1.0f }), new DenseVector(new[] { 1.0f }), new DenseVector(new[] { (i + 1)*(Increase - 0.01f) })); Assert.AreEqual(IterationStatus.Continue, status, "Status check fail."); } } /// <summary> /// Can determine status with divergence through NaN. /// </summary> [Test] public void DetermineStatusWithDivergenceThroughNaN() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<float>(Increase, Iterations); // Add residuals. We should not diverge because we'll have to few iterations for (var i = 0; i < Iterations - 5; i++) { var status = criterion.DetermineStatus( i, new DenseVector(new[] { 1.0f }), new DenseVector(new[] { 1.0f }), new DenseVector(new[] { (i + 1)*(Increase - 0.01f) })); Assert.AreEqual(IterationStatus.Continue, status, "Status check fail."); } // Now make it fail by throwing in a NaN var status2 = criterion.DetermineStatus( Iterations, new DenseVector(new[] { 1.0f }), new DenseVector(new[] { 1.0f }), new DenseVector(new[] { float.NaN })); Assert.AreEqual(IterationStatus.Diverged, status2, "Status check fail."); } /// <summary> /// Can determine status with divergence. /// </summary> [Test] public void DetermineStatusWithDivergence() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<float>(Increase, Iterations); // Add residuals. We should not diverge because we'll have one to few iterations float previous = 1; for (var i = 0; i < Iterations - 1; i++) { previous *= 1 + Increase + 0.01f; var status = criterion.DetermineStatus( i, new DenseVector(new[] { 1.0f }), new DenseVector(new[] { 1.0f }), new DenseVector(new[] { previous })); Assert.AreEqual(IterationStatus.Continue, status, "Status check fail."); } // Add the final residual. Now we should have divergence previous *= 1 + Increase + 0.01f; var status2 = criterion.DetermineStatus( Iterations - 1, new DenseVector(new[] { 1.0f }), new DenseVector(new[] { 1.0f }), new DenseVector(new[] { previous })); Assert.AreEqual(IterationStatus.Diverged, status2, "Status check fail."); } /// <summary> /// Can reset calculation state. /// </summary> [Test] public void ResetCalculationState() { const double Increase = 0.5; const int Iterations = 10; var criterion = new DivergenceStopCriterion<float>(Increase, Iterations); // Add residuals. Blow it up instantly var status = criterion.DetermineStatus( 1, new DenseVector(new[] { 1.0f }), new DenseVector(new[] { 1.0f }), new DenseVector(new[] { float.NaN })); Assert.AreEqual(IterationStatus.Diverged, status, "Status check fail."); // Reset the state criterion.Reset(); Assert.AreEqual(Increase, criterion.MaximumRelativeIncrease, "Incorrect maximum"); Assert.AreEqual(Iterations, criterion.MinimumNumberOfIterations, "Incorrect iteration count"); Assert.AreEqual(IterationStatus.Continue, criterion.Status, "Status check fail."); } /// <summary> /// Can clone stop criterion. /// </summary> [Test] public void Clone() { const double Increase = 0.5; const int Iterations = 10; var criterion = new DivergenceStopCriterion<float>(Increase, Iterations); Assert.IsNotNull(criterion, "There should be a criterion"); var clone = criterion.Clone(); Assert.IsInstanceOf(typeof (DivergenceStopCriterion<float>), clone, "Wrong criterion type"); var clonedCriterion = clone as DivergenceStopCriterion<float>; Assert.IsNotNull(clonedCriterion); Assert.AreEqual(criterion.MaximumRelativeIncrease, clonedCriterion.MaximumRelativeIncrease, "Incorrect maximum"); Assert.AreEqual(criterion.MinimumNumberOfIterations, clonedCriterion.MinimumNumberOfIterations, "Incorrect iteration count"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace BioMarket.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Security.Cryptography.X509Certificates; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml; using ComponentSpace.SAML2; using ComponentSpace.SAML2.Assertions; using ComponentSpace.SAML2.Protocols; using ComponentSpace.SAML2.Bindings; using ComponentSpace.SAML2.Profiles.ArtifactResolution; using ComponentSpace.SAML2.Profiles.SSOBrowser; namespace GoogleIdP.SAML { public partial class SSOService : System.Web.UI.Page { // The SSO state saved during a local login. private class SSOState { private AuthnRequest authnRequest; private string relayState; public AuthnRequest AuthnRequest { get { return authnRequest; } set { authnRequest = value; } } public string RelayState { get { return relayState; } set { relayState = value; } } } // The session key for saving the SSO state during a local login. private const string ssoSessionKey = "sso"; // Create an absolute URL from an application relative URL. private string CreateAbsoluteURL(string relativeURL) { return new Uri(Request.Url, ResolveUrl(relativeURL)).ToString(); } // Receive the authentication request and relay state. private void ReceiveAuthnRequest(out AuthnRequest authnRequest, out string relayState) { Trace.Write("IdP", "Receiving authentication request over binding"); XmlElement authnRequestXml = null; bool signed = false; IdentityProvider.ReceiveAuthnRequestByHTTPRedirect(Request, out authnRequestXml, out relayState, out signed, null); if (SAMLMessageSignature.IsSigned(authnRequestXml)) { Trace.Write("IdP", "Verifying request signature"); if (!SAMLMessageSignature.Verify(authnRequestXml)) { throw new ArgumentException("The authentication request signature failed to verify."); } } authnRequest = new AuthnRequest(authnRequestXml); Trace.Write("IdP", "Received authentication request"); } // Indicate whether a local login is required. private bool IsLocalLoginRequired(bool forceAuthn) { bool requireLocalLogin = false; if (forceAuthn) { requireLocalLogin = true; } else { if (!User.Identity.IsAuthenticated) { requireLocalLogin = true; } } return requireLocalLogin; } // Create a SAML response with the user's local identity, if any, or indicating an error. private SAMLResponse CreateSAMLResponse(AuthnRequest authnRequest) { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = authnRequest.AssertionConsumerServiceURL; Issuer issuer = new Issuer(CreateAbsoluteURL("~/")); samlResponse.Issuer = issuer; if (User.Identity.IsAuthenticated) { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; samlAssertion.Conditions = new Conditions(new TimeSpan(0, 10, 0)); AudienceRestriction audienceRestriction = new AudienceRestriction(); audienceRestriction.Audiences.Add(new Audience(authnRequest.AssertionConsumerServiceURL)); samlAssertion.Conditions.ConditionsList.Add(audienceRestriction); Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.InResponseTo = authnRequest.ID; subjectConfirmationData.Recipient = authnRequest.AssertionConsumerServiceURL; subjectConfirmationData.NotBefore = samlAssertion.Conditions.NotBefore; subjectConfirmationData.NotOnOrAfter = samlAssertion.Conditions.NotOnOrAfter; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); samlResponse.Assertions.Add(samlAssertion); } else { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider"); } Trace.Write("IdP", "Created SAML response"); return samlResponse; } // Send the SAML response to the SP. private void SendSAMLResponse(SAMLResponse samlResponse, string relayState, string assertionConsumerServiceURL) { Trace.Write("IdP", "Sending SAML response"); // Serialize the SAML response for transmission. XmlElement samlResponseXml = samlResponse.ToXml(); // Sign the SAML response. X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; SAMLMessageSignature.Generate(samlResponseXml, x509Certificate.PrivateKey, x509Certificate); IdentityProvider.SendSAMLResponseByHTTPPost(Response, assertionConsumerServiceURL, samlResponseXml, relayState); Trace.Write("IdP", "Sent SAML response"); } protected void Page_Load(object sender, EventArgs e) { try { // Get the saved SSO state, if any. // If there isn't saved state then receive the authentication request. // If there is saved state then we've just completed a local login in response to a prior authentication request. SSOState ssoState = (SSOState)Session[ssoSessionKey]; if (ssoState == null) { Trace.Write("IdP", "SSO service"); // Receive the authentication request and relay state. AuthnRequest authnRequest = null; string relayState = null; ReceiveAuthnRequest(out authnRequest, out relayState); // Process the request. bool forceAuthn = authnRequest.ForceAuthn; ssoState = new SSOState(); ssoState.AuthnRequest = authnRequest; ssoState.RelayState = relayState; // Determine whether or not a local login is required. bool requireLocalLogin = IsLocalLoginRequired(forceAuthn); // If a local login is required then save the session state and initiate a local login. if (requireLocalLogin) { Session[ssoSessionKey] = ssoState; FormsAuthentication.RedirectToLoginPage(); return; } } // Create a SAML response with the user's local identity, if any. SAMLResponse samlResponse = CreateSAMLResponse(ssoState.AuthnRequest); // Send the SAML response to the service provider. SendSAMLResponse(samlResponse, ssoState.RelayState, ssoState.AuthnRequest.AssertionConsumerServiceURL); // Clear the SSO state. Session[ssoSessionKey] = null; } catch (Exception exception) { Trace.Write("IdP", "Error in SSO service", exception); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public static class UnionTests { private const int DuplicateFactor = 8; // Get two ranges, with the right starting where the left ends public static IEnumerable<object[]> UnionUnorderedCountData(int[] counts) { foreach (int left in counts) { foreach (int right in counts) { yield return new object[] { left, right }; } } } private static IEnumerable<object[]> UnionUnorderedData(int[] counts) { foreach (object[] parms in UnorderedSources.BinaryRanges(counts, (l, r) => l, counts)) { yield return parms.Take(4).ToArray(); } } // Union returns only the ordered portion ordered. // Get two ranges, both ordered. public static IEnumerable<object[]> UnionData(int[] counts) { foreach (object[] parms in UnionUnorderedData(counts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } // Get two ranges, with only the left being ordered. public static IEnumerable<object[]> UnionFirstOrderedData(int[] counts) { foreach (object[] parms in UnionUnorderedData(counts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] }; } } // Get two ranges, with only the right being ordered. public static IEnumerable<object[]> UnionSecondOrderedData(int[] counts) { foreach (object[] parms in UnionUnorderedData(counts)) { yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } // Get two ranges, both sourced from arrays, with duplicate items in each array. // Used in distinctness tests, in contrast to relying on a Select predicate to generate duplicate items. public static IEnumerable<object[]> UnionSourceMultipleData(int[] counts) { foreach (int leftCount in counts) { ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel(); foreach (int rightCount in new[] { 0, 1, Math.Max(DuplicateFactor, leftCount / 2), Math.Max(DuplicateFactor, leftCount) }.Distinct()) { int rightStart = leftCount - Math.Min(leftCount, rightCount) / 2; ParallelQuery<int> right = Enumerable.Range(0, rightCount * DuplicateFactor).Select(x => x % rightCount + rightStart).ToArray().AsParallel(); yield return new object[] { left, leftCount, right, rightCount, Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2 }; } } } // // Union // [Theory] [MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })] public static void Union_Unordered(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount); IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount); foreach (int i in leftQuery.Union(rightQuery)) { seen.Add(i); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Union_Unordered_Longrunning() { Union_Unordered(Sources.OuterLoopCount, Sources.OuterLoopCount); } [Theory] [MemberData(nameof(UnionData), new[] { 0, 1, 2, 16 })] public static void Union(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; foreach (int i in leftQuery.Union(rightQuery)) { Assert.Equal(seen++, i); } Assert.Equal(leftCount + rightCount, seen); } [Theory] [OuterLoop] [MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })] public static void Union_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(UnionFirstOrderedData), new[] { 0, 1, 2, 16 })] public static void Union_FirstOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount); int seen = 0; foreach (int i in leftQuery.Union(rightQuery)) { if (i < leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(UnionFirstOrderedData), new[] { 512, 1024 * 8 })] public static void Union_FirstOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(UnionSecondOrderedData), new[] { 0, 1, 2, 16 })] public static void Union_SecondOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Union(rightQuery)) { if (i >= leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount + rightCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(UnionSecondOrderedData), new[] { 512, 1024 * 8 })] public static void Union_SecondOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })] public static void Union_Unordered_NotPipelined(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount); IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount); Assert.All(leftQuery.Union(rightQuery).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Union_Unordered_NotPipelined_Longrunning() { Union_Unordered_NotPipelined(Sources.OuterLoopCount, Sources.OuterLoopCount); } [Theory] [MemberData(nameof(UnionData), new[] { 0, 1, 2, 16 })] public static void Union_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; Assert.All(leftQuery.Union(rightQuery).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(leftCount + rightCount, seen); } [Theory] [OuterLoop] [MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })] public static void Union_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(UnionFirstOrderedData), new[] { 0, 1, 2, 16 })] public static void Union_FirstOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount); int seen = 0; Assert.All(leftQuery.Union(rightQuery).ToList(), x => { if (x < leftCount) Assert.Equal(seen++, x); else seenUnordered.Add(x); }); Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(UnionFirstOrderedData), new[] { 512, 1024 * 8 })] public static void Union_FirstOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(UnionSecondOrderedData), new[] { 0, 1, 2, 16 })] public static void Union_SecondOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; Assert.All(leftQuery.Union(rightQuery).ToList(), x => { if (x >= leftCount) Assert.Equal(seen++, x); else seenUnordered.Add(x); }); Assert.Equal(leftCount + rightCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(UnionSecondOrderedData), new[] { 512, 1024 * 8 })] public static void Union_SecondOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })] public static void Union_Unordered_Distinct(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount); leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount); foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { seen.Add(i); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Union_Unordered_Distinct_Longrunning() { Union_Unordered_Distinct(Sources.OuterLoopCount, Sources.OuterLoopCount); } [Theory] [MemberData(nameof(UnionData), new[] { 0, 1, 2, 16 })] public static void Union_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; int seen = 0; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { Assert.Equal(seen++, i); } Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })] public static void Union_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })] public static void Union_Unordered_Distinct_NotPipelined(int leftCount, int rightCount) { ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount); ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount); leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount); Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Union_Unordered_Distinct_NotPipelined_Longrunning() { Union_Unordered_Distinct_NotPipelined(Sources.OuterLoopCount, Sources.OuterLoopCount); } [Theory] [MemberData(nameof(UnionData), new[] { 0, 1, 2, DuplicateFactor * 2 })] public static void Union_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; int seen = 0; Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })] public static void Union_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Distinct_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(UnionSourceMultipleData), new[] { 0, 1, 2, DuplicateFactor * 2 })] public static void Union_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { // The difference between this test and the previous, is that it's not possible to // get non-unique results from ParallelEnumerable.Range()... // Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar, // or via a comparator that considers some elements equal. IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(leftQuery.Union(rightQuery), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(UnionSourceMultipleData), new[] { 512, 1024 * 8 })] public static void Union_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData(nameof(UnionSourceMultipleData), new[] { 0, 1, 2, DuplicateFactor * 2 })] public static void Union_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { int seen = 0; Assert.All(leftQuery.AsOrdered().Union(rightQuery.AsOrdered()), x => Assert.Equal(seen++, x)); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(UnionSourceMultipleData), new[] { 512, 1024 * 8 })] public static void Union_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Fact] public static void Union_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1))); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1), null)); #pragma warning restore 618 } [Fact] // Should not get the same setting from both operands. public static void Union_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Union(ParallelEnumerable.Range(0, 1).WithCancellation(t))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Union(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Union(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Union(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default))); } [Fact] public static void Union_ArgumentNullException() { Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1))); Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Union(null)); Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Union(null, EqualityComparer<int>.Default)); } } }
/* * daap-sharp * Copyright (C) 2005 James Willcox <snorp@snorp.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Collections.Generic; using Hyena; using Mono.Zeroconf; namespace Daap { public delegate void ServiceHandler (object o, ServiceArgs args); public class ServiceArgs : EventArgs { private Service service; public Service Service { get { return service; } } public ServiceArgs (Service service) { this.service = service; } } public class Service { private IPAddress address; private ushort port; private string name; private bool isprotected; public IPAddress Address { get { return address; } } public ushort Port { get { return port; } } public string Name { get { return name; } } public bool IsProtected { get { return isprotected; } } public Service (IPAddress address, ushort port, string name, bool isprotected) { this.address = address; this.port = port; this.name = name; this.isprotected = isprotected; } public override string ToString() { return String.Format("{0}:{1} ({2})", Address, Port, Name); } } public class ServiceLocator { private ServiceBrowser browser; private Dictionary <string, Service> services = new Dictionary <string, Service> (); private bool showLocals = false; public event ServiceHandler Found; public event ServiceHandler Removed; public bool ShowLocalServices { get { return showLocals; } set { showLocals = value; } } public Service [] Services { get { Service [] ret = new Service [services.Count]; services.Values.CopyTo (ret, 0); return ret; } } public ServiceLocator () { } public void Start () { if (browser != null) { Stop (); } browser = new ServiceBrowser (); browser.ServiceAdded += OnServiceAdded; browser.ServiceRemoved += OnServiceRemoved; browser.Browse ("_daap._tcp", null); } public void Stop () { if (browser != null) { browser.Dispose (); browser = null; } services.Clear (); } private void OnServiceAdded (object o, ServiceBrowseEventArgs args) { args.Service.Resolved += OnServiceResolved; Log.DebugFormat ("Found DAAP share {0}, trying to resolve...", args.Service.Name); args.Service.Resolve (); } private void OnServiceResolved (object o, ServiceResolvedEventArgs args) { string name = args.Service.Name; Log.DebugFormat ("Managed to resolve DAAP share {0}.", args.Service.Name); bool password_required = false; // iTunes tacks this on to indicate a passsword protected share. Ugh. if (name.EndsWith ("_PW")) { name = name.Substring (0, name.Length - 3); password_required = true; } IResolvableService service = (IResolvableService) args.Service; foreach(TxtRecordItem item in service.TxtRecord) { if(item.Key.ToLower () == "password") { password_required = item.ValueString.ToLower () == "true"; } else if (item.Key.ToLower () == "machine name") { name = item.ValueString; } } IPAddress address = args.Service.HostEntry.AddressList[0]; Log.DebugFormat ("OnServiceResolved provided {0}", address); // XXX: Workaround a Mono bug where we can't resolve IPv6 addresses properly if (services.ContainsKey (name) && address.AddressFamily == AddressFamily.InterNetworkV6) { // Only skip this service if it resolves to a IPv6 address, and we already have info // for this service already. Log.Debug ("Skipping service", "already have IPv4 address."); return; } else if (!services.ContainsKey (name) && address.AddressFamily == AddressFamily.InterNetworkV6) { // This is the first address we've resolved, however, it's an IPv6 address. // Try and resolve the hostname in hope that it'll end up as an IPv4 address - it doesn't // really matter if it still ends up with an IPv6 address, we're not risking anything. foreach (IPAddress addr in Dns.GetHostEntry (args.Service.HostEntry.HostName).AddressList) { if (addr.AddressFamily == AddressFamily.InterNetwork) { address = addr; } } } Log.DebugFormat ("Using address {0}", address); Daap.Service svc = new Daap.Service (address, (ushort)service.Port, name, password_required); if (services.ContainsKey (name)) { services[name] = svc; } else { services.Add (name, svc); } if (Found != null) Found (this, new ServiceArgs (svc)); } private void OnServiceRemoved (object o, ServiceBrowseEventArgs args) { if (services.ContainsKey (args.Service.Name)) { Service svc = (Service) services[args.Service.Name]; if (svc != null) { services.Remove (svc.Name); if (Removed != null) Removed (this, new ServiceArgs (svc)); } } } } }
/* ==================================================================== 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.HSSF.Record.CF; using NPOI.SS.Util; using NPOI.Util; /** * Parent of Conditional Formatting Header records, * {@link CFHeaderRecord} and {@link CFHeader12Record}. */ public abstract class CFHeaderBase : StandardRecord, ICloneable { private int field_1_numcf; private int field_2_need_recalculation_and_id; private CellRangeAddress field_3_enclosing_cell_range; private CellRangeAddressList field_4_cell_ranges; /** Creates new CFHeaderBase */ protected CFHeaderBase() { } protected CFHeaderBase(CellRangeAddress[] regions, int nRules) { CellRangeAddress[] unmergedRanges = regions; CellRangeAddress[] mergeCellRanges = CellRangeUtil.MergeCellRanges(unmergedRanges); CellRanges = (mergeCellRanges); field_1_numcf = nRules; } protected void CreateEmpty() { field_3_enclosing_cell_range = new CellRangeAddress(0, 0, 0, 0); field_4_cell_ranges = new CellRangeAddressList(); } protected void Read(RecordInputStream in1) { field_1_numcf = in1.ReadShort(); field_2_need_recalculation_and_id = in1.ReadShort(); field_3_enclosing_cell_range = new CellRangeAddress(in1); field_4_cell_ranges = new CellRangeAddressList(in1); } public int NumberOfConditionalFormats { get { return field_1_numcf; } set { field_1_numcf = value; } } public bool NeedRecalculation { get { // Held on the 1st bit return (field_2_need_recalculation_and_id & 1) == 1; } set { // held on the first bit if (value == NeedRecalculation) return; if (value) field_2_need_recalculation_and_id++; else field_2_need_recalculation_and_id--; } } public int ID { get { // Remaining 15 bits of field 2 return field_2_need_recalculation_and_id >> 1; } set { // Remaining 15 bits of field 2 bool needsRecalc = NeedRecalculation; field_2_need_recalculation_and_id = (value << 1); if (needsRecalc) field_2_need_recalculation_and_id++; } } public CellRangeAddress EnclosingCellRange { get { return field_3_enclosing_cell_range; } set { field_3_enclosing_cell_range = value; } } /** * Set cell ranges list to a single cell range and * modify the enclosing cell range accordingly. * @param cellRanges - list of CellRange objects */ public CellRangeAddress[] CellRanges { get { return field_4_cell_ranges.CellRangeAddresses; } set { if (value == null) { throw new ArgumentException("cellRanges must not be null"); } CellRangeAddressList cral = new CellRangeAddressList(); CellRangeAddress enclosingRange = null; for (int i = 0; i < value.Length; i++) { CellRangeAddress cr = value[i]; enclosingRange = CellRangeUtil.CreateEnclosingCellRange(cr, enclosingRange); cral.AddCellRangeAddress(cr); } field_3_enclosing_cell_range = enclosingRange; field_4_cell_ranges = cral; } } protected abstract String RecordName { get; } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[").Append(RecordName).Append("]\n"); buffer.Append("\t.numCF = ").Append(NumberOfConditionalFormats).Append("\n"); buffer.Append("\t.needRecalc = ").Append(NeedRecalculation).Append("\n"); buffer.Append("\t.id = ").Append(ID).Append("\n"); buffer.Append("\t.enclosingCellRange= ").Append(EnclosingCellRange).Append("\n"); buffer.Append("\t.CFranges=["); for (int i = 0; i < field_4_cell_ranges.CountRanges(); i++) { buffer.Append(i == 0 ? "" : ",").Append(field_4_cell_ranges.GetCellRangeAddress(i).ToString()); } buffer.Append("]\n"); buffer.Append("[/").Append(RecordName).Append("]\n"); return buffer.ToString(); } protected override int DataSize { get { return 4 // 2 short fields + CellRangeAddress.ENCODED_SIZE + field_4_cell_ranges.Size; } } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(field_1_numcf); out1.WriteShort(field_2_need_recalculation_and_id); field_3_enclosing_cell_range.Serialize(out1); field_4_cell_ranges.Serialize(out1); } protected void CopyTo(CFHeaderBase result) { result.field_1_numcf = field_1_numcf; result.field_2_need_recalculation_and_id = field_2_need_recalculation_and_id; result.field_3_enclosing_cell_range = field_3_enclosing_cell_range.Copy(); result.field_4_cell_ranges = field_4_cell_ranges.Copy(); } } }
using System; using NUnit.Framework; using Raksha.Crypto; using Raksha.Crypto.Digests; using Raksha.Crypto.Engines; using Raksha.Crypto.Modes; using Raksha.Crypto.Parameters; using Raksha.Math; using Raksha.Security; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; namespace Raksha.Tests.Crypto { [TestFixture] public class Gost28147Test : CipherTest { static string input1 = "0000000000000000"; static string output1 = "1b0bbc32cebcab42"; static string input2 = "bc350e71aac5f5c2"; static string output2 = "d35ab653493b49f5"; static string input3 = "bc350e71aa11345709acde"; static string output3 = "8824c124c4fd14301fb1e8"; static string input4 = "000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f"; static string output4 = "29b7083e0a6d955ca0ec5b04fdb4ea41949f1dd2efdf17baffc1780b031f3934"; static byte[] TestSBox = { 0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xE,0xF, 0xF,0xE,0xD,0xC,0xB,0xA,0x9,0x8,0x7,0x6,0x5,0x4,0x3,0x2,0x1,0x0, 0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xE,0xF, 0xF,0xE,0xD,0xC,0xB,0xA,0x9,0x8,0x7,0x6,0x5,0x4,0x3,0x2,0x1,0x0, 0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xE,0xF, 0xF,0xE,0xD,0xC,0xB,0xA,0x9,0x8,0x7,0x6,0x5,0x4,0x3,0x2,0x1,0x0, 0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xE,0xF, 0xF,0xE,0xD,0xC,0xB,0xA,0x9,0x8,0x7,0x6,0x5,0x4,0x3,0x2,0x1,0x0 }; static SimpleTest[] tests = { new BlockCipherVectorTest(1, new Gost28147Engine(), new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")), input1, output1), new BlockCipherVectorTest(2, new CbcBlockCipher(new Gost28147Engine()), new ParametersWithIV(new KeyParameter(Hex.Decode("00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF")), Hex.Decode("1234567890abcdef")), input2, output2), new BlockCipherVectorTest(3, new GOfbBlockCipher(new Gost28147Engine()), new ParametersWithIV(new KeyParameter(Hex.Decode("0011223344556677889900112233445566778899001122334455667788990011")), Hex.Decode("1234567890abcdef")), //IV input3, output3), new BlockCipherVectorTest(4, new CfbBlockCipher(new Gost28147Engine(), 64), new ParametersWithIV(new KeyParameter(Hex.Decode("aafd12f659cae63489b479e5076ddec2f06cb58faafd12f659cae63489b479e5")), Hex.Decode("aafd12f659cae634")), input4, output4), //tests with parameters, set S-box. new BlockCipherVectorTest(5, new Gost28147Engine(), new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")),//key , default parameter S-box set to D-Test input1, output1), new BlockCipherVectorTest(6, new CfbBlockCipher(new Gost28147Engine(), 64), new ParametersWithIV( new ParametersWithSBox( new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")), //key Gost28147Engine.GetSBox("D-Test")), //type S-box Hex.Decode("1234567890abcdef")), //IV "0000000000000000", //input message "b587f7a0814c911d"), //encrypt message new BlockCipherVectorTest(7, new CfbBlockCipher(new Gost28147Engine(), 64), new ParametersWithIV( new ParametersWithSBox( new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")), //key Gost28147Engine.GetSBox("E-Test")), //type S-box Hex.Decode("1234567890abcdef")), //IV "0000000000000000", //input message "e8287f53f991d52b"), //encrypt message new BlockCipherVectorTest(8, new CfbBlockCipher(new Gost28147Engine(), 64), new ParametersWithIV( new ParametersWithSBox( new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")), //key Gost28147Engine.GetSBox("E-A")), //type S-box Hex.Decode("1234567890abcdef")), //IV "0000000000000000", //input message "c41009dba22ebe35"), //encrypt message new BlockCipherVectorTest(9, new CfbBlockCipher(new Gost28147Engine(), 8), new ParametersWithIV( new ParametersWithSBox( new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")), //key Gost28147Engine.GetSBox("E-B")), //type S-box Hex.Decode("1234567890abcdef")), //IV "0000000000000000", //input message "80d8723fcd3aba28"), //encrypt message new BlockCipherVectorTest(10, new CfbBlockCipher(new Gost28147Engine(), 8), new ParametersWithIV( new ParametersWithSBox( new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")), //key Gost28147Engine.GetSBox("E-C")), //type S-box Hex.Decode("1234567890abcdef")), //IV "0000000000000000", //input message "739f6f95068499b5"), //encrypt message new BlockCipherVectorTest(11, new CfbBlockCipher(new Gost28147Engine(), 8), new ParametersWithIV( new ParametersWithSBox( new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")), //key Gost28147Engine.GetSBox("E-D")), //type S-box Hex.Decode("1234567890abcdef")), //IV "0000000000000000", //input message "4663f720f4340f57"), //encrypt message new BlockCipherVectorTest(12, new CfbBlockCipher(new Gost28147Engine(), 8), new ParametersWithIV( new ParametersWithSBox( new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")), //key Gost28147Engine.GetSBox("D-A")), //type S-box Hex.Decode("1234567890abcdef")), //IV "0000000000000000", //input message "5bb0a31d218ed564"), //encrypt message new BlockCipherVectorTest(13, new CfbBlockCipher(new Gost28147Engine(), 8), new ParametersWithIV( new ParametersWithSBox( new KeyParameter(Hex.Decode("546d203368656c326973652073736e62206167796967747473656865202c3d73")), //key TestSBox), //set own S-box Hex.Decode("1234567890abcdef")), //IV "0000000000000000", //input message "c3af96ef788667c5"), //encrypt message new BlockCipherVectorTest(14, new GOfbBlockCipher(new Gost28147Engine()), new ParametersWithIV( new ParametersWithSBox( new KeyParameter(Hex.Decode("4ef72b778f0b0bebeef4f077551cb74a927b470ad7d7f2513454569a247e989d")), //key Gost28147Engine.GetSBox("E-A")), //type S-box Hex.Decode("1234567890abcdef")), //IV "bc350e71aa11345709acde", //input message "1bcc2282707c676fb656dc"), //encrypt message }; private const int Gost28147_KEY_LENGTH = 32; private byte[] generateKey(byte[] startkey) { byte[] newKey = new byte[Gost28147_KEY_LENGTH]; Gost3411Digest digest = new Gost3411Digest(); digest.BlockUpdate(startkey, 0, startkey.Length); digest.DoFinal(newKey, 0); return newKey; } public Gost28147Test() : base(tests, new Gost28147Engine(), new KeyParameter(new byte[32])) { } public override void PerformTest() { base.PerformTest(); //advanced tests with Gost28147KeyGenerator: //encrypt on hesh message; ECB mode: byte[] inBytes = Hex.Decode("4e6f77206973207468652074696d6520666f7220616c6c20"); byte[] output = Hex.Decode("8ad3c8f56b27ff1fbd46409359bdc796bc350e71aac5f5c0"); byte[] outBytes = new byte[inBytes.Length]; byte[] key = generateKey(Hex.Decode("0123456789abcdef")); //!!! heshing start_key - get 256 bits !!! // System.out.println(new string(Hex.Encode(key))); ICipherParameters param = new ParametersWithSBox(new KeyParameter(key), Gost28147Engine.GetSBox("E-A")); //CipherParameters param = new Gost28147Parameters(key,"D-Test"); BufferedBlockCipher cipher = new BufferedBlockCipher(new Gost28147Engine()); cipher.Init(true, param); int len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); try { cipher.DoFinal(outBytes, len1); } catch (CryptoException e) { Fail("failed - exception " + e.ToString(), e); } if (outBytes.Length != output.Length) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } for (int i = 0; i != outBytes.Length; i++) { if (outBytes[i] != output[i]) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } } //encrypt on hesh message; CFB mode: inBytes = Hex.Decode("bc350e71aac5f5c2"); output = Hex.Decode("0ebbbafcf38f14a5"); outBytes = new byte[inBytes.Length]; key = generateKey(Hex.Decode("0123456789abcdef")); //!!! heshing start_key - get 256 bits !!! param = new ParametersWithIV( new ParametersWithSBox( new KeyParameter(key), //key Gost28147Engine.GetSBox("E-A")), //type S-box Hex.Decode("1234567890abcdef")); //IV cipher = new BufferedBlockCipher(new CfbBlockCipher(new Gost28147Engine(), 64)); cipher.Init(true, param); len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); try { cipher.DoFinal(outBytes, len1); } catch (CryptoException e) { Fail("failed - exception " + e.ToString(), e); } if (outBytes.Length != output.Length) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } for (int i = 0; i != outBytes.Length; i++) { if (outBytes[i] != output[i]) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } } //encrypt on hesh message; CFB mode: inBytes = Hex.Decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f"); output = Hex.Decode("64988982819f0a1655e226e19ecad79d10cc73bac95c5d7da034786c12294225"); outBytes = new byte[inBytes.Length]; key = generateKey(Hex.Decode("aafd12f659cae63489b479e5076ddec2f06cb58faafd12f659cae63489b479e5")); //!!! heshing start_key - get 256 bits !!! param = new ParametersWithIV( new ParametersWithSBox( new KeyParameter(key), //key Gost28147Engine.GetSBox("E-A")), //type S-box Hex.Decode("aafd12f659cae634")); //IV cipher = new BufferedBlockCipher(new CfbBlockCipher(new Gost28147Engine(), 64)); cipher.Init(true, param); len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); cipher.DoFinal(outBytes, len1); if (outBytes.Length != output.Length) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } for (int i = 0; i != outBytes.Length; i++) { if (outBytes[i] != output[i]) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } } //encrypt on hesh message; OFB mode: inBytes = Hex.Decode("bc350e71aa11345709acde"); output = Hex.Decode("1bcc2282707c676fb656dc"); outBytes = new byte[inBytes.Length]; key = generateKey(Hex.Decode("0123456789abcdef")); //!!! heshing start_key - get 256 bits !!! param = new ParametersWithIV( new ParametersWithSBox( new KeyParameter(key), //key Gost28147Engine.GetSBox("E-A")), //type S-box Hex.Decode("1234567890abcdef")); //IV cipher = new BufferedBlockCipher(new GOfbBlockCipher(new Gost28147Engine())); cipher.Init(true, param); len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); cipher.DoFinal(outBytes, len1); if (outBytes.Length != output.Length) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } for (int i = 0; i != outBytes.Length; i++) { if (outBytes[i] != output[i]) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } } } public override string Name { get { return "Gost28147"; } } public static void Main( string[] args) { ITest test = new Gost28147Test(); ITestResult result = test.Perform(); Console.WriteLine(result); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
/* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace IBApi { /** * @class OrderState * @brief Provides an active order's current state * @sa Order */ [ComVisible(true)] public class OrderState : TWSLib.IOrderState { private string status; private string initMargin; private string maintMargin; private string equityWithLoan; private double commission; private double minCommission; private double maxCommission; private string commissionCurrency; private string warningText; /** * @brief The order's current status */ public string Status { get { return status; } set { status = value; } } /** * @brief The order's impact on the account's initial margin. */ public string InitMargin { get { return initMargin; } set { initMargin = value; } } /** * @brief The order's impact on the account's maintenance margin */ public string MaintMargin { get { return maintMargin; } set { maintMargin = value; } } /** * @brief Shows the impact the order would have on the account's equity with loan */ public string EquityWithLoan { get { return equityWithLoan; } set { equityWithLoan = value; } } /** * @brief The order's generated commission. */ public double Commission { get { return commission; } set { commission = value; } } /** * @brief The execution's minimum commission. */ public double MinCommission { get { return minCommission; } set { minCommission = value; } } /** * @brief The executions maximum commission. */ public double MaxCommission { get { return maxCommission; } set { maxCommission = value; } } /** * @brief The generated commission currency * @sa CommissionReport */ public string CommissionCurrency { get { return commissionCurrency; } set { commissionCurrency = value; } } /** * @brief If the order is warranted, a descriptive message will be provided. */ public string WarningText { get { return warningText; } set { warningText = value; } } public OrderState() { Status = null; InitMargin = null; MaintMargin = null; EquityWithLoan = null; Commission = 0.0; MinCommission = 0.0; MaxCommission = 0.0; CommissionCurrency = null; WarningText = null; } public OrderState(string status, string initMargin, string maintMargin, string equityWithLoan, double commission, double minCommission, double maxCommission, string commissionCurrency, string warningText) { InitMargin = initMargin; MaintMargin = maintMargin; EquityWithLoan = equityWithLoan; Commission = commission; MinCommission = minCommission; MaxCommission = maxCommission; CommissionCurrency = commissionCurrency; WarningText = warningText; } public override bool Equals(Object other) { if (this == other) return true; if (other == null) return false; OrderState state = (OrderState)other; if (commission != state.commission || minCommission != state.minCommission || maxCommission != state.maxCommission) { return false; } if (Util.StringCompare(status, state.status) != 0 || Util.StringCompare(initMargin, state.initMargin) != 0 || Util.StringCompare(maintMargin, state.maintMargin) != 0 || Util.StringCompare(equityWithLoan, state.equityWithLoan) != 0 || Util.StringCompare(commissionCurrency, state.commissionCurrency) != 0) { return false; } return true; } string TWSLib.IOrderState.status { get { return status; } } string TWSLib.IOrderState.initMargin { get { return initMargin; } } string TWSLib.IOrderState.maintMargin { get { return maintMargin; } } string TWSLib.IOrderState.equityWithLoan { get { return equityWithLoan; } } double TWSLib.IOrderState.commission { get { return commission; } } double TWSLib.IOrderState.minCommission { get { return minCommission; } } double TWSLib.IOrderState.maxCommission { get { return maxCommission; } } string TWSLib.IOrderState.commissionCurrency { get { return commissionCurrency; } } string TWSLib.IOrderState.warningText { get { return warningText; } } } }
namespace java.lang { [global::MonoJavaBridge.JavaClass()] public sealed partial class Double : java.lang.Number, Comparable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Double() { InitJNI(); } internal Double(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _equals12916; public sealed override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.Double._equals12916, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._equals12916, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString12917; public static global::java.lang.String toString(double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Double.staticClass, global::java.lang.Double._toString12917, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _toString12918; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.Double._toString12918)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._toString12918)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode12919; public sealed override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Double._hashCode12919); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._hashCode12919); } internal static global::MonoJavaBridge.MethodId _doubleToRawLongBits12920; public static long doubleToRawLongBits(double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Double.staticClass, global::java.lang.Double._doubleToRawLongBits12920, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _doubleToLongBits12921; public static long doubleToLongBits(double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Double.staticClass, global::java.lang.Double._doubleToLongBits12921, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _longBitsToDouble12922; public static double longBitsToDouble(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticDoubleMethod(java.lang.Double.staticClass, global::java.lang.Double._longBitsToDouble12922, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo12923; public int compareTo(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Double._compareTo12923, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._compareTo12923, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo12924; public int compareTo(java.lang.Double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Double._compareTo12924, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._compareTo12924, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toHexString12925; public static global::java.lang.String toHexString(double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Double.staticClass, global::java.lang.Double._toHexString12925, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _valueOf12926; public static global::java.lang.Double valueOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Double.staticClass, global::java.lang.Double._valueOf12926, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Double; } internal static global::MonoJavaBridge.MethodId _valueOf12927; public static global::java.lang.Double valueOf(double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Double.staticClass, global::java.lang.Double._valueOf12927, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Double; } internal static global::MonoJavaBridge.MethodId _compare12928; public static int compare(double arg0, double arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(java.lang.Double.staticClass, global::java.lang.Double._compare12928, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isNaN12929; public bool isNaN() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.Double._isNaN12929); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._isNaN12929); } internal static global::MonoJavaBridge.MethodId _isNaN12930; public static bool isNaN(double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(java.lang.Double.staticClass, global::java.lang.Double._isNaN12930, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isInfinite12931; public static bool isInfinite(double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(java.lang.Double.staticClass, global::java.lang.Double._isInfinite12931, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isInfinite12932; public bool isInfinite() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.Double._isInfinite12932); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._isInfinite12932); } internal static global::MonoJavaBridge.MethodId _byteValue12933; public sealed override byte byteValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallByteMethod(this.JvmHandle, global::java.lang.Double._byteValue12933); else return @__env.CallNonVirtualByteMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._byteValue12933); } internal static global::MonoJavaBridge.MethodId _shortValue12934; public sealed override short shortValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::java.lang.Double._shortValue12934); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._shortValue12934); } internal static global::MonoJavaBridge.MethodId _intValue12935; public sealed override int intValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Double._intValue12935); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._intValue12935); } internal static global::MonoJavaBridge.MethodId _longValue12936; public sealed override long longValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.lang.Double._longValue12936); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._longValue12936); } internal static global::MonoJavaBridge.MethodId _floatValue12937; public sealed override float floatValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::java.lang.Double._floatValue12937); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._floatValue12937); } internal static global::MonoJavaBridge.MethodId _doubleValue12938; public sealed override double doubleValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::java.lang.Double._doubleValue12938); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::java.lang.Double.staticClass, global::java.lang.Double._doubleValue12938); } internal static global::MonoJavaBridge.MethodId _parseDouble12939; public static double parseDouble(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticDoubleMethod(java.lang.Double.staticClass, global::java.lang.Double._parseDouble12939, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _Double12940; public Double(double arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Double.staticClass, global::java.lang.Double._Double12940, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Double12941; public Double(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Double.staticClass, global::java.lang.Double._Double12941, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.Double.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Double")); global::java.lang.Double._equals12916 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::java.lang.Double._toString12917 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "toString", "(D)Ljava/lang/String;"); global::java.lang.Double._toString12918 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "toString", "()Ljava/lang/String;"); global::java.lang.Double._hashCode12919 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "hashCode", "()I"); global::java.lang.Double._doubleToRawLongBits12920 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "doubleToRawLongBits", "(D)J"); global::java.lang.Double._doubleToLongBits12921 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "doubleToLongBits", "(D)J"); global::java.lang.Double._longBitsToDouble12922 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "longBitsToDouble", "(J)D"); global::java.lang.Double._compareTo12923 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "compareTo", "(Ljava/lang/Object;)I"); global::java.lang.Double._compareTo12924 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "compareTo", "(Ljava/lang/Double;)I"); global::java.lang.Double._toHexString12925 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "toHexString", "(D)Ljava/lang/String;"); global::java.lang.Double._valueOf12926 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "valueOf", "(Ljava/lang/String;)Ljava/lang/Double;"); global::java.lang.Double._valueOf12927 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "valueOf", "(D)Ljava/lang/Double;"); global::java.lang.Double._compare12928 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "compare", "(DD)I"); global::java.lang.Double._isNaN12929 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "isNaN", "()Z"); global::java.lang.Double._isNaN12930 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "isNaN", "(D)Z"); global::java.lang.Double._isInfinite12931 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "isInfinite", "(D)Z"); global::java.lang.Double._isInfinite12932 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "isInfinite", "()Z"); global::java.lang.Double._byteValue12933 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "byteValue", "()B"); global::java.lang.Double._shortValue12934 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "shortValue", "()S"); global::java.lang.Double._intValue12935 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "intValue", "()I"); global::java.lang.Double._longValue12936 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "longValue", "()J"); global::java.lang.Double._floatValue12937 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "floatValue", "()F"); global::java.lang.Double._doubleValue12938 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "doubleValue", "()D"); global::java.lang.Double._parseDouble12939 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Double.staticClass, "parseDouble", "(Ljava/lang/String;)D"); global::java.lang.Double._Double12940 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "<init>", "(D)V"); global::java.lang.Double._Double12941 = @__env.GetMethodIDNoThrow(global::java.lang.Double.staticClass, "<init>", "(Ljava/lang/String;)V"); } } }
/* **************************************************************************** * * 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_NATIVE using System; using System.Collections.Generic; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; #if CLR2 using Microsoft.Scripting.Math; #else using System.Numerics; using Microsoft.Scripting.Utils; #endif namespace IronPython.Modules { /// <summary> /// Provides support for interop with native code from Python code. /// </summary> public static partial class CTypes { /// <summary> /// The meta class for ctypes simple data types. These include primitives like ints, /// floats, etc... char/wchar pointers, and untyped pointers. /// </summary> [PythonType, PythonHidden] public class SimpleType : PythonType, INativeType { internal readonly SimpleTypeKind _type; private readonly char _charType; public SimpleType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict) : base(context, name, bases, dict) { object val; string sVal; const string allowedTypes = "?cbBghHiIlLdfuzZqQPXOv"; if (!TryGetBoundCustomMember(context, "_type_", out val) || (sVal = StringOps.AsString(val)) == null || sVal.Length != 1 || allowedTypes.IndexOf(sVal[0]) == -1) { throw PythonOps.AttributeError("AttributeError: class must define a '_type_' attribute which must be a single character string containing one of '{0}'.", allowedTypes); } _charType = sVal[0]; switch (sVal[0]) { case '?': _type = SimpleTypeKind.Boolean; break; case 'c': _type = SimpleTypeKind.Char; break; case 'b': _type = SimpleTypeKind.SignedByte; break; case 'B': _type = SimpleTypeKind.UnsignedByte; break; case 'h': _type = SimpleTypeKind.SignedShort; break; case 'H': _type = SimpleTypeKind.UnsignedShort; break; case 'i': _type = SimpleTypeKind.SignedInt; break; case 'I': _type = SimpleTypeKind.UnsignedInt; break; case 'l': _type = SimpleTypeKind.SignedLong; break; case 'L': _type = SimpleTypeKind.UnsignedLong; break; case 'f': _type = SimpleTypeKind.Single; break; case 'g': // long double, new in 2.6 case 'd': _type = SimpleTypeKind.Double; break; case 'q': _type = SimpleTypeKind.SignedLongLong; break; case 'Q': _type = SimpleTypeKind.UnsignedLongLong; break; case 'O': _type = SimpleTypeKind.Object; break; case 'P': _type = SimpleTypeKind.Pointer; break; case 'z': _type = SimpleTypeKind.CharPointer; break; case 'Z': _type = SimpleTypeKind.WCharPointer; break; case 'u': _type = SimpleTypeKind.WChar; break; case 'v': _type = SimpleTypeKind.VariantBool; break; case 'X': _type = SimpleTypeKind.BStr; break; default: throw new NotImplementedException("simple type " + sVal); } } private SimpleType(Type underlyingSystemType) : base(underlyingSystemType) { } public static ArrayType/*!*/ operator *(SimpleType type, int count) { return MakeArrayType(type, count); } public static ArrayType/*!*/ operator *(int count, SimpleType type) { return MakeArrayType(type, count); } internal static PythonType MakeSystemType(Type underlyingSystemType) { return PythonType.SetPythonType(underlyingSystemType, new SimpleType(underlyingSystemType)); } public SimpleCData from_address(CodeContext/*!*/ context, int address) { return from_address(context, new IntPtr(address)); } public SimpleCData from_address(CodeContext/*!*/ context, BigInteger address) { return from_address(context, new IntPtr((long)address)); } public SimpleCData from_address(CodeContext/*!*/ context, IntPtr ptr) { SimpleCData res = (SimpleCData)CreateInstance(context); res.SetAddress(ptr); return res; } public SimpleCData from_buffer(ArrayModule.array array, [DefaultParameterValue(0)]int offset) { ValidateArraySizes(array, offset, ((INativeType)this).Size); SimpleCData res = (SimpleCData)CreateInstance(Context.SharedContext); IntPtr addr = array.GetArrayAddress(); res._memHolder = new MemoryHolder(addr.Add(offset), ((INativeType)this).Size); res._memHolder.AddObject("ffffffff", array); return res; } public SimpleCData from_buffer_copy(ArrayModule.array array, [DefaultParameterValue(0)]int offset) { ValidateArraySizes(array, offset, ((INativeType)this).Size); SimpleCData res = (SimpleCData)CreateInstance(Context.SharedContext); res._memHolder = new MemoryHolder(((INativeType)this).Size); res._memHolder.CopyFrom(array.GetArrayAddress().Add(offset), new IntPtr(((INativeType)this).Size)); GC.KeepAlive(array); return res; } /// <summary> /// Converts an object into a function call parameter. /// </summary> public object from_param(object obj) { // TODO: This isn't right as we have an obj associated w/ the argument, CPython doesn't. return new NativeArgument((CData)PythonCalls.Call(this, obj), _charType.ToString()); } public SimpleCData in_dll(CodeContext/*!*/ context, object library, string name) { IntPtr handle = GetHandleFromObject(library, "in_dll expected object with _handle attribute"); IntPtr addr = NativeFunctions.LoadFunction(handle, name); if (addr == IntPtr.Zero) { throw PythonOps.ValueError("{0} not found when attempting to load {1} from dll", name, Name); } SimpleCData res = (SimpleCData)CreateInstance(context); res.SetAddress(addr); return res; } #region INativeType Members int INativeType.Size { get { switch (_type) { case SimpleTypeKind.Char: case SimpleTypeKind.SignedByte: case SimpleTypeKind.UnsignedByte: case SimpleTypeKind.Boolean: return 1; case SimpleTypeKind.SignedShort: case SimpleTypeKind.UnsignedShort: case SimpleTypeKind.WChar: case SimpleTypeKind.VariantBool: return 2; case SimpleTypeKind.SignedInt: case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: case SimpleTypeKind.SignedLong: case SimpleTypeKind.Single: return 4; case SimpleTypeKind.Double: case SimpleTypeKind.UnsignedLongLong: case SimpleTypeKind.SignedLongLong: return 8; case SimpleTypeKind.Object: case SimpleTypeKind.Pointer: case SimpleTypeKind.CharPointer: case SimpleTypeKind.WCharPointer: case SimpleTypeKind.BStr: return IntPtr.Size; } throw new InvalidOperationException(_type.ToString()); } } int INativeType.Alignment { get { return ((INativeType)this).Size; } } object INativeType.GetValue(MemoryHolder/*!*/ owner, object readingFrom, int offset, bool raw) { object res; switch (_type) { case SimpleTypeKind.Boolean: res = owner.ReadByte(offset) != 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False; break; case SimpleTypeKind.Char: res = new string((char)owner.ReadByte(offset), 1); break; case SimpleTypeKind.SignedByte: res = GetIntReturn((int)(sbyte)owner.ReadByte(offset)); break; case SimpleTypeKind.UnsignedByte: res = GetIntReturn((int)owner.ReadByte(offset)); break; case SimpleTypeKind.SignedShort: res = GetIntReturn((int)owner.ReadInt16(offset)); break; case SimpleTypeKind.WChar: res = new string((char)owner.ReadInt16(offset), 1); break; case SimpleTypeKind.UnsignedShort: res = GetIntReturn((int)(ushort)owner.ReadInt16(offset)); break; case SimpleTypeKind.VariantBool: res = owner.ReadInt16(offset) != 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False; break; case SimpleTypeKind.SignedInt: res = GetIntReturn((int)owner.ReadInt32(offset)); break; case SimpleTypeKind.UnsignedInt: res = GetIntReturn((uint)owner.ReadInt32(offset)); break; case SimpleTypeKind.UnsignedLong: res = GetIntReturn((uint)owner.ReadInt32(offset)); break; case SimpleTypeKind.SignedLong: res = GetIntReturn(owner.ReadInt32(offset)); break; case SimpleTypeKind.Single: res = GetSingleReturn(owner.ReadInt32(offset)); break; case SimpleTypeKind.Double: res = GetDoubleReturn(owner.ReadInt64(offset)); break; case SimpleTypeKind.UnsignedLongLong: res = GetIntReturn((ulong)owner.ReadInt64(offset)); break; case SimpleTypeKind.SignedLongLong: res = GetIntReturn(owner.ReadInt64(offset)); break; case SimpleTypeKind.Object: res = GetObjectReturn(owner.ReadIntPtr(offset)); break; case SimpleTypeKind.Pointer: res = owner.ReadIntPtr(offset).ToPython(); break; case SimpleTypeKind.CharPointer: res = owner.ReadMemoryHolder(offset).ReadAnsiString(0); break; case SimpleTypeKind.WCharPointer: res = owner.ReadMemoryHolder(offset).ReadUnicodeString(0); break; case SimpleTypeKind.BStr: res = Marshal.PtrToStringBSTR(owner.ReadIntPtr(offset)); break; default: throw new InvalidOperationException(); } if (!raw && IsSubClass) { res = PythonCalls.Call(this, res); } return res; } /// <summary> /// Helper function for reading char/wchar's. This is used for reading from /// arrays and pointers to avoid creating lots of 1-char strings. /// </summary> internal char ReadChar(MemoryHolder/*!*/ owner, int offset) { switch (_type) { case SimpleTypeKind.Char: return (char)owner.ReadByte(offset); case SimpleTypeKind.WChar: return (char)owner.ReadInt16(offset); default: throw new InvalidOperationException(); } } object INativeType.SetValue(MemoryHolder/*!*/ owner, int offset, object value) { SimpleCData data = value as SimpleCData; if (data != null && data.NativeType == this) { data._memHolder.CopyTo(owner, offset, ((INativeType)this).Size); return null; } switch (_type) { case SimpleTypeKind.Boolean: owner.WriteByte(offset, ModuleOps.GetBoolean(value, this)); break; case SimpleTypeKind.Char: owner.WriteByte(offset, ModuleOps.GetChar(value, this)); break; case SimpleTypeKind.SignedByte: owner.WriteByte(offset, ModuleOps.GetSignedByte(value, this)); break; case SimpleTypeKind.UnsignedByte: owner.WriteByte(offset, ModuleOps.GetUnsignedByte(value, this)); break; case SimpleTypeKind.WChar: owner.WriteInt16(offset, (short)ModuleOps.GetWChar(value, this)); break; case SimpleTypeKind.SignedShort: owner.WriteInt16(offset, ModuleOps.GetSignedShort(value, this)); break; case SimpleTypeKind.UnsignedShort: owner.WriteInt16(offset, ModuleOps.GetUnsignedShort(value, this)); break; case SimpleTypeKind.VariantBool: owner.WriteInt16(offset, (short)ModuleOps.GetVariantBool(value, this)); break; case SimpleTypeKind.SignedInt: owner.WriteInt32(offset, ModuleOps.GetSignedInt(value, this)); break; case SimpleTypeKind.UnsignedInt: owner.WriteInt32(offset, ModuleOps.GetUnsignedInt(value, this)); break; case SimpleTypeKind.UnsignedLong: owner.WriteInt32(offset, ModuleOps.GetUnsignedLong(value, this)); break; case SimpleTypeKind.SignedLong: owner.WriteInt32(offset, ModuleOps.GetSignedLong(value, this)); break; case SimpleTypeKind.Single: owner.WriteInt32(offset, ModuleOps.GetSingleBits(value)); break; case SimpleTypeKind.Double: owner.WriteInt64(offset, ModuleOps.GetDoubleBits(value)); break; case SimpleTypeKind.UnsignedLongLong: owner.WriteInt64(offset, ModuleOps.GetUnsignedLongLong(value, this)); break; case SimpleTypeKind.SignedLongLong: owner.WriteInt64(offset, ModuleOps.GetSignedLongLong(value, this)); break; case SimpleTypeKind.Object: owner.WriteIntPtr(offset, ModuleOps.GetObject(value)); break; case SimpleTypeKind.Pointer: owner.WriteIntPtr(offset, ModuleOps.GetPointer(value)); break; case SimpleTypeKind.CharPointer: owner.WriteIntPtr(offset, ModuleOps.GetCharPointer(value)); return value; case SimpleTypeKind.WCharPointer: owner.WriteIntPtr(offset, ModuleOps.GetWCharPointer(value)); return value; case SimpleTypeKind.BStr: owner.WriteIntPtr(offset, ModuleOps.GetBSTR(value)); return value; default: throw new InvalidOperationException(); } return null; } Type/*!*/ INativeType.GetNativeType() { switch (_type) { case SimpleTypeKind.Boolean: return typeof(bool); case SimpleTypeKind.Char: return typeof(byte); case SimpleTypeKind.SignedByte: return typeof(sbyte); case SimpleTypeKind.UnsignedByte: return typeof(byte); case SimpleTypeKind.SignedShort: case SimpleTypeKind.VariantBool: return typeof(short); case SimpleTypeKind.UnsignedShort: return typeof(ushort); case SimpleTypeKind.WChar: return typeof(char); case SimpleTypeKind.SignedInt: case SimpleTypeKind.SignedLong: return typeof(int); case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: return typeof(uint); case SimpleTypeKind.Single: return typeof(float); case SimpleTypeKind.Double: return typeof(double); case SimpleTypeKind.UnsignedLongLong: return typeof(ulong); case SimpleTypeKind.SignedLongLong: return typeof(long); case SimpleTypeKind.Object: return typeof(IntPtr); case SimpleTypeKind.Pointer: case SimpleTypeKind.CharPointer: case SimpleTypeKind.WCharPointer: case SimpleTypeKind.BStr: return typeof(IntPtr); } throw new InvalidOperationException(); } MarshalCleanup INativeType.EmitMarshalling(ILGenerator/*!*/ method, LocalOrArg argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { MarshalCleanup cleanup = null; Label marshalled = method.DefineLabel(); Type argumentType = argIndex.Type; if (!argumentType.IsValueType && _type != SimpleTypeKind.Object && _type != SimpleTypeKind.Pointer) { // check if we have an explicit CData instance. If we have a CData but it's the // wrong type CheckSimpleCDataType will throw. Label primitive = method.DefineLabel(); argIndex.Emit(method); constantPool.Add(this); method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CheckSimpleCDataType")); method.Emit(OpCodes.Brfalse, primitive); argIndex.Emit(method); method.Emit(OpCodes.Castclass, typeof(CData)); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Ldobj, ((INativeType)this).GetNativeType()); method.Emit(OpCodes.Br, marshalled); method.MarkLabel(primitive); } argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } switch (_type) { case SimpleTypeKind.Boolean: case SimpleTypeKind.Char: case SimpleTypeKind.SignedByte: case SimpleTypeKind.UnsignedByte: case SimpleTypeKind.SignedShort: case SimpleTypeKind.UnsignedShort: case SimpleTypeKind.WChar: case SimpleTypeKind.SignedInt: case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: case SimpleTypeKind.SignedLong: case SimpleTypeKind.Single: case SimpleTypeKind.Double: case SimpleTypeKind.UnsignedLongLong: case SimpleTypeKind.SignedLongLong: case SimpleTypeKind.VariantBool: constantPool.Add(this); method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("Get" + _type)); break; case SimpleTypeKind.Pointer: Label done = method.DefineLabel(); TryBytesConversion(method, done); Label nextTry = method.DefineLabel(); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } method.Emit(OpCodes.Isinst, typeof(string)); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); LocalBuilder lb = method.DeclareLocal(typeof(string), true); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); method.Emit(OpCodes.Conv_I); method.Emit(OpCodes.Ldc_I4, RuntimeHelpers.OffsetToStringData); method.Emit(OpCodes.Add); method.Emit(OpCodes.Br, done); method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("GetPointer")); method.MarkLabel(done); break; case SimpleTypeKind.Object: // TODO: Need cleanup here method.Emit(OpCodes.Call, typeof(CTypes).GetMethod("PyObj_ToPtr")); break; case SimpleTypeKind.CharPointer: done = method.DefineLabel(); TryToCharPtrConversion(method, argIndex, argumentType, done); cleanup = MarshalCharPointer(method, argIndex); method.MarkLabel(done); break; case SimpleTypeKind.WCharPointer: done = method.DefineLabel(); TryArrayToWCharPtrConversion(method, argIndex, argumentType, done); MarshalWCharPointer(method, argIndex); method.MarkLabel(done); break; case SimpleTypeKind.BStr: throw new NotImplementedException("BSTR marshalling"); } method.MarkLabel(marshalled); return cleanup; } private static void TryBytesConversion(ILGenerator method, Label done) { Label nextTry = method.DefineLabel(); LocalBuilder lb = method.DeclareLocal(typeof(byte).MakeByRefType(), true); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("TryCheckBytes")); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Ldelema, typeof(Byte)); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); method.Emit(OpCodes.Br, done); method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); } internal static void TryArrayToWCharPtrConversion(ILGenerator method, LocalOrArg argIndex, Type argumentType, Label done) { Label nextTry = method.DefineLabel(); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("TryCheckWCharArray")); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Br, done); method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } } internal static void TryToCharPtrConversion(ILGenerator method, LocalOrArg argIndex, Type argumentType, Label done) { TryBytesConversion(method, done); Label nextTry = method.DefineLabel(); argIndex.Emit(method); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("TryCheckCharArray")); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Br, done); method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } } internal static void MarshalWCharPointer(ILGenerator method, LocalOrArg argIndex) { Type argumentType = argIndex.Type; Label isNull; Label done; LocalBuilder lb; isNull = method.DefineLabel(); done = method.DefineLabel(); method.Emit(OpCodes.Brfalse, isNull); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } lb = method.DeclareLocal(typeof(string), true); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); method.Emit(OpCodes.Conv_I); method.Emit(OpCodes.Ldc_I4, RuntimeHelpers.OffsetToStringData); method.Emit(OpCodes.Add); method.Emit(OpCodes.Br, done); method.MarkLabel(isNull); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_I); method.MarkLabel(done); } internal static MarshalCleanup MarshalCharPointer(ILGenerator method, LocalOrArg argIndex) { Type argumentType = argIndex.Type; Label isNull, done; LocalBuilder lb; isNull = method.DefineLabel(); done = method.DefineLabel(); method.Emit(OpCodes.Brfalse, isNull); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } lb = method.DeclareLocal(typeof(IntPtr)); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("StringToHGlobalAnsi")); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); method.Emit(OpCodes.Br, done); method.MarkLabel(isNull); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_I); method.MarkLabel(done); return new StringCleanup(lb); } Type/*!*/ INativeType.GetPythonType() { if (IsSubClass) { return typeof(object); } return GetPythonTypeWorker(); } private Type GetPythonTypeWorker() { switch (_type) { case SimpleTypeKind.Boolean: return typeof(bool); case SimpleTypeKind.CharPointer: case SimpleTypeKind.WCharPointer: case SimpleTypeKind.WChar: case SimpleTypeKind.Char: case SimpleTypeKind.BStr: return typeof(string); case SimpleTypeKind.VariantBool: case SimpleTypeKind.SignedByte: case SimpleTypeKind.UnsignedByte: case SimpleTypeKind.SignedShort: case SimpleTypeKind.UnsignedShort: case SimpleTypeKind.SignedInt: case SimpleTypeKind.SignedLong: return typeof(int); case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: case SimpleTypeKind.UnsignedLongLong: case SimpleTypeKind.SignedLongLong: case SimpleTypeKind.Pointer: case SimpleTypeKind.Object: return typeof(object); case SimpleTypeKind.Single: case SimpleTypeKind.Double: return typeof(double); default: throw new InvalidOperationException(); } } void INativeType.EmitReverseMarshalling(ILGenerator method, LocalOrArg value, List<object> constantPool, int constantPoolArgument) { value.Emit(method); switch (_type) { case SimpleTypeKind.SignedByte: case SimpleTypeKind.UnsignedByte: case SimpleTypeKind.SignedShort: case SimpleTypeKind.UnsignedShort: case SimpleTypeKind.VariantBool: method.Emit(OpCodes.Conv_I4); break; case SimpleTypeKind.SignedInt: case SimpleTypeKind.SignedLong: case SimpleTypeKind.Boolean: break; case SimpleTypeKind.Single: method.Emit(OpCodes.Conv_R8); break; case SimpleTypeKind.Double: break; case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: EmitInt32ToObject(method, value); break; case SimpleTypeKind.UnsignedLongLong: case SimpleTypeKind.SignedLongLong: EmitInt64ToObject(method, value); break; case SimpleTypeKind.Object: method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("IntPtrToObject")); break; case SimpleTypeKind.WCharPointer: method.Emit(OpCodes.Call, typeof(Marshal).GetMethod("PtrToStringUni", new[] { typeof(IntPtr) })); break; case SimpleTypeKind.CharPointer: method.Emit(OpCodes.Call, typeof(Marshal).GetMethod("PtrToStringAnsi", new[] { typeof(IntPtr) })); break; case SimpleTypeKind.BStr: method.Emit(OpCodes.Call, typeof(Marshal).GetMethod("PtrToStringBSTR", new[] { typeof(IntPtr) })); break; case SimpleTypeKind.Char: method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CharToString")); break; case SimpleTypeKind.WChar: method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("WCharToString")); break; case SimpleTypeKind.Pointer: Label done, notNull; done = method.DefineLabel(); notNull = method.DefineLabel(); if (IntPtr.Size == 4) { LocalBuilder tmpLocal = method.DeclareLocal(typeof(uint)); method.Emit(OpCodes.Conv_U4); method.Emit(OpCodes.Stloc, tmpLocal); method.Emit(OpCodes.Ldloc, tmpLocal); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_U4); method.Emit(OpCodes.Bne_Un, notNull); method.Emit(OpCodes.Ldnull); method.Emit(OpCodes.Br, done); method.MarkLabel(notNull); method.Emit(OpCodes.Ldloc, tmpLocal); EmitInt32ToObject(method, new Local(tmpLocal)); } else { LocalBuilder tmpLocal = method.DeclareLocal(typeof(long)); method.Emit(OpCodes.Conv_I8); method.Emit(OpCodes.Stloc, tmpLocal); method.Emit(OpCodes.Ldloc, tmpLocal); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_U8); method.Emit(OpCodes.Bne_Un, notNull); method.Emit(OpCodes.Ldnull); method.Emit(OpCodes.Br, done); method.MarkLabel(notNull); method.Emit(OpCodes.Ldloc, tmpLocal); EmitInt64ToObject(method, new Local(tmpLocal)); } method.MarkLabel(done); break; } if (IsSubClass) { LocalBuilder tmp = method.DeclareLocal(typeof(object)); if (GetPythonTypeWorker().IsValueType) { method.Emit(OpCodes.Box, GetPythonTypeWorker()); } method.Emit(OpCodes.Stloc, tmp); constantPool.Add(this); method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Ldloc, tmp); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CreateSubclassInstance")); } } private static void EmitInt64ToObject(ILGenerator method, LocalOrArg value) { Label done; Label bigInt = method.DefineLabel(); done = method.DefineLabel(); method.Emit(OpCodes.Ldc_I4, Int32.MaxValue); method.Emit(OpCodes.Conv_I8); method.Emit(OpCodes.Bgt, bigInt); value.Emit(method); method.Emit(OpCodes.Ldc_I4, Int32.MinValue); method.Emit(OpCodes.Conv_I8); method.Emit(OpCodes.Blt, bigInt); value.Emit(method); method.Emit(OpCodes.Conv_I4); method.Emit(OpCodes.Box, typeof(int)); method.Emit(OpCodes.Br, done); method.MarkLabel(bigInt); value.Emit(method); method.Emit(OpCodes.Call, typeof(BigInteger).GetMethod("op_Implicit", new[] { value.Type })); #if !CLR2 method.Emit(OpCodes.Box, typeof(BigInteger)); #endif method.MarkLabel(done); } private static void EmitInt32ToObject(ILGenerator method, LocalOrArg value) { Label intVal, done; intVal = method.DefineLabel(); done = method.DefineLabel(); method.Emit(OpCodes.Ldc_I4, Int32.MaxValue); method.Emit(value.Type == typeof(uint) ? OpCodes.Conv_U4 : OpCodes.Conv_U8); method.Emit(OpCodes.Ble, intVal); value.Emit(method); method.Emit(OpCodes.Call, typeof(BigInteger).GetMethod("op_Implicit", new[] { value.Type })); #if !CLR2 method.Emit(OpCodes.Box, typeof(BigInteger)); #endif method.Emit(OpCodes.Br, done); method.MarkLabel(intVal); value.Emit(method); method.Emit(OpCodes.Conv_I4); method.Emit(OpCodes.Box, typeof(int)); method.MarkLabel(done); } private bool IsSubClass { get { return BaseTypes.Count != 1 || BaseTypes[0] != CTypes._SimpleCData; } } private object GetObjectReturn(IntPtr intPtr) { GCHandle handle = GCHandle.FromIntPtr(intPtr); object res = handle.Target; // TODO: handle lifetime management return res; } private object GetDoubleReturn(long p) { return BitConverter.ToDouble(BitConverter.GetBytes(p), 0); } private object GetSingleReturn(int p) { return BitConverter.ToSingle(BitConverter.GetBytes(p), 0); } private static object GetIntReturn(int value) { return ScriptingRuntimeHelpers.Int32ToObject((int)value); } private static object GetIntReturn(uint value) { if (value > Int32.MaxValue) { return (BigInteger)value; } return ScriptingRuntimeHelpers.Int32ToObject((int)value); } private static object GetIntReturn(long value) { if (value <= Int32.MaxValue && value >= Int32.MinValue) { return (int)value; } return (BigInteger)value; } private static object GetIntReturn(ulong value) { if (value <= Int32.MaxValue) { return (int)value; } return (BigInteger)value; } string INativeType.TypeFormat { get { return (BitConverter.IsLittleEndian ? '<' : '>') + _charType.ToString(); } } #endregion } } } #endif
using UnityEngine; using UnityEditor; using UnityEditorInternal; using System; using System.Linq; using System.Collections; using System.Collections.Generic; namespace Fungus { public class FlowchartWindow : EditorWindow { public static List<Block> deleteList = new List<Block>(); protected List<Block> windowBlockMap = new List<Block>(); // The ReorderableList control doesn't drag properly when used with GUI.DragWindow(), // so we just implement dragging ourselves. protected int dragWindowId = -1; protected Vector2 startDragPosition; public const float minZoomValue = 0.25f; public const float maxZoomValue = 1f; protected GUIStyle nodeStyle = new GUIStyle(); protected static BlockInspector blockInspector; protected bool mouseOverVariables = false; protected int forceRepaintCount; protected Texture2D addTexture; [MenuItem("Tools/Fungus/Flowchart Window")] static void Init() { GetWindow(typeof(FlowchartWindow), false, "Flowchart"); } protected virtual void OnEnable() { // All block nodes use the same GUIStyle, but with a different background nodeStyle.border.left = 20; nodeStyle.border.right = 20; nodeStyle.border.top = 5; nodeStyle.border.bottom = 5; nodeStyle.padding.left = 20; nodeStyle.padding.right = 20; nodeStyle.padding.top = 5; nodeStyle.padding.bottom = 5; nodeStyle.contentOffset = Vector2.zero; nodeStyle.alignment = TextAnchor.MiddleCenter; nodeStyle.wordWrap = true; addTexture = Resources.Load("Icons/add_small") as Texture2D; } protected virtual void OnInspectorUpdate() { // Ensure the Block Inspector is always showing the currently selected block Flowchart flowchart = GetFlowchart(); if (flowchart == null) { return; } if (Selection.activeGameObject == null && flowchart.selectedBlock != null) { if (blockInspector == null) { ShowBlockInspector(flowchart); } blockInspector.block = flowchart.selectedBlock; } forceRepaintCount--; forceRepaintCount = Math.Max(0, forceRepaintCount); Repaint(); } static public Flowchart GetFlowchart() { // Using a temp hidden object to track the active Flowchart across // serialization / deserialization when playing the game in the editor. FungusState fungusState = GameObject.FindObjectOfType<FungusState>(); if (fungusState == null) { GameObject go = new GameObject("_FungusState"); go.hideFlags = HideFlags.HideInHierarchy; fungusState = go.AddComponent<FungusState>(); } if (Selection.activeGameObject != null) { Flowchart fs = Selection.activeGameObject.GetComponent<Flowchart>(); if (fs != null) { fungusState.selectedFlowchart = fs; } } return fungusState.selectedFlowchart; } protected virtual void OnGUI() { Flowchart flowchart = GetFlowchart(); if (flowchart == null) { GUILayout.Label("No Flowchart scene object selected"); return; } // Delete any scheduled objects foreach (Block deleteBlock in deleteList) { bool isSelected = (flowchart.selectedBlock == deleteBlock); foreach (Command command in deleteBlock.commandList) { Undo.DestroyObjectImmediate(command); } Undo.DestroyObjectImmediate(deleteBlock); flowchart.ClearSelectedCommands(); if (isSelected) { // Revert to showing properties for the Flowchart Selection.activeGameObject = flowchart.gameObject; } } deleteList.Clear(); DrawFlowchartView(flowchart); DrawOverlay(flowchart); if (forceRepaintCount > 0) { // Redraw on next frame to get crisp refresh rate Repaint(); } } protected virtual void DrawOverlay(Flowchart flowchart) { GUILayout.Space(8); GUILayout.BeginHorizontal(); GUILayout.Space(8); if (GUILayout.Button(new GUIContent(addTexture, "Add a new block"))) { Vector2 newNodePosition = new Vector2(50 - flowchart.scrollPos.x, 50 - flowchart.scrollPos.y); CreateBlock(flowchart, newNodePosition); } GUILayout.Space(8); flowchart.zoom = GUILayout.HorizontalSlider(flowchart.zoom, minZoomValue, maxZoomValue, GUILayout.Width(100)); GUILayout.FlexibleSpace(); GUILayout.BeginVertical(); GUILayout.Label(flowchart.name, EditorStyles.whiteBoldLabel); if (flowchart.description.Length > 0) { GUILayout.Label(flowchart.description, EditorStyles.helpBox); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.BeginVertical(GUILayout.Width(440)); GUILayout.FlexibleSpace(); flowchart.variablesScrollPos = GUILayout.BeginScrollView(flowchart.variablesScrollPos, GUILayout.MaxHeight(position.height * 0.75f)); GUILayout.FlexibleSpace(); GUILayout.Space(8); FlowchartEditor flowchartEditor = Editor.CreateEditor (flowchart) as FlowchartEditor; flowchartEditor.DrawVariablesGUI(); DestroyImmediate(flowchartEditor); Rect variableWindowRect = GUILayoutUtility.GetLastRect(); if (flowchart.variablesExpanded && flowchart.variables.Count > 0) { variableWindowRect.y -= 20; variableWindowRect.height += 20; } if (Event.current.type == EventType.Repaint) { mouseOverVariables = variableWindowRect.Contains(Event.current.mousePosition); } GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } protected virtual void DrawFlowchartView(Flowchart flowchart) { Block[] blocks = flowchart.GetComponentsInChildren<Block>(true); foreach (Block block in blocks) { flowchart.scrollViewRect.xMin = Mathf.Min(flowchart.scrollViewRect.xMin, block.nodeRect.xMin - 400); flowchart.scrollViewRect.xMax = Mathf.Max(flowchart.scrollViewRect.xMax, block.nodeRect.xMax + 400); flowchart.scrollViewRect.yMin = Mathf.Min(flowchart.scrollViewRect.yMin, block.nodeRect.yMin - 400); flowchart.scrollViewRect.yMax = Mathf.Max(flowchart.scrollViewRect.yMax, block.nodeRect.yMax + 400); } // Calc rect for script view Rect scriptViewRect = new Rect(0, 0, this.position.width / flowchart.zoom, this.position.height / flowchart.zoom); EditorZoomArea.Begin(flowchart.zoom, scriptViewRect); DrawGrid(flowchart); GLDraw.BeginGroup(scriptViewRect); if (Event.current.button == 0 && Event.current.type == EventType.MouseDown && !mouseOverVariables) { flowchart.selectedBlock = null; if (!EditorGUI.actionKey) { flowchart.ClearSelectedCommands(); } Selection.activeGameObject = flowchart.gameObject; } // The center of the Flowchart depends on the block positions and window dimensions, so we calculate it // here in the FlowchartWindow class and store it on the Flowchart object for use later. CalcFlowchartCenter(flowchart, blocks); // Draw connections foreach (Block block in blocks) { DrawConnections(flowchart, block, false); } foreach (Block block in blocks) { DrawConnections(flowchart, block, true); } GUIStyle windowStyle = new GUIStyle(); windowStyle.stretchHeight = true; BeginWindows(); windowBlockMap.Clear(); for (int i = 0; i < blocks.Length; ++i) { Block block = blocks[i]; float nodeWidthA = nodeStyle.CalcSize(new GUIContent(block.blockName)).x + 10; float nodeWidthB = 0f; if (block.eventHandler != null) { nodeWidthB = nodeStyle.CalcSize(new GUIContent(block.eventHandler.GetSummary())).x + 10; } block.nodeRect.width = Mathf.Max(Mathf.Max(nodeWidthA, nodeWidthB), 120); block.nodeRect.height = 40; if (Event.current.button == 0) { if (Event.current.type == EventType.MouseDrag && dragWindowId == i) { block.nodeRect.x += Event.current.delta.x; block.nodeRect.y += Event.current.delta.y; forceRepaintCount = 6; } else if (Event.current.type == EventType.MouseUp && dragWindowId == i) { Vector2 newPos = new Vector2(block.nodeRect.x, block.nodeRect.y); block.nodeRect.x = startDragPosition.x; block.nodeRect.y = startDragPosition.y; Undo.RecordObject(block, "Node Position"); block.nodeRect.x = newPos.x; block.nodeRect.y = newPos.y; dragWindowId = -1; forceRepaintCount = 6; } } Rect windowRect = new Rect(block.nodeRect); windowRect.x += flowchart.scrollPos.x; windowRect.y += flowchart.scrollPos.y; GUILayout.Window(i, windowRect, DrawWindow, "", windowStyle); GUI.backgroundColor = Color.white; windowBlockMap.Add(block); } EndWindows(); // Draw Event Handler labels foreach (Block block in blocks) { if (block.eventHandler != null) { string handlerLabel = ""; EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(block.eventHandler.GetType()); if (info != null) { handlerLabel = "<" + info.EventHandlerName + "> "; } GUIStyle handlerStyle = new GUIStyle(EditorStyles.whiteLabel); handlerStyle.wordWrap = true; handlerStyle.margin.top = 0; handlerStyle.margin.bottom = 0; handlerStyle.alignment = TextAnchor.MiddleCenter; Rect rect = new Rect(block.nodeRect); rect.height = handlerStyle.CalcHeight(new GUIContent(handlerLabel), block.nodeRect.width); rect.x += flowchart.scrollPos.x; rect.y += flowchart.scrollPos.y - rect.height; GUI.Label(rect, handlerLabel, handlerStyle); } } // Draw play icons beside all executing blocks if (Application.isPlaying) { foreach (Block b in blocks) { if (b.IsExecuting()) { b.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime; b.activeCommand.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime; forceRepaintCount = 6; } if (b.executingIconTimer > Time.realtimeSinceStartup) { Rect rect = new Rect(b.nodeRect); rect.x += flowchart.scrollPos.x - 37; rect.y += flowchart.scrollPos.y + 3; rect.width = 34; rect.height = 34; if (!b.IsExecuting()) { float alpha = (b.executingIconTimer - Time.realtimeSinceStartup) / Block.executingIconFadeTime; alpha = Mathf.Clamp01(alpha); GUI.color = new Color(1f, 1f, 1f, alpha); } if (GUI.Button(rect, FungusEditorResources.texPlayBig as Texture, new GUIStyle())) { SelectBlock(flowchart, b); } GUI.color = Color.white; } } } PanAndZoom(flowchart); GLDraw.EndGroup(); EditorZoomArea.End(); } public virtual void CalcFlowchartCenter(Flowchart flowchart, Block[] blocks) { if (flowchart == null || blocks.Count() == 0) { return; } Vector2 min = blocks[0].nodeRect.min; Vector2 max = blocks[0].nodeRect.max; foreach (Block block in blocks) { min.x = Mathf.Min(min.x, block.nodeRect.center.x); min.y = Mathf.Min(min.y, block.nodeRect.center.y); max.x = Mathf.Max(max.x, block.nodeRect.center.x); max.y = Mathf.Max(max.y, block.nodeRect.center.y); } Vector2 center = (min + max) * -0.5f; center.x += position.width * 0.5f; center.y += position.height * 0.5f; flowchart.centerPosition = center; } protected virtual void PanAndZoom(Flowchart flowchart) { // Right click to drag view bool drag = false; // Pan tool if (UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Pan && Event.current.button == 0 && Event.current.type == EventType.MouseDrag) { drag = true; } // Right or middle button drag if (Event.current.button > 0 && Event.current.type == EventType.MouseDrag) { drag = true; } // Alt + left mouse drag if (Event.current.alt && Event.current.button == 0 && Event.current.type == EventType.MouseDrag) { drag = true; } if (drag) { flowchart.scrollPos += Event.current.delta; forceRepaintCount = 6; } bool zoom = false; // Scroll wheel if (Event.current.type == EventType.ScrollWheel) { zoom = true; } // Zoom tool if (UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Zoom && Event.current.button == 0 && Event.current.type == EventType.MouseDrag) { zoom = true; } if (zoom) { flowchart.zoom -= Event.current.delta.y * 0.01f; flowchart.zoom = Mathf.Clamp(flowchart.zoom, minZoomValue, maxZoomValue); forceRepaintCount = 6; } } protected virtual void DrawGrid(Flowchart flowchart) { float width = this.position.width / flowchart.zoom; float height = this.position.height / flowchart.zoom; // Match background color of scene view if (EditorGUIUtility.isProSkin) { GUI.color = new Color32(71, 71, 71, 255); } else { GUI.color = new Color32(86, 86, 86, 255); } GUI.DrawTexture( new Rect(0,0, width, height), EditorGUIUtility.whiteTexture ); GUI.color = Color.white; Color color = new Color32(96, 96, 96, 255); float gridSize = 128f; float x = flowchart.scrollPos.x % gridSize; while (x < width) { GLDraw.DrawLine(new Vector2(x, 0), new Vector2(x, height), color, 1f); x += gridSize; } float y = (flowchart.scrollPos.y % gridSize); while (y < height) { if (y >= 0) { GLDraw.DrawLine(new Vector2(0, y), new Vector2(width, y), color, 1f); } y += gridSize; } } protected virtual void SelectBlock(Flowchart flowchart, Block block) { // Select the block and also select currently executing command ShowBlockInspector(flowchart); flowchart.selectedBlock = block; flowchart.ClearSelectedCommands(); if (block.activeCommand != null) { flowchart.AddSelectedCommand(block.activeCommand); } } public static Block CreateBlock(Flowchart flowchart, Vector2 position) { Block newBlock = flowchart.CreateBlock(position); Undo.RegisterCreatedObjectUndo(newBlock, "New Block"); ShowBlockInspector(flowchart); flowchart.selectedBlock = newBlock; flowchart.ClearSelectedCommands(); return newBlock; } protected virtual void DeleteBlock(Flowchart flowchart, Block block) { foreach (Command command in block.commandList) { Undo.DestroyObjectImmediate(command); } Undo.DestroyObjectImmediate(block); flowchart.ClearSelectedCommands(); } protected virtual void DrawWindow(int windowId) { Block block = windowBlockMap[windowId]; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null) { return; } // Select block when node is clicked if (Event.current.button == 0 && Event.current.type == EventType.MouseDown && !mouseOverVariables) { // Check if might be start of a window drag if (Event.current.button == 0 && Event.current.alt == false) { dragWindowId = windowId; startDragPosition.x = block.nodeRect.x; startDragPosition.y = block.nodeRect.y; } if (windowId < windowBlockMap.Count) { Undo.RecordObject(flowchart, "Select"); SelectBlock(flowchart, block); GUIUtility.keyboardControl = 0; // Fix for textarea not refeshing (change focus) } } bool selected = (flowchart.selectedBlock == block); GUIStyle nodeStyleCopy = new GUIStyle(nodeStyle); if (block.eventHandler != null) { nodeStyleCopy.normal.background = selected ? FungusEditorResources.texEventNodeOn : FungusEditorResources.texEventNodeOff; } else { // Count the number of unique connections (excluding self references) List<Block> uniqueList = new List<Block>(); List<Block> connectedBlocks = block.GetConnectedBlocks(); foreach (Block connectedBlock in connectedBlocks) { if (connectedBlock == block || uniqueList.Contains(connectedBlock)) { continue; } uniqueList.Add(connectedBlock); } if (uniqueList.Count > 1) { nodeStyleCopy.normal.background = selected ? FungusEditorResources.texChoiceNodeOn : FungusEditorResources.texChoiceNodeOff; } else { nodeStyleCopy.normal.background = selected ? FungusEditorResources.texProcessNodeOn : FungusEditorResources.texProcessNodeOff; } } nodeStyleCopy.normal.textColor = Color.black; // Make sure node is wide enough to fit the node name text float width = nodeStyleCopy.CalcSize(new GUIContent(block.blockName)).x; block.nodeRect.width = Mathf.Max (block.nodeRect.width, width); GUI.backgroundColor = Color.white; GUILayout.Box(block.blockName, nodeStyleCopy, GUILayout.Width(block.nodeRect.width), GUILayout.Height(block.nodeRect.height)); if (block.description.Length > 0) { GUIStyle descriptionStyle = new GUIStyle(EditorStyles.helpBox); descriptionStyle.wordWrap = true; GUILayout.Label(block.description, descriptionStyle); } if (Event.current.type == EventType.ContextClick) { GenericMenu menu = new GenericMenu (); menu.AddItem(new GUIContent ("Duplicate"), false, DuplicateBlock, block); menu.AddItem(new GUIContent ("Delete"), false, DeleteBlock, block); menu.ShowAsContext(); } } protected virtual void DrawConnections(Flowchart flowchart, Block block, bool highlightedOnly) { if (block == null) { return; } List<Block> connectedBlocks = new List<Block>(); bool blockIsSelected = (flowchart.selectedBlock == block); foreach (Command command in block.commandList) { if (command == null) { continue; } bool commandIsSelected = false; foreach (Command selectedCommand in flowchart.selectedCommands) { if (selectedCommand == command) { commandIsSelected = true; break; } } bool highlight = command.isExecuting || (blockIsSelected && commandIsSelected); if (highlightedOnly && !highlight || !highlightedOnly && highlight) { continue; } connectedBlocks.Clear(); command.GetConnectedBlocks(ref connectedBlocks); foreach (Block blockB in connectedBlocks) { if (blockB == null || block == blockB || blockB.GetFlowchart() != flowchart) { continue; } Rect startRect = new Rect(block.nodeRect); startRect.x += flowchart.scrollPos.x; startRect.y += flowchart.scrollPos.y; Rect endRect = new Rect(blockB.nodeRect); endRect.x += flowchart.scrollPos.x; endRect.y += flowchart.scrollPos.y; DrawRectConnection(startRect, endRect, highlight); } } } protected virtual void DrawRectConnection(Rect rectA, Rect rectB, bool highlight) { Vector2[] pointsA = new Vector2[] { new Vector2(rectA.xMin + 5, rectA.center.y), new Vector2(rectA.xMin + rectA.width / 2, rectA.yMin + 2), new Vector2(rectA.xMin + rectA.width / 2, rectA.yMax - 2), new Vector2(rectA.xMax - 5, rectA.center.y) }; Vector2[] pointsB = new Vector2[] { new Vector2(rectB.xMin + 5, rectB.center.y), new Vector2(rectB.xMin + rectB.width / 2, rectB.yMin + 2), new Vector2(rectB.xMin + rectB.width / 2, rectB.yMax - 2), new Vector2(rectB.xMax - 5, rectB.center.y) }; Vector2 pointA = Vector2.zero; Vector2 pointB = Vector2.zero; float minDist = float.MaxValue; foreach (Vector2 a in pointsA) { foreach (Vector2 b in pointsB) { float d = Vector2.Distance(a, b); if (d < minDist) { pointA = a; pointB = b; minDist = d; } } } Color color = Color.grey; if (highlight) { color = Color.green; } GLDraw.DrawConnectingCurve(pointA, pointB, color, 1.025f); Rect dotARect = new Rect(pointA.x - 5, pointA.y - 5, 10, 10); GUI.Label(dotARect, "", new GUIStyle("U2D.dragDotActive")); Rect dotBRect = new Rect(pointB.x - 5, pointB.y - 5, 10, 10); GUI.Label(dotBRect, "", new GUIStyle("U2D.dragDotActive")); } public static void DeleteBlock(object obj) { Block block = obj as Block; FlowchartWindow.deleteList.Add(block); } protected static void DuplicateBlock(object obj) { Flowchart flowchart = GetFlowchart(); Block block = obj as Block; Vector2 newPosition = new Vector2(block.nodeRect.position.x + block.nodeRect.width + 20, block.nodeRect.y); Block oldBlock = block; Block newBlock = FlowchartWindow.CreateBlock(flowchart, newPosition); newBlock.blockName = flowchart.GetUniqueBlockKey(oldBlock.blockName + " (Copy)"); Undo.RecordObject(newBlock, "Duplicate Block"); foreach (Command command in oldBlock.commandList) { if (ComponentUtility.CopyComponent(command)) { if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject)) { Command[] commands = flowchart.GetComponents<Command>(); Command pastedCommand = commands.Last<Command>(); if (pastedCommand != null) { pastedCommand.itemId = flowchart.NextItemId(); newBlock.commandList.Add (pastedCommand); } } // This stops the user pasting the command manually into another game object. ComponentUtility.CopyComponent(flowchart.transform); } } if (oldBlock.eventHandler != null) { if (ComponentUtility.CopyComponent(oldBlock.eventHandler)) { if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject)) { EventHandler[] eventHandlers = flowchart.GetComponents<EventHandler>(); EventHandler pastedEventHandler = eventHandlers.Last<EventHandler>(); if (pastedEventHandler != null) { pastedEventHandler.parentBlock = newBlock; newBlock.eventHandler = pastedEventHandler; } } } } } protected static void ShowBlockInspector(Flowchart flowchart) { if (blockInspector == null) { // Create a Scriptable Object with a custom editor which we can use to inspect the selected block. // Editors for Scriptable Objects display using the full height of the inspector window. blockInspector = ScriptableObject.CreateInstance<BlockInspector>() as BlockInspector; blockInspector.hideFlags = HideFlags.DontSave; } Selection.activeObject = blockInspector; EditorUtility.SetDirty(blockInspector); } /** * Displays a temporary text alert in the center of the Flowchart window. */ public static void ShowNotification(string notificationText) { EditorWindow window = EditorWindow.GetWindow(typeof(FlowchartWindow), false, "Flowchart"); if (window != null) { window.ShowNotification(new GUIContent(notificationText)); } } } }
/* Copyright (C) 2009 Volker Berlin (vberlin@inetsoftware.de) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters jeroen@frijters.net */ using System; using System.Collections.Generic; using System.Text; namespace ikvm.debugger.requests { /// <summary> /// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_EventRequest /// </summary> class EventRequest { internal const int CmdSet = 1; internal const int CmdClear = 2; internal const int CmdClearAllBreakpoints = 3; private static int eventRequestCounter; private readonly byte eventKind; private readonly byte suspendPolicy; private readonly List<EventModifier> modifiers; private readonly int requestId; private EventRequest(byte eventKind, byte suspendPolicy, List<EventModifier> modifiers) { this.eventKind = eventKind; this.suspendPolicy = suspendPolicy; this.modifiers = modifiers; this.requestId = ++eventRequestCounter; } /// <summary> /// Create a new EventRequest with the data in the Packet /// </summary> /// <param name="packet">a data packet send from the Java debugger</param> /// <returns>a new packet or null if there are some unknown types.</returns> internal static EventRequest create(Packet packet) { byte eventKind = packet.ReadByte(); // class EventKind switch (eventKind) { case ikvm.debugger.EventKind.SINGLE_STEP: case ikvm.debugger.EventKind.BREAKPOINT: case ikvm.debugger.EventKind.FRAME_POP: case ikvm.debugger.EventKind.EXCEPTION: case ikvm.debugger.EventKind.USER_DEFINED: case ikvm.debugger.EventKind.THREAD_START: case ikvm.debugger.EventKind.THREAD_DEATH: case ikvm.debugger.EventKind.CLASS_PREPARE: case ikvm.debugger.EventKind.CLASS_UNLOAD: case ikvm.debugger.EventKind.CLASS_LOAD: case ikvm.debugger.EventKind.FIELD_ACCESS: case ikvm.debugger.EventKind.FIELD_MODIFICATION: case ikvm.debugger.EventKind.EXCEPTION_CATCH: case ikvm.debugger.EventKind.METHOD_ENTRY: case ikvm.debugger.EventKind.METHOD_EXIT: case ikvm.debugger.EventKind.METHOD_EXIT_WITH_RETURN_VALUE: case ikvm.debugger.EventKind.MONITOR_CONTENDED_ENTER: case ikvm.debugger.EventKind.MONITOR_CONTENDED_ENTERED: case ikvm.debugger.EventKind.MONITOR_WAIT: case ikvm.debugger.EventKind.MONITOR_WAITED: case ikvm.debugger.EventKind.VM_START: case ikvm.debugger.EventKind.VM_DEATH: case ikvm.debugger.EventKind.VM_DISCONNECTED: break; default: return null; //Invalid or not supported EventKind } byte suspendPolicy = packet.ReadByte(); int count = packet.ReadInt(); Console.Error.WriteLine("Set:" + eventKind + "-" + suspendPolicy + "-" + count); List<EventModifier> modifiers = new List<EventModifier>(); for (int i = 0; i < count; i++) { byte modKind = packet.ReadByte(); // class EventModifierKind Console.Error.WriteLine("EventModifierKind:" + modKind); EventModifier modifier; switch (modKind) { case EventModifierKind.Count: modifier = new CountEventModifier(packet); break; case EventModifierKind.Conditional: modifier = new ConditionalEventModifier(packet); break; case EventModifierKind.ThreadOnly: modifier = new ThreadOnlyEventModifier(packet); break; case EventModifierKind.ClassOnly: modifier = new ThreadOnlyEventModifier(packet); break; case EventModifierKind.ClassMatch: modifier = new ClassMatchEventModifier(packet); break; case EventModifierKind.ClassExclude: modifier = new ClassExcludeEventModifier(packet); break; case EventModifierKind.LocationOnly: modifier = new LocationOnlyEventModifier(packet); break; case EventModifierKind.ExceptionOnly: modifier = new ExceptionOnlyEventModifier(packet); break; case EventModifierKind.FieldOnly: modifier = new FieldOnlyEventModifier(packet); break; case EventModifierKind.Step: modifier = new StepEventModifier(packet); break; case EventModifierKind.InstanceOnly: modifier = new InstanceOnlyEventModifier(packet); break; case EventModifierKind.SourceNameMatch: modifier = new SourceNameMatchEventModifier(packet); break; default: return null; //Invalid or not supported EventModifierKind } modifiers.Add(modifier); } return new EventRequest(eventKind, suspendPolicy, modifiers); } internal int RequestId { get { return requestId; } } internal int EventKind { get { return eventKind; } } public override String ToString() { //for debugging String str = "EventRequest:" + eventKind + "," + suspendPolicy + "["; for (int i = 0; i < modifiers.Count; i++) { str += modifiers[i] + ","; } str += "]"; return str; } } abstract class EventModifier { } /// <summary> /// Limit the requested event to be reported at most once after a given number of occurrences. /// The event is not reported the first count - 1 times this filter is reached. /// To request a one-off event, call this method with a count of 1. /// /// Once the count reaches 0, any subsequent filters in this request are applied. /// If none of those filters cause the event to be suppressed, the event is reported. /// Otherwise, the event is not reported. In either case subsequent events are never reported /// for this request. This modifier can be used with any event kind. /// </summary> class CountEventModifier : EventModifier { /// <summary> /// Count before event. One for one-off. /// </summary> private readonly int count; internal CountEventModifier(Packet packet) { count = packet.ReadInt(); } public override String ToString() { // for debugging return "Count:" + count; } } /// <summary> /// Conditional on expression /// </summary> class ConditionalEventModifier : EventModifier { /// <summary> /// For the future /// </summary> private readonly int exprID; internal ConditionalEventModifier(Packet packet) { exprID = packet.ReadObjectID(); } public override String ToString() { // for debugging return "Conditional:" + exprID; } } /// <summary> /// Restricts reported events to those in the given thread. /// This modifier can be used with any event kind except for class unload. /// </summary> class ThreadOnlyEventModifier : EventModifier { /// <summary> /// Required thread /// </summary> private readonly int threadID; internal ThreadOnlyEventModifier(Packet packet) { threadID = packet.ReadObjectID(); } public override String ToString() { // for debugging return "ThreadOnly:" + threadID; } } /// <summary> /// For class prepare events, restricts the events generated by this request to be the preparation /// of the given reference type and any subtypes. For monitor wait and waited events, /// restricts the events generated by this request to those whose monitor object /// is of the given reference type or any of its subtypes. For other events, /// restricts the events generated by this request to those whose location is /// in the given reference type or any of its subtypes. An event will be generated /// for any location in a reference type that can be safely cast to the given reference type. /// This modifier can be used with any event kind except class unload, thread start, and thread end. /// </summary> class ClassOnlyEventModifier : EventModifier { /// <summary> /// Required class /// </summary> private readonly int classID; internal ClassOnlyEventModifier(Packet packet) { classID = packet.ReadObjectID(); } public override String ToString() { // for debugging return "ClassOnly:" + classID; } } /// <summary> /// Restricts reported events to those for classes whose name matches the given restricted /// regular expression. For class prepare events, the prepared class name is matched. /// For class unload events, the unloaded class name is matched. For monitor wait and waited events, /// the name of the class of the monitor object is matched. For other events, /// the class name of the event's location is matched. /// This modifier can be used with any event kind except thread start and thread end. /// </summary> class ClassMatchEventModifier : EventModifier { /// <summary> /// Required class pattern. Matches are limited to exact matches of the given class pattern /// and matches of patterns that begin or end with '*'; for example, "*.Foo" or "java.*". /// </summary> private readonly String classPattern; internal ClassMatchEventModifier(Packet packet) { classPattern = packet.ReadString(); } public override String ToString() { // for debugging return "ClassMatch:" + classPattern; } } /// <summary> /// Restricts reported events to those for classes whose name does not match the given /// restricted regular expression. For class prepare events, the prepared class name is matched. /// For class unload events, the unloaded class name is matched. For monitor wait and waited events, /// the name of the class of the monitor object is matched. For other events, /// the class name of the event's location is matched. /// This modifier can be used with any event kind except thread start and thread end. /// </summary> class ClassExcludeEventModifier : EventModifier { /// <summary> /// Disallowed class pattern. Matches are limited to exact matches of the given class pattern /// and matches of patterns that begin or end with '*'; for example, "*.Foo" or "java.*". /// </summary> private readonly String classPattern; internal ClassExcludeEventModifier(Packet packet) { classPattern = packet.ReadString(); } public override String ToString() { // for debugging return "ClassExclude:" + classPattern; } } /// <summary> /// Restricts reported events to those that occur at the given location. This modifier can be used /// with breakpoint, field access, field modification, step, and exception event kinds. /// </summary> class LocationOnlyEventModifier : EventModifier { /// <summary> /// Required location /// </summary> private readonly Location location; internal LocationOnlyEventModifier(Packet packet) { location = packet.ReadLocation(); } public override String ToString() { // for debugging return "LocationOnly:" + location; } } /// <summary> /// Restricts reported exceptions by their class and whether they are caught or uncaught. /// This modifier can be used with exception event kinds only. /// </summary> class ExceptionOnlyEventModifier : EventModifier { /// <summary> /// Exception to report. Null (0) means report exceptions of all types. A non-null type /// restricts the reported exception events to exceptions of the given type or any of its subtypes. /// </summary> private readonly int refTypeID; /// <summary> /// Report caught exceptions /// </summary> private readonly bool caught; /// <summary> /// Report uncaught exceptions. Note that it is not always possible to determine /// whether an exception is caught or uncaught at the time it is thrown. /// See the exception event catch location under composite events for more information. /// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_Event_Composite /// </summary> private readonly bool uncaught; internal ExceptionOnlyEventModifier(Packet packet) { refTypeID = packet.ReadObjectID(); caught = packet.ReadBool(); uncaught = packet.ReadBool(); } public override String ToString() { // for debugging return "ExceptionOnly:" + refTypeID + "," + caught + "," + uncaught; } } /// <summary> /// Restricts reported events to those that occur for a given field. /// This modifier can be used with field access and field modification event kinds only. /// </summary> class FieldOnlyEventModifier : EventModifier { /// <summary> /// Type in which field is declared. /// </summary> private readonly int refTypeID; /// <summary> /// Required field /// </summary> private readonly int fieldID; internal FieldOnlyEventModifier(Packet packet) { refTypeID = packet.ReadObjectID(); fieldID = packet.ReadObjectID(); } public override String ToString() { // for debugging return "FieldOnly:" + refTypeID + "," + fieldID; } } /// <summary> /// Restricts reported step events to those which satisfy depth and size constraints. /// This modifier can be used with step event kinds only. /// </summary> class StepEventModifier : EventModifier { /// <summary> /// Thread in which to step /// </summary> private readonly int threadID; /// <summary> /// size of each step. See class StepSize /// </summary> /// <see cref="StepSize"/> private readonly int size; /// <summary> /// relative call stack limit. See class StepDepth /// </summary> /// <see cref="StepDepth"/> private readonly int depth; internal StepEventModifier(Packet packet) { threadID = packet.ReadObjectID(); size = packet.ReadInt(); depth = packet.ReadInt(); } public override String ToString() { // for debugging return "Step:" + threadID + "," + size + "," + depth; } } /// <summary> /// Restricts reported events to those whose active 'this' object is the given object. /// Match value is the null object for static methods. /// This modifier can be used with any event kind except class prepare, /// class unload, thread start, and thread end. Introduced in JDWP version 1.4. /// </summary> class InstanceOnlyEventModifier : EventModifier { /// <summary> /// Required 'this' object /// </summary> private readonly int instanceID; internal InstanceOnlyEventModifier(Packet packet) { instanceID = packet.ReadObjectID(); } public override String ToString() { // for debugging return "InstanceOnly:" + instanceID; } } /// <summary> /// Restricts reported class prepare events to those for reference types /// which have a source name which matches the given restricted regular expression. /// The source names are determined by the reference type's SourceDebugExtension. /// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_ReferenceType_SourceDebugExtension /// This modifier can only be used with class prepare events. /// Since JDWP version 1.6. Requires the canUseSourceNameFilters capability - see CapabilitiesNew. /// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_VirtualMachine_CapabilitiesNew /// </summary> class SourceNameMatchEventModifier : EventModifier { /// <summary> /// Required source name pattern. Matches are limited to exact matches of the given pattern and matches of patterns /// that begin or end with '*'; for example, "*.Foo" or "java.*". /// </summary> private readonly String sourceNamePattern; internal SourceNameMatchEventModifier(Packet packet) { sourceNamePattern = packet.ReadString(); } public override String ToString() { // for debugging return "SourceNameMatch:" + sourceNamePattern; } } }
//Copyright (C) 2004 by Autodesk, Inc. // //Permission to use, copy, modify, and distribute this software in //object code form for any purpose and without fee is hereby granted, //provided that the above copyright notice appears in all copies and //that both that copyright notice and the limited warranty and //restricted rights notice below appear in all supporting //documentation. // //AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. //AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF //MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. //DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE //UNINTERRUPTED OR ERROR FREE. // //Use, duplication, or disclosure by the U.S. Government is subject to //restrictions set forth in FAR 52.227-19 (Commercial Computer //Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) //(Rights in Technical Data and Computer Software), as applicable using System; using System.Collections; using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; namespace EventsWatcher { /// <summary> /// DocumentEvents. /// </summary> public class DocumentEvents { public DocumentEvents() { m_bDone = false; m_docsTable = new Hashtable(); collectAllDocs(); Do(); } public void collectAllDocs() { try{ DocumentCollection m_docCol = Application.DocumentManager; IEnumerator docEnum = m_docCol.GetEnumerator(); while( docEnum.MoveNext() ) { Document doc = (Document)docEnum.Current; addDoc(ref doc); } } catch (System.Exception ex) { Helper.Message(ex); } } public void addDoc(ref Document doc) { if(!m_docsTable.ContainsKey(doc)) m_docsTable.Add( doc, new CBoolClass(false) ); } public void removeDoc(ref Document doc) { if(m_docsTable.ContainsKey(doc)) { UndoADoc(ref doc); m_docsTable.Remove(doc); } } private Document m_doc; // Used as a temporary var only. private Hashtable m_docsTable; // Document(key)/bool(value) pair private bool m_bDone; // A flag to indicate if events have been planted. // A counterpart flag to the On option in the UI. public void Do() { if(m_bDone == false) m_bDone = true; else // Don't return because we may need to address some new docs. {} try { foreach(DictionaryEntry entry in m_docsTable) { CBoolClass boolClassVar = (CBoolClass)entry.Value; // Continue if events have alrealy planted for the specific doc if(boolClassVar.ToString().ToLower() == "true") continue; m_doc = (Document)entry.Key; m_doc.BeginDocumentClose += new DocumentBeginCloseEventHandler(callback_BeginDocumentClose); m_doc.CloseAborted += new EventHandler(callback_CloseAborted); m_doc.CloseWillStart += new EventHandler(callback_CloseWillStart); m_doc.CommandCancelled += new CommandEventHandler(callback_CommandCancelled); m_doc.CommandEnded += new CommandEventHandler(callback_CommandEnded); m_doc.CommandFailed += new CommandEventHandler(callback_CommandFailed); m_doc.CommandWillStart += new CommandEventHandler(callback_CommandWillStart); m_doc.LispCancelled += new EventHandler(callback_LispCancelled); m_doc.LispEnded += new EventHandler(callback_LispEnded); m_doc.LispWillStart += new LispWillStartEventHandler(callback_LispWillStart); m_doc.UnknownCommand += new UnknownCommandEventHandler(callback_UnknownCommand); boolClassVar.val = true; } } catch (System.Exception ex) { Helper.Message(ex); } } public void Undo() { if(m_bDone == false) return; else m_bDone = false; try { IDictionaryEnumerator docsEnumerator = m_docsTable.GetEnumerator(); while(docsEnumerator.MoveNext()) { DictionaryEntry entry = (DictionaryEntry)docsEnumerator.Current; CBoolClass boolClassVar = (CBoolClass)entry.Value; // Continue if events have alrealy been removed from the specific doc if(boolClassVar.ToString().ToLower() == "false") continue; m_doc = (Document)entry.Key; m_doc.BeginDocumentClose -= new DocumentBeginCloseEventHandler(callback_BeginDocumentClose); m_doc.CloseAborted -= new EventHandler(callback_CloseAborted); m_doc.CloseWillStart -= new EventHandler(callback_CloseWillStart); m_doc.CommandCancelled -= new CommandEventHandler(callback_CommandCancelled); m_doc.CommandEnded -= new CommandEventHandler(callback_CommandEnded); m_doc.CommandFailed -= new CommandEventHandler(callback_CommandFailed); m_doc.CommandWillStart -= new CommandEventHandler(callback_CommandWillStart); m_doc.LispCancelled -= new EventHandler(callback_LispCancelled); m_doc.LispEnded -= new EventHandler(callback_LispEnded); m_doc.LispWillStart -= new LispWillStartEventHandler(callback_LispWillStart); m_doc.UnknownCommand -= new UnknownCommandEventHandler(callback_UnknownCommand); boolClassVar.val = false; } } catch (System.Exception ex) { Helper.Message(ex); } } public void UndoADoc(ref Document doc) { try { if( !m_docsTable.Contains(doc) ) return; CBoolClass boolClassVar = (CBoolClass)m_docsTable[doc]; // Return if events have not been planted for it. if(boolClassVar.ToString().ToLower() == "false") return; m_doc = doc; m_doc.BeginDocumentClose -= new DocumentBeginCloseEventHandler(callback_BeginDocumentClose); m_doc.CloseAborted -= new EventHandler(callback_CloseAborted); m_doc.CloseWillStart -= new EventHandler(callback_CloseWillStart); m_doc.CommandCancelled -= new CommandEventHandler(callback_CommandCancelled); m_doc.CommandEnded -= new CommandEventHandler(callback_CommandEnded); m_doc.CommandFailed -= new CommandEventHandler(callback_CommandFailed); m_doc.CommandWillStart -= new CommandEventHandler(callback_CommandWillStart); m_doc.LispCancelled -= new EventHandler(callback_LispCancelled); m_doc.LispEnded -= new EventHandler(callback_LispEnded); m_doc.LispWillStart -= new LispWillStartEventHandler(callback_LispWillStart); m_doc.UnknownCommand -= new UnknownCommandEventHandler(callback_UnknownCommand); boolClassVar.val = false; } catch (System.Exception ex) { Helper.Message(ex); } } private void callback_BeginDocumentClose(Object o, DocumentBeginCloseEventArgs e) { WriteLine("BeginDocumentClose"); } private void callback_CloseAborted(Object o, EventArgs e) { WriteLine("CloseAborted"); } private void callback_CloseWillStart(Object o, EventArgs e) { WriteLine("CloseWillStart"); } private void callback_CommandWillStart(Object o, CommandEventArgs e) { WriteLine(String.Format("CommandWillStart - {0}", e.GlobalCommandName)); } private void callback_CommandEnded(Object o, CommandEventArgs e) { WriteLine(String.Format("CommandEnded - {0}", e.GlobalCommandName)); } private void callback_CommandCancelled(Object o, CommandEventArgs e) { WriteLine(String.Format("CommandCancelled - {0}", e.GlobalCommandName)); } private void callback_CommandFailed(Object o, CommandEventArgs e) { WriteLine(String.Format("CommandFailed - {0}", e.GlobalCommandName)); } private void callback_LispCancelled(Object o, EventArgs e) { WriteLine("LispCancelled"); } private void callback_LispEnded(Object o, EventArgs e) { WriteLine("LispEnded"); } private void callback_LispWillStart(Object o, LispWillStartEventArgs e) { WriteLine(String.Format("LispWillStart - {0}", e.FirstLine)); } private void callback_UnknownCommand(Object o, UnknownCommandEventArgs e) { WriteLine(String.Format("UnknownCommand - {0}", e.GlobalCommandName)); } private void WriteLine(object obj) { try { string str = "\nDoc Events: " + obj.ToString(); Helper.StreamMessage(str); } catch (System.Exception ex) { Helper.Message(ex); } } // end of WriteLine } // end of class DocumentEvents }
/***************************************************************************\ * * File: WindowsTab.cs * * Description: * HWND-based tab control proxy * * Copyright (C) 2002 by Microsoft Corporation. All rights reserved. * \***************************************************************************/ using System; using System.Collections; using System.Text; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Runtime.InteropServices; using System.ComponentModel; using System.Windows; using System.Windows.Input; using MS.Win32; using NativeMethodsSetLastError = MS.Internal.UIAutomationClientSideProviders.NativeMethodsSetLastError; namespace MS.Internal.AutomationProxies { class WindowsTab: ProxyHwnd, ISelectionProvider, IScrollProvider, IRawElementProviderHwndOverride { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors public WindowsTab (IntPtr hwnd, ProxyFragment parent, int item) : base( hwnd, parent, item ) { // Set the strings to return properly the properties. _cControlType = ControlType.Tab; // force initialisation of this so it can be used later _windowsForms = WindowsFormsHelper.GetControlState (hwnd); // support for events _createOnEvent = new WinEventTracker.ProxyRaiseEvents (RaiseEvents); _fIsContent = IsValidControl(_hwnd); } static WindowsTab () { _upDownEvents = new WinEventTracker.EvtIdProperty [1]; _upDownEvents[0]._evtId = NativeMethods.EventObjectValueChange; _upDownEvents[0]._idProp = ScrollPattern.HorizontalScrollPercentProperty; } #endregion #region Proxy Create // Static Create method called by UIAutomation to create this proxy. // returns null if unsuccessful internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild, int idObject) { return Create(hwnd, idChild); } private static IRawElementProviderSimple Create(IntPtr hwnd, int idChild) { WindowsTab wTab = new WindowsTab(hwnd, null, 0); return idChild == 0 ? wTab : wTab.CreateTabItem (idChild - 1); } // Static Create method called by the event tracker system // WinEvents are one throwns because items exist. so it makes sense to create the item and // check for details afterward. internal static void RaiseEvents (IntPtr hwnd, int eventId, object idProp, int idObject, int idChild) { ProxySimple el = null; switch (idObject) { case NativeMethods.OBJID_CLIENT : { WindowsTab wlv = new WindowsTab (hwnd, null, -1); if (eventId == NativeMethods.EventObjectSelection || eventId == NativeMethods.EventObjectSelectionRemove || eventId == NativeMethods.EventObjectSelectionAdd) { el = wlv.CreateTabItem (idChild - 1); } else { el = wlv; } break; } default : if ((idProp == ScrollPattern.VerticalScrollPercentProperty && idObject != NativeMethods.OBJID_VSCROLL) || (idProp == ScrollPattern.HorizontalScrollPercentProperty && idObject != NativeMethods.OBJID_HSCROLL)) { return; } el = new WindowsTab(hwnd, null, -1); break; } if (el != null) { el.DispatchEvents (eventId, idProp, idObject, idChild); } } #endregion //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple Interface // Returns a pattern interface if supported. // Param name="iid", UIAutomation Pattern // Returns null or pattern interface internal override object GetPatternProvider (AutomationPattern iid) { if (iid == SelectionPattern.Pattern) { return this; } if (iid == ScrollPattern.Pattern) { return this; } return null; } // Process all the Logical and Raw Element Properties internal override object GetElementProperty(AutomationProperty idProp) { if (idProp == AutomationElement.IsControlElementProperty) { return IsValidControl(_hwnd); } else if (idProp == AutomationElement.OrientationProperty) { return IsVerticalTab() ? OrientationType.Vertical : OrientationType.Horizontal; } else if (idProp == ScrollPatternIdentifiers.HorizontalScrollPercentProperty) { return ((IScrollProvider)this).HorizontalScrollPercent; } else if (idProp == ScrollPatternIdentifiers.HorizontallyScrollableProperty) { return ((IScrollProvider)this).HorizontallyScrollable; } else if (idProp == ScrollPatternIdentifiers.HorizontalViewSizeProperty) { return ((IScrollProvider)this).HorizontalViewSize; } return base.GetElementProperty(idProp); } #endregion ProxySimple Interface #region ProxyFragment Interface // Returns the next sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Param name="child", the current child // Returns null if no next child internal override ProxySimple GetNextSibling (ProxySimple child) { int item = child._item; if (item != SpinControl) { int count = GetItemCount(_hwnd); // Next for an item that does not exist in the list if (item >= count) { throw new ElementNotAvailableException (); } if (item + 1 < count) { return CreateTabItem(item + 1); } } return null; } // Returns the previous sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Param name="child", the current child // Returns null is no previous internal override ProxySimple GetPreviousSibling (ProxySimple child) { int count = GetItemCount(_hwnd); int item = child._item; if (item == SpinControl) item = count; // Next for an item that does not exist in the list if (item >= count) { throw new ElementNotAvailableException (); } if (item > 0 && item <= count) { return CreateTabItem(item - 1); } return null; } // Returns the first child element in the raw hierarchy. internal override ProxySimple GetFirstChild () { int count = GetItemCount(_hwnd); if (count > 0) { return CreateTabItem(0); } return null; } // Returns the last child element in the raw hierarchy. internal override ProxySimple GetLastChild () { int count = GetItemCount(_hwnd); if (count > 0) { return CreateTabItem(count - 1); } return null; } // Returns a Proxy element corresponding to the specified screen coordinates. internal override ProxySimple ElementProviderFromPoint (int x, int y) { UnsafeNativeMethods.TCHITTESTINFO hti = new UnsafeNativeMethods.TCHITTESTINFO(); hti.pt = new NativeMethods.Win32Point (x, y); if (!Misc.MapWindowPoints(IntPtr.Zero, _hwnd, ref hti.pt, 1)) { return null; } // updown control goes over the tabs hence the order of the check // We cannot let UIAutomation do the do the drilling for the updown as the spinner covers the tab IntPtr updownHwnd = this.GetUpDownHwnd (); if (updownHwnd != IntPtr.Zero && Misc.PtInWindowRect(updownHwnd, x, y)) { return null; } int index; unsafe { index = XSendMessage.XSendGetIndex(_hwnd, NativeMethods.TCM_HITTEST, IntPtr.Zero, new IntPtr(&hti), Marshal.SizeOf(hti.GetType())); } if (index >= 0) { return CreateTabItem (index); } return null; } // Returns an item corresponding to the focused element (if there is one), or null otherwise. internal override ProxySimple GetFocus () { int focusIndex = Misc.ProxySendMessageInt(_hwnd, NativeMethods.TCM_GETCURFOCUS, IntPtr.Zero, IntPtr.Zero); if (focusIndex >= 0 && focusIndex < GetItemCount(_hwnd)) { return CreateTabItem (focusIndex); } else { return null; } } #endregion #region ProxyHwnd Interface internal override void AdviseEventAdded( AutomationEvent eventId, AutomationProperty[] aidProps) { if (eventId == AutomationElementIdentifiers.AutomationPropertyChangedEvent && aidProps.Length > 0 && aidProps[0] == ScrollPatternIdentifiers.HorizontalScrollPercentProperty) { IntPtr upDownHwnd = GetUpDownHwnd(); if (upDownHwnd != IntPtr.Zero) { // Register for UpDown ValueChange WinEvents, which will be // translated to scrolling events for the tab control. WinEventTracker.AddToNotificationList( upDownHwnd, new WinEventTracker.ProxyRaiseEvents(UpDownControlRaiseEvents), _upDownEvents, 1); } } base.AdviseEventAdded(eventId, aidProps); } internal override void AdviseEventRemoved( AutomationEvent eventId, AutomationProperty[] aidProps) { if (eventId == AutomationElementIdentifiers.AutomationPropertyChangedEvent && aidProps.Length > 0 && aidProps[0] == ScrollPatternIdentifiers.HorizontalScrollPercentProperty) { IntPtr upDownHwnd = GetUpDownHwnd(); if (upDownHwnd != IntPtr.Zero) { WinEventTracker.RemoveToNotificationList( upDownHwnd, _upDownEvents, null, 1); } } base.AdviseEventRemoved(eventId, aidProps); } #endregion ProxyHwnd Interface #region IRawElementProviderHwndOverride Interface //------------------------------------------------------ // // Interface IRawElementProviderHwndOverride // //------------------------------------------------------ IRawElementProviderSimple IRawElementProviderHwndOverride.GetOverrideProviderForHwnd (IntPtr hwnd) { // return the appropriate placeholder for the given hwnd... // loop over all the tabs to find it. string sTitle = Misc.ProxyGetText(hwnd); // If there is no hwnd title there is no way to match to the tab item. if (string.IsNullOrEmpty(sTitle)) { return null; } for (int i = 0, c = GetItemCount(_hwnd); i < c; i++) { if (sTitle == WindowsTabItem.GetName(_hwnd, i, true)) { return new WindowsTabChildOverrideProxy(hwnd, CreateTabItem(i), i); } } return null; } #endregion IRawElementProviderHwndOverride Interface #region Selection Pattern // Returns an enumerator over the current selection. IRawElementProviderSimple[] ISelectionProvider.GetSelection() { IRawElementProviderSimple[] selection = null; // If only one selection allowed, get selected item, if any, and add to list if (!WindowsTab.SupportMultipleSelection (_hwnd)) { int selectedItem = WindowsTabItem.GetCurrentSelectedItem(_hwnd); if (selectedItem >= 0) { selection = new IRawElementProviderSimple[1]; selection[0] = CreateTabItem(selectedItem); } } // If multiple selections allowed, check each tab for selected state else { ArrayList list = new ArrayList(); for (ProxySimple child = GetFirstChild(); child != null; child = GetNextSibling(child)) { if (((ISelectionItemProvider) child).IsSelected) { list.Add (child); } } int count = list.Count; if (count <= 0) { return null; } selection = new IRawElementProviderSimple[count]; for (int i = 0; i < count; i++) { selection[i] = (ProxySimple)list[i]; } } return selection; } // Returns whether the control supports multiple selection. bool ISelectionProvider.CanSelectMultiple { get { return SupportMultipleSelection (_hwnd); } } // Returns whether the control requires a minimum of one selected element at all times. bool ISelectionProvider.IsSelectionRequired { get { return !Misc.IsBitSet(WindowStyle, NativeMethods.TCS_BUTTONS); } } #endregion ISelectionProvider #region Scroll Pattern void IScrollProvider.Scroll (ScrollAmount horizontalAmount, ScrollAmount verticalAmount) { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } if (!IsScrollable()) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } if (verticalAmount != ScrollAmount.NoAmount) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } if (!Scroll(horizontalAmount)) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } } void IScrollProvider.SetScrollPercent (double horizontalPercent, double verticalPercent) { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } if (!IsScrollable()) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } if ((int)verticalPercent != (int)ScrollPattern.NoScroll) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } else if ((int)horizontalPercent == (int)ScrollPattern.NoScroll) { return; } else if (horizontalPercent < 0 || horizontalPercent > 100) { throw new ArgumentOutOfRangeException("horizontalPercent", SR.Get(SRID.ScrollBarOutOfRange)); } // Get up/down control's hwnd IntPtr updownHwnd = this.GetUpDownHwnd (); if (updownHwnd == IntPtr.Zero) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } // Get available range int range = Misc.ProxySendMessageInt(updownHwnd, NativeMethods.UDM_GETRANGE, IntPtr.Zero, IntPtr.Zero); int minPos = NativeMethods.Util.HIWORD(range); int maxPos = NativeMethods.Util.LOWORD(range); // Calculate new position int newPos = (int) Math.Round ((maxPos - minPos) * horizontalPercent / 100) + minPos; // Set position Misc.ProxySendMessage(updownHwnd, NativeMethods.UDM_SETPOS, IntPtr.Zero, (IntPtr)newPos); Misc.ProxySendMessage(_hwnd, NativeMethods.WM_HSCROLL, (IntPtr)NativeMethods.Util.MAKELPARAM(NativeMethods.SB_THUMBPOSITION, newPos), IntPtr.Zero); } // Calc the position of the horizontal scroll bar thumb in the 0..100 % range double IScrollProvider.HorizontalScrollPercent { get { double minPos, maxPos, currentPos; // Get up/down control's hwnd IntPtr updownHwnd = this.GetUpDownHwnd (); if (updownHwnd == IntPtr.Zero) { return (double)ScrollPattern.NoScroll; } // Get range of position values int range = Misc.ProxySendMessageInt(updownHwnd, NativeMethods.UDM_GETRANGE, IntPtr.Zero, IntPtr.Zero); // Get current position int posResult = Misc.ProxySendMessageInt(updownHwnd, NativeMethods.UDM_GETPOS, IntPtr.Zero, IntPtr.Zero); // Calculate percentage position minPos = NativeMethods.Util.HIWORD(range); maxPos = NativeMethods.Util.LOWORD(range); currentPos = NativeMethods.Util.LOWORD(posResult); return (currentPos - minPos) / (maxPos - minPos) * 100; } } // Calc the position of the Vertical scroll bar thumb in the 0..100 % range double IScrollProvider.VerticalScrollPercent { get { // Tab controls can never be vertically scrolling // since vertical tab controls must have the multiline style return (double)ScrollPattern.NoScroll; } } // Percentage of the window that is visible along the horizontal axis. // Value 0..100 double IScrollProvider.HorizontalViewSize { get { ProxySimple firstChild = GetFirstChild (); ProxySimple lastChild = GetLastChild (); // Get rectangles Rect firstRect = firstChild.BoundingRectangle; Rect lastRect = lastChild.BoundingRectangle; NativeMethods.Win32Rect viewable = new NativeMethods.Win32Rect (); viewable.left = 0; if (!Misc.GetWindowRect(_hwnd, ref viewable)) { return 100.0; } // Calculate ranges double totalRange = (double)lastRect.Right - (double)firstRect.Left; double viewableRange = viewable.right - viewable.left; // Get the rectangle of the up/down control and adjust viewable range IntPtr updownHwnd = this.GetUpDownHwnd (); if (updownHwnd == IntPtr.Zero) { return 100.0; } NativeMethods.Win32Rect rectW32 = new NativeMethods.Win32Rect (); if (!Misc.GetWindowRect(updownHwnd, ref rectW32)) { return 100.0; } viewableRange -= rectW32.right - rectW32.left; return viewableRange / totalRange * 100; } } // Percentage of the window that is visible along the vertical axis. // Value 0..100 double IScrollProvider.VerticalViewSize { get { return 100.0; } } // Can the element be horizontaly scrolled bool IScrollProvider.HorizontallyScrollable { get { return IsScrollable(); } } // Can the element be verticaly scrolled bool IScrollProvider.VerticallyScrollable { get { return false; } } #endregion IScrollProvider // ------------------------------------------------------ // // Internal Methods // // ------------------------------------------------------ #region Internal Methods internal static int GetItemCount(IntPtr hwnd) { // The Display Property Dialog is doing something strange with the their tab control. The // last tab is invisable. So if that is the case remove it from the count, since UIAutomation // can not do anything with it. int count = Misc.ProxySendMessageInt(hwnd, NativeMethods.TCM_GETITEMCOUNT, IntPtr.Zero, IntPtr.Zero); if (count > 0) { NativeMethods.Win32Rect rectW32 = NativeMethods.Win32Rect.Empty; bool result; unsafe { result = XSendMessage.XSend(hwnd, NativeMethods.TCM_GETITEMRECT, new IntPtr(count - 1), new IntPtr(&rectW32), Marshal.SizeOf(rectW32.GetType()), XSendMessage.ErrorValue.Zero); } if (!result) { count--; } if (rectW32.IsEmpty) { count--; } } return count; } // Create a WindowsTab instance internal ProxyFragment CreateTabItem(int index) { return new WindowsTabItem(_hwnd, this, index, _windowsForms == WindowsFormsHelper.FormControlState.True); } internal void ScrollToItem(int index) { if (!IsScrollable()) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } // Get up/down control's hwnd IntPtr updownHwnd = this.GetUpDownHwnd(); if (updownHwnd == IntPtr.Zero) return; int range = Misc.ProxySendMessageInt(updownHwnd, NativeMethods.UDM_GETRANGE, IntPtr.Zero, IntPtr.Zero); int max = NativeMethods.Util.LOWORD(range); int newPos = index < max ? index : max; Misc.ProxySendMessage(updownHwnd, NativeMethods.UDM_SETPOS, IntPtr.Zero, (IntPtr)newPos); Misc.ProxySendMessage(_hwnd, NativeMethods.WM_HSCROLL, NativeMethods.Util.MAKELPARAM(NativeMethods.SB_THUMBPOSITION, newPos), IntPtr.Zero); } internal bool IsScrollable() { return GetUpDownHwnd(_hwnd) != IntPtr.Zero; } // if all the tab items have no name then the control is not useful internal static bool IsValidControl(IntPtr hwnd) { for (int i = 0, c = GetItemCount(hwnd); i < c; i++) { if (!string.IsNullOrEmpty(WindowsTabItem.GetName(hwnd, i, true))) { return true; } } return false; } // Process events for the associated UpDown control, and relay // them to the WindowsTab control instead. internal static void UpDownControlRaiseEvents( IntPtr hwnd, int eventId, object idProp, int idObject, int idChild) { if (eventId == NativeMethods.EventObjectValueChange && idProp == ScrollPattern.HorizontalScrollPercentProperty) { IntPtr hwndParent = NativeMethodsSetLastError.GetAncestor(hwnd, NativeMethods.GA_PARENT); if (hwndParent != IntPtr.Zero && Misc.ProxyGetClassName(hwndParent).Contains("SysTabControl32")) { WindowsTab el = new WindowsTab(hwndParent, null, 0); el.DispatchEvents(eventId, idProp, 0, 0); } } } #endregion Internal Methods // ------------------------------------------------------ // // Private Methods // // ------------------------------------------------------ #region Private Methods // Gets the windows handle of the UpDown control in the tab control // Returns the handle to the UpDown control or IntPtr.Zero if this tab control isn't scrollable. private IntPtr GetUpDownHwnd() { return GetUpDownHwnd(_hwnd); } private static IntPtr GetUpDownHwnd(IntPtr hwnd) { IntPtr childHwnd = Misc.GetWindow(hwnd, NativeMethods.GW_CHILD); string className; int i; // UpDown control is either the first or last child, so do this check twice for (i = 0; i < 2; i++) { if (childHwnd != IntPtr.Zero) { className = Misc.ProxyGetClassName(childHwnd); if (className.IndexOf("updown", StringComparison.Ordinal) > -1) { // found it return childHwnd; } childHwnd = Misc.GetWindow(childHwnd, NativeMethods.GW_HWNDLAST); } else { // didn't find it break; } } return IntPtr.Zero; } private bool IsVerticalTab() { int style = WindowStyle; return Misc.IsBitSet(style, NativeMethods.TCS_MULTILINE) && (Misc.IsBitSet(style, NativeMethods.TCS_RIGHT) || Misc.IsBitSet(style, NativeMethods.TCS_VERTICAL)); } #endregion Private Methods #region Scroll Helper private bool Scroll(ScrollAmount amount) { // Done if (amount == ScrollAmount.NoAmount) { return true; } // Get up/down control's hwnd IntPtr updownHwnd = this.GetUpDownHwnd (); if (updownHwnd == IntPtr.Zero) { return false; } // int newPos = Misc.ProxySendMessageInt(updownHwnd, NativeMethods.UDM_GETPOS, IntPtr.Zero, IntPtr.Zero); int range = Misc.ProxySendMessageInt(updownHwnd, NativeMethods.UDM_GETRANGE, IntPtr.Zero, IntPtr.Zero); int max = NativeMethods.Util.LOWORD(range); int min = NativeMethods.Util.HIWORD(range); if (NativeMethods.Util.HIWORD (newPos) == 0) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } newPos = NativeMethods.Util.LOWORD (newPos); switch (amount) { case ScrollAmount.LargeDecrement : case ScrollAmount.LargeIncrement : // Not supported. return false; case ScrollAmount.SmallDecrement : newPos--; break; case ScrollAmount.SmallIncrement : newPos++; break; default : // should never get here return false; } if (newPos < min || newPos > max) { // Attempt to scroll before beginning or past end. // As long as this is a supported operation (namely, // SmallIncrement or SmallDecrement), do nothing but // return success. return true; } // Update both the spiner and the tabs Misc.ProxySendMessage(updownHwnd, NativeMethods.UDM_SETPOS, IntPtr.Zero, (IntPtr)newPos); Misc.ProxySendMessage(_hwnd, NativeMethods.WM_HSCROLL, NativeMethods.Util.MAKELPARAM(NativeMethods.SB_THUMBPOSITION, newPos), IntPtr.Zero); return true; } #endregion #region Selection Helper // detect if tab-control supports multiple selection static internal bool SupportMultipleSelection (IntPtr hwnd) { return Misc.IsBitSet(Misc.GetWindowStyle(hwnd), (NativeMethods.TCS_BUTTONS | NativeMethods.TCS_MULTISELECT)); } #endregion // ------------------------------------------------------ // // Private Fields // // ------------------------------------------------------ #region Private Fields private const int SpinControl = -2; // Updown specific events. private readonly static WinEventTracker.EvtIdProperty[] _upDownEvents; #endregion } // ------------------------------------------------------ // // WindowsTabItem Private Class // // ------------------------------------------------------ #region WindowsTabItem class WindowsTabItem : ProxyFragment, ISelectionItemProvider, IScrollItemProvider { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors internal WindowsTabItem(IntPtr hwnd, ProxyFragment parent, int item, bool fIsWinform) : base( hwnd, parent, item ) { // Set the strings to return properly the properties. _cControlType = ControlType.TabItem; _fIsKeyboardFocusable = true; _fIsWinform = fIsWinform; _fIsContent = !string.IsNullOrEmpty(GetName(_hwnd, _item, true)); } #endregion // ------------------------------------------------------ // // Patterns Implementation // // ------------------------------------------------------ #region ProxySimple Interface // Returns a pattern interface if supported. internal override object GetPatternProvider(AutomationPattern iid) { if(iid == SelectionItemPattern.Pattern) { return this; } else if (iid == ScrollItemPattern.Pattern) { return this; } return null; } // Gets the bounding rectangle for this element internal override Rect BoundingRectangle { get { // Don't need to normalize, BoundingRect returns absolute coordinates. return BoundingRect().ToRect(false); } } // Process all the Logical and Raw Element Properties internal override object GetElementProperty(AutomationProperty idProp) { if (idProp == AutomationElement.AccessKeyProperty && _windowsForms != WindowsFormsHelper.FormControlState.True) { return Misc.AccessKey(WindowsTabItem.GetItemText(_hwnd, _item)); } else if (idProp == AutomationElement.IsControlElementProperty) { return !string.IsNullOrEmpty(GetName(_hwnd, _item, true)); } return base.GetElementProperty(idProp); } //Gets the controls help text internal override string HelpText { get { IntPtr hwndToolTip = Misc.ProxySendMessage(_hwnd, NativeMethods.TCM_GETTOOLTIPS, IntPtr.Zero, IntPtr.Zero); return Misc.GetItemToolTipText(_hwnd, hwndToolTip, _item); } } //Gets the localized name internal override string LocalizedName { get { // If this is a [....] tab page and the AccessibleName is set, use it. if (WindowsFormsHelper.IsWindowsFormsControl(_hwnd, ref _windowsForms)) { string name = GetAccessibleName(_item + 1); if (!string.IsNullOrEmpty(name)) { return name; } } return GetName(_hwnd, _item, _windowsForms == WindowsFormsHelper.FormControlState.True); } } // Sets the focus to this item. internal override bool SetFocus() { if (Misc.IsBitSet(WindowStyle, NativeMethods.TCS_FOCUSNEVER)) { return false; } WindowsTab tab = (WindowsTab)_parent; ProxySimple focused = tab.GetFocus(); if (focused == null || _item != focused._item) { Misc.ProxySendMessage(_hwnd, NativeMethods.TCM_SETCURFOCUS, new IntPtr(_item), IntPtr.Zero); } return true; } #endregion ProxySimple Interface #region ProxyFragment Interface // Returns the next sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Param name="child", the current child // Returns null if no next child internal override ProxySimple GetNextSibling(ProxySimple child) { return null; } // Returns the previous sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Param name="child", the current child // Returns null is no previous internal override ProxySimple GetPreviousSibling(ProxySimple child) { return null; } // Returns the first child element in the raw hierarchy. internal override ProxySimple GetFirstChild() { IntPtr hwndChild = GetItemHwndByIndex(); if (hwndChild != IntPtr.Zero && SafeNativeMethods.IsWindowVisible(hwndChild)) { return new WindowsTabChildOverrideProxy(hwndChild, this, _item); } return null; } // Returns the last child element in the raw hierarchy. internal override ProxySimple GetLastChild() { // One children at most for form or nothing for Win32 controls. return GetFirstChild(); } #endregion ProxyFragment Interface #region Selection Pattern // Selects this element void ISelectionItemProvider.Select() { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } if (!IsSelectable()) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } if (((ISelectionItemProvider)this).IsSelected == false) { Select(); } } // Adds this element to the selection void ISelectionItemProvider.AddToSelection() { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } // If not selectable, can't add to selection if (!IsSelectable()) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } // If already selected, done if (((ISelectionItemProvider)this).IsSelected) { return; } // If multiple selections allowed, add requested selection if (WindowsTab.SupportMultipleSelection(_hwnd) == true) { // Press ctrl and mouse click tab NativeMethods.Win32Point pt = new NativeMethods.Win32Point(); if (GetClickablePoint(out pt, true)) { Input.SendKeyboardInput(Key.LeftCtrl, true); Misc.MouseClick(pt.x, pt.y); Input.SendKeyboardInput(Key.LeftCtrl, false); return; } throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } // else only single selection allowed else { throw new InvalidOperationException(SR.Get(SRID.DoesNotSupportMultipleSelection)); } } // Removes this element from the selection void ISelectionItemProvider.RemoveFromSelection() { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } // If not selected, done if (!((ISelectionItemProvider)this).IsSelected) { return; } // If multiple selections allowed, unselect element if (WindowsTab.SupportMultipleSelection(_hwnd) == true) { NativeMethods.Win32Point pt = new NativeMethods.Win32Point(); if (GetClickablePoint(out pt, true)) { Input.SendKeyboardInput(Key.LeftCtrl, true); Misc.MouseClick(pt.x, pt.y); Input.SendKeyboardInput(Key.LeftCtrl, false); return; } throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } // else if button style and single select, send deselectall message else if (Misc.IsBitSet(WindowStyle, NativeMethods.TCS_BUTTONS)) { Misc.ProxySendMessage(_hwnd, NativeMethods.TCM_DESELECTALL, IntPtr.Zero, IntPtr.Zero); return; } throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } // True if this element is part of the the selection bool ISelectionItemProvider.IsSelected { get { // If only a single selection is allowed, check which one is selected and compare if (!WindowsTab.SupportMultipleSelection(_hwnd)) { int selectedItem = GetCurrentSelectedItem(_hwnd); return (_item == selectedItem); } // If multiple selections possible, get state information on the tab else { NativeMethods.TCITEM TCItem = new NativeMethods.TCITEM(); TCItem.Init(NativeMethods.TCIF_STATE); if (!XSendMessage.GetItem(_hwnd, _item, ref TCItem)) { System.Diagnostics.Debug.Assert(false, "XSendMessage.GetItem() failed!"); return false; } return Misc.IsBitSet(TCItem.dwState, NativeMethods.TCIS_BUTTONPRESSED); } } } // Returns the container for this element IRawElementProviderSimple ISelectionItemProvider.SelectionContainer { get { System.Diagnostics.Debug.Assert(_parent is WindowsTab, "Invalid Parent for a Tab Item"); return _parent; } } #endregion SelectionItem Pattern #region ScrollItem Pattern void IScrollItemProvider.ScrollIntoView() { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } WindowsTab parent = (WindowsTab)_parent; if (!parent.IsScrollable()) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } parent.ScrollToItem(_item); } #endregion ScrollItem Pattern // ------------------------------------------------------ // // Internal Methods // // ------------------------------------------------------ #region Internal Methods // Retrieve the text in a tab item internal static string GetName(IntPtr hwnd, int item, bool fIsWinform) { string sName = GetItemText(hwnd, item); // Win32 controls '&' is used as an accelerator. This is not the case for [....] !!! return !fIsWinform ? Misc.StripMnemonic(sName) : sName; } internal static int GetCurrentSelectedItem(IntPtr hwnd) { return Misc.ProxySendMessageInt(hwnd, NativeMethods.TCM_GETCURSEL, IntPtr.Zero, IntPtr.Zero); } #endregion Internal Methods //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods // This routine is only called on elements belonging to an hwnd that has the focus. protected override bool IsFocused() { return Misc.ProxySendMessageInt(_hwnd, NativeMethods.TCM_GETCURFOCUS, IntPtr.Zero, IntPtr.Zero) == _item; } #endregion Protected Methods // ------------------------------------------------------ // // Private Methods // // ------------------------------------------------------ #region Private Methods private unsafe NativeMethods.Win32Rect BoundingRect() { NativeMethods.Win32Rect rectW32 = new NativeMethods.Win32Rect(); if (!XSendMessage.XSend(_hwnd, NativeMethods.TCM_GETITEMRECT, new IntPtr(_item), new IntPtr(&rectW32), Marshal.SizeOf(rectW32.GetType()), XSendMessage.ErrorValue.Zero)) { return NativeMethods.Win32Rect.Empty; } return Misc.MapWindowPoints(_hwnd, IntPtr.Zero, ref rectW32, 2) ? rectW32 : NativeMethods.Win32Rect.Empty; } private bool IsSelectable() { return (SafeNativeMethods.IsWindowEnabled(_hwnd) && SafeNativeMethods.IsWindowVisible(_hwnd)); } // Press a tab private void Select() { if (Misc.IsBitSet(WindowStyle, (NativeMethods.TCS_BUTTONS | NativeMethods.TCS_FOCUSNEVER))) { // The TCM_SETCURFOCUS message cannot be used with TCS_FOCUSNEVER // use a convulated way faking a mouse action NativeMethods.Win32Point pt = new NativeMethods.Win32Point(); if (GetClickablePoint(out pt, true)) { // Convert screen coordinates to client coordinates. if (Misc.MapWindowPoints(IntPtr.Zero, _hwnd, ref pt, 1)) { Misc.PostMessage(_hwnd, NativeMethods.WM_LBUTTONDOWN, (IntPtr)NativeMethods.MK_LBUTTON, NativeMethods.Util.MAKELPARAM(pt.x, pt.y)); Misc.PostMessage(_hwnd, NativeMethods.WM_LBUTTONUP, (IntPtr)NativeMethods.MK_LBUTTON, NativeMethods.Util.MAKELPARAM(pt.x, pt.y)); } } } else { Misc.ProxySendMessage(_hwnd, NativeMethods.TCM_SETCURFOCUS, new IntPtr(_item), IntPtr.Zero); } } // Gets the windows handle of an individual tab in a Windows Forms control private IntPtr GetItemHwndByIndex() { // On Win32 Tab controls the table page is parented by the dialog box not the // Tab control. IntPtr hwndParent = _hwnd; if (!_fIsWinform) { hwndParent = Misc.GetParent(hwndParent); } if (hwndParent != IntPtr.Zero) { // Get the tab name and match it with the window title of one of the children string sName = WindowsTabItem.GetName(_hwnd, _item, true); // If there is no tab name there is no way to match to one of the childrens window title. if (!string.IsNullOrEmpty(sName)) { return Misc.FindWindowEx(hwndParent, IntPtr.Zero, null, sName); } } return IntPtr.Zero; } private static string GetItemText(IntPtr hwnd, int itemIndex) { NativeMethods.TCITEM tcitem = new NativeMethods.TCITEM(); tcitem.Init(); tcitem.mask = NativeMethods.TCIF_TEXT; tcitem.cchTextMax = Misc.MaxLengthNameProperty; return XSendMessage.GetItemText(hwnd, itemIndex, tcitem); } #endregion Private Methods // ------------------------------------------------------ // // Private Fields // // ------------------------------------------------------ #region Private Fields // Cached value for a winform bool _fIsWinform; #endregion Private Fields } #endregion // ------------------------------------------------------ // // WindowsTabChildOverrideProxy Class // //------------------------------------------------------ #region WindowsTabChildOverrideProxy class WindowsTabChildOverrideProxy : ProxyHwnd { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors // Constructor // Usually the hwnd passed to the constructor is wrong. As the base class is doing // nothing this does not matter. // This avoid to making some extra calls to get this right. internal WindowsTabChildOverrideProxy(IntPtr hwnd, ProxyFragment parent, int item) : base (hwnd, parent, item) { } #endregion //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple Interface internal override ProviderOptions ProviderOptions { get { return base.ProviderOptions | ProviderOptions.OverrideProvider; } } // Process all the Logical and Raw Element Properties internal override object GetElementProperty(AutomationProperty idProp) { if (idProp == AutomationElement.IsControlElementProperty) { return false; } // Overrides the ProxySimple implementation to remove and default // property handling // This proxy is about tree rearranging, it does not do any // property overrride. return null; } #endregion } #endregion }
using System; using System.Collections; using System.Configuration; using System.IO; using System.Drawing; using jk.plaveninycz.Interfaces; using jk.plaveninycz.BO; using jk.plaveninycz.DataSources; using jk.plaveninycz.search; using jk.plaveninycz.Validation; using jk.plaveninycz.Bll; using ZedGraph; using grafy.Properties; using System.Collections.Generic; namespace jk.plaveninycz.graph { /// <summary> /// This is the class for creating chart output. /// given input parameters, a png image is /// created and can be used as response output stream /// or saved to disk. /// </summary> public class ChartEngine { #region Declarations int _width = 656; int _height = 240; bool _showText = true; #endregion #region Constructors /// <summary> /// Creates a new ChartEngine with default 'width' and 'height' values /// </summary> public ChartEngine() { _width = DefaultWidth; _height = DefaultHeight; } /// <summary> /// Creates a new ChartEngine, with resulting image width and height specified /// </summary> public ChartEngine(int width, int height) { _width = width; //_width = 656; //width for hydro=696 _height = height; //_height= 240; //width for hydro= } #endregion #region Properties public bool ShowText { get { return ShowText; } set { _showText = value; } } public int Width { get { return _width; } set { _width = value; } } public int Height { get { return _height; } set { _height = value; } } public static int DefaultWidth { get { return 656; } } public static int DefaultHeight { get { return 290; } } #endregion Properties #region Create Chart /// <summary> /// Generates a new 'chart' image to be written to http output stream. /// Also saves the newly generated image to file on disk. /// </summary> /// <param name="ImagePath">Http request path of the chart image</param> public Bitmap GenerateImage(string ImagePath) { Bitmap bmp; ChartEngine ChartGen = new ChartEngine(); Width = 600; Height = 275; ShowText = true; QueryStringValidator QVal = new QueryStringValidator(ImagePath); QVal.Validate(); //the language and culture is also set in the validator if (QVal.IsValid) { // get query string parameters string lang = QVal.Culture; int StId = QVal.StationId; Variable curVar = QVal.Variable; DateTime startTime = QVal.StartDate; DateTime endTime = QVal.EndDate; // TODO: for longer intervals change curVar to [precip_day] // search for the channel corresponding to station/variable combination ChannelSearchResult found = ChannelSearchEngine.FindByStationIdAndVariable( StId, curVar); if (!found.HasMatchingStations) //no matching station { return ChartGen.CreateErrorChart(found.ErrorMessage); } if (found.HasMatchingChannels) //correct results found { Channel ch = found.Channels[0]; ITimeSeries ts; TimeInterval interval = new TimeInterval(startTime, endTime); MessageWriter writer = new MessageWriter(ch.Station.Name, ch.Variable.Name); // for precipitation, if it's hourly and a longer period, // always select daily precipitation to display a readable graph // otherwise, hourly precipitation will be displayed. int maxHourPrecipPeriod = 10; VariableEnum var = ch.Variable.VarEnum; if (var == VariableEnum.PrecipHour && interval.Length.TotalDays > maxHourPrecipPeriod) { var = VariableEnum.Precip; } //here we retrieve the time series ts = TimeSeriesManager.GetTimeSeries(ch, interval); if (ts.Count == 0) //this also means 'no data for time series' { bmp = ChartGen.CreateErrorChart (writer.WriteErrorMessage(MessageType.NoDataForPeriod)); } bmp = ChartGen.CreateChart(ch, ts); } else { // incorrect input - create a 'chart' with an error message bmp = ChartGen.CreateErrorChart(found.ErrorMessage); } } else { // incorrect input - create a 'chart' with an error message bmp = ChartGen.CreateErrorChart(QVal.ErrorMessage); } return bmp; } /// <summary> /// Creates a chart - plots are made for all sensors in the time series /// </summary> /// <param name="ts">The time series of data to be ploted</param> /// <param name="ch">The channel (contains station, variable and copyright description) /// </param> /// <returns>The chart png image</returns> public Bitmap CreateChart(Channel ch, ITimeSeries ts) { GraphPane pane = SetupGraphPane(); SetupChart(ts, ch, pane); PlotChartForChannel(ts, ch, pane); return ExportGraph(pane); } private void PlotChartForChannel(ITimeSeries ts, Channel ch, GraphPane pane) { VariableEnum varEnum = ch.Variable.VarEnum; if (ts.End < Convert.ToDateTime("2013-01-01") && ts.PercentAvailableData < 1.0) //no data.. { ShowNoDataTextBox(Resources.no_data, pane); ShowErrorTextBox(Resources.no_data_message, pane); } else { switch (varEnum) { case VariableEnum.Stage: PlotStageDischarge(ts, pane); break; case VariableEnum.Discharge: PlotStageDischarge(ts, pane); break; case VariableEnum.Snow: PlotSnow(ts, pane); break; case VariableEnum.SoilWater10: case VariableEnum.SoilWater50: PlotSoilWater(ts, pane); break; case VariableEnum.Precip: PlotPrecip(ts, pane); break; case VariableEnum.PrecipHour: PlotPrecipHour(ts, pane); break; case VariableEnum.Temperature: PlotTemperature(ts, pane); break; default: break; } //also plot 'no data' if necessary if (ch.Variable.VarEnum != VariableEnum.Stage && ch.Variable.VarEnum != VariableEnum.Discharge && ts.PercentAvailableData > 0.01) { //PlotMissingData(ts, pane); } //add 'copyright' notice ShowCopyrightTextBox("data: " + ch.Station.Operator, pane); } } private GraphPane SetupGraphPane() { GraphPane myPane = new GraphPane(new RectangleF(0, 0, this.Width, this.Height), "no data", "", "y"); myPane.Border.IsVisible = false; myPane.Legend.IsVisible = true; return myPane; } private void SetupChart(ITimeSeries ts, Channel ch, GraphPane pane) { Station st = ch.Station; Variable var = ch.Variable; DateTime start = ts.Start; DateTime end = ts.End; DrawTitle(pane, var, st, start, end); SetupAxis(pane, var, start, end); SetupGrid(pane, var.VarEnum); SetupLegend(pane); } private void DrawTitle(GraphPane myPane, Variable var, Station st, DateTime minDate, DateTime maxDate) { string title; string stName; // TEMPORARILY COMMENT OUT RIVER NAME !!!!!! //if ( var.VarEnum == VariableEnum.Discharge || var.VarEnum == VariableEnum.Stage ) //{ // stName = string.Format("{0} ({1})", st.Name, st.River.Name); //} //else //{ stName = st.Name; //} title = String.Format("{0} - {1} {2} - {3}", var.Name, stName, minDate.ToShortDateString(), maxDate.ToShortDateString()); myPane.Title.Text = title; myPane.Title.FontSpec.Size = 18; myPane.Title.FontSpec.IsBold = false; } private void SetupAxis(GraphPane myPane, Variable var, DateTime minDate, DateTime maxDate) { //setup font for axis name and tick marks text int scaleFontSize = 16; int titleFontSize = 18; // X axis ZedGraph.Axis myXAxis = myPane.XAxis; myXAxis.Type = AxisType.Date; myXAxis.Scale.Min = XDate.DateTimeToXLDate(minDate); myXAxis.Scale.Max = XDate.DateTimeToXLDate(maxDate); myXAxis.Scale.FontSpec.Size = scaleFontSize; myPane.XAxis.Title.FontSpec.Size = titleFontSize; // Y axis ZedGraph.Axis myYAxis = myPane.YAxis; if (var.VarEnum != VariableEnum.Temperature) { myYAxis.Scale.Min = 0; } myYAxis.Scale.FontSpec.Size = scaleFontSize; myYAxis.Title.FontSpec.Size = titleFontSize; //special Y axis for temperature // special Y axis for discharge if (var.VarEnum == VariableEnum.Discharge) { char exp3 = (char)179; myYAxis.Title.Text = string.Format("{0} (m{1}/s)", var.Name, exp3); } else { myYAxis.Title.Text = var.Name + " (" + var.Units + ")"; } // Y2 axis - setup for cumulative precipitation if ( var.VarEnum == VariableEnum.Precip || var.VarEnum == VariableEnum.PrecipHour ) { ZedGraph.Axis myY2Axis = myPane.Y2Axis; myY2Axis.Scale.Min = 0; myY2Axis.Scale.FontSpec.Size = scaleFontSize; myY2Axis.Title.Text = Resources.precip_sum_axis; myY2Axis.Title.FontSpec.Size = titleFontSize; myY2Axis.IsVisible = true; } } private void SetupGrid(GraphPane myPane, VariableEnum v) { //first do common grid settings myPane.XAxis.MajorGrid.DashOn = 6.0f; myPane.XAxis.MajorGrid.DashOff = 2.0f; myPane.XAxis.MajorGrid.Color = Color.LightGray; myPane.XAxis.MajorGrid.IsVisible = true; myPane.YAxis.MajorGrid.Color = Color.LightGray; myPane.YAxis.MajorGrid.DashOn = 6.0f; myPane.YAxis.MajorGrid.DashOff = 2.0f; myPane.YAxis.MajorGrid.IsVisible = true; //special variable-specific settings switch ( v ) { case VariableEnum.Snow: myPane.XAxis.MajorGrid.IsVisible = false; break; default: break; } } private void SetupLegend(GraphPane myPane) { int legendFontSize = 18; ZedGraph.Legend leg = myPane.Legend; leg.FontSpec.Size = legendFontSize; } private Bitmap ExportGraph(GraphPane pane) { Bitmap bm = new Bitmap(1, 1); using ( Graphics g = Graphics.FromImage(bm) ) { pane.AxisChange(g); } return pane.GetImage(); } // plot the stage! private void PlotStageDischarge(ITimeSeries ts, GraphPane myPane) { TimeInterval interval = new TimeInterval(ts.Start, ts.End); if ( ts.Count > 0 ) { List<HydroTimeSeries> tsList = TimeSeriesManager.SplitTimeSeries(ts); foreach (HydroTimeSeries ts2 in tsList) { LineItem myCurve = myPane.AddCurve("", ts2, Color.Blue, SymbolType.None); myCurve.Line.Width = 1F; myCurve.Line.Fill = new Fill(Color.FromArgb(128, Color.Blue)); } //mark missing data points if (tsList.Count > 1) { TimeStep step = TimeSeriesManager.GetDefaultTimeStep(VariableEnum.Stage, interval); HydroTimeSeries missingTs = TimeSeriesManager.GetMissingValuesHydro(ts, ts.Start, ts.End, step); PlotMissingData(missingTs, myPane); } } } /// <summary> /// Plot the snow !!!! /// </summary> /// <param name="ts"></param> /// <param name="myPane"></param> private void PlotSnow(ITimeSeries ts, GraphPane myPane) { TimeInterval interval = new TimeInterval(ts.Start, ts.End); //Main creation of curve if ( interval.Length.TotalDays < 160 ) { BarItem myCurve = myPane.AddBar("", ts, Color.Blue); myCurve.Bar.Border.Color = Color.Blue; myCurve.Bar.Border.IsVisible = true; myCurve.Bar.Fill.Type = FillType.Solid; myCurve.Bar.Fill.IsScaled = false; } else if (interval.Length.TotalDays < 200) { StickItem myCurve = myPane.AddStick("", ts, Color.Blue); } else if (interval.Length.TotalDays < 400) { BarItem myCurve = myPane.AddBar("", ts, Color.Blue); myCurve.Bar.Border.Color = Color.Blue; myCurve.Bar.Border.IsVisible = true; myCurve.Bar.Fill.Type = FillType.Solid; myCurve.Bar.Fill.IsScaled = false; } else { StickItem myCurve = myPane.AddStick("", ts, Color.Blue); } //else //{ // StickItem myCurve = myPane.AddStick("", ts, Color.Blue); // //LineItem myCurve = myPane.AddCurve("", ts, Color.Blue, SymbolType.None); // //myCurve.Line.Width = 0F; // //myCurve.Line.Fill = new Fill(Color.Blue); //} } private void PlotSoilWater(ITimeSeries ts, GraphPane myPane) { if ( ts.Count > 0 ) { //Main creation of curve LineItem myCurve = myPane.AddCurve("", ts, Color.Blue, SymbolType.None); myCurve.Line.Width = 2F; } } private void PlotTemperature(ITimeSeries ts, GraphPane myPane) { if (ts.Count > 0) { TimeInterval interv = new TimeInterval(ts.Start, ts.End); TimeStep step = TimeSeriesManager.GetDefaultTimeStep(VariableEnum.Temperature, interv); ITimeSeries ts2 = TimeSeriesManager.FillDataGaps(ts, step); LineItem myCurve = myPane.AddCurve("", ts2, Color.Blue, SymbolType.None); myCurve.Line.Width = 0.5F; } } /// <summary> /// Plot the daily precipitation !!!! /// </summary> private void PlotPrecip(ITimeSeries ts, GraphPane myPane) { TimeInterval interval = new TimeInterval(ts.Start, ts.End); string label = Resources.precip_label; if ( interval.Length.TotalDays < 100 ) { BarItem myCurve = myPane.AddBar(label, ts, Color.Blue); myCurve.Bar.Border.Color = Color.Blue; myCurve.Bar.Border.IsVisible = true; myCurve.Bar.Fill.Type = FillType.Solid; myCurve.Bar.Fill.IsScaled = false; } else { StickItem myCurve = myPane.AddStick(label, ts, Color.Blue); } //cumulative precipitation.. ITimeSeries ts2 = ts.ShowCumulative(); if ( ts2.Count > 0 ) { LineItem myCurve2 = myPane.AddCurve(Resources.precip_sum_label, ts2, Color.Red, SymbolType.None); myCurve2.IsY2Axis = true; myPane.AxisChange(); } } /// <summary> /// Plot the hourly precipitation !!!! /// </summary> private void PlotPrecipHour(ITimeSeries ts, GraphPane myPane) { TimeInterval interval = new TimeInterval(ts.Start, ts.End); string varName = Resources.precip_label; //Main creation of curve if ( interval.Length.TotalDays <= 2 ) { BarItem myCurve = myPane.AddBar(varName, ts, Color.Blue); myCurve.Bar.Border.Color = Color.Blue; myCurve.Bar.Border.IsVisible = true; myCurve.Bar.Fill.Type = FillType.Solid; myCurve.Bar.Fill.IsScaled = false; } else { StickItem myCurve = myPane.AddStick(varName, ts, Color.Blue); } //cumulative precipitation.. ITimeSeries ts2 = ts.ShowCumulative(); LineItem myCurve2 = myPane.AddCurve(Resources.precip_sum_label, ts2, Color.Red, SymbolType.None); myCurve2.IsY2Axis = true; myPane.AxisChange(); } /// <summary> /// puts little "crosses" on missing data points /// </summary> private void PlotMissingData(ITimeSeries ts, GraphPane myPane) { string noDataText = Resources.no_data; float crossSize = 10F; //double yAxisH = myPane.YAxis.Scale.ReverseTransform(crossSize); double yAxisH = myPane.YAxis.Scale.Max / 25.0; //ITimeSeries ts2 = ts.ShowUnknown(yAxisH); for (int i = 0; i < ts.Count; i++ ) { ts[i].Y = yAxisH; } if ( ts != null ) { if ( ts.Count > 0 ) { LineItem missingCurve = myPane.AddCurve(noDataText, ts, Color.Red, SymbolType.XCross); missingCurve.Line.IsVisible = false; missingCurve.Symbol.Size = crossSize; missingCurve.Symbol.IsVisible = true; myPane.AxisChange(); } } } private void ShowCopyrightTextBox(string text, GraphPane myPane) { TextObj obj = new TextObj(text, 0.025F, 0.05F, CoordType.ChartFraction); obj.FontSpec = new FontSpec("MS Sans Serif", 20, Color.DarkBlue, false, false, false); obj.Location.AlignH = AlignH.Left; obj.Location.AlignV = AlignV.Top; obj.FontSpec.Border.Color = Color.Green; obj.FontSpec.Border.IsVisible = false; //obj.FontSpec.IsItalic = true; obj.FontSpec.Fill.IsVisible = true; myPane.GraphObjList.Add(obj); } private void ShowNoDataTextBox(string noDataText, GraphPane myPane) { //show a 'no data' box TextObj noDataObj = new TextObj(noDataText.ToUpper(), 0.5, 0.5, CoordType.PaneFraction); noDataObj.Location.AlignH = AlignH.Center; noDataObj.Location.AlignV = AlignV.Center; noDataObj.FontSpec.Size = 40f; noDataObj.IsVisible = true; noDataObj.IsClippedToChartRect = true; myPane.GraphObjList.Add(noDataObj); myPane.AxisChange(); } private void ShowErrorTextBox(string errorMessage, GraphPane myPane) { string HeadingText = Resources.ChartError_Heading; TextObj HeadingObj = new TextObj(HeadingText, 0.1F, 0.2F, CoordType.PaneFraction); HeadingObj.FontSpec = new FontSpec("Arial", 40, Color.Red, true, false, false); HeadingObj.Location.AlignH = AlignH.Left; HeadingObj.Location.AlignV = AlignV.Top; myPane.GraphObjList.Add(HeadingObj); TextObj ErrorObj = new TextObj(errorMessage, 0.1F, 0.4F); ErrorObj.Location.CoordinateFrame = CoordType.PaneFraction; //ErrorObj.Location.Height = 0.2; ErrorObj.Location.AlignH = AlignH.Left; ErrorObj.Location.AlignV = AlignV.Top; //ErrorObj.Text = errorMessage; //TextObj ErrorObj = new TextObj(errorMessage, 0.75, 0.5, CoordType.PaneFraction); ErrorObj.FontSpec = new FontSpec("Arial", 20, Color.Black, false, false, false); ErrorObj.FontSpec.Border.IsVisible = false; ErrorObj.FontSpec.StringAlignment = StringAlignment.Near; //ErrorObj.FontSpec.StringAlignment = StringAlignment.Center; myPane.GraphObjList.Add(ErrorObj); myPane.AxisChange(); } //generate chart with error message // and write it directly to output stream public System.Drawing.Bitmap CreateErrorChart(string ErrorMessage) { GraphPane pane = SetupGraphPane(); ShowErrorTextBox(ErrorMessage, pane); return ExportGraph(pane); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using AccountSetting = System.Collections.Generic.KeyValuePair<string, System.Func<string, bool>>; using ConnectionStringFilter = System.Func<System.Collections.Generic.IDictionary<string, string>, System.Collections.Generic.IDictionary<string, string>>; #pragma warning disable SA1402 // File may only contain a single type namespace Azure.Storage { internal class StorageConnectionString { /// <summary> /// Gets or sets a value indicating whether the FISMA MD5 setting will be used. /// </summary> /// <value><c>false</c> to use the FISMA MD5 setting; <c>true</c> to use the .NET default implementation.</value> internal static bool UseV1MD5 => true; /// <summary> /// Validator for the UseDevelopmentStorage setting. Must be "true". /// </summary> private static readonly AccountSetting s_useDevelopmentStorageSetting = Setting(Constants.ConnectionStrings.UseDevelopmentSetting, "true"); /// <summary> /// Validator for the DevelopmentStorageProxyUri setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_developmentStorageProxyUriSetting = Setting(Constants.ConnectionStrings.DevelopmentProxyUriSetting, IsValidUri); /// <summary> /// Validator for the DefaultEndpointsProtocol setting. Must be either "http" or "https". /// </summary> private static readonly AccountSetting s_defaultEndpointsProtocolSetting = Setting(Constants.ConnectionStrings.DefaultEndpointsProtocolSetting, "http", "https"); /// <summary> /// Validator for the AccountName setting. No restrictions. /// </summary> private static readonly AccountSetting s_accountNameSetting = Setting(Constants.ConnectionStrings.AccountNameSetting); /// <summary> /// Validator for the AccountKey setting. No restrictions. /// </summary> private static readonly AccountSetting s_accountKeyNameSetting = Setting(Constants.ConnectionStrings.AccountKeyNameSetting); /// <summary> /// Validator for the AccountKey setting. Must be a valid base64 string. /// </summary> private static readonly AccountSetting s_accountKeySetting = Setting(Constants.ConnectionStrings.AccountKeySetting, IsValidBase64String); /// <summary> /// Validator for the BlobEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_blobEndpointSetting = Setting(Constants.ConnectionStrings.BlobEndpointSetting, IsValidUri); /// <summary> /// Validator for the QueueEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_queueEndpointSetting = Setting(Constants.ConnectionStrings.QueueEndpointSetting, IsValidUri); /// <summary> /// Validator for the FileEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_fileEndpointSetting = Setting(Constants.ConnectionStrings.FileEndpointSetting, IsValidUri); /// <summary> /// Validator for the TableEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_tableEndpointSetting = Setting(Constants.ConnectionStrings.TableEndpointSetting, IsValidUri); /// <summary> /// Validator for the BlobSecondaryEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_blobSecondaryEndpointSetting = Setting(Constants.ConnectionStrings.BlobSecondaryEndpointSetting, IsValidUri); /// <summary> /// Validator for the QueueSecondaryEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_queueSecondaryEndpointSetting = Setting(Constants.ConnectionStrings.QueueSecondaryEndpointSetting, IsValidUri); /// <summary> /// Validator for the FileSecondaryEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_fileSecondaryEndpointSetting = Setting(Constants.ConnectionStrings.FileSecondaryEndpointSetting, IsValidUri); /// <summary> /// Validator for the TableSecondaryEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_tableSecondaryEndpointSetting = Setting(Constants.ConnectionStrings.TableSecondaryEndpointSetting, IsValidUri); /// <summary> /// Validator for the EndpointSuffix setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_endpointSuffixSetting = Setting(Constants.ConnectionStrings.EndpointSuffixSetting, IsValidDomain); /// <summary> /// Validator for the SharedAccessSignature setting. No restrictions. /// </summary> private static readonly AccountSetting s_sharedAccessSignatureSetting = Setting(Constants.ConnectionStrings.SharedAccessSignatureSetting); /// <summary> /// Singleton instance for the development storage account. /// </summary> private static StorageConnectionString s_devStoreAccount; /// <summary> /// Initializes a new instance of the <see cref="StorageConnectionString"/> class using the specified /// account credentials and service endpoints. /// </summary> /// <param name="storageCredentials">A StorageCredentials object.</param> /// <param name="blobStorageUri">A <see cref="System.Uri"/> specifying the Blob service endpoint or endpoints.</param> /// <param name="queueStorageUri">A <see cref="System.Uri"/> specifying the Queue service endpoint or endpoints.</param> /// <param name="tableStorageUri">A <see cref="System.Uri"/> specifying the Table service endpoint or endpoints.</param> /// <param name="fileStorageUri">A <see cref="System.Uri"/> specifying the File service endpoint or endpoints.</param> public StorageConnectionString( object storageCredentials, (Uri Primary, Uri Secondary) blobStorageUri = default, (Uri Primary, Uri Secondary) queueStorageUri = default, (Uri Primary, Uri Secondary) tableStorageUri = default, (Uri Primary, Uri Secondary) fileStorageUri = default) { Credentials = storageCredentials; BlobStorageUri = blobStorageUri; QueueStorageUri = queueStorageUri; TableStorageUri = tableStorageUri; FileStorageUri = fileStorageUri; DefaultEndpoints = false; } /// <summary> /// Gets a <see cref="StorageConnectionString"/> object that references the well-known development storage account. /// </summary> /// <value>A <see cref="StorageConnectionString"/> object representing the development storage account.</value> public static StorageConnectionString DevelopmentStorageAccount { get { if (s_devStoreAccount == null) { s_devStoreAccount = GetDevelopmentStorageAccount(null); } return s_devStoreAccount; } } /// <summary> /// Indicates whether this account is a development storage account. /// </summary> internal bool IsDevStoreAccount { get; set; } /// <summary> /// The storage service hostname suffix set by the user, if any. /// </summary> internal string EndpointSuffix { get; set; } /// <summary> /// The connection string parsed into settings. /// </summary> internal IDictionary<string, string> Settings { get; set; } /// <summary> /// True if the user used a constructor that auto-generates endpoints. /// </summary> internal bool DefaultEndpoints { get; set; } /// <summary> /// Gets the primary endpoint for the Blob service, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the primary Blob service endpoint.</value> public Uri BlobEndpoint => BlobStorageUri.PrimaryUri; /// <summary> /// Gets the primary endpoint for the Queue service, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the primary Queue service endpoint.</value> public Uri QueueEndpoint => QueueStorageUri.PrimaryUri; /// <summary> /// Gets the primary endpoint for the Table service, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the primary Table service endpoint.</value> public Uri TableEndpoint => TableStorageUri.PrimaryUri; /// <summary> /// Gets the primary endpoint for the File service, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the primary File service endpoint.</value> public Uri FileEndpoint => FileStorageUri.PrimaryUri; /// <summary> /// Gets the endpoints for the Blob service at the primary and secondary location, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the Blob service endpoints.</value> public (Uri PrimaryUri, Uri SecondaryUri) BlobStorageUri { get; set; } /// <summary> /// Gets the endpoints for the Queue service at the primary and secondary location, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the Queue service endpoints.</value> public (Uri PrimaryUri, Uri SecondaryUri) QueueStorageUri { get; set; } /// <summary> /// Gets the endpoints for the Table service at the primary and secondary location, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the Table service endpoints.</value> public (Uri PrimaryUri, Uri SecondaryUri) TableStorageUri { get; set; } /// <summary> /// Gets the endpoints for the File service at the primary and secondary location, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the File service endpoints.</value> public (Uri PrimaryUri, Uri SecondaryUri) FileStorageUri { get; set; } /// <summary> /// Gets the credentials used to create this <see cref="StorageConnectionString"/> object. /// </summary> /// <value>A StorageCredentials object.</value> public object Credentials { get; set; } /// <summary> /// Private record of the account name for use in ToString(bool). /// </summary> internal string _accountName; /// <summary> /// Parses a connection string and returns a <see cref="StorageConnectionString"/> created /// from the connection string. /// </summary> /// <param name="connectionString">A valid connection string.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="connectionString"/> is null or empty.</exception> /// <exception cref="FormatException">Thrown if <paramref name="connectionString"/> is not a valid connection string.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="connectionString"/> cannot be parsed.</exception> /// <returns>A <see cref="StorageConnectionString"/> object constructed from the values provided in the connection string.</returns> public static StorageConnectionString Parse(string connectionString) { if (string.IsNullOrEmpty(connectionString)) { throw Errors.ArgumentNull(nameof(connectionString)); } if (ParseCore(connectionString, out StorageConnectionString ret, err => { throw Errors.InvalidFormat(err); })) { return ret; } throw Errors.ParsingConnectionStringFailed(); } /// <summary> /// Indicates whether a connection string can be parsed to return a <see cref="StorageConnectionString"/> object. /// </summary> /// <param name="connectionString">The connection string to parse.</param> /// <param name="account">A <see cref="StorageConnectionString"/> object to hold the instance returned if /// the connection string can be parsed.</param> /// <returns><b>true</b> if the connection string was successfully parsed; otherwise, <b>false</b>.</returns> public static bool TryParse(string connectionString, out StorageConnectionString account) { if (string.IsNullOrEmpty(connectionString)) { account = null; return false; } try { return ParseCore(connectionString, out account, err => { }); } catch (Exception) { account = null; return false; } } ///// <summary> ///// Returns a shared access signature for the account. ///// </summary> ///// <param name="policy">A <see cref="SharedAccessAccountPolicy"/> object specifying the access policy for the shared access signature.</param> ///// <returns>A shared access signature, as a URI query string.</returns> ///// <remarks>The query string returned includes the leading question mark.</remarks> //public string GetSharedAccessSignature(SharedAccessAccountPolicy policy) //{ // if (!this.Credentials.IsSharedKey) // { // var errorMessage = String.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey); // throw new InvalidOperationException(errorMessage); // } // StorageAccountKey accountKey = this.Credentials.Key; // string signature = SharedAccessSignatureHelper.GetHash(policy, this.Credentials.AccountName, Constants.HeaderConstants.TargetStorageVersion, accountKey.KeyValue); // UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(policy, signature, accountKey.KeyName, Constants.HeaderConstants.TargetStorageVersion); // return builder.ToString(); //} /// <summary> /// Returns a <see cref="StorageConnectionString"/> with development storage credentials using the specified proxy Uri. /// </summary> /// <param name="proxyUri">The proxy endpoint to use.</param> /// <returns>The new <see cref="StorageConnectionString"/>.</returns> private static StorageConnectionString GetDevelopmentStorageAccount(Uri proxyUri) { UriBuilder builder = proxyUri != null ? new UriBuilder(proxyUri.Scheme, proxyUri.Host) : new UriBuilder("http", "127.0.0.1"); builder.Path = Constants.ConnectionStrings.DevStoreAccountName; builder.Port = Constants.ConnectionStrings.BlobEndpointPortNumber; Uri blobEndpoint = builder.Uri; builder.Port = Constants.ConnectionStrings.TableEndpointPortNumber; Uri tableEndpoint = builder.Uri; builder.Port = Constants.ConnectionStrings.QueueEndpointPortNumber; Uri queueEndpoint = builder.Uri; builder.Path = Constants.ConnectionStrings.DevStoreAccountName + Constants.ConnectionStrings.SecondaryLocationAccountSuffix; builder.Port = Constants.ConnectionStrings.BlobEndpointPortNumber; Uri blobSecondaryEndpoint = builder.Uri; builder.Port = Constants.ConnectionStrings.QueueEndpointPortNumber; Uri queueSecondaryEndpoint = builder.Uri; builder.Port = Constants.ConnectionStrings.TableEndpointPortNumber; Uri tableSecondaryEndpoint = builder.Uri; var credentials = new StorageSharedKeyCredential(Constants.ConnectionStrings.DevStoreAccountName, Constants.ConnectionStrings.DevStoreAccountKey); #pragma warning disable IDE0017 // Simplify object initialization var account = new StorageConnectionString( credentials, blobStorageUri: (blobEndpoint, blobSecondaryEndpoint), queueStorageUri: (queueEndpoint, queueSecondaryEndpoint), tableStorageUri: (tableEndpoint, tableSecondaryEndpoint), fileStorageUri: (default, default) /* fileStorageUri */); #pragma warning restore IDE0017 // Simplify object initialization #pragma warning disable IDE0028 // Simplify collection initialization account.Settings = new Dictionary<string, string>(); #pragma warning restore IDE0028 // Simplify collection initialization account.Settings.Add(Constants.ConnectionStrings.UseDevelopmentSetting, "true"); if (proxyUri != null) { account.Settings.Add(Constants.ConnectionStrings.DevelopmentProxyUriSetting, proxyUri.AbsoluteUri); } account.IsDevStoreAccount = true; return account; } /// <summary> /// Internal implementation of Parse/TryParse. /// </summary> /// <param name="connectionString">The string to parse.</param> /// <param name="accountInformation">The <see cref="StorageConnectionString"/> to return.</param> /// <param name="error">A callback for reporting errors.</param> /// <returns>If true, the parse was successful. Otherwise, false.</returns> internal static bool ParseCore(string connectionString, out StorageConnectionString accountInformation, Action<string> error) { IDictionary<string, string> settings = ParseStringIntoSettings(connectionString, error); // malformed settings string if (settings == null) { accountInformation = null; return false; } // helper method string settingOrDefault(string key) { settings.TryGetValue(key, out var result); return result; } // devstore case if (MatchesSpecification( settings, AllRequired(s_useDevelopmentStorageSetting), Optional(s_developmentStorageProxyUriSetting))) { accountInformation = settings.TryGetValue(Constants.ConnectionStrings.DevelopmentProxyUriSetting, out var proxyUri) ? GetDevelopmentStorageAccount(new Uri(proxyUri)) : DevelopmentStorageAccount; accountInformation.Settings = s_validCredentials(settings); return true; } // non-devstore case ConnectionStringFilter endpointsOptional = Optional( s_blobEndpointSetting, s_blobSecondaryEndpointSetting, s_queueEndpointSetting, s_queueSecondaryEndpointSetting, s_fileEndpointSetting, s_fileSecondaryEndpointSetting, s_tableEndpointSetting, s_tableSecondaryEndpointSetting // not supported but we don't want default connection string from portal to fail ); ConnectionStringFilter primaryEndpointRequired = AtLeastOne( s_blobEndpointSetting, s_queueEndpointSetting, s_fileEndpointSetting, s_tableEndpointSetting ); ConnectionStringFilter secondaryEndpointsOptional = Optional( s_blobSecondaryEndpointSetting, s_queueSecondaryEndpointSetting, s_fileSecondaryEndpointSetting, s_tableSecondaryEndpointSetting ); ConnectionStringFilter automaticEndpointsMatchSpec = MatchesExactly(MatchesAll( MatchesOne( MatchesAll(AllRequired(s_accountKeySetting), Optional(s_accountKeyNameSetting)), // Key + Name, Endpoints optional AllRequired(s_sharedAccessSignatureSetting) // SAS + Name, Endpoints optional ), AllRequired(s_accountNameSetting), // Name required to automatically create URIs endpointsOptional, Optional(s_defaultEndpointsProtocolSetting, s_endpointSuffixSetting) )); ConnectionStringFilter explicitEndpointsMatchSpec = MatchesExactly(MatchesAll( // Any Credentials, Endpoints must be explicitly declared s_validCredentials, primaryEndpointRequired, secondaryEndpointsOptional )); var matchesAutomaticEndpointsSpec = MatchesSpecification(settings, automaticEndpointsMatchSpec); var matchesExplicitEndpointsSpec = MatchesSpecification(settings, explicitEndpointsMatchSpec); if (matchesAutomaticEndpointsSpec || matchesExplicitEndpointsSpec) { if (matchesAutomaticEndpointsSpec && !settings.ContainsKey(Constants.ConnectionStrings.DefaultEndpointsProtocolSetting)) { settings.Add(Constants.ConnectionStrings.DefaultEndpointsProtocolSetting, "https"); } var blobEndpoint = settingOrDefault(Constants.ConnectionStrings.BlobEndpointSetting); var queueEndpoint = settingOrDefault(Constants.ConnectionStrings.QueueEndpointSetting); var tableEndpoint = settingOrDefault(Constants.ConnectionStrings.TableEndpointSetting); var fileEndpoint = settingOrDefault(Constants.ConnectionStrings.FileEndpointSetting); var blobSecondaryEndpoint = settingOrDefault(Constants.ConnectionStrings.BlobSecondaryEndpointSetting); var queueSecondaryEndpoint = settingOrDefault(Constants.ConnectionStrings.QueueSecondaryEndpointSetting); var tableSecondaryEndpoint = settingOrDefault(Constants.ConnectionStrings.TableSecondaryEndpointSetting); var fileSecondaryEndpoint = settingOrDefault(Constants.ConnectionStrings.FileSecondaryEndpointSetting); var sasToken = settingOrDefault(Constants.ConnectionStrings.SharedAccessSignatureSetting); // if secondary is specified, primary must also be specified static bool s_isValidEndpointPair(string primary, string secondary) => !string.IsNullOrWhiteSpace(primary) || /* primary is null, and... */ string.IsNullOrWhiteSpace(secondary); (Uri Primary, Uri Secondary) createStorageUri(string primary, string secondary, string sasToken, Func<IDictionary<string, string>, (Uri Primary, Uri Secondary)> factory) { return !string.IsNullOrWhiteSpace(secondary) && !string.IsNullOrWhiteSpace(primary) ? (CreateUri(primary, sasToken), CreateUri(secondary, sasToken)) : !string.IsNullOrWhiteSpace(primary) ? (CreateUri(primary, sasToken), default) : matchesAutomaticEndpointsSpec && factory != null ? factory(settings) : (default, default); static Uri CreateUri(string endpoint, string sasToken) { var builder = new UriBuilder(endpoint); if (!string.IsNullOrEmpty(builder.Query)) { builder.Query += "&" + sasToken; } else { builder.Query = sasToken; } return builder.Uri; } } if ( s_isValidEndpointPair(blobEndpoint, blobSecondaryEndpoint) && s_isValidEndpointPair(queueEndpoint, queueSecondaryEndpoint) && s_isValidEndpointPair(tableEndpoint, tableSecondaryEndpoint) && s_isValidEndpointPair(fileEndpoint, fileSecondaryEndpoint) ) { accountInformation = new StorageConnectionString( GetCredentials(settings), blobStorageUri: createStorageUri(blobEndpoint, blobSecondaryEndpoint, sasToken, ConstructBlobEndpoint), queueStorageUri: createStorageUri(queueEndpoint, queueSecondaryEndpoint, sasToken, ConstructQueueEndpoint), tableStorageUri: createStorageUri(tableEndpoint, tableSecondaryEndpoint, sasToken, ConstructTableEndpoint), fileStorageUri: createStorageUri(fileEndpoint, fileSecondaryEndpoint, sasToken, ConstructFileEndpoint) ) { EndpointSuffix = settingOrDefault(Constants.ConnectionStrings.EndpointSuffixSetting), Settings = s_validCredentials(settings) }; accountInformation._accountName = settingOrDefault(Constants.ConnectionStrings.AccountNameSetting); return true; } } // not valid accountInformation = null; error("No valid combination of account information found."); return false; } /// <summary> /// Tokenizes input and stores name value pairs. /// </summary> /// <param name="connectionString">The string to parse.</param> /// <param name="error">Error reporting delegate.</param> /// <returns>Tokenized collection.</returns> private static IDictionary<string, string> ParseStringIntoSettings(string connectionString, Action<string> error) { IDictionary<string, string> settings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); var splitted = connectionString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var nameValue in splitted) { var splittedNameValue = nameValue.Split(new char[] { '=' }, 2); if (splittedNameValue.Length != 2) { error("Settings must be of the form \"name=value\"."); return null; } if (settings.ContainsKey(splittedNameValue[0])) { error(string.Format(CultureInfo.InvariantCulture, "Duplicate setting '{0}' found.", splittedNameValue[0])); return null; } settings.Add(splittedNameValue[0], splittedNameValue[1]); } return settings; } /// <summary> /// Encapsulates a validation rule for an enumeration based account setting. /// </summary> /// <param name="name">The name of the setting.</param> /// <param name="validValues">A list of valid values for the setting.</param> /// <returns>An <see cref="AccountSetting"/> representing the enumeration constraint.</returns> private static AccountSetting Setting(string name, params string[] validValues) => new AccountSetting( name, (settingValue) => validValues.Length == 0 ? true : validValues.Contains(settingValue, StringComparer.OrdinalIgnoreCase) ); /// <summary> /// Encapsulates a validation rule using a func. /// </summary> /// <param name="name">The name of the setting.</param> /// <param name="isValid">A func that determines if the value is valid.</param> /// <returns>An <see cref="AccountSetting"/> representing the constraint.</returns> private static AccountSetting Setting(string name, Func<string, bool> isValid) => new AccountSetting(name, isValid); /// <summary> /// Determines whether the specified setting value is a valid base64 string. /// </summary> /// <param name="settingValue">The setting value.</param> /// <returns><c>true</c> if the specified setting value is a valid base64 string; otherwise, <c>false</c>.</returns> private static bool IsValidBase64String(string settingValue) { try { Convert.FromBase64String(settingValue); return true; } catch (FormatException) { return false; } } /// <summary> /// Validation function that validates Uris. /// </summary> /// <param name="settingValue">Value to validate.</param> /// <returns><c>true</c> if the specified setting value is a valid Uri; otherwise, <c>false</c>.</returns> private static bool IsValidUri(string settingValue) => Uri.IsWellFormedUriString(settingValue, UriKind.Absolute); /// <summary> /// Validation function that validates a domain name. /// </summary> /// <param name="settingValue">Value to validate.</param> /// <returns><c>true</c> if the specified setting value is a valid domain; otherwise, <c>false</c>.</returns> private static bool IsValidDomain(string settingValue) => Uri.CheckHostName(settingValue).Equals(UriHostNameType.Dns); /// <summary> /// Settings filter that requires all specified settings be present and valid. /// </summary> /// <param name="requiredSettings">A list of settings that must be present.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter AllRequired(params AccountSetting[] requiredSettings) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); foreach (AccountSetting requirement in requiredSettings) { if (result.TryGetValue(requirement.Key, out var value) && requirement.Value(value)) { result.Remove(requirement.Key); } else { return null; } } return result; }; /// <summary> /// Settings filter that removes optional values. /// </summary> /// <param name="optionalSettings">A list of settings that are optional.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter Optional(params AccountSetting[] optionalSettings) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); foreach (AccountSetting requirement in optionalSettings) { if (result.TryGetValue(requirement.Key, out var value) && requirement.Value(value)) { result.Remove(requirement.Key); } } return result; }; /// <summary> /// Settings filter that ensures that at least one setting is present. /// </summary> /// <param name="atLeastOneSettings">A list of settings of which one must be present.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")] private static ConnectionStringFilter AtLeastOne(params AccountSetting[] atLeastOneSettings) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); var foundOne = false; foreach (AccountSetting requirement in atLeastOneSettings) { if (result.TryGetValue(requirement.Key, out var value) && requirement.Value(value)) { result.Remove(requirement.Key); foundOne = true; } } return foundOne ? result : null; }; /// <summary> /// Settings filter that ensures that none of the specified settings are present. /// </summary> /// <param name="atLeastOneSettings">A list of settings of which one must not be present.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")] private static ConnectionStringFilter None(params AccountSetting[] atLeastOneSettings) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); var foundOne = false; foreach (AccountSetting requirement in atLeastOneSettings) { if (result.TryGetValue(requirement.Key, out var value) && requirement.Value(value)) { foundOne = true; } } return foundOne ? null : result; }; /// <summary> /// Settings filter that ensures that all of the specified filters match. /// </summary> /// <param name="filters">A list of filters of which all must match.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter MatchesAll(params ConnectionStringFilter[] filters) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); foreach (ConnectionStringFilter filter in filters) { if (result == null) { break; } result = filter(result); } return result; }; /// <summary> /// Settings filter that ensures that exactly one filter matches. /// </summary> /// <param name="filters">A list of filters of which exactly one must match.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter MatchesOne(params ConnectionStringFilter[] filters) => (settings) => { IDictionary<string, string>[] results = filters .Select(filter => filter(new Dictionary<string, string>(settings))) .Where(result => result != null) .Take(2) .ToArray(); return results.Length != 1 ? null : results.First(); }; /// <summary> /// Settings filter that ensures that the specified filter is an exact match. /// </summary> /// <param name="filter">A list of filters of which ensures that the specified filter is an exact match.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter MatchesExactly(ConnectionStringFilter filter) => (settings) => { IDictionary<string, string> results = filter(settings); return results == null || results.Any() ? null : results; }; /// <summary> /// Settings filter that ensures that a valid combination of credentials is present. /// </summary> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static readonly ConnectionStringFilter s_validCredentials = MatchesOne( MatchesAll(AllRequired(s_accountNameSetting, s_accountKeySetting), Optional(s_accountKeyNameSetting), None(s_sharedAccessSignatureSetting)), // AccountAndKey MatchesAll(AllRequired(s_sharedAccessSignatureSetting), Optional(s_accountNameSetting), None(s_accountKeySetting, s_accountKeyNameSetting)), // SharedAccessSignature (AccountName optional) None(s_accountNameSetting, s_accountKeySetting, s_accountKeyNameSetting, s_sharedAccessSignatureSetting) // Anonymous ); /// <summary> /// Tests to see if a given list of settings matches a set of filters exactly. /// </summary> /// <param name="settings">The settings to check.</param> /// <param name="constraints">A list of filters to check.</param> /// <returns> /// If any filter returns null, false. /// If there are any settings left over after all filters are processed, false. /// Otherwise true. /// </returns> private static bool MatchesSpecification( IDictionary<string, string> settings, params ConnectionStringFilter[] constraints) { foreach (ConnectionStringFilter constraint in constraints) { IDictionary<string, string> remainingSettings = constraint(settings); if (remainingSettings == null) { return false; } else { settings = remainingSettings; } } return !settings.Any(); } /// <summary> /// Gets a StorageCredentials object corresponding to whatever credentials are supplied in the given settings. /// </summary> /// <param name="settings">The settings to check.</param> /// <returns>The StorageCredentials object specified in the settings.</returns> private static object GetCredentials(IDictionary<string, string> settings) { settings.TryGetValue(Constants.ConnectionStrings.AccountNameSetting, out var accountName); settings.TryGetValue(Constants.ConnectionStrings.AccountKeySetting, out var accountKey); settings.TryGetValue(Constants.ConnectionStrings.SharedAccessSignatureSetting, out var sharedAccessSignature); // The accountKeyName isn't used //settings.TryGetValue(Constants.ConnectionStrings.AccountKeyNameSetting, out var accountKeyName); return accountName != null && accountKey != null && sharedAccessSignature == null ? new StorageSharedKeyCredential(accountName, accountKey/*, accountKeyName */) : (object)(accountKey == null /* && accountKeyName == null */ && sharedAccessSignature != null ? new SharedAccessSignatureCredentials(sharedAccessSignature) : null); } /// <summary> /// Gets the default blob endpoint using specified settings. /// </summary> /// <param name="settings">The settings to use.</param> /// <returns>The default blob endpoint.</returns> private static (Uri Primary, Uri Secondary) ConstructBlobEndpoint(IDictionary<string, string> settings) => ConstructBlobEndpoint( settings[Constants.ConnectionStrings.DefaultEndpointsProtocolSetting], settings[Constants.ConnectionStrings.AccountNameSetting], settings.ContainsKey(Constants.ConnectionStrings.EndpointSuffixSetting) ? settings[Constants.ConnectionStrings.EndpointSuffixSetting] : null, settings.ContainsKey(Constants.ConnectionStrings.SharedAccessSignatureSetting) ? settings[Constants.ConnectionStrings.SharedAccessSignatureSetting] : null); /// <summary> /// Gets the default blob endpoint using the specified protocol and account name. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns>The default blob endpoint.</returns> internal static (Uri Primary, Uri Secondary) ConstructBlobEndpoint(string scheme, string accountName, string endpointSuffix, string sasToken) { if (string.IsNullOrEmpty(scheme)) { throw Errors.ArgumentNull(nameof(scheme)); } if (string.IsNullOrEmpty(accountName)) { throw Errors.ArgumentNull(nameof(accountName)); } if (string.IsNullOrEmpty(endpointSuffix)) { endpointSuffix = Constants.ConnectionStrings.DefaultEndpointSuffix; } return ConstructUris(scheme, accountName, Constants.ConnectionStrings.DefaultBlobHostnamePrefix, endpointSuffix, sasToken); } /// <summary> /// Gets the default file endpoint using specified settings. /// </summary> /// <param name="settings">The settings to use.</param> /// <returns>The default file endpoint.</returns> private static (Uri Primary, Uri Secondary) ConstructFileEndpoint(IDictionary<string, string> settings) => ConstructFileEndpoint( settings[Constants.ConnectionStrings.DefaultEndpointsProtocolSetting], settings[Constants.ConnectionStrings.AccountNameSetting], settings.ContainsKey(Constants.ConnectionStrings.EndpointSuffixSetting) ? settings[Constants.ConnectionStrings.EndpointSuffixSetting] : null, settings.ContainsKey(Constants.ConnectionStrings.SharedAccessSignatureSetting) ? settings[Constants.ConnectionStrings.SharedAccessSignatureSetting] : null); /// <summary> /// Gets the default file endpoint using the specified protocol and account name. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns>The default file endpoint.</returns> internal static (Uri Primary, Uri Secondary) ConstructFileEndpoint(string scheme, string accountName, string endpointSuffix, string sasToken) { if (string.IsNullOrEmpty(scheme)) { throw Errors.ArgumentNull(nameof(scheme)); } if (string.IsNullOrEmpty(accountName)) { throw Errors.ArgumentNull(nameof(accountName)); } if (string.IsNullOrEmpty(endpointSuffix)) { endpointSuffix = Constants.ConnectionStrings.DefaultEndpointSuffix; } return ConstructUris(scheme, accountName, Constants.ConnectionStrings.DefaultFileHostnamePrefix, endpointSuffix, sasToken); } /// <summary> /// Gets the default queue endpoint using the specified settings. /// </summary> /// <param name="settings">The settings.</param> /// <returns>The default queue endpoint.</returns> private static (Uri Primary, Uri Secondary) ConstructQueueEndpoint(IDictionary<string, string> settings) => ConstructQueueEndpoint( settings[Constants.ConnectionStrings.DefaultEndpointsProtocolSetting], settings[Constants.ConnectionStrings.AccountNameSetting], settings.ContainsKey(Constants.ConnectionStrings.EndpointSuffixSetting) ? settings[Constants.ConnectionStrings.EndpointSuffixSetting] : null, settings.ContainsKey(Constants.ConnectionStrings.SharedAccessSignatureSetting) ? settings[Constants.ConnectionStrings.SharedAccessSignatureSetting] : null); /// <summary> /// Gets the default queue endpoint using the specified protocol and account name. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns>The default queue endpoint.</returns> internal static (Uri Primary, Uri Secondary) ConstructQueueEndpoint(string scheme, string accountName, string endpointSuffix, string sasToken) { if (string.IsNullOrEmpty(scheme)) { throw Errors.ArgumentNull(nameof(scheme)); } if (string.IsNullOrEmpty(accountName)) { throw Errors.ArgumentNull(nameof(accountName)); } if (string.IsNullOrEmpty(endpointSuffix)) { endpointSuffix = Constants.ConnectionStrings.DefaultEndpointSuffix; } return ConstructUris(scheme, accountName, Constants.ConnectionStrings.DefaultQueueHostnamePrefix, endpointSuffix, sasToken); } /// <summary> /// Gets the default table endpoint using the specified settings. /// </summary> /// <param name="settings">The settings.</param> /// <returns>The default table endpoint.</returns> private static (Uri Primary, Uri Secondary) ConstructTableEndpoint(IDictionary<string, string> settings) => ConstructTableEndpoint( settings[Constants.ConnectionStrings.DefaultEndpointsProtocolSetting], settings[Constants.ConnectionStrings.AccountNameSetting], settings.ContainsKey(Constants.ConnectionStrings.EndpointSuffixSetting) ? settings[Constants.ConnectionStrings.EndpointSuffixSetting] : null, settings.ContainsKey(Constants.ConnectionStrings.SharedAccessSignatureSetting) ? settings[Constants.ConnectionStrings.SharedAccessSignatureSetting] : null); /// <summary> /// Gets the default queue endpoint using the specified protocol and account name. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns>The default table endpoint.</returns> internal static (Uri Primary, Uri Secondary) ConstructTableEndpoint(string scheme, string accountName, string endpointSuffix, string sasToken) { if (string.IsNullOrEmpty(scheme)) { throw Errors.ArgumentNull(nameof(scheme)); } if (string.IsNullOrEmpty(accountName)) { throw Errors.ArgumentNull(nameof(accountName)); } if (string.IsNullOrEmpty(endpointSuffix)) { endpointSuffix = Constants.ConnectionStrings.DefaultEndpointSuffix; } return ConstructUris(scheme, accountName, Constants.ConnectionStrings.DefaultTableHostnamePrefix, endpointSuffix, sasToken); } /// <summary> /// Construct the Primary/Secondary Uri tuple. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="hostNamePrefix">Prefix that appears before the host name, e.g. "blob".</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns></returns> private static (Uri Primary, Uri Secondary) ConstructUris( string scheme, string accountName, string hostNamePrefix, string endpointSuffix, string sasToken) { var primaryUriBuilder = new UriBuilder { Scheme = scheme, Host = string.Format( CultureInfo.InvariantCulture, "{0}.{1}.{2}", accountName, hostNamePrefix, endpointSuffix), Query = sasToken }; var secondaryUriBuilder = new UriBuilder { Scheme = scheme, Host = string.Format( CultureInfo.InvariantCulture, "{0}{1}.{2}.{3}", accountName, Constants.ConnectionStrings.SecondaryLocationAccountSuffix, hostNamePrefix, endpointSuffix), Query = sasToken }; return (primaryUriBuilder.Uri, secondaryUriBuilder.Uri); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ObjectCreationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { public ObjectCreationExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new ObjectCreationExpressionSignatureHelpProvider(); } #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParameters() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> C() { } void Foo() { C c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", "Summary for C", null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param a", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParen() { var markup = @" class C { void foo() { var c = [|new C($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParenWithParameters() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParenWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnLambda() { var markup = @" using System; class C { void foo() { var bar = [|new Action<int, int>($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Action<int, int>(void (int, int) target)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(b: string.Empty, $$a: 2|]); } }"; await VerifyCurrentParameterNameAsync(markup, "a"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParens() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2,$$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, string b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2, $$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableAlways() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableNever() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableAdvanced() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableMixed() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(long y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(long y)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif void foo() { var x = new D($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif #if BAR void foo() { var x = new D($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // new foo($$"; await TestAsync(markup); } [WorkItem(1078993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078993")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestSigHelpInIncorrectObjectCreationExpression() { var markup = @" class C { void foo(C c) { foo([|new C{$$|] } }"; await TestAsync(markup); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Census Student Validation Data Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SCEN_STVDataSet : EduHubDataSet<SCEN_STV> { /// <inheritdoc /> public override string Name { get { return "SCEN_STV"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return false; } } internal SCEN_STVDataSet(EduHubContext Context) : base(Context) { Index_ID = new Lazy<Dictionary<int, SCEN_STV>>(() => this.ToDictionary(i => i.ID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SCEN_STV" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SCEN_STV" /> fields for each CSV column header</returns> internal override Action<SCEN_STV, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SCEN_STV, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "ID": mapper[i] = (e, v) => e.ID = int.Parse(v); break; case "STKEY": mapper[i] = (e, v) => e.STKEY = v; break; case "REGISTRATION": mapper[i] = (e, v) => e.REGISTRATION = v == null ? (short?)null : short.Parse(v); break; case "ID_STUDENTVALIDATIONTYPE": mapper[i] = (e, v) => e.ID_STUDENTVALIDATIONTYPE = v == null ? (short?)null : short.Parse(v); break; case "FIELDVALUES": mapper[i] = (e, v) => e.FIELDVALUES = v; break; case "STATUS": mapper[i] = (e, v) => e.STATUS = v; break; case "CREATEUSER": mapper[i] = (e, v) => e.CREATEUSER = v; break; case "CREATED": mapper[i] = (e, v) => e.CREATED = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LUPDATEUSER": mapper[i] = (e, v) => e.LUPDATEUSER = v; break; case "LUPDATED": mapper[i] = (e, v) => e.LUPDATED = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SCEN_STV" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SCEN_STV" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SCEN_STV" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SCEN_STV}"/> of entities</returns> internal override IEnumerable<SCEN_STV> ApplyDeltaEntities(IEnumerable<SCEN_STV> Entities, List<SCEN_STV> DeltaEntities) { HashSet<int> Index_ID = new HashSet<int>(DeltaEntities.Select(i => i.ID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.ID; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_ID.Remove(entity.ID); if (entity.ID.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, SCEN_STV>> Index_ID; #endregion #region Index Methods /// <summary> /// Find SCEN_STV by ID field /// </summary> /// <param name="ID">ID value used to find SCEN_STV</param> /// <returns>Related SCEN_STV entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SCEN_STV FindByID(int ID) { return Index_ID.Value[ID]; } /// <summary> /// Attempt to find SCEN_STV by ID field /// </summary> /// <param name="ID">ID value used to find SCEN_STV</param> /// <param name="Value">Related SCEN_STV entity</param> /// <returns>True if the related SCEN_STV entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByID(int ID, out SCEN_STV Value) { return Index_ID.Value.TryGetValue(ID, out Value); } /// <summary> /// Attempt to find SCEN_STV by ID field /// </summary> /// <param name="ID">ID value used to find SCEN_STV</param> /// <returns>Related SCEN_STV entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SCEN_STV TryFindByID(int ID) { SCEN_STV value; if (Index_ID.Value.TryGetValue(ID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SCEN_STV table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SCEN_STV]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SCEN_STV]( [ID] int IDENTITY NOT NULL, [STKEY] varchar(10) NULL, [REGISTRATION] smallint NULL, [ID_STUDENTVALIDATIONTYPE] smallint NULL, [FIELDVALUES] varchar(255) NULL, [STATUS] varchar(1) NULL, [CREATEUSER] varchar(128) NULL, [CREATED] datetime NULL, [LUPDATEUSER] varchar(128) NULL, [LUPDATED] datetime NULL, CONSTRAINT [SCEN_STV_Index_ID] PRIMARY KEY CLUSTERED ( [ID] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="SCEN_STVDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="SCEN_STVDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SCEN_STV"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SCEN_STV"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SCEN_STV> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_ID = new List<int>(); foreach (var entity in Entities) { Index_ID.Add(entity.ID); } builder.AppendLine("DELETE [dbo].[SCEN_STV] WHERE"); // Index_ID builder.Append("[ID] IN ("); for (int index = 0; index < Index_ID.Count; index++) { if (index != 0) builder.Append(", "); // ID var parameterID = $"@p{parameterIndex++}"; builder.Append(parameterID); command.Parameters.Add(parameterID, SqlDbType.Int).Value = Index_ID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SCEN_STV data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SCEN_STV data set</returns> public override EduHubDataSetDataReader<SCEN_STV> GetDataSetDataReader() { return new SCEN_STVDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SCEN_STV data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SCEN_STV data set</returns> public override EduHubDataSetDataReader<SCEN_STV> GetDataSetDataReader(List<SCEN_STV> Entities) { return new SCEN_STVDataReader(new EduHubDataSetLoadedReader<SCEN_STV>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SCEN_STVDataReader : EduHubDataSetDataReader<SCEN_STV> { public SCEN_STVDataReader(IEduHubDataSetReader<SCEN_STV> Reader) : base (Reader) { } public override int FieldCount { get { return 10; } } public override object GetValue(int i) { switch (i) { case 0: // ID return Current.ID; case 1: // STKEY return Current.STKEY; case 2: // REGISTRATION return Current.REGISTRATION; case 3: // ID_STUDENTVALIDATIONTYPE return Current.ID_STUDENTVALIDATIONTYPE; case 4: // FIELDVALUES return Current.FIELDVALUES; case 5: // STATUS return Current.STATUS; case 6: // CREATEUSER return Current.CREATEUSER; case 7: // CREATED return Current.CREATED; case 8: // LUPDATEUSER return Current.LUPDATEUSER; case 9: // LUPDATED return Current.LUPDATED; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // STKEY return Current.STKEY == null; case 2: // REGISTRATION return Current.REGISTRATION == null; case 3: // ID_STUDENTVALIDATIONTYPE return Current.ID_STUDENTVALIDATIONTYPE == null; case 4: // FIELDVALUES return Current.FIELDVALUES == null; case 5: // STATUS return Current.STATUS == null; case 6: // CREATEUSER return Current.CREATEUSER == null; case 7: // CREATED return Current.CREATED == null; case 8: // LUPDATEUSER return Current.LUPDATEUSER == null; case 9: // LUPDATED return Current.LUPDATED == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // ID return "ID"; case 1: // STKEY return "STKEY"; case 2: // REGISTRATION return "REGISTRATION"; case 3: // ID_STUDENTVALIDATIONTYPE return "ID_STUDENTVALIDATIONTYPE"; case 4: // FIELDVALUES return "FIELDVALUES"; case 5: // STATUS return "STATUS"; case 6: // CREATEUSER return "CREATEUSER"; case 7: // CREATED return "CREATED"; case 8: // LUPDATEUSER return "LUPDATEUSER"; case 9: // LUPDATED return "LUPDATED"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "ID": return 0; case "STKEY": return 1; case "REGISTRATION": return 2; case "ID_STUDENTVALIDATIONTYPE": return 3; case "FIELDVALUES": return 4; case "STATUS": return 5; case "CREATEUSER": return 6; case "CREATED": return 7; case "LUPDATEUSER": return 8; case "LUPDATED": return 9; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// // DatabaseTrackInfo.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007 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.Generic; using System.Data; using System.IO; using Hyena; using Hyena.Data; using Hyena.Data.Sqlite; using Hyena.Query; using Banshee.Base; using Banshee.Configuration.Schema; using Banshee.Database; using Banshee.Metadata; using Banshee.Preferences; using Banshee.Query; using Banshee.Sources; using Banshee.Library; using Banshee.ServiceStack; using Banshee.Streaming; // Disabling "is never used" warnings here because there are a lot // of properties/fields that are set via reflection at the database // layer - that is, they really are used, but the compiler doesn't // think so. #pragma warning disable 0169 namespace Banshee.Collection.Database { public class DatabaseTrackInfo : TrackInfo { private static DatabaseTrackModelProvider<DatabaseTrackInfo> provider; public static DatabaseTrackModelProvider<DatabaseTrackInfo> Provider { get { return provider ?? (provider = new DatabaseTrackModelProvider<DatabaseTrackInfo> (ServiceManager.DbConnection)); } } private bool artist_changed = false, album_changed = false; public DatabaseTrackInfo () : base () { } public DatabaseTrackInfo (DatabaseTrackInfo original) : base () { Provider.Copy (original, this); } // Changing these fields shouldn't change DateUpdated (which triggers file save) private static readonly HashSet<QueryField> transient_fields; static DatabaseTrackInfo () { transient_fields = new HashSet<QueryField> () { BansheeQuery.ScoreField, BansheeQuery.SkipCountField, BansheeQuery.LastSkippedField, BansheeQuery.LastPlayedField, BansheeQuery.PlaybackErrorField, BansheeQuery.PlayCountField, BansheeQuery.RatingField }; Action<Root> handler = delegate { if (SaveTrackMetadataService.WriteRatingsAndPlayCountsEnabled.Value) { transient_fields.Remove (BansheeQuery.PlayCountField); transient_fields.Remove (BansheeQuery.RatingField); } else { transient_fields.Add (BansheeQuery.PlayCountField); transient_fields.Add (BansheeQuery.RatingField); } }; SaveTrackMetadataService.WriteRatingsAndPlayCountsEnabled.ValueChanged += handler; handler (null); } public override void OnPlaybackFinished (double percentCompleted) { if (ProviderRefresh()) { base.OnPlaybackFinished (percentCompleted); Save (true, BansheeQuery.ScoreField, BansheeQuery.SkipCountField, BansheeQuery.LastSkippedField, BansheeQuery.PlayCountField, BansheeQuery.LastPlayedField); } } public override bool TrackEqual (TrackInfo track) { if (PrimarySource != null && PrimarySource.TrackEqualHandler != null) { return PrimarySource.TrackEqualHandler (this, track); } DatabaseTrackInfo db_track = track as DatabaseTrackInfo; if (db_track == null) { return base.TrackEqual (track); } return TrackEqual (this, db_track); } public override string ArtworkId { get { if (PrimarySource != null && PrimarySource.TrackArtworkIdHandler != null) { return PrimarySource.TrackArtworkIdHandler (this); } return base.ArtworkId; } } public override bool IsPlaying { get { if (PrimarySource != null && PrimarySource.TrackIsPlayingHandler != null) { return PrimarySource.TrackIsPlayingHandler (this); } return base.IsPlaying; } } public static bool TrackEqual (DatabaseTrackInfo a, DatabaseTrackInfo b) { return a != null && b != null && a.TrackId == b.TrackId; } public DatabaseArtistInfo Artist { get { return DatabaseArtistInfo.FindOrCreate (ArtistName, ArtistNameSort, ArtistMusicBrainzId); } } public DatabaseAlbumInfo Album { get { return DatabaseAlbumInfo.FindOrCreate ( DatabaseArtistInfo.FindOrCreate (AlbumArtist, AlbumArtistSort, ArtistMusicBrainzId), AlbumTitle, AlbumTitleSort, IsCompilation, AlbumMusicBrainzId); } } private static bool notify_saved = true; public static bool NotifySaved { get { return notify_saved; } set { notify_saved = value; } } public override void Save () { Save (NotifySaved); } public override void UpdateLastPlayed () { Refresh (); base.UpdateLastPlayed (); Save (NotifySaved, BansheeQuery.LastPlayedField); } public void Save (bool notify, params QueryField [] fields_changed) { // If either the artist or album changed, if (ArtistId == 0 || AlbumId == 0 || artist_changed == true || album_changed == true) { DatabaseArtistInfo artist = Artist; ArtistId = artist.DbId; DatabaseAlbumInfo album = Album; AlbumId = album.DbId; // TODO get rid of unused artists/albums } // If PlayCountField is not transient we still want to update the file only if it's from the music library var transient = transient_fields; if (!transient.Contains (BansheeQuery.PlayCountField) && !ServiceManager.SourceManager.MusicLibrary.Equals (PrimarySource)) { transient = new HashSet<QueryField> (transient_fields); transient.Add (BansheeQuery.PlayCountField); } if (fields_changed.Length == 0 || !transient.IsSupersetOf (fields_changed)) { DateUpdated = DateTime.Now; } bool is_new = (TrackId == 0); if (is_new) { DateAdded = DateUpdated = DateTime.Now; } ProviderSave (); if (notify && PrimarySource != null) { if (is_new) { PrimarySource.NotifyTracksAdded (); } else { PrimarySource.NotifyTracksChanged (fields_changed); } } } protected virtual void ProviderSave () { Provider.Save (this); } public void Refresh () { ProviderRefresh (); } protected virtual bool ProviderRefresh () { return Provider.Refresh (this); } private int track_id; [DatabaseColumn ("TrackID", Constraints = DatabaseColumnConstraints.PrimaryKey)] public int TrackId { get { return track_id; } protected set { track_id = value; } } private int primary_source_id; [DatabaseColumn ("PrimarySourceID")] public int PrimarySourceId { get { return primary_source_id; } set { primary_source_id = value; } } public PrimarySource PrimarySource { get { return PrimarySource.GetById (primary_source_id); } set { PrimarySourceId = value.DbId; } } private int artist_id; [DatabaseColumn ("ArtistID")] public int ArtistId { get { return artist_id; } set { artist_id = value; } } private int album_id; [DatabaseColumn ("AlbumID")] public int AlbumId { get { return album_id; } set { album_id = value; } } [VirtualDatabaseColumn ("Name", "CoreArtists", "ArtistID", "ArtistID")] protected string ArtistNameField { get { return ArtistName; } set { base.ArtistName = value; } } public override string ArtistName { get { return base.ArtistName; } set { value = CleanseString (value, ArtistName); if (value == null) return; base.ArtistName = value; artist_changed = true; } } [VirtualDatabaseColumn ("NameSort", "CoreArtists", "ArtistID", "ArtistID")] protected string ArtistNameSortField { get { return ArtistNameSort; } set { base.ArtistNameSort = value; } } public override string ArtistNameSort { get { return base.ArtistNameSort; } set { value = CleanseString (value, ArtistNameSort); if (value == null) return; base.ArtistNameSort = value; artist_changed = true; } } [VirtualDatabaseColumn ("Title", "CoreAlbums", "AlbumID", "AlbumID")] protected string AlbumTitleField { get { return AlbumTitle; } set { base.AlbumTitle = value; } } public override string AlbumTitle { get { return base.AlbumTitle; } set { value = CleanseString (value, AlbumTitle); if (value == null) return; base.AlbumTitle = value; album_changed = true; } } [VirtualDatabaseColumn ("TitleSort", "CoreAlbums", "AlbumID", "AlbumID")] protected string AlbumTitleSortField { get { return AlbumTitleSort; } set { base.AlbumTitleSort = value; } } public override string AlbumTitleSort { get { return base.AlbumTitleSort; } set { value = CleanseString (value, AlbumTitleSort); if (value == null) return; base.AlbumTitleSort = value; album_changed = true; } } [VirtualDatabaseColumn ("ArtistName", "CoreAlbums", "AlbumID", "AlbumID")] protected string AlbumArtistField { get { return AlbumArtist; } set { base.AlbumArtist = value; } } public override string AlbumArtist { get { return base.AlbumArtist; } set { value = CleanseString (value, AlbumArtist); if (value == null) return; base.AlbumArtist = value; album_changed = true; } } [VirtualDatabaseColumn ("ArtistNameSort", "CoreAlbums", "AlbumID", "AlbumID")] protected string AlbumArtistSortField { get { return AlbumArtistSort; } set { base.AlbumArtistSort = value; } } public override string AlbumArtistSort { get { return base.AlbumArtistSort; } set { value = CleanseString (value, AlbumArtistSort); if (value == null) return; base.AlbumArtistSort = value; album_changed = true; } } [VirtualDatabaseColumn ("IsCompilation", "CoreAlbums", "AlbumID", "AlbumID")] protected bool IsCompilationField { get { return IsCompilation; } set { base.IsCompilation = value; } } public override bool IsCompilation { get { return base.IsCompilation; } set { base.IsCompilation = value; album_changed = true; } } private static string CleanseString (string input, string old_val) { if (input == old_val) return null; if (input != null) input = input.Trim (); if (input == old_val) return null; return input; } private int tag_set_id; [DatabaseColumn] public int TagSetID { get { return tag_set_id; } set { tag_set_id = value; } } [DatabaseColumn ("MusicBrainzID")] public override string MusicBrainzId { get { return base.MusicBrainzId; } set { base.MusicBrainzId = value; } } [VirtualDatabaseColumn ("MusicBrainzID", "CoreAlbums", "AlbumID", "AlbumID")] protected string AlbumMusicBrainzIdField { get { return base.AlbumMusicBrainzId; } set { base.AlbumMusicBrainzId = value; } } public override string AlbumMusicBrainzId { get { return base.AlbumMusicBrainzId; } set { value = CleanseString (value, AlbumMusicBrainzId); if (value == null) return; base.AlbumMusicBrainzId = value; album_changed = true; } } [VirtualDatabaseColumn ("MusicBrainzID", "CoreArtists", "ArtistID", "ArtistID")] protected string ArtistMusicBrainzIdField { get { return base.ArtistMusicBrainzId; } set { base.ArtistMusicBrainzId = value; } } public override string ArtistMusicBrainzId { get { return base.ArtistMusicBrainzId; } set { value = CleanseString (value, ArtistMusicBrainzId); if (value == null) return; base.ArtistMusicBrainzId = value; artist_changed = true; } } [DatabaseColumn ("Uri")] protected string UriField { get { return Uri == null ? null : Uri.AbsoluteUri; } set { Uri = value == null ? null : new SafeUri (value); } } [DatabaseColumn] public override string MimeType { get { return base.MimeType; } set { base.MimeType = value; } } [DatabaseColumn] public override long FileSize { get { return base.FileSize; } set { base.FileSize = value; } } [DatabaseColumn] public override long FileModifiedStamp { get { return base.FileModifiedStamp; } set { base.FileModifiedStamp = value; } } [DatabaseColumn] public override DateTime LastSyncedStamp { get { return base.LastSyncedStamp; } set { base.LastSyncedStamp = value; } } [DatabaseColumn ("Attributes")] public override TrackMediaAttributes MediaAttributes { get { return base.MediaAttributes; } set { base.MediaAttributes = value; } } [DatabaseColumn ("Title")] public override string TrackTitle { get { return base.TrackTitle; } set { base.TrackTitle = value; } } [DatabaseColumn ("TitleSort")] public override string TrackTitleSort { get { return base.TrackTitleSort; } set { base.TrackTitleSort = value; } } [DatabaseColumn("TitleSortKey", Select = false)] internal byte[] TrackTitleSortKey { get { return Hyena.StringUtil.SortKey (TrackTitleSort ?? DisplayTrackTitle); } } [DatabaseColumn(Select = false)] internal string TitleLowered { get { return Hyena.StringUtil.SearchKey (DisplayTrackTitle); } } [DatabaseColumn(Select = false)] public override string MetadataHash { get { return base.MetadataHash; } } [DatabaseColumn] public override int TrackNumber { get { return base.TrackNumber; } set { base.TrackNumber = value; } } [DatabaseColumn] public override int TrackCount { get { return base.TrackCount; } set { base.TrackCount = value; } } [DatabaseColumn ("Disc")] public override int DiscNumber { get { return base.DiscNumber; } set { base.DiscNumber = value; } } [DatabaseColumn] public override int DiscCount { get { return base.DiscCount; } set { base.DiscCount = value; } } [DatabaseColumn] public override TimeSpan Duration { get { return base.Duration; } set { base.Duration = value; } } [DatabaseColumn] public override int Year { get { return base.Year; } set { base.Year = value; } } [DatabaseColumn] public override string Genre { get { return base.Genre; } set { base.Genre = value; } } [DatabaseColumn] public override string Composer { get { return base.Composer; } set { base.Composer = value; } } [DatabaseColumn] public override string Conductor { get { return base.Conductor; } set { base.Conductor = value; } } [DatabaseColumn] public override string Grouping { get { return base.Grouping; } set { base.Grouping = value; } } [DatabaseColumn] public override string Copyright { get { return base.Copyright; } set { base.Copyright = value; } } [DatabaseColumn] public override string LicenseUri { get { return base.LicenseUri; } set { base.LicenseUri = value; } } [DatabaseColumn] public override string Comment { get { return base.Comment; } set { base.Comment = value; } } [DatabaseColumn("BPM")] public override int Bpm { get { return base.Bpm; } set { base.Bpm = value; } } [DatabaseColumn] public override int BitRate { get { return base.BitRate; } set { base.BitRate = value; } } [DatabaseColumn] public override int SampleRate { get { return base.SampleRate; } set { base.SampleRate = value; } } [DatabaseColumn] public override int BitsPerSample { get { return base.BitsPerSample; } set { base.BitsPerSample = value; } } [DatabaseColumn("Rating")] protected int rating; public override int Rating { get { return rating; } set { rating = value; } } [DatabaseColumn] public override int Score { get { return base.Score; } set { base.Score = value; } } public int SavedRating { get { return rating; } set { if (rating != value) { rating = value; Save (true, BansheeQuery.RatingField); } } } [DatabaseColumn] public override int PlayCount { get { return base.PlayCount; } set { base.PlayCount = value; } } [DatabaseColumn] public override int SkipCount { get { return base.SkipCount; } set { base.SkipCount = value; } } private long external_id; [DatabaseColumn ("ExternalID")] public long ExternalId { get { return external_id; } set { external_id = value; } } private object external_object; public override object ExternalObject { get { if (external_id > 0 && external_object == null && PrimarySource != null && PrimarySource.TrackExternalObjectHandler != null) { external_object = PrimarySource.TrackExternalObjectHandler (this); } return external_object; } } [DatabaseColumn ("LastPlayedStamp")] public override DateTime LastPlayed { get { return base.LastPlayed; } set { base.LastPlayed = value; } } [DatabaseColumn ("LastSkippedStamp")] public override DateTime LastSkipped { get { return base.LastSkipped; } set { base.LastSkipped = value; } } [DatabaseColumn ("DateAddedStamp")] public override DateTime DateAdded { get { return base.DateAdded; } set { base.DateAdded = value; } } private DateTime date_updated; [DatabaseColumn ("DateUpdatedStamp")] public DateTime DateUpdated { get { return date_updated; } set { date_updated = value; } } [DatabaseColumn ("LastStreamError")] protected StreamPlaybackError playback_error; public override StreamPlaybackError PlaybackError { get { return playback_error; } set { if (playback_error == value) { return; } playback_error = value; } } public PathPattern PathPattern { get { var src = PrimarySource; var pattern = src == null ? null : src.PathPattern; return pattern ?? MusicLibrarySource.MusicFileNamePattern; } } public bool CopyToLibraryIfAppropriate (bool force_copy) { bool copy_success = true; SafeUri old_uri = this.Uri; if (old_uri == null) { // Get out quick, no URI set yet. return copy_success; } bool in_library = old_uri.IsLocalPath ? old_uri.AbsolutePath.StartsWith (PrimarySource.BaseDirectoryWithSeparator) : false; if (!in_library && (LibrarySchema.CopyOnImport.Get () || force_copy)) { string new_filename = PathPattern.BuildFull (PrimarySource.BaseDirectory, this, Path.GetExtension (old_uri.ToString ())); SafeUri new_uri = new SafeUri (new_filename); try { if (Banshee.IO.File.Exists (new_uri)) { if (Banshee.IO.File.GetSize (old_uri) == Banshee.IO.File.GetSize (new_uri)) { Hyena.Log.DebugFormat ("Not copying {0} to library because there is already a file of same size at {1}", old_uri, new_uri); copy_success = false; return copy_success; } else { string extension = Path.GetExtension (new_filename); string filename_no_ext = new_filename.Remove (new_filename.Length - extension.Length); int duplicate_index = 1; while (Banshee.IO.File.Exists (new_uri)) { new_filename = String.Format ("{0} ({1}){2}", filename_no_ext, duplicate_index, extension); new_uri = new SafeUri (new_filename); duplicate_index++; } } } Banshee.IO.File.Copy (old_uri, new_uri, false); Uri = new_uri; } catch (Exception e) { Log.ErrorFormat ("Exception copying into library: {0}", e); } } return copy_success; } private static HyenaSqliteCommand get_uri_id_cmd = new HyenaSqliteCommand ("SELECT TrackID FROM CoreTracks WHERE Uri = ? LIMIT 1"); public static int GetTrackIdForUri (string uri) { return ServiceManager.DbConnection.Query<int> (get_uri_id_cmd, new SafeUri (uri).AbsoluteUri); } private static HyenaSqliteCommand get_track_id_by_uri = new HyenaSqliteCommand ( "SELECT TrackID FROM CoreTracks WHERE PrimarySourceId IN (?) AND Uri = ? LIMIT 1" ); public static int GetTrackIdForUri (SafeUri uri, int [] primary_sources) { return ServiceManager.DbConnection.Query<int> (get_track_id_by_uri, primary_sources, uri.AbsoluteUri); } public static int GetTrackIdForUri (string absoluteUri, int [] primary_sources) { return ServiceManager.DbConnection.Query<int> (get_track_id_by_uri, primary_sources, absoluteUri); } public static bool ContainsUri (SafeUri uri, int [] primary_sources) { return GetTrackIdForUri (uri, primary_sources) > 0; } public static void UpdateMetadataHash (string albumTitle, string artistName, string condition) { // Keep this field set/order in sync with MetadataHash in TrackInfo.cs ServiceManager.DbConnection.Execute (String.Format ( @"UPDATE CoreTracks SET MetadataHash = HYENA_MD5 (6, ?, ?, Genre, Title, TrackNumber, Year) WHERE {0}", condition), albumTitle, artistName ); } } } #pragma warning restore 0169
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Compatibility; namespace NUnit.Framework.Constraints { /// <summary> /// EqualConstraint is able to compare an actual value with the /// expected value provided in its constructor. Two objects are /// considered equal if both are null, or if both have the same /// value. NUnit has special semantics for some object types. /// </summary> public class EqualConstraint : Constraint { #region Static and Instance Fields private readonly object _expected; private Tolerance _tolerance = Tolerance.Default; /// <summary> /// NUnitEqualityComparer used to test equality. /// </summary> private NUnitEqualityComparer _comparer = new NUnitEqualityComparer(); #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="EqualConstraint"/> class. /// </summary> /// <param name="expected">The expected value.</param> public EqualConstraint(object expected) : base(expected) { AdjustArgumentIfNeeded(ref expected); _expected = expected; ClipStrings = true; } #endregion #region Properties // TODO: Remove public properties // They are only used by EqualConstraintResult // EqualConstraint should inject them into the constructor. /// <summary> /// Gets the tolerance for this comparison. /// </summary> /// <value> /// The tolerance. /// </value> public Tolerance Tolerance { get { return _tolerance; } } /// <summary> /// Gets a value indicating whether to compare case insensitive. /// </summary> /// <value> /// <c>true</c> if comparing case insensitive; otherwise, <c>false</c>. /// </value> public bool CaseInsensitive { get { return _comparer.IgnoreCase; } } /// <summary> /// Gets a value indicating whether or not to clip strings. /// </summary> /// <value> /// <c>true</c> if set to clip strings otherwise, <c>false</c>. /// </value> public bool ClipStrings { get; private set; } /// <summary> /// Gets the failure points. /// </summary> /// <value> /// The failure points. /// </value> public IList<NUnitEqualityComparer.FailurePoint> FailurePoints { get { return _comparer.FailurePoints; } } #endregion #region Constraint Modifiers /// <summary> /// Flag the constraint to ignore case and return self. /// </summary> public EqualConstraint IgnoreCase { get { _comparer.IgnoreCase = true; return this; } } /// <summary> /// Flag the constraint to suppress string clipping /// and return self. /// </summary> public EqualConstraint NoClip { get { ClipStrings = false; return this; } } /// <summary> /// Flag the constraint to compare arrays as collections /// and return self. /// </summary> public EqualConstraint AsCollection { get { _comparer.CompareAsCollection = true; return this; } } /// <summary> /// Flag the constraint to use a tolerance when determining equality. /// </summary> /// <param name="amount">Tolerance value to be used</param> /// <returns>Self.</returns> public EqualConstraint Within(object amount) { if (!_tolerance.IsUnsetOrDefault) throw new InvalidOperationException("Within modifier may appear only once in a constraint expression"); _tolerance = new Tolerance(amount); return this; } /// <summary> /// Flags the constraint to include <see cref="DateTimeOffset.Offset"/> /// property in comparison of two <see cref="DateTimeOffset"/> values. /// </summary> /// <remarks> /// Using this modifier does not allow to use the <see cref="Within"/> /// constraint modifier. /// </remarks> public EqualConstraint WithSameOffset { get { _comparer.WithSameOffset = true; return this; } } /// <summary> /// Switches the .Within() modifier to interpret its tolerance as /// a distance in representable _values (see remarks). /// </summary> /// <returns>Self.</returns> /// <remarks> /// Ulp stands for "unit in the last place" and describes the minimum /// amount a given value can change. For any integers, an ulp is 1 whole /// digit. For floating point _values, the accuracy of which is better /// for smaller numbers and worse for larger numbers, an ulp depends /// on the size of the number. Using ulps for comparison of floating /// point results instead of fixed tolerances is safer because it will /// automatically compensate for the added inaccuracy of larger numbers. /// </remarks> public EqualConstraint Ulps { get { _tolerance = _tolerance.Ulps; return this; } } /// <summary> /// Switches the .Within() modifier to interpret its tolerance as /// a percentage that the actual _values is allowed to deviate from /// the expected value. /// </summary> /// <returns>Self</returns> public EqualConstraint Percent { get { _tolerance = _tolerance.Percent; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in days. /// </summary> /// <returns>Self</returns> public EqualConstraint Days { get { _tolerance = _tolerance.Days; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in hours. /// </summary> /// <returns>Self</returns> public EqualConstraint Hours { get { _tolerance = _tolerance.Hours; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in minutes. /// </summary> /// <returns>Self</returns> public EqualConstraint Minutes { get { _tolerance = _tolerance.Minutes; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in seconds. /// </summary> /// <returns>Self</returns> public EqualConstraint Seconds { get { _tolerance = _tolerance.Seconds; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in milliseconds. /// </summary> /// <returns>Self</returns> public EqualConstraint Milliseconds { get { _tolerance = _tolerance.Milliseconds; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in clock ticks. /// </summary> /// <returns>Self</returns> public EqualConstraint Ticks { get { _tolerance = _tolerance.Ticks; return this; } } /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using(IComparer comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using<T>(IComparer<T> comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied Comparison object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using<T>(Comparison<T> comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using(IEqualityComparer comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using<T>(IEqualityComparer<T> comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } #endregion #region Public Methods /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override ConstraintResult ApplyTo<TActual>(TActual actual) { AdjustArgumentIfNeeded(ref actual); return new EqualConstraintResult(this, actual, _comparer.AreEqual(_expected, actual, ref _tolerance)); } /// <summary> /// The Description of what this constraint tests, for /// use in messages and in the ConstraintResult. /// </summary> public override string Description { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(MsgUtils.FormatValue(_expected)); if (_tolerance != null && !_tolerance.IsUnsetOrDefault) { sb.Append(" +/- "); sb.Append(MsgUtils.FormatValue(_tolerance.Amount)); if (_tolerance.Mode != ToleranceMode.Linear) { sb.Append(" "); sb.Append(_tolerance.Mode.ToString()); } } if (_comparer.IgnoreCase) sb.Append(", ignoring case"); return sb.ToString(); } } #endregion #region Helper Methods // Currently, we only adjust for ArraySegments that have a // null array reference. Others could be added in the future. private void AdjustArgumentIfNeeded<T>(ref T arg) { #if !PORTABLE if (arg != null) { Type argType = arg.GetType(); Type genericTypeDefinition = argType.GetTypeInfo().IsGenericType ? argType.GetGenericTypeDefinition() : null; if (genericTypeDefinition == typeof(ArraySegment<>) && argType.GetProperty("Array").GetValue(arg, null) == null) { var elementType = argType.GetGenericArguments()[0]; var array = Array.CreateInstance(elementType, 0); var ctor = argType.GetConstructor(new Type[] { array.GetType() }); arg = (T)ctor.Invoke(new object[] { array }); } } #endif } #endregion } }
using UnityEngine; using System.Collections; using Pathfinding; public class ProceduralGridMover : MonoBehaviour { public float updateDistance = 5; public Transform target; /** Flood fill the graph after updating. * If this is set to false, areas of the graph will not be recalculated. * Enable this only if the graph will only have a single area (i.e * from all walkable nodes there is a valid path to every other walkable * node). One case where this might be appropriate is a large * outdoor area such as a forrest. * If there are multiple areas in the graph and this * is not enabled, pathfinding could fail later on. * * Enabling it will make the graph updates faster. */ public bool floodFill; /** Grid graph to update */ GridGraph graph; GridNode[] tmp; public void Start () { if ( AstarPath.active == null ) throw new System.Exception ("There is no AstarPath object in the scene"); graph = AstarPath.active.astarData.gridGraph; if ( graph == null ) throw new System.Exception ("The AstarPath object has no GridGraph"); UpdateGraph (); } // Update is called once per frame void Update () { // Check the distance along the XZ plane // we only move the graph in the X and Z directions so // checking for if the Y coordinate has changed is // not something we want to do if ( AstarMath.SqrMagnitudeXZ (target.position, graph.center) > updateDistance*updateDistance ) { UpdateGraph (); } } public void UpdateGraph () { // Start a work item for updating the graph // This will pause the pathfinding threads // so that it is safe to update the graph // and then do it over several frames // (hence the IEnumerator coroutine) // to avoid too large FPS drops IEnumerator ie = UpdateGraphCoroutine (); AstarPath.active.AddWorkItem (new AstarPath.AstarWorkItem (delegate (bool force) { if ( force ) while ( ie.MoveNext () ) {} return !ie.MoveNext (); })); } IEnumerator UpdateGraphCoroutine () { // Find the direction // that we want to move the graph in Vector3 dir = target.position - graph.center; // Snap to a whole number of nodes dir.x = Mathf.Round(dir.x/graph.nodeSize)*graph.nodeSize; dir.z = Mathf.Round(dir.z/graph.nodeSize)*graph.nodeSize; dir.y = 0; // Nothing do to if ( dir == Vector3.zero ) yield break; // Number of nodes to offset in each // direction Int2 offset = new Int2 ( -Mathf.RoundToInt(dir.x/graph.nodeSize), -Mathf.RoundToInt(dir.z/graph.nodeSize) ); // Move the center graph.center += dir; graph.GenerateMatrix (); // Create a temporary buffer // required for the calculations if ( tmp == null || tmp.Length != graph.nodes.Length ) { tmp = new GridNode[graph.nodes.Length]; } // Cache some variables for easier access int width = graph.width; int depth = graph.depth; GridNode[] nodes = graph.nodes; // Check if we have moved // less than a whole graph // width in any direction if ( Mathf.Abs(offset.x) <= width && Mathf.Abs(offset.y) <= depth ) { // Offset each node by the #offset variable // nodes which would end up outside the graph // will wrap around to the other side of it for ( int z=0; z < depth; z++ ) { int pz = z*width; int tz = ((z+offset.y + depth)%depth)*width; for ( int x=0; x < width; x++ ) { tmp[tz + ((x+offset.x + width) % width)] = nodes[pz + x]; } } yield return null; // Copy the nodes back to the graph // and set the correct indices for ( int z=0; z < depth; z++ ) { int pz = z*width; for ( int x=0; x < width; x++ ) { GridNode node = tmp[pz + x]; node.NodeInGridIndex = pz + x; nodes[pz + x] = node; } } IntRect r = new IntRect ( 0, 0, offset.x, offset.y ); int minz = r.ymax; int maxz = depth; // If offset.x < 0, adjust the rect if ( r.xmin > r.xmax ) { int tmp2 = r.xmax; r.xmax = width + r.xmin; r.xmin = width + tmp2; } // If offset.y < 0, adjust the rect if ( r.ymin > r.ymax ) { int tmp2 = r.ymax; r.ymax = depth + r.ymin; r.ymin = depth + tmp2; minz = 0; maxz = r.ymin; } // Make sure erosion is taken into account // Otherwise we would end up with ugly artifacts r = r.Expand ( graph.erodeIterations + 1 ); // Makes sure the rect stays inside the grid r = IntRect.Intersection ( r, new IntRect ( 0, 0, width, depth ) ); yield return null; // Update all nodes along one edge of the graph // With the same width as the rect for ( int z = r.ymin; z < r.ymax; z++ ) { for ( int x = 0; x < width; x++ ) { graph.UpdateNodePositionCollision ( nodes[z*width + x], x, z, false ); } } yield return null; // Update all nodes along the other edge of the graph // With the same width as the rect for ( int z = minz; z < maxz; z++ ) { for ( int x = r.xmin; x < r.xmax; x++ ) { graph.UpdateNodePositionCollision ( nodes[z*width + x], x, z, false ); } } yield return null; // Calculate all connections for the nodes // that might have changed for ( int z = r.ymin; z < r.ymax; z++ ) { for ( int x = 0; x < width; x++ ) { graph.CalculateConnections (nodes, x, z, nodes[z*width+x]); } } yield return null; // Calculate all connections for the nodes // that might have changed for ( int z = minz; z < maxz; z++ ) { for ( int x = r.xmin; x < r.xmax; x++ ) { graph.CalculateConnections (nodes, x, z, nodes[z*width+x]); } } yield return null; // Calculate all connections for the nodes along the boundary // of the graph, these always need to be updated /** \todo Optimize to not traverse all nodes in the graph, only those at the edges */ for ( int z = 0; z < depth; z++ ) { for ( int x = 0; x < width; x++ ) { if ( x == 0 || z == 0 || x >= width-1 || z >= depth-1 ) graph.CalculateConnections (nodes, x, z, nodes[z*width+x]); } } } else { // Just update all nodes for ( int z = 0; z < depth; z++ ) { for ( int x = 0; x < width; x++ ) { graph.UpdateNodePositionCollision ( nodes[z*width + x], x, z, false ); } } // Recalculate the connections of all nodes for ( int z = 0; z < depth; z++ ) { for ( int x = 0; x < width; x++ ) { graph.CalculateConnections (nodes, x, z, nodes[z*width+x]); } } } if ( floodFill ) { yield return null; // Make sure the areas for the graph // have been recalculated // not doing this can cause pathfinding to fail AstarPath.active.QueueWorkItemFloodFill (); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: A Stream whose backing store is memory. Great ** for temporary storage without creating a temp file. Also ** lets users expose a byte[] as a stream. ** ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; using System.Security.Permissions; namespace System.IO { // A MemoryStream represents a Stream in memory (ie, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. [Serializable] [ComVisible(true)] public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. [ContractPublicPropertyName("Length")] private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? [NonSerialized] private Task<int> _lastReadTask; // The last successful task returned from ReadAsync private const int MemStreamMaxLength = Int32.MaxValue; public MemoryStream() : this(0) { } public MemoryStream(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity")); } Contract.EndContractBlock(); _buffer = capacity != 0 ? new byte[capacity] : EmptyArray<byte>.Value; _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } public MemoryStream(byte[] buffer) : this(buffer, true) { } public MemoryStream(byte[] buffer, bool writable) { if (buffer == null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); Contract.EndContractBlock(); _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream(byte[] buffer, int index, int count) : this(buffer, index, count, true, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) : this(buffer, index, count, writable, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _writable; } } private void EnsureWriteable() { if (!CanWrite) __Error.WriteNotSupported(); } protected override void Dispose(bool disposing) { try { if (disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work. _lastReadTask = null; } } finally { // Call base.Close() to cleanup async IO resources base.Dispose(disposing); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity(int value) { // Check for overflow if (value < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (value > _capacity) { int newCapacity = value; if (newCapacity < 256) newCapacity = 256; // We are ok with this overflowing since the next statement will deal // with the cases where _capacity*2 overflows. if (newCapacity < _capacity * 2) newCapacity = _capacity * 2; // We want to expand the array up to Array.MaxArrayLengthOneDimensional // And we want to give the user the value that they asked for if ((uint)(_capacity * 2) > Array.MaxByteArrayLength) newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength; Capacity = newCapacity; return true; } return false; } public override void Flush() { } [HostProtection(ExternalThreading=true)] [ComVisible(false)] public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); try { Flush(); return Task.CompletedTask; } catch(Exception ex) { return Task.FromException(ex); } } public virtual byte[] GetBuffer() { if (!_exposable) throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer")); return _buffer; } public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) { if (!_exposable) { buffer = default(ArraySegment<byte>); return false; } buffer = new ArraySegment<byte>(_buffer, offset:_origin, count:(_length - _origin)); return true; } // -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) --------------- // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) internal byte[] InternalGetBuffer() { return _buffer; } // PERF: Get origin and length - used in ResourceWriter. [FriendAccessAllowed] internal void InternalGetOriginAndLength(out int origin, out int length) { if (!_isOpen) __Error.StreamIsClosed(); origin = _origin; length = _length; } // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() { if (!_isOpen) __Error.StreamIsClosed(); return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if (!_isOpen) __Error.StreamIsClosed(); int pos = (_position += 4); // use temp to avoid a race condition if (pos > _length) { _position = _length; __Error.EndOfFile(); } return (int)(_buffer[pos-4] | _buffer[pos-3] << 8 | _buffer[pos-2] << 16 | _buffer[pos-1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead(int count) { if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n < 0) n = 0; Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. _position += n; return n; } // Gets & sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if (!_isOpen) __Error.StreamIsClosed(); return _capacity - _origin; } set { // Only update the capacity if the MS is expandable and the value is different than the current capacity. // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity if (value < Length) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); Contract.Ensures(_capacity - _origin == value); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable(); // MemoryStream has this invariant: _origin > 0 => !expandable (see ctors) if (_expandable && value != _capacity) { if (value > 0) { byte[] newBuffer = new byte[value]; if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length); _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { get { if (!_isOpen) __Error.StreamIsClosed(); return _length - _origin; } } public override long Position { get { if (!_isOpen) __Error.StreamIsClosed(); return _position - _origin; } set { if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.Ensures(Position == value); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (value > MemStreamMaxLength) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); _position = _origin + (int)value; } } public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n <= 0) return 0; Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. if (n <= 8) { int byteCount = n; while (--byteCount >= 0) buffer[offset + byteCount] = _buffer[_position + byteCount]; } else Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n); _position += n; return n; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Read(...) // If cancellation was requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCancellation<int>(cancellationToken); try { int n = Read(buffer, offset, count); var t = _lastReadTask; Contract.Assert(t == null || t.Status == TaskStatus.RanToCompletion, "Expected that a stored last task completed successfully"); return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n)); } catch (OperationCanceledException oce) { return Task.FromCancellation<int>(oce); } catch (Exception exception) { return Task.FromException<int>(exception); } } public override int ReadByte() { if (!_isOpen) __Error.StreamIsClosed(); if (_position >= _length) return -1; return _buffer[_position++]; } public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { // This implementation offers beter performance compared to the base class version. // The parameter checks must be in sync with the base version: if (destination == null) throw new ArgumentNullException("destination"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); if (!CanRead && !CanWrite) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!destination.CanRead && !destination.CanWrite) throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed")); if (!CanRead) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream")); if (!destination.CanWrite) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream")); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() or Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/Write) when we are not sure. if (this.GetType() != typeof(MemoryStream)) return base.CopyToAsync(destination, bufferSize, cancellationToken); // If cancelled - return fast: if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); // Avoid copying data from this buffer into a temp buffer: // (require that InternalEmulateRead does not throw, // otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below) Int32 pos = _position; Int32 n = InternalEmulateRead(_length - _position); // If destination is not a memory stream, write there asynchronously: MemoryStream memStrDest = destination as MemoryStream; if (memStrDest == null) return destination.WriteAsync(_buffer, pos, n, cancellationToken); try { // If destination is a MemoryStream, CopyTo synchronously: memStrDest.Write(_buffer, pos, n); return Task.CompletedTask; } catch(Exception ex) { return Task.FromException(ex); } } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) __Error.StreamIsClosed(); if (offset > MemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); switch(loc) { case SeekOrigin.Begin: { int tempPosition = unchecked(_origin + (int)offset); if (offset < 0 || tempPosition < _origin) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); _position = tempPosition; break; } case SeekOrigin.Current: { int tempPosition = unchecked(_position + (int)offset); if (unchecked(_position + offset) < _origin || tempPosition < _origin) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); _position = tempPosition; break; } case SeekOrigin.End: { int tempPosition = unchecked(_length + (int)offset); if ( unchecked(_length + offset) < _origin || tempPosition < _origin ) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); _position = tempPosition; break; } default: throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin")); } Contract.Assert(_position >= 0, "_position >= 0"); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength(long value) { if (value < 0 || value > Int32.MaxValue) { throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } Contract.Ensures(_length - _origin == value); Contract.EndContractBlock(); EnsureWriteable(); // Origin wasn't publicly exposed above. Contract.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails. if (value > (Int32.MaxValue - _origin)) { throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity(newLength); if (!allocatedNewArray && newLength > _length) Array.Clear(_buffer, _length, newLength - _length); _length = newLength; if (_position > newLength) _position = newLength; } public virtual byte[] ToArray() { BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy."); byte[] copy = new byte[_length - _origin]; Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin); return copy; } public override void Write(byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); int i = _position + count; // Check for overflow if (i < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (i > _length) { bool mustZero = _position > _length; if (i > _capacity) { bool allocatedNewArray = EnsureCapacity(i); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, i - _length); _length = i; } if ((count <= 8) && (buffer != _buffer)) { int byteCount = count; while (--byteCount >= 0) _buffer[_position + byteCount] = buffer[offset + byteCount]; } else Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count); _position = i; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Write(...) // If cancellation is already requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (OperationCanceledException oce) { return Task.FromCancellation<VoidTaskResult>(oce); } catch (Exception exception) { return Task.FromException(exception); } } public override void WriteByte(byte value) { if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); if (_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if (newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity(newLength); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, _position - _length); _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo(Stream stream) { if (stream==null) throw new ArgumentNullException("stream", Environment.GetResourceString("ArgumentNull_Stream")); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); stream.Write(_buffer, _origin, _length - _origin); } #if CONTRACTS_FULL [ContractInvariantMethod] private void ObjectInvariantMS() { Contract.Invariant(_origin >= 0); Contract.Invariant(_origin <= _position); Contract.Invariant(_length <= _capacity); // equivalent to _origin > 0 => !expandable, and using fact that _origin is non-negative. Contract.Invariant(_origin == 0 || !_expandable); } #endif } }
namespace Boxed.DotnetNewTest { using System; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; /// <summary> /// <see cref="Project"/> extension methods. /// </summary> public static class ProjectExtensions { private static readonly string[] DefaultUrls = new string[] { "http://localhost", "https://localhost" }; /// <summary> /// Runs 'dotnet restore' on the specified project. /// </summary> /// <param name="project">The project.</param> /// <param name="timeout">The timeout.</param> /// <returns>A task representing the operation.</returns> public static Task DotnetRestore(this Project project, TimeSpan? timeout = null) => AssertStartAsync( project.DirectoryPath, "dotnet", "restore", CancellationTokenFactory.GetCancellationToken(timeout)); /// <summary> /// Runs 'dotnet build' on the specified project. /// </summary> /// <param name="project">The project.</param> /// <param name="noRestore">Whether to restore the project.</param> /// <param name="timeout">The timeout.</param> /// <returns>A task representing the operation.</returns> public static Task DotnetBuild(this Project project, bool? noRestore = true, TimeSpan? timeout = null) { var noRestoreArgument = noRestore == null ? null : "--no-restore"; return AssertStartAsync( project.DirectoryPath, "dotnet", $"build {noRestoreArgument}", CancellationTokenFactory.GetCancellationToken(timeout)); } /// <summary> /// Runs 'dotnet publish' on the specified project. /// </summary> /// <param name="project">The project.</param> /// <param name="framework">The framework.</param> /// <param name="runtime">The runtime.</param> /// <param name="noRestore">Whether to restore the project.</param> /// <param name="timeout">The timeout.</param> /// <returns>A task representing the operation.</returns> public static Task DotnetPublish( this Project project, string framework = null, string runtime = null, bool? noRestore = true, TimeSpan? timeout = null) { var frameworkArgument = framework == null ? null : $"--framework {framework}"; var runtimeArgument = runtime == null ? null : $"--self-contained --runtime {runtime}"; var noRestoreArgument = noRestore == null ? null : "--no-restore"; DirectoryExtensions.CheckCreate(project.PublishDirectoryPath); return AssertStartAsync( project.DirectoryPath, "dotnet", $"publish {noRestoreArgument} {frameworkArgument} {runtimeArgument} --output {project.PublishDirectoryPath}", CancellationTokenFactory.GetCancellationToken(timeout)); } /// <summary> /// Runs 'dotnet run' on the specified project while only exposing a HTTP endpoint. /// </summary> /// <param name="project">The project.</param> /// <param name="projectRelativeDirectoryPath">The project relative directory path.</param> /// <param name="action">The action to perform while the project is running.</param> /// <param name="noRestore">Whether to restore the project.</param> /// <param name="validateCertificate">Validate the project certificate.</param> /// <param name="timeout">The timeout.</param> /// <returns>A task representing the operation.</returns> public static async Task DotnetRun( this Project project, string projectRelativeDirectoryPath, Func<HttpClient, Task> action, bool? noRestore = true, Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> validateCertificate = null, TimeSpan? timeout = null) { var httpPort = PortHelper.GetFreeTcpPort(); var httpUrl = $"http://localhost:{httpPort}"; var projectFilePath = Path.Combine(project.DirectoryPath, projectRelativeDirectoryPath); var dotnetRun = await DotnetRunInternal(projectFilePath, noRestore, timeout, httpUrl); var httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false, ServerCertificateCustomValidationCallback = validateCertificate ?? DefaultValidateCertificate, }; var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(httpUrl) }; try { await action(httpClient); } finally { httpClient.Dispose(); httpClientHandler.Dispose(); dotnetRun.Dispose(); } } /// <summary> /// Runs 'dotnet run' on the specified project while only exposing a HTTP and HTTPS endpoint. /// </summary> /// <param name="project">The project.</param> /// <param name="projectRelativeDirectoryPath">The project relative directory path.</param> /// <param name="action">The action to perform while the project is running.</param> /// <param name="noRestore">Whether to restore the project.</param> /// <param name="validateCertificate">Validate the project certificate.</param> /// <param name="timeout">The timeout.</param> /// <returns>A task representing the operation.</returns> public static async Task DotnetRun( this Project project, string projectRelativeDirectoryPath, Func<HttpClient, HttpClient, Task> action, bool? noRestore = true, Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> validateCertificate = null, TimeSpan? timeout = null) { var httpPort = PortHelper.GetFreeTcpPort(); var httpsPort = PortHelper.GetFreeTcpPort(); var httpUrl = $"http://localhost:{httpPort}"; var httpsUrl = $"https://localhost:{httpsPort}"; var projectFilePath = Path.Combine(project.DirectoryPath, projectRelativeDirectoryPath); var dotnetRun = await DotnetRunInternal(projectFilePath, noRestore, timeout, httpUrl, httpsUrl); var httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false, ServerCertificateCustomValidationCallback = validateCertificate ?? DefaultValidateCertificate, }; var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(httpUrl) }; var httpsClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(httpsUrl) }; try { await action(httpClient, httpsClient); } finally { httpClient.Dispose(); httpsClient.Dispose(); httpClientHandler.Dispose(); dotnetRun.Dispose(); } } /// <summary> /// Runs the project in-memory. /// </summary> /// <param name="project">The project.</param> /// <param name="action">The action to perform while the project is running.</param> /// <param name="environmentName">Name of the environment.</param> /// <param name="startupTypeName">Name of the startup type.</param> /// <returns>A task representing the operation.</returns> /// <remarks>This doesn't work yet, needs API's from .NET Core 3.0.</remarks> internal static async Task DotnetRunInMemory( this Project project, Func<TestServer, Task> action, string environmentName = "Development", string startupTypeName = "Startup") { var projectName = Path.GetFileName(project.DirectoryPath); var directoryPath = project.PublishDirectoryPath; var assemblyFilePath = Path.Combine(directoryPath, $"{projectName}.dll"); if (string.IsNullOrEmpty(assemblyFilePath)) { throw new FileNotFoundException($"Project assembly not found.", assemblyFilePath); } else { var assembly = new AssemblyResolver(assemblyFilePath).Assembly; var startupType = assembly .DefinedTypes .FirstOrDefault(x => string.Equals(x.Name, startupTypeName, StringComparison.Ordinal)); if (startupType == null) { throw new Exception($"Startup type '{startupTypeName}' not found."); } var webHostBuilder = new WebHostBuilder() .UseEnvironment(environmentName) .UseStartup(startupType) .UseUrls(DefaultUrls); using (var testServer = new TestServer(webHostBuilder)) { await action(testServer); } // TODO: Unload startupType when supported: https://github.com/dotnet/corefx/issues/14724 } } private static async Task<IDisposable> DotnetRunInternal( string directoryPath, bool? noRestore = true, TimeSpan? timeout = null, params string[] urls) { var cancellationTokenSource = new CancellationTokenSource(); var noRestoreArgument = noRestore == null ? null : "--no-restore"; var urlsParameter = string.Join(";", urls); var task = AssertStartAsync( directoryPath, "dotnet", $"run {noRestoreArgument} --urls {urlsParameter}", cancellationTokenSource.Token); await WaitForStart(urls.First(), timeout ?? TimeSpan.FromMinutes(1)); return new DisposableAction( () => { cancellationTokenSource.Cancel(); try { task.Wait(); } catch (AggregateException exception) when (exception.GetBaseException().GetBaseException() is TaskCanceledException) { } }); } private static async Task WaitForStart(string url, TimeSpan timeout) { const int intervalMilliseconds = 100; var httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false, ServerCertificateCustomValidationCallback = DefaultValidateCertificate, }; using (var httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri(url) }) { for (var i = 0; i < (timeout.TotalMilliseconds / intervalMilliseconds); ++i) { try { _ = await httpClient.GetAsync("/"); return; } catch (HttpRequestException exception) when (IsApiDownException(exception)) { await Task.Delay(intervalMilliseconds); } } throw new TimeoutException( $"Timed out after waiting {timeout} for application to start using dotnet run."); } } private static bool IsApiDownException(Exception exception) { var result = false; var baseException = exception.GetBaseException(); if (baseException is SocketException socketException) { result = string.Equals( socketException.Message, "No connection could be made because the target machine actively refused it", StringComparison.Ordinal) || string.Equals( socketException.Message, "Connection refused", StringComparison.Ordinal); } return result; } private static bool DefaultValidateCertificate( HttpRequestMessage request, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors) => true; private static async Task AssertStartAsync( string workingDirectory, string fileName, string arguments, CancellationToken cancellationToken) { var (processResult, message) = await ProcessExtensions.StartAsync( workingDirectory, fileName, arguments, cancellationToken); if (processResult != ProcessResult.Succeeded) { throw new Exception(message); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** Purpose: An array implementation of a generic stack. ** ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.Collections.Generic { // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(StackDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public class Stack<T> : IEnumerable<T>, System.Collections.ICollection, IReadOnlyCollection<T> { private T[] _array; // Storage for stack elements private int _size; // Number of items in the stack. private int _version; // Used to keep enumerator in sync w/ collection. [NonSerialized] private object _syncRoot; private const int DefaultCapacity = 4; public Stack() { _array = Array.Empty<T>(); } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. public Stack(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); _array = new T[capacity]; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. public Stack(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); _array = EnumerableHelpers.ToArray(collection, out _size); } public int Count { get { return _size; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null); } return _syncRoot; } } // Removes all Objects from the Stack. public void Clear() { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. } _size = 0; _version++; } public bool Contains(T item) { // Compare items using the default equality comparer // PERF: Internally Array.LastIndexOf calls // EqualityComparer<T>.Default.LastIndexOf, which // is specialized for different types. This // boosts performance since instead of making a // virtual method call each iteration of the loop, // via EqualityComparer<T>.Default.Equals, we // only make one virtual call to EqualityComparer.LastIndexOf. return _size != 0 && Array.LastIndexOf(_array, item, _size - 1) != -1; } // Copies the stack into an array. public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Debug.Assert(array != _array); int srcIndex = 0; int dstIndex = arrayIndex + _size; while(srcIndex < _size) { array[--dstIndex] = _array[srcIndex++]; } } void ICollection.CopyTo(Array array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } try { Array.Copy(_array, 0, array, arrayIndex, _size); Array.Reverse(array, arrayIndex, _size); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } // Returns an IEnumerator for this Stack. public Enumerator GetEnumerator() { return new Enumerator(this); } /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } public void TrimExcess() { int threshold = (int)(((double)_array.Length) * 0.9); if (_size < threshold) { Array.Resize(ref _array, _size); _version++; } } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. public T Peek() { if (_size == 0) { ThrowForEmptyStack(); } return _array[_size - 1]; } public bool TryPeek(out T result) { if (_size == 0) { result = default(T); return false; } result = _array[_size - 1]; return true; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. public T Pop() { if (_size == 0) { ThrowForEmptyStack(); } _version++; T item = _array[--_size]; if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { _array[_size] = default(T); // Free memory quicker. } return item; } public bool TryPop(out T result) { if (_size == 0) { result = default(T); return false; } _version++; result = _array[--_size]; if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { _array[_size] = default(T); // Free memory quicker. } return true; } // Pushes an item to the top of the stack. public void Push(T item) { if (_size == _array.Length) { Array.Resize(ref _array, (_array.Length == 0) ? DefaultCapacity : 2 * _array.Length); } _array[_size++] = item; _version++; } // Copies the Stack to an array, in the same order Pop would return the items. public T[] ToArray() { if (_size == 0) return Array.Empty<T>(); T[] objArray = new T[_size]; int i = 0; while (i < _size) { objArray[i] = _array[_size - i - 1]; i++; } return objArray; } private void ThrowForEmptyStack() { Debug.Assert(_size == 0); throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] [Serializable] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private readonly Stack<T> _stack; private readonly int _version; private int _index; private T _currentElement; internal Enumerator(Stack<T> stack) { _stack = stack; _version = stack._version; _index = -2; _currentElement = default(T); } public void Dispose() { _index = -1; } public bool MoveNext() { bool retval; if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index == -2) { // First call to enumerator. _index = _stack._size - 1; retval = (_index >= 0); if (retval) _currentElement = _stack._array[_index]; return retval; } if (_index == -1) { // End of enumeration. return false; } retval = (--_index >= 0); if (retval) _currentElement = _stack._array[_index]; else _currentElement = default(T); return retval; } public T Current { get { if (_index < 0) ThrowEnumerationNotStartedOrEnded(); return _currentElement; } } private void ThrowEnumerationNotStartedOrEnded() { Debug.Assert(_index == -1 || _index == -2); throw new InvalidOperationException(_index == -2 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded); } object System.Collections.IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -2; _currentElement = default(T); } } } }
/* ==================================================================== */ using System; using System.Xml; using System.Collections; using System.Collections.Specialized; using System.Threading; using Oranikle.Report.Engine; namespace Oranikle.Report.Engine { ///<summary> /// A report expression: includes original source, parsed expression and type information. ///</summary> [Serializable] public class DynamicExpression: IExpr { string _Source; // source of expression IExpr _Expr; // expression after parse TypeCode _Type; ReportLink _rl; public DynamicExpression(Report rpt, ReportLink p, string expr, Row row) { _Source=expr; _Expr = null; _rl = p; _Type = DoParse(rpt); } public TypeCode DoParse(Report rpt) { // optimization: avoid expression overhead if this isn't really an expression if (_Source == null) { _Expr = new Constant(""); return _Expr.GetTypeCode(); } else if (_Source == string.Empty || // empty expression _Source[0] != '=') // if 1st char not '=' { _Expr = new Constant(_Source); // this is a constant value return _Expr.GetTypeCode(); } Parser p = new Parser(new System.Collections.Generic.List<ICacheData>()); // find the fields that are part of the DataRegion (if there is one) IDictionary fields=null; ReportLink dr = _rl.Parent; Grouping grp= null; // remember if in a table group or detail group or list group Matrix m=null; while (dr != null) { if (dr is Grouping) p.NoAggregateFunctions = true; else if (dr is TableGroup) grp = ((TableGroup) dr).Grouping; else if (dr is Matrix) { m = (Matrix) dr; // if matrix we need to pass special break; } else if (dr is Details) { grp = ((Details) dr).Grouping; } else if (dr is List) { grp = ((List) dr).Grouping; break; } else if (dr is DataRegion || dr is DataSetDefn) break; dr = dr.Parent; } if (dr != null) { if (dr is DataSetDefn) { DataSetDefn d = (DataSetDefn) dr; if (d.Fields != null) fields = d.Fields.Items; } else // must be a DataRegion { DataRegion d = (DataRegion) dr; if (d.DataSetDefn != null && d.DataSetDefn.Fields != null) fields = d.DataSetDefn.Fields.Items; } } NameLookup lu = new NameLookup(fields, rpt.ReportDefinition.LUReportParameters, rpt.ReportDefinition.LUReportItems, rpt.ReportDefinition.LUGlobals, rpt.ReportDefinition.LUUser, rpt.ReportDefinition.LUAggrScope, grp, m, rpt.ReportDefinition.CodeModules, rpt.ReportDefinition.Classes, rpt.ReportDefinition.DataSetsDefn, rpt.ReportDefinition.CodeType); try { _Expr = p.Parse(lu, _Source); } catch (Exception e) { _Expr = new ConstantError(e.Message); // Invalid expression rpt.rl.LogError(8, ErrorText(e.Message)); } // Optimize removing any expression that always result in a constant try { _Expr = _Expr.ConstantOptimization(); } catch(Exception ex) { rpt.rl.LogError(4, "Expression:" + _Source + "\r\nConstant Optimization exception:\r\n" + ex.Message + "\r\nStack trace:\r\n" + ex.StackTrace ); } return _Expr.GetTypeCode(); } private string ErrorText(string msg) { ReportLink rl = _rl.Parent; while (rl != null) { if (rl is ReportItem) break; rl = rl.Parent; } string prefix="Expression"; if (rl != null) { ReportItem ri = rl as ReportItem; if (ri.Name != null) prefix = ri.Name.Nm + " expression"; } return prefix + " '" + _Source + "' failed to parse: " + msg; } private void ReportError(Report rpt, int severity, string err) { rpt.rl.LogError(severity, err); } public string Source { get { return _Source; } } public IExpr Expr { get { return _Expr; } } public TypeCode Type { get { return _Type; } } #region IExpr Members public System.TypeCode GetTypeCode() { return _Expr.GetTypeCode(); } public bool IsConstant() { return _Expr.IsConstant(); } public IExpr ConstantOptimization() { return this; } public object Evaluate(Report rpt, Row row) { try { return _Expr.Evaluate(rpt, row); } catch (Exception e) { string err; if (e.InnerException != null) err = String.Format("Exception evaluating {0}. {1}. {2}", _Source, e.Message, e.InnerException.Message); else err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return null; } } public string EvaluateString(Report rpt, Row row) { try { return _Expr.EvaluateString(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return null; } } public double EvaluateDouble(Report rpt, Row row) { try { return _Expr.EvaluateDouble(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return double.NaN; } } public decimal EvaluateDecimal(Report rpt, Row row) { try { return _Expr.EvaluateDecimal(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return decimal.MinValue; } } public int EvaluateInt32(Report rpt, Row row) { try { return _Expr.EvaluateInt32(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return int.MinValue; } } public DateTime EvaluateDateTime(Report rpt, Row row) { try { return _Expr.EvaluateDateTime(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return DateTime.MinValue; } } public bool EvaluateBoolean(Report rpt, Row row) { try { return _Expr.EvaluateBoolean(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return false; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class OrderByTests : EnumerableTests { private class BadComparer1 : IComparer<int> { public int Compare(int x, int y) { return 1; } } private class BadComparer2 : IComparer<int> { public int Compare(int x, int y) { return -1; } } [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x1 in new int[] { 1, 6, 0, -1, 3 } from x2 in new int[] { 55, 49, 9, -100, 24, 25 } select new { a1 = x1, a2 = x2 }; Assert.Equal(q.OrderBy(e => e.a1).ThenBy(f => f.a2), q.OrderBy(e => e.a1).ThenBy(f => f.a2)); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x1 in new[] { 55, 49, 9, -100, 24, 25, -1, 0 } from x2 in new[] { "!@#$%^", "C", "AAA", "", null, "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x2) select new { a1 = x1, a2 = x2 }; Assert.Equal(q.OrderBy(e => e.a1), q.OrderBy(e => e.a1)); } [Fact] public void SourceEmpty() { int[] source = { }; Assert.Empty(source.OrderBy(e => e)); } //FIXME: This will hang with a larger source. Do we want to deal with that case? [Fact] public void SurviveBadComparerAlwaysReturnsNegative() { int[] source = { 1 }; int[] expected = { 1 }; Assert.Equal(expected, source.OrderBy(e => e, new BadComparer2())); } [Fact] public void KeySelectorReturnsNull() { int?[] source = { null, null, null }; int?[] expected = { null, null, null }; Assert.Equal(expected, source.OrderBy(e => e)); } [Fact] public void ElementsAllSameKey() { int?[] source = { 9, 9, 9, 9, 9, 9 }; int?[] expected = { 9, 9, 9, 9, 9, 9 }; Assert.Equal(expected, source.OrderBy(e => e)); } [Fact] public void KeySelectorCalled() { var source = new[] { new { Name = "Tim", Score = 90 }, new { Name = "Robert", Score = 45 }, new { Name = "Prakash", Score = 99 } }; var expected = new[] { new { Name = "Prakash", Score = 99 }, new { Name = "Robert", Score = 45 }, new { Name = "Tim", Score = 90 } }; Assert.Equal(expected, source.OrderBy(e => e.Name, null)); } [Fact] public void FirstAndLastAreDuplicatesCustomComparer() { string[] source = { "Prakash", "Alpha", "dan", "DAN", "Prakash" }; string[] expected = { "Alpha", "dan", "DAN", "Prakash", "Prakash" }; Assert.Equal(expected, source.OrderBy(e => e, StringComparer.OrdinalIgnoreCase)); } [Fact] public void FirstAndLastAreDuplicatesNullPassedAsComparer() { int[] source = { 5, 1, 3, 2, 5 }; int[] expected = { 1, 2, 3, 5, 5 }; Assert.Equal(expected, source.OrderBy(e => e, null)); } [Fact] public void SourceReverseOfResultNullPassedAsComparer() { int?[] source = { 100, 30, 9, 5, 0, -50, -75, null }; int?[] expected = { null, -75, -50, 0, 5, 9, 30, 100 }; Assert.Equal(expected, source.OrderBy(e => e, null)); } [Fact] public void SameKeysVerifySortStable() { var source = new[] { new { Name = "Tim", Score = 90 }, new { Name = "Robert", Score = 90 }, new { Name = "Prakash", Score = 90 }, new { Name = "Jim", Score = 90 }, new { Name = "John", Score = 90 }, new { Name = "Albert", Score = 90 }, }; var expected = new[] { new { Name = "Tim", Score = 90 }, new { Name = "Robert", Score = 90 }, new { Name = "Prakash", Score = 90 }, new { Name = "Jim", Score = 90 }, new { Name = "John", Score = 90 }, new { Name = "Albert", Score = 90 }, }; Assert.Equal(expected, source.OrderBy(e => e.Score)); } [Fact] public void OrderedToArray() { var source = new [] { new { Name = "Tim", Score = 90 }, new { Name = "Robert", Score = 90 }, new { Name = "Prakash", Score = 90 }, new { Name = "Jim", Score = 90 }, new { Name = "John", Score = 90 }, new { Name = "Albert", Score = 90 }, }; var expected = new [] { new { Name = "Tim", Score = 90 }, new { Name = "Robert", Score = 90 }, new { Name = "Prakash", Score = 90 }, new { Name = "Jim", Score = 90 }, new { Name = "John", Score = 90 }, new { Name = "Albert", Score = 90 }, }; Assert.Equal(expected, source.OrderBy(e => e.Score).ToArray()); } [Fact] public void EmptyOrderedToArray() { Assert.Empty(Enumerable.Empty<int>().OrderBy(e => e).ToArray()); } [Fact] public void OrderedToList() { var source = new[] { new { Name = "Tim", Score = 90 }, new { Name = "Robert", Score = 90 }, new { Name = "Prakash", Score = 90 }, new { Name = "Jim", Score = 90 }, new { Name = "John", Score = 90 }, new { Name = "Albert", Score = 90 }, }; var expected = new[] { new { Name = "Tim", Score = 90 }, new { Name = "Robert", Score = 90 }, new { Name = "Prakash", Score = 90 }, new { Name = "Jim", Score = 90 }, new { Name = "John", Score = 90 }, new { Name = "Albert", Score = 90 }, }; Assert.Equal(expected, source.OrderBy(e => e.Score).ToList()); } [Fact] public void EmptyOrderedToList() { Assert.Empty(Enumerable.Empty<int>().OrderBy(e => e).ToList()); } //FIXME: This will hang with a larger source. Do we want to deal with that case? [Fact] public void SurviveBadComparerAlwaysReturnsPositive() { int[] source = { 1 }; int[] expected = { 1 }; Assert.Equal(expected, source.OrderBy(e => e, new BadComparer1())); } private class ExtremeComparer : IComparer<int> { public int Compare(int x, int y) { if (x == y) return 0; if (x < y) return int.MinValue; return int.MaxValue; } } [Fact] public void OrderByExtremeComparer() { var outOfOrder = new[] { 7, 1, 0, 9, 3, 5, 4, 2, 8, 6 }; Assert.Equal(Enumerable.Range(0, 10), outOfOrder.OrderBy(i => i, new ExtremeComparer())); } [Fact] public void NullSource() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.OrderBy(i => i)); } [Fact] public void NullKeySelector() { Func<DateTime, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Empty<DateTime>().OrderBy(keySelector)); } [Fact] public void FirstOnOrdered() { Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).First()); Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).First()); Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderByDescending(i => i.ToString().Length).ThenBy(i => i).First()); } [Fact] public void FirstOnEmptyOrderedThrows() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).First()); } [Fact] public void FirstOrDefaultOnOrdered() { Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).FirstOrDefault()); Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).FirstOrDefault()); Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderByDescending(i => i.ToString().Length).ThenBy(i => i).FirstOrDefault()); Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).FirstOrDefault()); } [Fact] public void LastOnOrdered() { Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).Last()); Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).Last()); Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i.ToString().Length).ThenByDescending(i => i).Last()); } [Fact] public void LastOnEmptyOrderedThrows() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).Last()); } [Fact] public void LastOrDefaultOnOrdered() { Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).LastOrDefault()); Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).LastOrDefault()); Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i.ToString().Length).ThenByDescending(i => i).LastOrDefault()); Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).LastOrDefault()); } [Fact] public void EnumeratorDoesntContinue() { var enumerator = NumberRangeGuaranteedNotCollectionType(0, 3).Shuffle().OrderBy(i => i).GetEnumerator(); while (enumerator.MoveNext()) { } Assert.False(enumerator.MoveNext()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.ServiceModel.Channels; namespace System.ServiceModel.Description { [DebuggerDisplay("Address={_address}")] [DebuggerDisplay("Name={_name}")] public class ServiceEndpoint { private EndpointAddress _address; private Binding _binding; private ContractDescription _contract; private Uri _listenUri; private ListenUriMode _listenUriMode = ListenUriMode.Explicit; private KeyedByTypeCollection<IEndpointBehavior> _behaviors; private string _id; private XmlName _name; private bool _isEndpointFullyConfigured = false; public ServiceEndpoint(ContractDescription contract) { if (contract == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contract"); _contract = contract; } public ServiceEndpoint(ContractDescription contract, Binding binding, EndpointAddress address) { if (contract == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contract"); _contract = contract; _binding = binding; _address = address; } public EndpointAddress Address { get { return _address; } set { _address = value; } } public KeyedCollection<Type, IEndpointBehavior> EndpointBehaviors { get { return this.Behaviors; } } [EditorBrowsable(EditorBrowsableState.Never)] public KeyedByTypeCollection<IEndpointBehavior> Behaviors { get { if (_behaviors == null) { _behaviors = new KeyedByTypeCollection<IEndpointBehavior>(); } return _behaviors; } } public Binding Binding { get { return _binding; } set { _binding = value; } } public ContractDescription Contract { get { return _contract; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } _contract = value; } } public bool IsSystemEndpoint { get; set; } public string Name { get { if (!XmlName.IsNullOrEmpty(_name)) { return _name.EncodedName; } else if (_binding != null) { return String.Format(CultureInfo.InvariantCulture, "{0}_{1}", new XmlName(Binding.Name).EncodedName, Contract.Name); } else { return Contract.Name; } } set { _name = new XmlName(value, true /*isEncoded*/); } } public Uri ListenUri { get { if (_listenUri == null) { if (_address == null) { return null; } else { return _address.Uri; } } else { return _listenUri; } } set { if (value != null && !value.IsAbsoluteUri) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.UriMustBeAbsolute); } _listenUri = value; } } public ListenUriMode ListenUriMode { get { return _listenUriMode; } set { if (!ListenUriModeHelper.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _listenUriMode = value; } } internal string Id { get { if (_id == null) _id = Guid.NewGuid().ToString(); return _id; } } internal Uri UnresolvedAddress { get; set; } internal Uri UnresolvedListenUri { get; set; } // This method ensures that the description object graph is structurally sound and that none // of the fundamental SFx framework assumptions have been violated. internal void EnsureInvariants() { if (Binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.AChannelServiceEndpointSBindingIsNull0)); } if (Contract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.AChannelServiceEndpointSContractIsNull0)); } this.Contract.EnsureInvariants(); this.Binding.EnsureInvariants(this.Contract.Name); } internal void ValidateForClient() { Validate(true, false); } internal void ValidateForService(bool runOperationValidators) { Validate(runOperationValidators, true); } internal bool IsFullyConfigured { get { return _isEndpointFullyConfigured; } set { _isEndpointFullyConfigured = value; } } // This method runs validators (both builtin and ones in description). // Precondition: EnsureInvariants() should already have been called. private void Validate(bool runOperationValidators, bool isForService) { // contract behaviors ContractDescription contract = this.Contract; for (int j = 0; j < contract.Behaviors.Count; j++) { IContractBehavior iContractBehavior = contract.Behaviors[j]; iContractBehavior.Validate(contract, this); } // endpoint behaviors if (!isForService) { } for (int j = 0; j < this.Behaviors.Count; j++) { IEndpointBehavior ieb = this.Behaviors[j]; ieb.Validate(this); } // operation behaviors if (runOperationValidators) { for (int j = 0; j < contract.Operations.Count; j++) { OperationDescription op = contract.Operations[j]; for (int k = 0; k < op.Behaviors.Count; k++) { IOperationBehavior iob = op.Behaviors[k]; iob.Validate(op); } } } } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using System.Collections.ObjectModel; using System.Collections.Specialized; using Sensus.UI.UiProperties; using Newtonsoft.Json; using System.ComponentModel; namespace Sensus.UI.Inputs { public class InputGroup : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _name; private string _description; public string Id { get; set; } public ObservableCollection<Input> Inputs { get; } public virtual bool HasInputs => Inputs.Any(); /// <summary> /// Name of the input group. /// </summary> /// <value>The name.</value> [EntryStringUiProperty(null, true, 0, true)] public string Name { get { return _name; } set { if (value != _name) { _name = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ListItemText))); } } } /// <summary> /// A short description of the <c>InputGroup</c> to distinguish it from <c>InputGroup</c>s with the same name. /// </summary> /// <value>The description.</value> [EntryStringUiProperty(null, true, 1, true)] public string Description { get { return _description; } set { if (value != _name) { _description = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Description))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ListItemText))); } } } [JsonIgnore] public string ListItemText { get { if (string.IsNullOrWhiteSpace(Description)) { return Name; } return $"{Name} ({Description})"; } } /// <summary> /// Whether or not to display the built in navigation buttons. If set to true, /// the input group page is responsible for providing a mechanism to navigate /// to the next and/or previous page. /// </summary> /// <value><c>true</c> to hide the navigation buttons; otherwise, <c>false</c>.</value> [ListUiProperty("Show Navigation:", true, 2, new object[] { ShowNavigationOptions.Always, ShowNavigationOptions.WhenValid, ShowNavigationOptions.WhenComplete, ShowNavigationOptions.WhenCorrect, ShowNavigationOptions.Never }, false)] public ShowNavigationOptions ShowNavigationButtons { get; set; } [OnOffUiProperty("Prevent Navigation Backward:", true, 3)] public bool HidePreviousButton { get; set; } /// <summary> /// Whether or not to tag inputs in this group with the device's current GPS location. /// </summary> /// <value><c>true</c> if geotag; otherwise, <c>false</c>.</value> [OnOffUiProperty(null, true, 3)] public bool Geotag { get; set; } /// <summary> /// Whether or not to force valid input values (e.g., all required fields completed, etc.) /// before allowing the user to move to the next input group. /// </summary> /// <value><c>true</c> if force valid inputs; otherwise, <c>false</c>.</value> [OnOffUiProperty("Force Valid Inputs:", true, 4)] public bool ForceValidInputs { get; set; } /// <summary> /// Whether or not to randomly shuffle the inputs in this group when displaying them to the user. /// </summary> /// <value><c>true</c> if shuffle inputs; otherwise, <c>false</c>.</value> [OnOffUiProperty("Shuffle Inputs:", true, 5)] public bool ShuffleInputs { get; set; } [OnOffUiProperty("Freeze Header:", true, 6)] public bool FreezeHeader { get; set; } [OnOffUiProperty("Hide Progress:", true, 7)] public bool HideProgress { get; set; } [OnOffUiProperty("Hide Required Field Label:", true, 8)] public bool HideRequiredFieldLabel { get; set; } /// <summary> /// Override the text for the Previous button. /// </summary> [EntryStringUiProperty("Previous Button Text:", true, 9, false)] public virtual string PreviousButtonText { get; set; } /// <summary> /// Override the text for the Next button. /// </summary> [EntryStringUiProperty("Next Button Text:", true, 10, false)] public virtual string NextButtonText { get; set; } /// <summary> /// Override the text for the Submit button. /// </summary> [EntryStringUiProperty("Submit Button Text:", true, 11, false)] public virtual string SubmitButtonText { get; set; } /// <summary> /// Override the text for the Cancel button. /// </summary> [EntryStringUiProperty("Cancel Button Text:", true, 12, false)] public virtual string CancelButtonText { get; set; } [EntryStringUiProperty("Title:", true, 13, false)] public virtual string Title { get; set; } [OnOffUiProperty("Use Navigation View", true, 14)] public virtual bool UseNavigationBar { get; set; } [EntryIntegerUiProperty("Timeout (S):", true, 15, false)] public virtual int? Timeout { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="InputGroup"/> is valid. /// A valid input group is one in which each <see cref="Input"/> in the group is valid. /// An input group with no inputs is deemed valid by default. /// </summary> [JsonIgnore] public bool Valid => Inputs.GroupBy(x => x?.RequiredGroup).All(x => (string.IsNullOrWhiteSpace(x.Key) && x.All(y => y?.Valid ?? true)) || (string.IsNullOrWhiteSpace(x.Key) == false && x.Any(y => y?.Valid ?? true))); //Inputs.All(input => input?.Valid ?? true); public InputGroup() { Id = Guid.NewGuid().ToString(); Inputs = NewObservableCollection(); Geotag = false; ForceValidInputs = false; ShuffleInputs = false; } private ObservableCollection<Input> NewObservableCollection() { ObservableCollection<Input> collection = new ObservableCollection<Input>(); // I've tested this and the closure still looks up Id by reference. // That means we don't need to update this handler when Id changes. collection.CollectionChanged += CollectionChanged; return collection; } private void CollectionChanged(object o, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach (Input input in e.NewItems) { input.GroupId = Id; } } if (e.Action == NotifyCollectionChangedAction.Remove) { foreach (Input input in e.OldItems) { input.GroupId = null; } } } /// <summary> /// Creates a copy of this <see cref="InputGroup"/>. /// </summary> /// <returns>The copy.</returns> /// <param name="newId">If set to <c>true</c>, set new random <see cref="Id"/> and <see cref="Input.Id"/> values for the current group /// and <see cref="Input"/>s associated with this <see cref="InputGroup"/>.</param> public InputGroup Copy(bool newId) { InputGroup copy = JsonConvert.DeserializeObject<InputGroup>(JsonConvert.SerializeObject(this, SensusServiceHelper.JSON_SERIALIZER_SETTINGS), SensusServiceHelper.JSON_SERIALIZER_SETTINGS); if (newId) { copy.Id = Guid.NewGuid().ToString(); // update all inputs to have the new group ID and new IDs themselves. foreach (Input input in copy.Inputs) { input.GroupId = copy.Id; input.Id = Guid.NewGuid().ToString(); } } return copy; } } }
// 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; using System.Globalization; using Xunit; namespace System.ComponentModel.Tests { public class TypeDescriptorTests { [Fact] public void AddAndRemoveProvider() { var provider = new InvocationRecordingTypeDescriptionProvider(); var component = new DescriptorTestComponent(); TypeDescriptor.AddProvider(provider, component); var retrievedProvider = TypeDescriptor.GetProvider(component); retrievedProvider.GetCache(component); Assert.True(provider.ReceivedCall); provider.Reset(); TypeDescriptor.RemoveProvider(provider, component); retrievedProvider = TypeDescriptor.GetProvider(component); retrievedProvider.GetCache(component); Assert.False(provider.ReceivedCall); } [Fact] public void AddAttribute() { var component = new DescriptorTestComponent(); var addedAttribute = new DescriptorTestAttribute("expected string"); TypeDescriptor.AddAttributes(component.GetType(), addedAttribute); AttributeCollection attributes = TypeDescriptor.GetAttributes(component); Assert.True(attributes.Contains(addedAttribute)); } [Fact] public void CreateInstancePassesCtorParameters() { var expectedString = "expected string"; var component = TypeDescriptor.CreateInstance(null, typeof(DescriptorTestComponent), new[] { expectedString.GetType() }, new[] { expectedString }); Assert.NotNull(component); Assert.IsType(typeof(DescriptorTestComponent), component); Assert.Equal(expectedString, (component as DescriptorTestComponent).StringProperty); } [Fact] public void GetAssociationReturnsExpectedObject() { var primaryObject = new DescriptorTestComponent(); var secondaryObject = new MockEventDescriptor(); TypeDescriptor.CreateAssociation(primaryObject, secondaryObject); var associatedObject = TypeDescriptor.GetAssociation(secondaryObject.GetType(), primaryObject); Assert.IsType(secondaryObject.GetType(), associatedObject); Assert.Equal(secondaryObject, associatedObject); } [Fact] public static void GetConverter() { foreach (Tuple<Type, Type> pair in s_typesWithConverters) { TypeConverter converter = TypeDescriptor.GetConverter(pair.Item1); Assert.NotNull(converter); Assert.Equal(pair.Item2, converter.GetType()); Assert.True(converter.CanConvertTo(typeof(string))); } } [Fact] public static void GetConverter_null() { Assert.Throws<ArgumentNullException>(() => TypeDescriptor.GetConverter(null)); } [Fact] public static void GetConverter_NotAvailable() { Assert.Throws<MissingMethodException>( () => TypeDescriptor.GetConverter(typeof(ClassWithInvalidConverter))); // GetConverter should throw MissingMethodException because parameterless constructor is missing in the InvalidConverter class. } [Fact] public void GetEvents() { var component = new DescriptorTestComponent(); EventDescriptorCollection events = TypeDescriptor.GetEvents(component); Assert.Equal(2, events.Count); } [Fact] public void GetEventsFiltersByAttribute() { var defaultValueAttribute = new DefaultValueAttribute(null); EventDescriptorCollection events = TypeDescriptor.GetEvents(typeof(DescriptorTestComponent), new[] { defaultValueAttribute }); Assert.Equal(1, events.Count); } [Fact] public void GetPropertiesFiltersByAttribute() { var defaultValueAttribute = new DefaultValueAttribute(DescriptorTestComponent.DefaultPropertyValue); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(DescriptorTestComponent), new[] { defaultValueAttribute }); Assert.Equal(1, properties.Count); } [Fact] public void RemoveAssociationsRemovesAllAssociations() { var primaryObject = new DescriptorTestComponent(); var firstAssociatedObject = new MockEventDescriptor(); var secondAssociatedObject = new MockPropertyDescriptor(); TypeDescriptor.CreateAssociation(primaryObject, firstAssociatedObject); TypeDescriptor.CreateAssociation(primaryObject, secondAssociatedObject); TypeDescriptor.RemoveAssociations(primaryObject); // GetAssociation never returns null. The default implementation returns the // primary object when an association doesn't exist. This isn't documented, // however, so here we only verify that the formerly associated objects aren't returned. var firstAssociation = TypeDescriptor.GetAssociation(firstAssociatedObject.GetType(), primaryObject); Assert.NotEqual(firstAssociatedObject, firstAssociation); var secondAssociation = TypeDescriptor.GetAssociation(secondAssociatedObject.GetType(), primaryObject); Assert.NotEqual(secondAssociatedObject, secondAssociation); } [Fact] public void RemoveSingleAssociation() { var primaryObject = new DescriptorTestComponent(); var firstAssociatedObject = new MockEventDescriptor(); var secondAssociatedObject = new MockPropertyDescriptor(); TypeDescriptor.CreateAssociation(primaryObject, firstAssociatedObject); TypeDescriptor.CreateAssociation(primaryObject, secondAssociatedObject); TypeDescriptor.RemoveAssociation(primaryObject, firstAssociatedObject); // the second association should remain var secondAssociation = TypeDescriptor.GetAssociation(secondAssociatedObject.GetType(), primaryObject); Assert.Equal(secondAssociatedObject, secondAssociation); // the first association should not var firstAssociation = TypeDescriptor.GetAssociation(firstAssociatedObject.GetType(), primaryObject); Assert.NotEqual(firstAssociatedObject, firstAssociation); } [Fact] public void DerivedPropertyAttribute() { PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(FooBarDerived))["Value"]; var descriptionAttribute = (DescriptionAttribute)property.Attributes[typeof(DescriptionAttribute)]; Assert.Equal("Derived", descriptionAttribute.Description); } private class InvocationRecordingTypeDescriptionProvider : TypeDescriptionProvider { public bool ReceivedCall { get; private set; } = false; public void Reset() => ReceivedCall = false; public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args) { ReceivedCall = true; return base.CreateInstance(provider, objectType, argTypes, args); } public override IDictionary GetCache(object instance) { ReceivedCall = true; return base.GetCache(instance); } public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) { ReceivedCall = true; return base.GetExtendedTypeDescriptor(instance); } public override string GetFullComponentName(object component) { ReceivedCall = true; return base.GetFullComponentName(component); } public override Type GetReflectionType(Type objectType, object instance) { ReceivedCall = true; return base.GetReflectionType(objectType, instance); } protected override IExtenderProvider[] GetExtenderProviders(object instance) { ReceivedCall = true; return base.GetExtenderProviders(instance); } public override Type GetRuntimeType(Type reflectionType) { ReceivedCall = true; return base.GetRuntimeType(reflectionType); } public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { ReceivedCall = true; return base.GetTypeDescriptor(objectType, instance); } public override bool IsSupportedType(Type type) { ReceivedCall = true; return base.IsSupportedType(type); } } class FooBarBase { [Description("Base")] public virtual int Value { get; set; } } class FooBarDerived : FooBarBase { [Description("Derived")] public override int Value { get; set; } } private static Tuple<Type, Type>[] s_typesWithConverters = { new Tuple<Type, Type> (typeof(bool), typeof(BooleanConverter)), new Tuple<Type, Type> (typeof(byte), typeof(ByteConverter)), new Tuple<Type, Type> (typeof(SByte), typeof(SByteConverter)), new Tuple<Type, Type> (typeof(char), typeof(CharConverter)), new Tuple<Type, Type> (typeof(double), typeof(DoubleConverter)), new Tuple<Type, Type> (typeof(string), typeof(StringConverter)), new Tuple<Type, Type> (typeof(short), typeof(Int16Converter)), new Tuple<Type, Type> (typeof(int), typeof(Int32Converter)), new Tuple<Type, Type> (typeof(long), typeof(Int64Converter)), new Tuple<Type, Type> (typeof(float), typeof(SingleConverter)), new Tuple<Type, Type> (typeof(UInt16), typeof(UInt16Converter)), new Tuple<Type, Type> (typeof(UInt32), typeof(UInt32Converter)), new Tuple<Type, Type> (typeof(UInt64), typeof(UInt64Converter)), new Tuple<Type, Type> (typeof(object), typeof(TypeConverter)), new Tuple<Type, Type> (typeof(void), typeof(TypeConverter)), new Tuple<Type, Type> (typeof(DateTime), typeof(DateTimeConverter)), new Tuple<Type, Type> (typeof(DateTimeOffset), typeof(DateTimeOffsetConverter)), new Tuple<Type, Type> (typeof(Decimal), typeof(DecimalConverter)), new Tuple<Type, Type> (typeof(TimeSpan), typeof(TimeSpanConverter)), new Tuple<Type, Type> (typeof(Guid), typeof(GuidConverter)), new Tuple<Type, Type> (typeof(Array), typeof(ArrayConverter)), new Tuple<Type, Type> (typeof(ICollection), typeof(CollectionConverter)), new Tuple<Type, Type> (typeof(Enum), typeof(EnumConverter)), new Tuple<Type, Type> (typeof(SomeEnum), typeof(EnumConverter)), new Tuple<Type, Type> (typeof(SomeValueType?), typeof(NullableConverter)), new Tuple<Type, Type> (typeof(int?), typeof(NullableConverter)), new Tuple<Type, Type> (typeof(ClassWithNoConverter), typeof(TypeConverter)), new Tuple<Type, Type> (typeof(BaseClass), typeof(BaseClassConverter)), new Tuple<Type, Type> (typeof(DerivedClass), typeof(DerivedClassConverter)), new Tuple<Type, Type> (typeof(IBase), typeof(IBaseConverter)), new Tuple<Type, Type> (typeof(IDerived), typeof(IBaseConverter)), new Tuple<Type, Type> (typeof(ClassIBase), typeof(IBaseConverter)), new Tuple<Type, Type> (typeof(ClassIDerived), typeof(IBaseConverter)), new Tuple<Type, Type> (typeof(Uri), typeof(UriTypeConverter)), new Tuple<Type, Type> (typeof(CultureInfo), typeof(CultureInfoConverter)) }; } }
using System; using System.Collections; using CookComputing.MetaWeblog; using CookComputing.XmlRpc; using umbraco.BusinessLogic; using umbraco.cms.businesslogic; using umbraco.cms.businesslogic.datatype; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.web; using umbraco.presentation.channels.businesslogic; namespace umbraco.presentation.channels { /// <summary> /// the umbraco channels API is xml-rpc webservice based on the metaweblog and blogger APIs /// for editing umbraco data froom external clients /// </summary> [XmlRpcService( Name = "umbraco metablog api", Description = "For editing umbraco data from external clients", AutoDocumentation = true)] public class api : UmbracoMetaWeblogAPI, IRemixWeblogApi { /// <summary> /// Initializes a new instance of the <see cref="api"/> class. /// </summary> public api() { } /// <summary> /// Makes a new file to a designated blog using the metaWeblog API /// </summary> /// <param name="blogid">The blogid.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="file">The file.</param> /// <returns>Returns url as a string of a struct.</returns> [XmlRpcMethod("metaWeblog.newMediaObject", Description = "Makes a new file to a designated blog using the " + "metaWeblog API. Returns url as a string of a struct.")] public UrlData newMediaObject( string blogid, string username, string password, FileData file) { return newMediaObjectLogic(blogid, username, password, file); } #region IRemixWeblogApi Members /// <summary> /// Gets a summary of all the pages from the blog with the spefied blogId. /// </summary> /// <param name="blogid">The blogid.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns></returns> public wpPageSummary[] getPageList(string blogid, string username, string password) { if (User.validateCredentials(username, password, false)) { ArrayList blogPosts = new ArrayList(); ArrayList blogPostsObjects = new ArrayList(); User u = new User(username); Channel userChannel = new Channel(u.Id); Document rootDoc; if (userChannel.StartNode > 0) rootDoc = new Document(userChannel.StartNode); else rootDoc = new Document(u.StartNodeId); //store children array here because iterating over an Array object is very inneficient. var c = rootDoc.Children; foreach (Document d in c) { int count = 0; blogPosts.AddRange( findBlogPosts(userChannel, d, u.Name, ref count, 999, userChannel.FullTree)); } blogPosts.Sort(new DocumentSortOrderComparer()); foreach (Object o in blogPosts) { Document d = (Document)o; wpPageSummary p = new wpPageSummary(); p.dateCreated = d.CreateDateTime; p.page_title = d.Text; p.page_id = d.Id; p.page_parent_id = d.ParentId; blogPostsObjects.Add(p); } return (wpPageSummary[])blogPostsObjects.ToArray(typeof(wpPageSummary)); } else { return null; } } /// <summary> /// Gets a specified number of pages from the blog with the spefied blogId /// </summary> /// <param name="blogid">The blogid.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="numberOfItems">The number of pages.</param> /// <returns></returns> public wpPage[] getPages(string blogid, string username, string password, int numberOfItems) { if (User.validateCredentials(username, password, false)) { ArrayList blogPosts = new ArrayList(); ArrayList blogPostsObjects = new ArrayList(); User u = new User(username); Channel userChannel = new Channel(u.Id); Document rootDoc; if (userChannel.StartNode > 0) rootDoc = new Document(userChannel.StartNode); else rootDoc = new Document(u.StartNodeId); //store children array here because iterating over an Array object is very inneficient. var c = rootDoc.Children; foreach (Document d in c) { int count = 0; blogPosts.AddRange( findBlogPosts(userChannel, d, u.Name, ref count, numberOfItems, userChannel.FullTree)); } blogPosts.Sort(new DocumentSortOrderComparer()); foreach (Object o in blogPosts) { Document d = (Document)o; wpPage p = new wpPage(); p.dateCreated = d.CreateDateTime; p.title = d.Text; p.page_id = d.Id; p.wp_page_parent_id = d.ParentId; p.wp_page_parent_title = d.Parent.Text; p.permalink = library.NiceUrl(d.Id); p.description = d.getProperty(userChannel.FieldDescriptionAlias).Value.ToString(); p.link = library.NiceUrl(d.Id); if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "" && d.getProperty(userChannel.FieldCategoriesAlias) != null && ((string)d.getProperty(userChannel.FieldCategoriesAlias).Value) != "") { String categories = d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString(); char[] splitter = { ',' }; String[] categoryIds = categories.Split(splitter); p.categories = categoryIds; } blogPostsObjects.Add(p); } return (wpPage[])blogPostsObjects.ToArray(typeof(wpPage)); } else { return null; } } /// <summary> /// Creates a new blog category / tag. /// </summary> /// <param name="blogid">The blogid.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="category">The category.</param> /// <returns></returns> public string newCategory( string blogid, string username, string password, wpCategory category) { if (User.validateCredentials(username, password, false)) { Channel userChannel = new Channel(username); if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "") { // Find the propertytype via the document type ContentType blogPostType = ContentType.GetByAlias(userChannel.DocumentTypeAlias); PropertyType categoryType = blogPostType.getPropertyType(userChannel.FieldCategoriesAlias); interfaces.IUseTags tags = UseTags(categoryType); if (tags != null) { tags.AddTag(category.name); } else { PreValue pv = new PreValue(); pv.DataTypeId = categoryType.DataTypeDefinition.Id; pv.Value = category.name; pv.Save(); } } } return ""; } #endregion } }
/* * WebClient.cs - Implementation of "WebClient" class * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * Contributed by Gopal.V * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.IO; using System.Text; using System.ComponentModel; using System.Collections.Specialized; using System.Runtime.InteropServices; namespace System.Net { #if !ECMA_COMPAT [ComVisible(true)] #endif public sealed class WebClient #if CONFIG_COMPONENT_MODEL : Component #endif { private WebRequest webrequest=null; private WebResponse webresponse=null; private String baseAddress=null; private ICredentials credentials = null; const String defaultContentType = "application/octet-stream"; const String fileContentType = "multipart/form-data"; const String formContentType = "application/x-www-form-urlencoded"; private void CreateWebrequest(String str) { if(str == null) { throw new ArgumentNullException("str"); } if(webrequest!=null) { throw new WebException("Multiple connection attempts"); } Uri uri = new Uri(str); webrequest = WebRequest.Create(uri); if(webrequest is HttpWebRequest) { (webrequest as HttpWebRequest).KeepAlive = false; } if(credentials != null) { webrequest.Credentials = credentials; } this.baseAddress = str; } private void WriteToStream(Stream inStream, Stream outStream, long maxBytes) { byte[] buf = new byte [4096]; int read; bool checkMax = (maxBytes != -1); while((read=inStream.Read(buf, 0 , 4096)) > 0) { outStream.Write(buf,0,read); maxBytes -= read; if(checkMax && maxBytes <= 0) { break; } } } public byte[] DownloadData(String address) { Stream stream = OpenRead(address); MemoryStream memory = new MemoryStream(); WriteToStream(stream, memory,webresponse.ContentLength); byte[] retval = new byte[memory.Length]; Array.Copy(memory.GetBuffer(),retval,retval.Length); memory.Close(); return retval; } public void DownloadFile(String address, String fileName) { Stream stream = OpenRead(address); FileStream file = File.OpenWrite(fileName); WriteToStream(stream, file, webresponse.ContentLength); file.Close(); } public Stream OpenRead(String address) { CreateWebrequest(address); webresponse = webrequest.GetResponse(); return webresponse.GetResponseStream(); } public Stream OpenWrite(String address) { return OpenWrite(address, "POST"); } public Stream OpenWrite(String address, String method) { CreateWebrequest(address); webrequest.Method = method; return webrequest.GetRequestStream(); } public byte[] UploadData(String address, byte[] data) { return UploadData(address, "POST", data); } public byte[] UploadData(String address, String method, byte[] data) { CreateWebrequest(address); webrequest.Method = method; webrequest.ContentLength = data.Length; webrequest.ContentType = defaultContentType; Stream stream = webrequest.GetRequestStream(); stream.Write(data,0,data.Length); webresponse = webrequest.GetResponse(); MemoryStream memory = new MemoryStream(1024); WriteToStream(webresponse.GetResponseStream(),memory, webresponse.ContentLength); byte [] retval = new byte[memory.Length]; Array.Copy(memory.GetBuffer(), retval, retval.Length); memory.Close(); return retval; } public byte[] UploadFile(String address, String fileName) { return UploadFile(address, "POST", fileName); } /* Note: refer rfc2068.txt for more info */ public byte[] UploadFile(String address, String method, String fileName) { String name=Path.GetFileName(fileName); /* Some inane boundary not likely in a data stream generally */ String mimeBoundary = "--DotGNU--Portable--message--"+ DateTime.Now.Ticks.ToString("X"); byte [] boundary = Encoding.ASCII.GetBytes("\r\n--" + mimeBoundary + "\r\n"); String headerString = "--"+boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\";filename\""+name+"\""+"\r\n" + "\r\n"; byte [] header = Encoding.UTF8.GetBytes(headerString); CreateWebrequest(address); webrequest.Method = method; webrequest.ContentType = fileContentType + "; " + "boundary="+mimeBoundary; Stream file = File.OpenRead(fileName); try { webrequest.ContentLength = file.Length; webrequest.ContentLength += header.Length+boundary.Length; } catch { } Stream stream = webrequest.GetRequestStream(); // Send in the mime header stream.Write(header,0,header.Length); WriteToStream(file,stream,-1); // Send in the boundary stream.Write(boundary,0,boundary.Length); webresponse = webrequest.GetResponse(); MemoryStream memory = new MemoryStream(1024); WriteToStream(webresponse.GetResponseStream(),memory, webresponse.ContentLength); byte [] retval = new byte[memory.Length]; Array.Copy(memory.GetBuffer(), retval, retval.Length); memory.Close(); return retval; } [TODO] public byte[] UploadValues(String address, NameValueCollection data) { throw new NotImplementedException("UploadValues"); } [TODO] public byte[] UploadValues(String address, String method, NameValueCollection data) { throw new NotImplementedException("UploadValues"); } public String BaseAddress { get { return this.baseAddress; } set { this.baseAddress=value; } } public ICredentials Credentials { get { return credentials; } set { credentials = value; } } public WebHeaderCollection Headers { get { if(webrequest!=null) { return webrequest.Headers; } throw new WebException("Headers not available"); } set { if(webrequest!=null) { webrequest.Headers = value; } throw new WebException("Headers not available"); } } [TODO] public NameValueCollection QueryString { get { throw new NotImplementedException("QueryString"); } set { throw new NotImplementedException("QueryString"); } } public WebHeaderCollection ResponseHeaders { get { if(webresponse!=null) { return webresponse.Headers; } throw new WebException("Headers not available"); } } } }//namespace
// // LanguageManager.cs // // The MIT License (MIT) // // Copyright (c) 2013 Niklas Borglund // // 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 UnityEngine; using System.Collections; using System.Collections.Generic; using System.Xml; using System.IO; using System.Globalization; /// <summary> /// Change language event handler. /// </summary> public delegate void ChangeLanguageEventHandler(LanguageManager thisLanguage); public class LanguageManager : MonoBehaviour { #region Singleton private static LanguageManager instance = null; public static LanguageManager Instance { get { if (instance == null) { GameObject go = new GameObject(); instance = go.AddComponent<LanguageManager>(); go.name = "LanguageManager"; } return instance; } } public static bool HasInstance { get { return (instance != null); } } #endregion /// <summary> /// Occurs when a new language is loaded and initialized /// create a delegate method(ChangeLanguage(LanguageManager thisLanguage, CultureInfo newLanguage)) and subscribe /// </summary> public event ChangeLanguageEventHandler OnChangeLanguage; /// <summary> /// The language that the system will try and load if LoadResources is called. /// </summary> public string language = "en"; /// <summary> /// The default language. /// </summary> public string defaultLanguage = "en"; /// <summary> /// The path to use in the Resources.Load Method. /// </summary> private string resourceFile = "Localization/Generated Assets/Language"; /// <summary> The header to add to the xmlFile after the unwanted resx-stuff is removed(To read the file with XMLReader) </summary> private string xmlHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>"; /// <summary> Dictionary with the raw text elements </summary> private SortedDictionary<string, string> textDataBase = new SortedDictionary<string,string>(); /// <summary> The parsed localizedObject list </summary> private SortedDictionary<string, LocalizedObject> localizedObjectDataBase = new SortedDictionary<string, LocalizedObject>(); /// <summary> /// a bool which indicates if a language is loaded /// </summary> private bool initialized = false; //A list of all the available languages private List<string> availableLanguages = new List<string>(); /// <summary> /// Gets a list of the available languages. /// </summary> /// <value> /// The available languages. /// </value> public List<string> AvailableLanguages { get { return availableLanguages; } } #if !UNITY_WP8 //Same as availableLanguages, but contains more info in the form of System.Globalization.CultureInfo private List<CultureInfo> availableLanguagesCultureInfo = new List<CultureInfo>(); /// <summary> /// Gets the available languages culture info.(Same as availableLanguages, but contains more info in the form of System.Globalization.CultureInfo) /// </summary> /// <value> /// The available languages culture info. /// </value> public List<CultureInfo> AvailableLanguagesCultureInfo { get { return availableLanguagesCultureInfo; } } #endif /// <summary> /// a bool which indicates if a language is loaded /// </summary> /// <value> /// <c>true</c> if a language is loaded; otherwise, <c>false</c>. /// </value> public bool IsInitialized { get { return initialized; } } void Awake () { if (instance == null) { instance = this; DontDestroyOnLoad (this.gameObject); } if(PlayerPrefs.HasKey("cws_defaultLanguage")) { defaultLanguage = PlayerPrefs.GetString("cws_defaultLanguage"); } GetAvailableLanguages(); Debug.Log ("LanguageManager.cs: Waking up"); //Load the default language(if it exists) foreach(string availableLanguage in availableLanguages) { if(availableLanguage == defaultLanguage) { ChangeLanguage(availableLanguage); break; } } //otherwise - load the first language in the list if(!initialized && availableLanguages.Count > 0) { ChangeLanguage(availableLanguages[0]); } else if(!initialized) { Debug.LogError("LanguageManager.cs: No language is available! Use Window->Smart Localization tool to create a language"); } } void OnDestroy() { //Clear the event handler OnChangeLanguage = null; } /// <summary> /// Loads the language file, language is specified with the language variable /// </summary> private void LoadResources() { //Reset values initialized = false; textDataBase.Clear(); localizedObjectDataBase.Clear(); //Load the root file if language is null TextAsset languageDocument; if(language == null) { languageDocument = Resources.Load(resourceFile) as TextAsset; } else { languageDocument = Resources.Load(resourceFile + "." + language) as TextAsset; } if (!languageDocument && defaultLanguage != language) { //If the language does not exist, revert back to the default language and reload Debug.LogError("ERROR: Language file:" + language + " could not be found! - reverting to default language:" + defaultLanguage); ChangeLanguage(defaultLanguage); return; } else if(!languageDocument) { Debug.LogError("ERROR: Language file:" + language + " could not be found!"); return; } //Remove beginning of the file that we don't need //The part of the .resx file that int length = "</xsd:schema>".Length; string resxDocument = languageDocument.text; int index = resxDocument.IndexOf("</xsd:schema>"); index += length; string xmlDocument = resxDocument.Substring(index); //add the header to the document xmlDocument = xmlHeader + xmlDocument; //Create the xml file with the new reduced resx document XmlReader reader = XmlReader.Create(new StringReader(xmlDocument)); //read through the document and save the data ReadElements(reader); //done reader.Close(); initialized = true; } /// <summary> /// Reads the elements from the loaded xmldocument in LoadResources /// </summary> /// <param name='reader'> /// Reader. /// </param> private void ReadElements(XmlReader reader) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: //If this is a chunk of data, then parse it if (reader.Name == "data") { ReadData(reader); } break; } } } /// <summary> /// Reads a specific data tag from the xml document. /// </summary> /// <param name='reader'> /// Reader. /// </param> private void ReadData(XmlReader reader) { //If these values are not being set, //something is wrong. string key = "ERROR"; string value = "ERROR"; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "name") { key = reader.Value; } } } //Move back to the element reader.MoveToElement(); //Read the child nodes if (reader.ReadToDescendant("value")) { do { value = reader.ReadString(); } while (reader.ReadToNextSibling("value")); } //Add the raw values to the dictionary textDataBase.Add(key, value); //Add the localized parsed values to the localizedObjectDataBase LocalizedObject newLocalizedObject = new LocalizedObject(); newLocalizedObject.ObjectType = LocalizedObject.GetLocalizedObjectType(key); newLocalizedObject.TextValue = value; localizedObjectDataBase.Add(LocalizedObject.GetCleanKey(key,newLocalizedObject.ObjectType), newLocalizedObject); } /// <summary> /// Gets all the available languages. /// </summary> private void GetAvailableLanguages() { //Clear the available languages list availableLanguages.Clear(); #if !UNITY_WP8 availableLanguagesCultureInfo.Clear(); #endif Object[] languageFiles = Resources.LoadAll("Localization/Generated Assets", typeof(TextAsset)); string languageStart = "Language."; foreach(Object languageFile in languageFiles) { if(languageFile.name != "Language") //Skip the root file { if(languageFile.name.StartsWith(languageStart)) { string thisLanguageName = languageFile.name.Substring(languageStart.Length); availableLanguages.Add(thisLanguageName); #if !UNITY_WP8 availableLanguagesCultureInfo.Add(CultureInfo.GetCultureInfo(thisLanguageName)); #endif } } } } /// <summary> /// Returns a text value in the current language for the key. Returns null if nothing is found. /// </summary> /// <returns> /// The value in the specified language, returns null if nothing is found /// </returns> /// <param name='key'> /// The Language Key. /// </param> public string GetTextValue(string key) { LocalizedObject thisObject = GetLocalizedObject(key); if(thisObject != null) { return thisObject.TextValue; } Debug.LogError("LanguageManager.cs: Invalid Key:" + key + "for language: " + language); return null; } /// <summary> /// Gets the audio clip for the current language, returns null if nothing is found /// </summary> /// <returns> /// The audio clip. Null if nothing is found /// </returns> /// <param name='key'> /// Key. /// </param> public AudioClip GetAudioClip(string key) { LocalizedObject thisObject = GetLocalizedObject(key); if(thisObject != null) { return Resources.Load("Localization/" + language + "/Audio Files/" + key) as AudioClip; } return null; } /// <summary> /// Gets the prefab game object for the current language, returns null if nothing is found /// </summary> /// <returns> /// The loaded prefab. Null if nothing is found /// </returns> /// <param name='key'> /// Key. /// </param> public GameObject GetPrefab(string key) { LocalizedObject thisObject = GetLocalizedObject(key); if(thisObject != null) { return Resources.Load("Localization/" + language + "/Prefabs/" + key) as GameObject; } return null; } /// <summary> /// Gets the texture for the current language, returns null if nothing is found /// </summary> /// <returns> /// The loaded prefab. Null if nothing is found /// </returns> /// <param name='key'> /// Key. /// </param> public Texture GetTexture(string key) { LocalizedObject thisObject = GetLocalizedObject(key); if(thisObject != null) { return Resources.Load("Localization/" + language + "/Textures/" + key) as Texture; } return null; } /// <summary> /// Gets the localized object from the localizedObjectDataBase /// </summary> /// <returns> /// The localized object. Returns null if nothing is found /// </returns> /// <param name='key'> /// Key. /// </param> private LocalizedObject GetLocalizedObject(string key) { LocalizedObject thisObject; localizedObjectDataBase.TryGetValue(key, out thisObject); return thisObject; } /// <summary> /// Changes the language and tries to load it. /// </summary> /// <param name='language'> /// Language. /// </param> public void ChangeLanguage(string language) { this.language = language; LoadResources(); if(IsInitialized && OnChangeLanguage != null) { OnChangeLanguage(this); } } /// <summary> /// Returns the entire RAW language database from the loaded language in a Dictionary /// it contains type keys and everything /// </summary> /// <returns> /// The text data base. /// </returns> public Dictionary<string, string> GetTextDataBase() { //Convert the sorted dictionary to a new, regular one return new Dictionary<string,string>(textDataBase); } /// <summary> /// Gets the localized, clean and parsed object data base. /// </summary> /// <returns> /// The localized object data base. /// </returns> public Dictionary<string, LocalizedObject> GetLocalizedObjectDataBase() { //Convert the sorted dictionary to a new, regular one return new Dictionary<string,LocalizedObject>(localizedObjectDataBase); } /// <summary> /// Clear this instance and Destroys it /// </summary> public void Clear () { instance = null; DestroyImmediate(this.gameObject); } /// <summary> /// Sets the default language. This language will be loaded in Awake() if it exists /// By default this is set to = "en" /// </summary> /// <param name='languageName'> /// Language name. /// </param> public void SetDefaultLanguage(string languageName) { PlayerPrefs.SetString("cws_defaultLanguage", languageName); } /// <summary> /// Sets the default language. This language will be loaded in Awake() if it exists /// By default this is set to = "en" /// </summary> /// <param name='languageName'> /// Language name. /// </param> public void SetDefaultLanguage(CultureInfo languageInfo) { SetDefaultLanguage(languageInfo.Name); } /// <summary> /// Checks if the language is supported by this application /// languageName = strings like "en", "es", "sv" /// </summary> public bool IsLanguageSupported(string languageName) { return availableLanguages.Contains(languageName); } /// <summary> /// Checks if the language is supported by this application /// </summary> public bool IsLanguageSupported(CultureInfo cultureInfo) { return IsLanguageSupported(cultureInfo.Name); } /// <summary> /// Gets the system language for this application using Application.systemLanguage /// If its SystemLanguage.Unknown, a string with the value "Unknown" will be returned /// </summary> /// <returns> /// The system language. /// </returns> public string GetSystemLanguage() { if(Application.systemLanguage == SystemLanguage.Unknown) { Debug.LogWarning("LanguageManager.cs: The system language of this application is Unknown"); return "Unknown"; } string systemLanguage = Application.systemLanguage.ToString(); #if !UNITY_WP8 CultureInfo[] cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures); foreach(CultureInfo info in cultureInfos) { if(info.EnglishName == systemLanguage) { return info.Name; } } Debug.LogError("LanguageManager.cs: A system language of this application is could not be found!"); return "System Language not found!"; #else Debug.LogError("LanguageManager.cs: GetSystemLanguage() Feature is not currently available in Smart Localization for Windows Phone 8"); return defaultLanguage; #endif } /// <summary> /// Gets the culture info of the specified string /// languageName = strings like "en", "es", "sv" /// </summary> public CultureInfo GetCultureInfo(string languageName) { return CultureInfo.GetCultureInfo(languageName); } /// <summary> /// Adds the language changed listener to ChangeLanguageEventHandler. /// </summary> /// <param name="listener">Language changed listener.</param> public void addLanguageChangedListener(ChangeLanguageEventHandler listener) { if (OnChangeLanguage != null) { OnChangeLanguage += listener; } } /// <summary> /// Removes the language changed listener from ChangeLanguageEventHandler. /// </summary> /// <param name="listener">Language changed listener.</param> public void removeLanguageChangedListener(ChangeLanguageEventHandler listener) { if (OnChangeLanguage != null) { OnChangeLanguage -= listener; } } }
// GameLayer.cs // // Author(s) // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2012 s. Delcroix // // 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 Cocos2D; using Microsoft.Xna.Framework; namespace Jumpy { public class GameLayer : MainLayer { public enum Bonus : int { Bonus5 = 0, Bonus10, Bonus50, Bonus100, NumBonuses } int score; int currentPlatformTag; bool gameSuspended; int numPlatforms = 10; int minPlatformStep = 50; int maxPlatformStep = 300; int minBonusStep = 20; int maxBonusStep = 50; int platformTopPadding = 10; bool birdLookingRight; CCPoint bird_pos; Vector2 bird_vel; Vector2 bird_acc; public static CCScene Scene { get { var scene = new CCScene (); var layer = new GameLayer (); scene.AddChild(layer); return scene; } } public GameLayer () { gameSuspended = true; var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; InitPlatforms (); var bird = new CCSprite(batchnode.Texture, new CCRect(608,16,44,32)); batchnode.AddChild (bird,4,(int)Tags.Bird); CCSprite bonus; for(int i=0; i<(int)Bonus.NumBonuses; i++) { bonus = new CCSprite(batchnode.Texture, new CCRect(608+i*32,256,25,25)); batchnode.AddChild(bonus,4,(int)Tags.BomusStart+i); bonus.Visible = false; } var scoreLabel = new CCLabelBMFont("0", "Fonts/bitmapFont.fnt"); scoreLabel.Position = new CCPoint(160,430); AddChild(scoreLabel, 5, (int)Tags.ScoreLabel); } public override void OnEnter () { base.OnEnter (); Schedule(Step); #if WINDOWS || MACOS AccelerometerEnabled = false; TouchEnabled = true; TouchMode = CCTouchMode.OneByOne; #else AccelerometerEnabled = true; SingleTouchEnabled = false; #endif //IsAccelerometerEnabled = true; // CCDirector.SharedDirector.Accelerometer.SetDelegate(new AccelerometerDelegate(DidAccelerate); StartGame (); } void InitPlatforms () { currentPlatformTag = (int)Tags.PlatformsStart; while(currentPlatformTag < (int)Tags.PlatformsStart + numPlatforms) { InitPlatform(); currentPlatformTag++; } ResetPlatforms (); } private Random ran = new Random(); void InitPlatform () { CCRect rect; switch(ran.Next()%2) { case 0: rect = new CCRect(608,64,102,36); break; default: rect = new CCRect(608,128,90,32); break; } var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; var platform = new CCSprite(batchnode.Texture, rect); batchnode.AddChild(platform,3,currentPlatformTag); } float currentPlatformY; float currentMaxPlatformStep; int currentBonusPlatformIndex; int currentBonusType; int platformCount; void ResetPlatforms () { currentPlatformY = -1; currentPlatformTag = (int)Tags.PlatformsStart; currentMaxPlatformStep = 60.0f; currentBonusPlatformIndex = 0; currentBonusType = 0; platformCount = 0; while(currentPlatformTag < (int)Tags.PlatformsStart + numPlatforms) { ResetPlatform(); currentPlatformTag++; } } void ResetPlatform () { if(currentPlatformY < 0) { currentPlatformY = 30.0f; } else { currentPlatformY += ran.Next() % (int)(currentMaxPlatformStep - minPlatformStep) + minPlatformStep; if(currentMaxPlatformStep < maxPlatformStep) { currentMaxPlatformStep += 0.5f; } } var batchnode = GetChildByTag ((int)Tags.SpriteManager) as CCSpriteBatchNode; var platform = batchnode.GetChildByTag(currentPlatformTag) as CCSprite; if (ran.Next() % 2 == 1) platform.ScaleX = -1.0f; float x; var size = platform.ContentSize; if(currentPlatformY == 30.0f) { x = 160.0f; } else { x = ran.Next() % (320 - (int)size.Width) + size.Width / 2; } platform.Position = new CCPoint(x,currentPlatformY); platformCount++; if(platformCount == currentBonusPlatformIndex) { var bonus = batchnode.GetChildByTag((int)Tags.BomusStart+currentBonusType) as CCSprite; bonus.Position = new CCPoint(x,currentPlatformY+30); bonus.Visible = true; } } void StartGame () { score = 0; ResetClouds (); ResetPlatforms (); ResetBird (); ResetBonus(); // UIApplication.SharedApplication.IdleTimerDisabled=true; gameSuspended = false;; } void ResetBird() { var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; var bird = batchnode.GetChildByTag((int)Tags.Bird) as CCSprite; bird_pos.X = 160; bird_pos.Y = 160; bird.Position = bird_pos; bird_vel.X = 0; bird_vel.Y = 0; bird_acc.X = 0; bird_acc.Y = -550.0f; birdLookingRight = true; bird.ScaleX = 1.0f; } void ResetBonus () { var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; var bonus = batchnode.GetChildByTag((int)Tags.BomusStart+currentBonusType) as CCSprite; bonus.Visible = false; currentBonusPlatformIndex += ran.Next() % (maxBonusStep - minBonusStep) + minBonusStep; if(score < 10000) { currentBonusType = 0; } else if(score < 50000) { currentBonusType = ran.Next() % 2; } else if(score < 100000) { currentBonusType = ran.Next() % 3; } else { currentBonusType = ran.Next() % 2 + 2; } } protected override void Step (float dt) { base.Step (dt); if (gameSuspended) return; var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; var bird = batchnode.GetChildByTag((int)Tags.Bird) as CCSprite; var particles = GetChildByTag((int)Tags.Particles) as CCParticleSystem; bird_pos.X += bird_vel.X * dt; if(bird_vel.X < -30.0f && birdLookingRight) { birdLookingRight = false; bird.ScaleX = -1.0f; } else if (bird_vel.X > 30.0f && !birdLookingRight) { birdLookingRight = true; bird.ScaleX = 1.0f; } var bird_size = bird.ContentSize; float max_x = 320-bird_size.Width/2; float min_x = 0+bird_size.Width/2; if(bird_pos.X>max_x) bird_pos.X = max_x; if(bird_pos.X<min_x) bird_pos.X = min_x; bird_vel.Y += bird_acc.Y * dt; bird_pos.Y += bird_vel.Y * dt; var bonus = batchnode.GetChildByTag((int)Tags.BomusStart + currentBonusType); if(bonus.Visible) { var bonus_pos = bonus.Position; float range = 20.0f; if(bird_pos.X > bonus_pos.X - range && bird_pos.X < bonus_pos.Y + range && bird_pos.Y > bonus_pos.Y - range && bird_pos.Y < bonus_pos.Y + range ) { switch(currentBonusType) { case (int)Bonus.Bonus5: score += 5000; break; case (int)Bonus.Bonus10: score += 10000; break; case (int)Bonus.Bonus50: score += 50000; break; case (int)Bonus.Bonus100: score += 100000; break; } var scorelabel = GetChildByTag((int)Tags.ScoreLabel) as CCLabelBMFont; scorelabel.Text = score.ToString(); var a1 = new CCScaleTo(.2f,1.5f,.08f); var a2 = new CCScaleTo(.2f,1f,1f); var a3 = new CCSequence(a1,a2,a1,a2,a1,a2); scorelabel.RunAction(a3); ResetBonus (); } } int t; if(bird_vel.Y < 0) { t = (int)Tags.PlatformsStart; for(t = (int)Tags.PlatformsStart; t < (int)Tags.PlatformsStart + numPlatforms; t++) { var platform = batchnode.GetChildByTag(t) as CCSprite; var platform_size = platform.ContentSize; var platform_pos = platform.Position; max_x = platform_pos.X - platform_size.Width/2 - 10; min_x = platform_pos.X + platform_size.Width/2 + 10; float min_y = platform_pos.Y + (platform_size.Height+bird_size.Height)/2 - platformTopPadding; if(bird_pos.X > max_x && bird_pos.X < min_x && bird_pos.Y > platform_pos.Y && bird_pos.Y < min_y) { Jump(); } } if(bird_pos.Y < -bird_size.Height/2) { ShowHighScores(); } } else if(bird_pos.Y > 240) { float delta = bird_pos.Y - 240; bird_pos.Y = 240; currentPlatformY -= delta; for(t = (int)Tags.CloudsStart; t < (int)Tags.CloudsStart + numClouds; t++) { var cloud = batchnode.GetChildByTag(t) as CCSprite; var pos = cloud.Position; pos.Y -= delta * cloud.ScaleY * 0.8f; if(pos.Y < -cloud.ContentSize.Height/2) { currentCloudTag = t; ResetCloud(); } else { cloud.Position = pos; } } for(t = (int)Tags.PlatformsStart; t < (int)Tags.PlatformsStart + numPlatforms; t++) { var platform = batchnode.GetChildByTag(t) as CCSprite; var pos = platform.Position; pos = new CCPoint(pos.X,pos.Y-delta); if(pos.Y < -platform.ContentSize.Height/2) { currentPlatformTag = t; ResetPlatform (); } else { platform.Position = pos; } } if(bonus.Visible) { var pos = bonus.Position; pos.Y -= delta; if(pos.Y < -bonus.ContentSize.Height/2) { ResetBonus (); //[self resetBonus]; } else { bonus.Position = pos; } } score += (int)delta; var scoreLabel = GetChildByTag((int)Tags.ScoreLabel) as CCLabelBMFont; scoreLabel.SetString(score.ToString()); } bird.Position = bird_pos; if (particles !=null) { var particle_pos = new CCPoint(bird_pos.X,bird_pos.Y-17); particles.Position = particle_pos; } } void Jump () { bird_vel.Y = 400.0f + Math.Abs(bird_vel.X); var old_part = GetChildByTag((int)Tags.Particles); if (old_part!=null) RemoveChild(old_part,true); var particle = new CCParticleFireworks(); particle.Position = bird_pos; particle.Gravity = new CCPoint(0,-5000); particle.Duration = .3f; AddChild(particle,-1,(int)Tags.Particles); } public override bool TouchBegan(CCTouch touch) { return (true); } public override void TouchEnded(CCTouch touch) { float accel_filter = 0.1f; float ax = ConvertTouchToNodeSpace(touch).X - ConvertToNodeSpace(touch.PreviousLocationInView).X; ax /= 500; bird_vel.X = bird_vel.X * accel_filter + (float)ax * (1.0f - accel_filter) * 500.0f; } void HandleAccelerate (CCAcceleration acceleration) { if(gameSuspended) return; float accel_filter = 0.1f; bird_vel.X = bird_vel.X * accel_filter + (float)acceleration.X * (1.0f - accel_filter) * 500.0f; } void ShowHighScores () { gameSuspended = true; CCDirector.SharedDirector.ReplaceScene(new CCTransitionFade(1, HighScoreLayer.Scene(score),new CCColor3B(255,255,255))); } } public class AccelerometerDelegate : ICCAccelerometerDelegate { public virtual void DidAccelerate(CCAcceleration pAccelerationValue) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using Xunit.Abstractions; using System; using System.IO; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using XmlCoreTest.Common; namespace System.Xml.Tests { public class CSameInstanceXsltArgTestCase : XsltApiTestCaseBase { // Variables from init string protected string _strPath; // Path of the data files // Other global variables public XsltArgumentList xsltArg1; // Shared XsltArgumentList for same instance testing private ITestOutputHelper _output; public CSameInstanceXsltArgTestCase(ITestOutputHelper output) : base(output) { _output = output; Init(null); } public new void Init(object objParam) { // Get parameter info _strPath = Path.Combine(@"TestFiles\", FilePathUtil.GetTestDataPath(), @"XsltApi\"); xsltArg1 = new XsltArgumentList(); MyObject obj1 = new MyObject(1, _output); MyObject obj2 = new MyObject(2, _output); MyObject obj3 = new MyObject(3, _output); MyObject obj4 = new MyObject(4, _output); MyObject obj5 = new MyObject(5, _output); xsltArg1.AddExtensionObject("urn:my-obj1", obj1); xsltArg1.AddExtensionObject("urn:my-obj2", obj2); xsltArg1.AddExtensionObject("urn:my-obj3", obj3); xsltArg1.AddExtensionObject("urn:my-obj4", obj4); xsltArg1.AddExtensionObject("urn:my-obj5", obj5); xsltArg1.AddParam("myArg1", szEmpty, "Test1"); xsltArg1.AddParam("myArg2", szEmpty, "Test2"); xsltArg1.AddParam("myArg3", szEmpty, "Test3"); xsltArg1.AddParam("myArg4", szEmpty, "Test4"); xsltArg1.AddParam("myArg5", szEmpty, "Test5"); return; } } //[TestCase(Name = "Same instance testing: XsltArgList - GetParam", Desc = "GetParam test cases")] public class CSameInstanceXsltArgumentListGetParam : CSameInstanceXsltArgTestCase { private ITestOutputHelper _output; public CSameInstanceXsltArgumentListGetParam(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple GetParam() over same ArgumentList //////////////////////////////////////////////////////////////// public int GetParam1(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetParam(((object[])args)[1].ToString(), szEmpty); _output.WriteLine("GetParam: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tAdded Value: {0}\tRetrieved Value:{1}\n", "Test1", retObj.ToString()); if (retObj.ToString() != "Test1") { _output.WriteLine("ERROR!!!"); return 0; } } return 1; } public int GetParam2(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetParam(((object[])args)[1].ToString(), szEmpty); string expected = "Test" + ((object[])args)[0]; _output.WriteLine("GetParam: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tAdded Value: {0}\tRetrieved Value:{1}\n", expected, retObj.ToString()); if (retObj.ToString() != expected) { _output.WriteLine("ERROR!!!"); return 0; } } return 1; } //[Variation("Multiple GetParam for same parameter name")] [InlineData()] [Theory] public void proc1() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 1, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 2, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 3, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 4, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam1), new Object[] { 5, "myArg1" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple GetParam for different parameter name")] [InlineData()] [Theory] public void proc2() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 1, "myArg1" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 2, "myArg2" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 3, "myArg3" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 4, "myArg4" }); rThreads.Add(new ThreadFunc(GetParam2), new Object[] { 5, "myArg5" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } //[TestCase(Name = "Same instance testing: XsltArgList - GetExtensionObject", Desc = "GetExtensionObject test cases")] public class CSameInstanceXsltArgumentListGetExtnObject : CSameInstanceXsltArgTestCase { private ITestOutputHelper _output; public CSameInstanceXsltArgumentListGetExtnObject(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple GetExtensionObject() over same ArgumentList //////////////////////////////////////////////////////////////// public int GetExtnObject1(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetExtensionObject(((object[])args)[1].ToString()); _output.WriteLine("GetExtensionObject: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tValue returned: " + ((MyObject)retObj).MyValue()); if (((MyObject)retObj).MyValue() != 1) { _output.WriteLine("ERROR!!! Set and retrieved value appear to be different"); return 0; } } return 1; } public int GetExtnObject2(object args) { Object retObj; for (int i = 1; i <= 100; i++) { retObj = xsltArg1.GetExtensionObject(((object[])args)[1].ToString()); _output.WriteLine("GetExtensionObject: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tValue returned: " + ((MyObject)retObj).MyValue()); if (((MyObject)retObj).MyValue() != (int)((object[])args)[0]) { _output.WriteLine("ERROR!!! Set and retrieved value appear to be different"); return 0; } } return 1; } //[Variation("Multiple GetExtensionObject for same namespace System.Xml.Tests")] [InlineData()] [Theory] public void proc1() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 1, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 2, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 3, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 4, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject1), new Object[] { 5, "urn:my-obj1" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple GetExtensionObject for different namespace System.Xml.Tests")] [InlineData()] [Theory] public void proc2() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 1, "urn:my-obj1" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 2, "urn:my-obj2" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 3, "urn:my-obj3" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 4, "urn:my-obj4" }); rThreads.Add(new ThreadFunc(GetExtnObject2), new Object[] { 5, "urn:my-obj5" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } //[TestCase(Name = "Same instance testing: XsltArgList - Transform", Desc = "Multiple transforms")] public class CSameInstanceXsltArgumentListTransform : CSameInstanceXsltArgTestCase { private ITestOutputHelper _output; public CSameInstanceXsltArgumentListTransform(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple Transform() using shared ArgumentList //////////////////////////////////////////////////////////////// public int SharedArgList(object args) { string _strXslFile = ((object[])args)[1].ToString(); string _strXmlFile = ((object[])args)[2].ToString(); if (_strXslFile.Substring(0, 5) != "http:") _strXslFile = Path.Combine(_strPath, _strXslFile); if (_strXmlFile.Substring(0, 5) != "http:") _strXmlFile = Path.Combine(_strPath, _strXmlFile); #pragma warning disable 0618 XmlValidatingReader xrData = new XmlValidatingReader(new XmlTextReader(_strXmlFile)); XPathDocument xd = new XPathDocument(xrData, XmlSpace.Preserve); xrData.Dispose(); XslTransform xslt = new XslTransform(); XmlValidatingReader xrTemp = new XmlValidatingReader(new XmlTextReader(_strXslFile)); #pragma warning restore 0618 xrTemp.ValidationType = ValidationType.None; xrTemp.EntityHandling = EntityHandling.ExpandCharEntities; xslt.Load(xrTemp); XmlReader xrXSLT = null; for (int i = 1; i <= 100; i++) { xrXSLT = xslt.Transform(xd, xsltArg1); _output.WriteLine("SharedArgumentList: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tDone with transform..."); } return 1; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple Transform() using shared ArgumentList //////////////////////////////////////////////////////////////// //[Variation("Multiple transforms using shared ArgumentList")] [InlineData()] [Theory] public void proc1() { CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 1, "xsltarg_multithreading1.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 2, "xsltarg_multithreading2.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 3, "xsltarg_multithreading3.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 4, "xsltarg_multithreading4.xsl", "foo.xml" }); rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 5, "xsltarg_multithreading5.xsl", "foo.xml" }); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } }
/* * 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.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Avatar.Chat { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ChatModule")] public class ChatModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int DEBUG_CHANNEL = 2147483647; private bool m_enabled = true; private int m_saydistance = 20; private int m_shoutdistance = 100; private int m_whisperdistance = 10; internal object m_syncy = new object(); internal IConfig m_config; #region ISharedRegionModule Members public virtual void Initialise(IConfigSource config) { m_config = config.Configs["Chat"]; if (null == m_config) { m_log.Info("[CHAT]: no config found, plugin disabled"); m_enabled = false; return; } if (!m_config.GetBoolean("enabled", true)) { m_log.Info("[CHAT]: plugin disabled by configuration"); m_enabled = false; return; } m_whisperdistance = config.Configs["Chat"].GetInt("whisper_distance", m_whisperdistance); m_saydistance = config.Configs["Chat"].GetInt("say_distance", m_saydistance); m_shoutdistance = config.Configs["Chat"].GetInt("shout_distance", m_shoutdistance); } public virtual void AddRegion(Scene scene) { if (!m_enabled) return; scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnChatFromWorld += OnChatFromWorld; scene.EventManager.OnChatBroadcast += OnChatBroadcast; m_log.InfoFormat("[CHAT]: Initialized for {0} w:{1} s:{2} S:{3}", scene.RegionInfo.RegionName, m_whisperdistance, m_saydistance, m_shoutdistance); } public virtual void RegionLoaded(Scene scene) { if (!m_enabled) return; ISimulatorFeaturesModule featuresModule = scene.RequestModuleInterface<ISimulatorFeaturesModule>(); if (featuresModule != null) featuresModule.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest; } public virtual void RemoveRegion(Scene scene) { if (!m_enabled) return; scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnChatFromWorld -= OnChatFromWorld; scene.EventManager.OnChatBroadcast -= OnChatBroadcast; } public virtual void Close() { } public virtual void PostInitialise() { } public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "ChatModule"; } } #endregion public virtual void OnNewClient(IClientAPI client) { client.OnChatFromClient += OnChatFromClient; } protected OSChatMessage FixPositionOfChatMessage(OSChatMessage c) { ScenePresence avatar; Scene scene = (Scene)c.Scene; if ((avatar = scene.GetScenePresence(c.Sender.AgentId)) != null) c.Position = avatar.AbsolutePosition; return c; } public virtual void OnChatFromClient(Object sender, OSChatMessage c) { c = FixPositionOfChatMessage(c); // redistribute to interested subscribers Scene scene = (Scene)c.Scene; scene.EventManager.TriggerOnChatFromClient(sender, c); // early return if not on public or debug channel if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; // sanity check: if (c.Sender == null) { m_log.ErrorFormat("[CHAT]: OnChatFromClient from {0} has empty Sender field!", sender); return; } DeliverChatToAvatars(ChatSourceType.Agent, c); } public virtual void OnChatFromWorld(Object sender, OSChatMessage c) { // early return if not on public or debug channel if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; DeliverChatToAvatars(ChatSourceType.Object, c); } protected virtual void DeliverChatToAvatars(ChatSourceType sourceType, OSChatMessage c) { string fromName = c.From; UUID fromID = UUID.Zero; UUID ownerID = UUID.Zero; UUID targetID = c.TargetUUID; string message = c.Message; Scene scene = (Scene)c.Scene; Vector3 fromPos = c.Position; Vector3 regionPos = new Vector3(scene.RegionInfo.WorldLocX, scene.RegionInfo.WorldLocY, 0); if (c.Channel == DEBUG_CHANNEL) c.Type = ChatTypeEnum.DebugChannel; switch (sourceType) { case ChatSourceType.Agent: ScenePresence avatar = scene.GetScenePresence(c.Sender.AgentId); fromPos = avatar.AbsolutePosition; fromName = avatar.Name; fromID = c.Sender.AgentId; ownerID = c.Sender.AgentId; break; case ChatSourceType.Object: fromID = c.SenderUUID; if (c.SenderObject != null && c.SenderObject is SceneObjectPart) ownerID = ((SceneObjectPart)c.SenderObject).OwnerID; break; } // TODO: iterate over message if (message.Length >= 1000) // libomv limit message = message.Substring(0, 1000); // m_log.DebugFormat( // "[CHAT]: DCTA: fromID {0} fromName {1}, region{2}, cType {3}, sType {4}, targetID {5}", // fromID, fromName, scene.RegionInfo.RegionName, c.Type, sourceType, targetID); HashSet<UUID> receiverIDs = new HashSet<UUID>(); if (targetID == UUID.Zero) { // This should use ForEachClient, but clients don't have a position. // If camera is moved into client, then camera position can be used scene.ForEachScenePresence( delegate(ScenePresence presence) { if (TrySendChatMessage( presence, fromPos, regionPos, fromID, ownerID, fromName, c.Type, message, sourceType, false)) receiverIDs.Add(presence.UUID); } ); } else { // This is a send to a specific client eg from llRegionSayTo // no need to check distance etc, jand send is as say ScenePresence presence = scene.GetScenePresence(targetID); if (presence != null && !presence.IsChildAgent) { if (TrySendChatMessage( presence, fromPos, regionPos, fromID, ownerID, fromName, ChatTypeEnum.Say, message, sourceType, true)) receiverIDs.Add(presence.UUID); } } scene.EventManager.TriggerOnChatToClients( fromID, receiverIDs, message, c.Type, fromPos, fromName, sourceType, ChatAudibleLevel.Fully); } static private Vector3 CenterOfRegion = new Vector3(128, 128, 30); public virtual void OnChatBroadcast(Object sender, OSChatMessage c) { if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; ChatTypeEnum cType = c.Type; if (c.Channel == DEBUG_CHANNEL) cType = ChatTypeEnum.DebugChannel; if (cType == ChatTypeEnum.Region) cType = ChatTypeEnum.Say; if (c.Message.Length > 1100) c.Message = c.Message.Substring(0, 1000); // broadcast chat works by redistributing every incoming chat // message to each avatar in the scene. string fromName = c.From; UUID fromID = UUID.Zero; ChatSourceType sourceType = ChatSourceType.Object; if (null != c.Sender) { ScenePresence avatar = (c.Scene as Scene).GetScenePresence(c.Sender.AgentId); fromID = c.Sender.AgentId; fromName = avatar.Name; sourceType = ChatSourceType.Agent; } else if (c.SenderUUID != UUID.Zero) { fromID = c.SenderUUID; } // m_log.DebugFormat("[CHAT] Broadcast: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, cType, sourceType); HashSet<UUID> receiverIDs = new HashSet<UUID>(); ((Scene)c.Scene).ForEachRootClient( delegate(IClientAPI client) { // don't forward SayOwner chat from objects to // non-owner agents if ((c.Type == ChatTypeEnum.Owner) && (null != c.SenderObject) && (((SceneObjectPart)c.SenderObject).OwnerID != client.AgentId)) return; client.SendChatMessage( c.Message, (byte)cType, CenterOfRegion, fromName, fromID, fromID, (byte)sourceType, (byte)ChatAudibleLevel.Fully); receiverIDs.Add(client.AgentId); }); (c.Scene as Scene).EventManager.TriggerOnChatToClients( fromID, receiverIDs, c.Message, cType, CenterOfRegion, fromName, sourceType, ChatAudibleLevel.Fully); } /// <summary> /// Try to send a message to the given presence /// </summary> /// <param name="presence">The receiver</param> /// <param name="fromPos"></param> /// <param name="regionPos">/param> /// <param name="fromAgentID"></param> /// <param name='ownerID'> /// Owner of the message. For at least some messages from objects, this has to be correctly filled with the owner's UUID. /// This is the case for script error messages in viewer 3 since LLViewer change EXT-7762 /// </param> /// <param name="fromName"></param> /// <param name="type"></param> /// <param name="message"></param> /// <param name="src"></param> /// <returns>true if the message was sent to the receiver, false if it was not sent due to failing a /// precondition</returns> protected virtual bool TrySendChatMessage( ScenePresence presence, Vector3 fromPos, Vector3 regionPos, UUID fromAgentID, UUID ownerID, string fromName, ChatTypeEnum type, string message, ChatSourceType src, bool ignoreDistance) { if (presence.LifecycleState != ScenePresenceState.Running) return false; if (!ignoreDistance) { Vector3 fromRegionPos = fromPos + regionPos; Vector3 toRegionPos = presence.AbsolutePosition + new Vector3(presence.Scene.RegionInfo.WorldLocX, presence.Scene.RegionInfo.WorldLocY, 0); int dis = (int)Util.GetDistanceTo(toRegionPos, fromRegionPos); if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance || type == ChatTypeEnum.Say && dis > m_saydistance || type == ChatTypeEnum.Shout && dis > m_shoutdistance) { return false; } } // TODO: should change so the message is sent through the avatar rather than direct to the ClientView presence.ControllingClient.SendChatMessage( message, (byte) type, fromPos, fromName, fromAgentID, ownerID, (byte)src, (byte)ChatAudibleLevel.Fully); return true; } #region SimulatorFeaturesRequest static OSDInteger m_SayRange, m_WhisperRange, m_ShoutRange; private void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features) { OSD extras = new OSDMap(); if (features.ContainsKey("OpenSimExtras")) extras = features["OpenSimExtras"]; else features["OpenSimExtras"] = extras; if (m_SayRange == null) { // Do this only once m_SayRange = new OSDInteger(m_saydistance); m_WhisperRange = new OSDInteger(m_whisperdistance); m_ShoutRange = new OSDInteger(m_shoutdistance); } ((OSDMap)extras)["say-range"] = m_SayRange; ((OSDMap)extras)["whisper-range"] = m_WhisperRange; ((OSDMap)extras)["shout-range"] = m_ShoutRange; } #endregion } }
// Copyright (c) 2015, Intel Corporation // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // File implements Slicing-by-8 CRC Generation, as described in // "Novel Table Lookup-Based Algorithms for High-Performance CRC Generation" // IEEE TRANSACTIONS ON COMPUTERS, VOL. 57, NO. 11, NOVEMBER 2008 using System.Diagnostics; namespace System.IO.Compression { internal static class Crc32Helper { // Generated tables for crc calculation. // Each table n (starting at 0) contains remainders from the long division of // all possible byte values, shifted by an offset of (n * 4 bits). // The divisor used is the crc32 standard polynomial 0xEDB88320 // Please see cited paper for more details. private static readonly uint[] s_crcTable_0 = new uint[256] { 0x00000000u, 0x77073096u, 0xee0e612cu, 0x990951bau, 0x076dc419u, 0x706af48fu, 0xe963a535u, 0x9e6495a3u, 0x0edb8832u, 0x79dcb8a4u, 0xe0d5e91eu, 0x97d2d988u, 0x09b64c2bu, 0x7eb17cbdu, 0xe7b82d07u, 0x90bf1d91u, 0x1db71064u, 0x6ab020f2u, 0xf3b97148u, 0x84be41deu, 0x1adad47du, 0x6ddde4ebu, 0xf4d4b551u, 0x83d385c7u, 0x136c9856u, 0x646ba8c0u, 0xfd62f97au, 0x8a65c9ecu, 0x14015c4fu, 0x63066cd9u, 0xfa0f3d63u, 0x8d080df5u, 0x3b6e20c8u, 0x4c69105eu, 0xd56041e4u, 0xa2677172u, 0x3c03e4d1u, 0x4b04d447u, 0xd20d85fdu, 0xa50ab56bu, 0x35b5a8fau, 0x42b2986cu, 0xdbbbc9d6u, 0xacbcf940u, 0x32d86ce3u, 0x45df5c75u, 0xdcd60dcfu, 0xabd13d59u, 0x26d930acu, 0x51de003au, 0xc8d75180u, 0xbfd06116u, 0x21b4f4b5u, 0x56b3c423u, 0xcfba9599u, 0xb8bda50fu, 0x2802b89eu, 0x5f058808u, 0xc60cd9b2u, 0xb10be924u, 0x2f6f7c87u, 0x58684c11u, 0xc1611dabu, 0xb6662d3du, 0x76dc4190u, 0x01db7106u, 0x98d220bcu, 0xefd5102au, 0x71b18589u, 0x06b6b51fu, 0x9fbfe4a5u, 0xe8b8d433u, 0x7807c9a2u, 0x0f00f934u, 0x9609a88eu, 0xe10e9818u, 0x7f6a0dbbu, 0x086d3d2du, 0x91646c97u, 0xe6635c01u, 0x6b6b51f4u, 0x1c6c6162u, 0x856530d8u, 0xf262004eu, 0x6c0695edu, 0x1b01a57bu, 0x8208f4c1u, 0xf50fc457u, 0x65b0d9c6u, 0x12b7e950u, 0x8bbeb8eau, 0xfcb9887cu, 0x62dd1ddfu, 0x15da2d49u, 0x8cd37cf3u, 0xfbd44c65u, 0x4db26158u, 0x3ab551ceu, 0xa3bc0074u, 0xd4bb30e2u, 0x4adfa541u, 0x3dd895d7u, 0xa4d1c46du, 0xd3d6f4fbu, 0x4369e96au, 0x346ed9fcu, 0xad678846u, 0xda60b8d0u, 0x44042d73u, 0x33031de5u, 0xaa0a4c5fu, 0xdd0d7cc9u, 0x5005713cu, 0x270241aau, 0xbe0b1010u, 0xc90c2086u, 0x5768b525u, 0x206f85b3u, 0xb966d409u, 0xce61e49fu, 0x5edef90eu, 0x29d9c998u, 0xb0d09822u, 0xc7d7a8b4u, 0x59b33d17u, 0x2eb40d81u, 0xb7bd5c3bu, 0xc0ba6cadu, 0xedb88320u, 0x9abfb3b6u, 0x03b6e20cu, 0x74b1d29au, 0xead54739u, 0x9dd277afu, 0x04db2615u, 0x73dc1683u, 0xe3630b12u, 0x94643b84u, 0x0d6d6a3eu, 0x7a6a5aa8u, 0xe40ecf0bu, 0x9309ff9du, 0x0a00ae27u, 0x7d079eb1u, 0xf00f9344u, 0x8708a3d2u, 0x1e01f268u, 0x6906c2feu, 0xf762575du, 0x806567cbu, 0x196c3671u, 0x6e6b06e7u, 0xfed41b76u, 0x89d32be0u, 0x10da7a5au, 0x67dd4accu, 0xf9b9df6fu, 0x8ebeeff9u, 0x17b7be43u, 0x60b08ed5u, 0xd6d6a3e8u, 0xa1d1937eu, 0x38d8c2c4u, 0x4fdff252u, 0xd1bb67f1u, 0xa6bc5767u, 0x3fb506ddu, 0x48b2364bu, 0xd80d2bdau, 0xaf0a1b4cu, 0x36034af6u, 0x41047a60u, 0xdf60efc3u, 0xa867df55u, 0x316e8eefu, 0x4669be79u, 0xcb61b38cu, 0xbc66831au, 0x256fd2a0u, 0x5268e236u, 0xcc0c7795u, 0xbb0b4703u, 0x220216b9u, 0x5505262fu, 0xc5ba3bbeu, 0xb2bd0b28u, 0x2bb45a92u, 0x5cb36a04u, 0xc2d7ffa7u, 0xb5d0cf31u, 0x2cd99e8bu, 0x5bdeae1du, 0x9b64c2b0u, 0xec63f226u, 0x756aa39cu, 0x026d930au, 0x9c0906a9u, 0xeb0e363fu, 0x72076785u, 0x05005713u, 0x95bf4a82u, 0xe2b87a14u, 0x7bb12baeu, 0x0cb61b38u, 0x92d28e9bu, 0xe5d5be0du, 0x7cdcefb7u, 0x0bdbdf21u, 0x86d3d2d4u, 0xf1d4e242u, 0x68ddb3f8u, 0x1fda836eu, 0x81be16cdu, 0xf6b9265bu, 0x6fb077e1u, 0x18b74777u, 0x88085ae6u, 0xff0f6a70u, 0x66063bcau, 0x11010b5cu, 0x8f659effu, 0xf862ae69u, 0x616bffd3u, 0x166ccf45u, 0xa00ae278u, 0xd70dd2eeu, 0x4e048354u, 0x3903b3c2u, 0xa7672661u, 0xd06016f7u, 0x4969474du, 0x3e6e77dbu, 0xaed16a4au, 0xd9d65adcu, 0x40df0b66u, 0x37d83bf0u, 0xa9bcae53u, 0xdebb9ec5u, 0x47b2cf7fu, 0x30b5ffe9u, 0xbdbdf21cu, 0xcabac28au, 0x53b39330u, 0x24b4a3a6u, 0xbad03605u, 0xcdd70693u, 0x54de5729u, 0x23d967bfu, 0xb3667a2eu, 0xc4614ab8u, 0x5d681b02u, 0x2a6f2b94u, 0xb40bbe37u, 0xc30c8ea1u, 0x5a05df1bu, 0x2d02ef8du }; private static readonly uint[] s_crcTable_1 = new uint[256] { 0x00000000u, 0x191B3141u, 0x32366282u, 0x2B2D53C3u, 0x646CC504u, 0x7D77F445u, 0x565AA786u, 0x4F4196C7u, 0xC8D98A08u, 0xD1C2BB49u, 0xFAEFE88Au, 0xE3F4D9CBu, 0xACB54F0Cu, 0xB5AE7E4Du, 0x9E832D8Eu, 0x87981CCFu, 0x4AC21251u, 0x53D92310u, 0x78F470D3u, 0x61EF4192u, 0x2EAED755u, 0x37B5E614u, 0x1C98B5D7u, 0x05838496u, 0x821B9859u, 0x9B00A918u, 0xB02DFADBu, 0xA936CB9Au, 0xE6775D5Du, 0xFF6C6C1Cu, 0xD4413FDFu, 0xCD5A0E9Eu, 0x958424A2u, 0x8C9F15E3u, 0xA7B24620u, 0xBEA97761u, 0xF1E8E1A6u, 0xE8F3D0E7u, 0xC3DE8324u, 0xDAC5B265u, 0x5D5DAEAAu, 0x44469FEBu, 0x6F6BCC28u, 0x7670FD69u, 0x39316BAEu, 0x202A5AEFu, 0x0B07092Cu, 0x121C386Du, 0xDF4636F3u, 0xC65D07B2u, 0xED705471u, 0xF46B6530u, 0xBB2AF3F7u, 0xA231C2B6u, 0x891C9175u, 0x9007A034u, 0x179FBCFBu, 0x0E848DBAu, 0x25A9DE79u, 0x3CB2EF38u, 0x73F379FFu, 0x6AE848BEu, 0x41C51B7Du, 0x58DE2A3Cu, 0xF0794F05u, 0xE9627E44u, 0xC24F2D87u, 0xDB541CC6u, 0x94158A01u, 0x8D0EBB40u, 0xA623E883u, 0xBF38D9C2u, 0x38A0C50Du, 0x21BBF44Cu, 0x0A96A78Fu, 0x138D96CEu, 0x5CCC0009u, 0x45D73148u, 0x6EFA628Bu, 0x77E153CAu, 0xBABB5D54u, 0xA3A06C15u, 0x888D3FD6u, 0x91960E97u, 0xDED79850u, 0xC7CCA911u, 0xECE1FAD2u, 0xF5FACB93u, 0x7262D75Cu, 0x6B79E61Du, 0x4054B5DEu, 0x594F849Fu, 0x160E1258u, 0x0F152319u, 0x243870DAu, 0x3D23419Bu, 0x65FD6BA7u, 0x7CE65AE6u, 0x57CB0925u, 0x4ED03864u, 0x0191AEA3u, 0x188A9FE2u, 0x33A7CC21u, 0x2ABCFD60u, 0xAD24E1AFu, 0xB43FD0EEu, 0x9F12832Du, 0x8609B26Cu, 0xC94824ABu, 0xD05315EAu, 0xFB7E4629u, 0xE2657768u, 0x2F3F79F6u, 0x362448B7u, 0x1D091B74u, 0x04122A35u, 0x4B53BCF2u, 0x52488DB3u, 0x7965DE70u, 0x607EEF31u, 0xE7E6F3FEu, 0xFEFDC2BFu, 0xD5D0917Cu, 0xCCCBA03Du, 0x838A36FAu, 0x9A9107BBu, 0xB1BC5478u, 0xA8A76539u, 0x3B83984Bu, 0x2298A90Au, 0x09B5FAC9u, 0x10AECB88u, 0x5FEF5D4Fu, 0x46F46C0Eu, 0x6DD93FCDu, 0x74C20E8Cu, 0xF35A1243u, 0xEA412302u, 0xC16C70C1u, 0xD8774180u, 0x9736D747u, 0x8E2DE606u, 0xA500B5C5u, 0xBC1B8484u, 0x71418A1Au, 0x685ABB5Bu, 0x4377E898u, 0x5A6CD9D9u, 0x152D4F1Eu, 0x0C367E5Fu, 0x271B2D9Cu, 0x3E001CDDu, 0xB9980012u, 0xA0833153u, 0x8BAE6290u, 0x92B553D1u, 0xDDF4C516u, 0xC4EFF457u, 0xEFC2A794u, 0xF6D996D5u, 0xAE07BCE9u, 0xB71C8DA8u, 0x9C31DE6Bu, 0x852AEF2Au, 0xCA6B79EDu, 0xD37048ACu, 0xF85D1B6Fu, 0xE1462A2Eu, 0x66DE36E1u, 0x7FC507A0u, 0x54E85463u, 0x4DF36522u, 0x02B2F3E5u, 0x1BA9C2A4u, 0x30849167u, 0x299FA026u, 0xE4C5AEB8u, 0xFDDE9FF9u, 0xD6F3CC3Au, 0xCFE8FD7Bu, 0x80A96BBCu, 0x99B25AFDu, 0xB29F093Eu, 0xAB84387Fu, 0x2C1C24B0u, 0x350715F1u, 0x1E2A4632u, 0x07317773u, 0x4870E1B4u, 0x516BD0F5u, 0x7A468336u, 0x635DB277u, 0xCBFAD74Eu, 0xD2E1E60Fu, 0xF9CCB5CCu, 0xE0D7848Du, 0xAF96124Au, 0xB68D230Bu, 0x9DA070C8u, 0x84BB4189u, 0x03235D46u, 0x1A386C07u, 0x31153FC4u, 0x280E0E85u, 0x674F9842u, 0x7E54A903u, 0x5579FAC0u, 0x4C62CB81u, 0x8138C51Fu, 0x9823F45Eu, 0xB30EA79Du, 0xAA1596DCu, 0xE554001Bu, 0xFC4F315Au, 0xD7626299u, 0xCE7953D8u, 0x49E14F17u, 0x50FA7E56u, 0x7BD72D95u, 0x62CC1CD4u, 0x2D8D8A13u, 0x3496BB52u, 0x1FBBE891u, 0x06A0D9D0u, 0x5E7EF3ECu, 0x4765C2ADu, 0x6C48916Eu, 0x7553A02Fu, 0x3A1236E8u, 0x230907A9u, 0x0824546Au, 0x113F652Bu, 0x96A779E4u, 0x8FBC48A5u, 0xA4911B66u, 0xBD8A2A27u, 0xF2CBBCE0u, 0xEBD08DA1u, 0xC0FDDE62u, 0xD9E6EF23u, 0x14BCE1BDu, 0x0DA7D0FCu, 0x268A833Fu, 0x3F91B27Eu, 0x70D024B9u, 0x69CB15F8u, 0x42E6463Bu, 0x5BFD777Au, 0xDC656BB5u, 0xC57E5AF4u, 0xEE530937u, 0xF7483876u, 0xB809AEB1u, 0xA1129FF0u, 0x8A3FCC33u, 0x9324FD72u }; private static readonly uint[] s_crcTable_2 = new uint[256] { 0x00000000u, 0x01C26A37u, 0x0384D46Eu, 0x0246BE59u, 0x0709A8DCu, 0x06CBC2EBu, 0x048D7CB2u, 0x054F1685u, 0x0E1351B8u, 0x0FD13B8Fu, 0x0D9785D6u, 0x0C55EFE1u, 0x091AF964u, 0x08D89353u, 0x0A9E2D0Au, 0x0B5C473Du, 0x1C26A370u, 0x1DE4C947u, 0x1FA2771Eu, 0x1E601D29u, 0x1B2F0BACu, 0x1AED619Bu, 0x18ABDFC2u, 0x1969B5F5u, 0x1235F2C8u, 0x13F798FFu, 0x11B126A6u, 0x10734C91u, 0x153C5A14u, 0x14FE3023u, 0x16B88E7Au, 0x177AE44Du, 0x384D46E0u, 0x398F2CD7u, 0x3BC9928Eu, 0x3A0BF8B9u, 0x3F44EE3Cu, 0x3E86840Bu, 0x3CC03A52u, 0x3D025065u, 0x365E1758u, 0x379C7D6Fu, 0x35DAC336u, 0x3418A901u, 0x3157BF84u, 0x3095D5B3u, 0x32D36BEAu, 0x331101DDu, 0x246BE590u, 0x25A98FA7u, 0x27EF31FEu, 0x262D5BC9u, 0x23624D4Cu, 0x22A0277Bu, 0x20E69922u, 0x2124F315u, 0x2A78B428u, 0x2BBADE1Fu, 0x29FC6046u, 0x283E0A71u, 0x2D711CF4u, 0x2CB376C3u, 0x2EF5C89Au, 0x2F37A2ADu, 0x709A8DC0u, 0x7158E7F7u, 0x731E59AEu, 0x72DC3399u, 0x7793251Cu, 0x76514F2Bu, 0x7417F172u, 0x75D59B45u, 0x7E89DC78u, 0x7F4BB64Fu, 0x7D0D0816u, 0x7CCF6221u, 0x798074A4u, 0x78421E93u, 0x7A04A0CAu, 0x7BC6CAFDu, 0x6CBC2EB0u, 0x6D7E4487u, 0x6F38FADEu, 0x6EFA90E9u, 0x6BB5866Cu, 0x6A77EC5Bu, 0x68315202u, 0x69F33835u, 0x62AF7F08u, 0x636D153Fu, 0x612BAB66u, 0x60E9C151u, 0x65A6D7D4u, 0x6464BDE3u, 0x662203BAu, 0x67E0698Du, 0x48D7CB20u, 0x4915A117u, 0x4B531F4Eu, 0x4A917579u, 0x4FDE63FCu, 0x4E1C09CBu, 0x4C5AB792u, 0x4D98DDA5u, 0x46C49A98u, 0x4706F0AFu, 0x45404EF6u, 0x448224C1u, 0x41CD3244u, 0x400F5873u, 0x4249E62Au, 0x438B8C1Du, 0x54F16850u, 0x55330267u, 0x5775BC3Eu, 0x56B7D609u, 0x53F8C08Cu, 0x523AAABBu, 0x507C14E2u, 0x51BE7ED5u, 0x5AE239E8u, 0x5B2053DFu, 0x5966ED86u, 0x58A487B1u, 0x5DEB9134u, 0x5C29FB03u, 0x5E6F455Au, 0x5FAD2F6Du, 0xE1351B80u, 0xE0F771B7u, 0xE2B1CFEEu, 0xE373A5D9u, 0xE63CB35Cu, 0xE7FED96Bu, 0xE5B86732u, 0xE47A0D05u, 0xEF264A38u, 0xEEE4200Fu, 0xECA29E56u, 0xED60F461u, 0xE82FE2E4u, 0xE9ED88D3u, 0xEBAB368Au, 0xEA695CBDu, 0xFD13B8F0u, 0xFCD1D2C7u, 0xFE976C9Eu, 0xFF5506A9u, 0xFA1A102Cu, 0xFBD87A1Bu, 0xF99EC442u, 0xF85CAE75u, 0xF300E948u, 0xF2C2837Fu, 0xF0843D26u, 0xF1465711u, 0xF4094194u, 0xF5CB2BA3u, 0xF78D95FAu, 0xF64FFFCDu, 0xD9785D60u, 0xD8BA3757u, 0xDAFC890Eu, 0xDB3EE339u, 0xDE71F5BCu, 0xDFB39F8Bu, 0xDDF521D2u, 0xDC374BE5u, 0xD76B0CD8u, 0xD6A966EFu, 0xD4EFD8B6u, 0xD52DB281u, 0xD062A404u, 0xD1A0CE33u, 0xD3E6706Au, 0xD2241A5Du, 0xC55EFE10u, 0xC49C9427u, 0xC6DA2A7Eu, 0xC7184049u, 0xC25756CCu, 0xC3953CFBu, 0xC1D382A2u, 0xC011E895u, 0xCB4DAFA8u, 0xCA8FC59Fu, 0xC8C97BC6u, 0xC90B11F1u, 0xCC440774u, 0xCD866D43u, 0xCFC0D31Au, 0xCE02B92Du, 0x91AF9640u, 0x906DFC77u, 0x922B422Eu, 0x93E92819u, 0x96A63E9Cu, 0x976454ABu, 0x9522EAF2u, 0x94E080C5u, 0x9FBCC7F8u, 0x9E7EADCFu, 0x9C381396u, 0x9DFA79A1u, 0x98B56F24u, 0x99770513u, 0x9B31BB4Au, 0x9AF3D17Du, 0x8D893530u, 0x8C4B5F07u, 0x8E0DE15Eu, 0x8FCF8B69u, 0x8A809DECu, 0x8B42F7DBu, 0x89044982u, 0x88C623B5u, 0x839A6488u, 0x82580EBFu, 0x801EB0E6u, 0x81DCDAD1u, 0x8493CC54u, 0x8551A663u, 0x8717183Au, 0x86D5720Du, 0xA9E2D0A0u, 0xA820BA97u, 0xAA6604CEu, 0xABA46EF9u, 0xAEEB787Cu, 0xAF29124Bu, 0xAD6FAC12u, 0xACADC625u, 0xA7F18118u, 0xA633EB2Fu, 0xA4755576u, 0xA5B73F41u, 0xA0F829C4u, 0xA13A43F3u, 0xA37CFDAAu, 0xA2BE979Du, 0xB5C473D0u, 0xB40619E7u, 0xB640A7BEu, 0xB782CD89u, 0xB2CDDB0Cu, 0xB30FB13Bu, 0xB1490F62u, 0xB08B6555u, 0xBBD72268u, 0xBA15485Fu, 0xB853F606u, 0xB9919C31u, 0xBCDE8AB4u, 0xBD1CE083u, 0xBF5A5EDAu, 0xBE9834EDu }; private static readonly uint[] s_crcTable_3 = new uint[256] { 0x00000000u, 0xB8BC6765u, 0xAA09C88Bu, 0x12B5AFEEu, 0x8F629757u, 0x37DEF032u, 0x256B5FDCu, 0x9DD738B9u, 0xC5B428EFu, 0x7D084F8Au, 0x6FBDE064u, 0xD7018701u, 0x4AD6BFB8u, 0xF26AD8DDu, 0xE0DF7733u, 0x58631056u, 0x5019579Fu, 0xE8A530FAu, 0xFA109F14u, 0x42ACF871u, 0xDF7BC0C8u, 0x67C7A7ADu, 0x75720843u, 0xCDCE6F26u, 0x95AD7F70u, 0x2D111815u, 0x3FA4B7FBu, 0x8718D09Eu, 0x1ACFE827u, 0xA2738F42u, 0xB0C620ACu, 0x087A47C9u, 0xA032AF3Eu, 0x188EC85Bu, 0x0A3B67B5u, 0xB28700D0u, 0x2F503869u, 0x97EC5F0Cu, 0x8559F0E2u, 0x3DE59787u, 0x658687D1u, 0xDD3AE0B4u, 0xCF8F4F5Au, 0x7733283Fu, 0xEAE41086u, 0x525877E3u, 0x40EDD80Du, 0xF851BF68u, 0xF02BF8A1u, 0x48979FC4u, 0x5A22302Au, 0xE29E574Fu, 0x7F496FF6u, 0xC7F50893u, 0xD540A77Du, 0x6DFCC018u, 0x359FD04Eu, 0x8D23B72Bu, 0x9F9618C5u, 0x272A7FA0u, 0xBAFD4719u, 0x0241207Cu, 0x10F48F92u, 0xA848E8F7u, 0x9B14583Du, 0x23A83F58u, 0x311D90B6u, 0x89A1F7D3u, 0x1476CF6Au, 0xACCAA80Fu, 0xBE7F07E1u, 0x06C36084u, 0x5EA070D2u, 0xE61C17B7u, 0xF4A9B859u, 0x4C15DF3Cu, 0xD1C2E785u, 0x697E80E0u, 0x7BCB2F0Eu, 0xC377486Bu, 0xCB0D0FA2u, 0x73B168C7u, 0x6104C729u, 0xD9B8A04Cu, 0x446F98F5u, 0xFCD3FF90u, 0xEE66507Eu, 0x56DA371Bu, 0x0EB9274Du, 0xB6054028u, 0xA4B0EFC6u, 0x1C0C88A3u, 0x81DBB01Au, 0x3967D77Fu, 0x2BD27891u, 0x936E1FF4u, 0x3B26F703u, 0x839A9066u, 0x912F3F88u, 0x299358EDu, 0xB4446054u, 0x0CF80731u, 0x1E4DA8DFu, 0xA6F1CFBAu, 0xFE92DFECu, 0x462EB889u, 0x549B1767u, 0xEC277002u, 0x71F048BBu, 0xC94C2FDEu, 0xDBF98030u, 0x6345E755u, 0x6B3FA09Cu, 0xD383C7F9u, 0xC1366817u, 0x798A0F72u, 0xE45D37CBu, 0x5CE150AEu, 0x4E54FF40u, 0xF6E89825u, 0xAE8B8873u, 0x1637EF16u, 0x048240F8u, 0xBC3E279Du, 0x21E91F24u, 0x99557841u, 0x8BE0D7AFu, 0x335CB0CAu, 0xED59B63Bu, 0x55E5D15Eu, 0x47507EB0u, 0xFFEC19D5u, 0x623B216Cu, 0xDA874609u, 0xC832E9E7u, 0x708E8E82u, 0x28ED9ED4u, 0x9051F9B1u, 0x82E4565Fu, 0x3A58313Au, 0xA78F0983u, 0x1F336EE6u, 0x0D86C108u, 0xB53AA66Du, 0xBD40E1A4u, 0x05FC86C1u, 0x1749292Fu, 0xAFF54E4Au, 0x322276F3u, 0x8A9E1196u, 0x982BBE78u, 0x2097D91Du, 0x78F4C94Bu, 0xC048AE2Eu, 0xD2FD01C0u, 0x6A4166A5u, 0xF7965E1Cu, 0x4F2A3979u, 0x5D9F9697u, 0xE523F1F2u, 0x4D6B1905u, 0xF5D77E60u, 0xE762D18Eu, 0x5FDEB6EBu, 0xC2098E52u, 0x7AB5E937u, 0x680046D9u, 0xD0BC21BCu, 0x88DF31EAu, 0x3063568Fu, 0x22D6F961u, 0x9A6A9E04u, 0x07BDA6BDu, 0xBF01C1D8u, 0xADB46E36u, 0x15080953u, 0x1D724E9Au, 0xA5CE29FFu, 0xB77B8611u, 0x0FC7E174u, 0x9210D9CDu, 0x2AACBEA8u, 0x38191146u, 0x80A57623u, 0xD8C66675u, 0x607A0110u, 0x72CFAEFEu, 0xCA73C99Bu, 0x57A4F122u, 0xEF189647u, 0xFDAD39A9u, 0x45115ECCu, 0x764DEE06u, 0xCEF18963u, 0xDC44268Du, 0x64F841E8u, 0xF92F7951u, 0x41931E34u, 0x5326B1DAu, 0xEB9AD6BFu, 0xB3F9C6E9u, 0x0B45A18Cu, 0x19F00E62u, 0xA14C6907u, 0x3C9B51BEu, 0x842736DBu, 0x96929935u, 0x2E2EFE50u, 0x2654B999u, 0x9EE8DEFCu, 0x8C5D7112u, 0x34E11677u, 0xA9362ECEu, 0x118A49ABu, 0x033FE645u, 0xBB838120u, 0xE3E09176u, 0x5B5CF613u, 0x49E959FDu, 0xF1553E98u, 0x6C820621u, 0xD43E6144u, 0xC68BCEAAu, 0x7E37A9CFu, 0xD67F4138u, 0x6EC3265Du, 0x7C7689B3u, 0xC4CAEED6u, 0x591DD66Fu, 0xE1A1B10Au, 0xF3141EE4u, 0x4BA87981u, 0x13CB69D7u, 0xAB770EB2u, 0xB9C2A15Cu, 0x017EC639u, 0x9CA9FE80u, 0x241599E5u, 0x36A0360Bu, 0x8E1C516Eu, 0x866616A7u, 0x3EDA71C2u, 0x2C6FDE2Cu, 0x94D3B949u, 0x090481F0u, 0xB1B8E695u, 0xA30D497Bu, 0x1BB12E1Eu, 0x43D23E48u, 0xFB6E592Du, 0xE9DBF6C3u, 0x516791A6u, 0xCCB0A91Fu, 0x740CCE7Au, 0x66B96194u, 0xDE0506F1u }; private static readonly uint[] s_crcTable_4 = new uint[256] { 0x00000000u, 0x3D6029B0u, 0x7AC05360u, 0x47A07AD0u, 0xF580A6C0u, 0xC8E08F70u, 0x8F40F5A0u, 0xB220DC10u, 0x30704BC1u, 0x0D106271u, 0x4AB018A1u, 0x77D03111u, 0xC5F0ED01u, 0xF890C4B1u, 0xBF30BE61u, 0x825097D1u, 0x60E09782u, 0x5D80BE32u, 0x1A20C4E2u, 0x2740ED52u, 0x95603142u, 0xA80018F2u, 0xEFA06222u, 0xD2C04B92u, 0x5090DC43u, 0x6DF0F5F3u, 0x2A508F23u, 0x1730A693u, 0xA5107A83u, 0x98705333u, 0xDFD029E3u, 0xE2B00053u, 0xC1C12F04u, 0xFCA106B4u, 0xBB017C64u, 0x866155D4u, 0x344189C4u, 0x0921A074u, 0x4E81DAA4u, 0x73E1F314u, 0xF1B164C5u, 0xCCD14D75u, 0x8B7137A5u, 0xB6111E15u, 0x0431C205u, 0x3951EBB5u, 0x7EF19165u, 0x4391B8D5u, 0xA121B886u, 0x9C419136u, 0xDBE1EBE6u, 0xE681C256u, 0x54A11E46u, 0x69C137F6u, 0x2E614D26u, 0x13016496u, 0x9151F347u, 0xAC31DAF7u, 0xEB91A027u, 0xD6F18997u, 0x64D15587u, 0x59B17C37u, 0x1E1106E7u, 0x23712F57u, 0x58F35849u, 0x659371F9u, 0x22330B29u, 0x1F532299u, 0xAD73FE89u, 0x9013D739u, 0xD7B3ADE9u, 0xEAD38459u, 0x68831388u, 0x55E33A38u, 0x124340E8u, 0x2F236958u, 0x9D03B548u, 0xA0639CF8u, 0xE7C3E628u, 0xDAA3CF98u, 0x3813CFCBu, 0x0573E67Bu, 0x42D39CABu, 0x7FB3B51Bu, 0xCD93690Bu, 0xF0F340BBu, 0xB7533A6Bu, 0x8A3313DBu, 0x0863840Au, 0x3503ADBAu, 0x72A3D76Au, 0x4FC3FEDAu, 0xFDE322CAu, 0xC0830B7Au, 0x872371AAu, 0xBA43581Au, 0x9932774Du, 0xA4525EFDu, 0xE3F2242Du, 0xDE920D9Du, 0x6CB2D18Du, 0x51D2F83Du, 0x167282EDu, 0x2B12AB5Du, 0xA9423C8Cu, 0x9422153Cu, 0xD3826FECu, 0xEEE2465Cu, 0x5CC29A4Cu, 0x61A2B3FCu, 0x2602C92Cu, 0x1B62E09Cu, 0xF9D2E0CFu, 0xC4B2C97Fu, 0x8312B3AFu, 0xBE729A1Fu, 0x0C52460Fu, 0x31326FBFu, 0x7692156Fu, 0x4BF23CDFu, 0xC9A2AB0Eu, 0xF4C282BEu, 0xB362F86Eu, 0x8E02D1DEu, 0x3C220DCEu, 0x0142247Eu, 0x46E25EAEu, 0x7B82771Eu, 0xB1E6B092u, 0x8C869922u, 0xCB26E3F2u, 0xF646CA42u, 0x44661652u, 0x79063FE2u, 0x3EA64532u, 0x03C66C82u, 0x8196FB53u, 0xBCF6D2E3u, 0xFB56A833u, 0xC6368183u, 0x74165D93u, 0x49767423u, 0x0ED60EF3u, 0x33B62743u, 0xD1062710u, 0xEC660EA0u, 0xABC67470u, 0x96A65DC0u, 0x248681D0u, 0x19E6A860u, 0x5E46D2B0u, 0x6326FB00u, 0xE1766CD1u, 0xDC164561u, 0x9BB63FB1u, 0xA6D61601u, 0x14F6CA11u, 0x2996E3A1u, 0x6E369971u, 0x5356B0C1u, 0x70279F96u, 0x4D47B626u, 0x0AE7CCF6u, 0x3787E546u, 0x85A73956u, 0xB8C710E6u, 0xFF676A36u, 0xC2074386u, 0x4057D457u, 0x7D37FDE7u, 0x3A978737u, 0x07F7AE87u, 0xB5D77297u, 0x88B75B27u, 0xCF1721F7u, 0xF2770847u, 0x10C70814u, 0x2DA721A4u, 0x6A075B74u, 0x576772C4u, 0xE547AED4u, 0xD8278764u, 0x9F87FDB4u, 0xA2E7D404u, 0x20B743D5u, 0x1DD76A65u, 0x5A7710B5u, 0x67173905u, 0xD537E515u, 0xE857CCA5u, 0xAFF7B675u, 0x92979FC5u, 0xE915E8DBu, 0xD475C16Bu, 0x93D5BBBBu, 0xAEB5920Bu, 0x1C954E1Bu, 0x21F567ABu, 0x66551D7Bu, 0x5B3534CBu, 0xD965A31Au, 0xE4058AAAu, 0xA3A5F07Au, 0x9EC5D9CAu, 0x2CE505DAu, 0x11852C6Au, 0x562556BAu, 0x6B457F0Au, 0x89F57F59u, 0xB49556E9u, 0xF3352C39u, 0xCE550589u, 0x7C75D999u, 0x4115F029u, 0x06B58AF9u, 0x3BD5A349u, 0xB9853498u, 0x84E51D28u, 0xC34567F8u, 0xFE254E48u, 0x4C059258u, 0x7165BBE8u, 0x36C5C138u, 0x0BA5E888u, 0x28D4C7DFu, 0x15B4EE6Fu, 0x521494BFu, 0x6F74BD0Fu, 0xDD54611Fu, 0xE03448AFu, 0xA794327Fu, 0x9AF41BCFu, 0x18A48C1Eu, 0x25C4A5AEu, 0x6264DF7Eu, 0x5F04F6CEu, 0xED242ADEu, 0xD044036Eu, 0x97E479BEu, 0xAA84500Eu, 0x4834505Du, 0x755479EDu, 0x32F4033Du, 0x0F942A8Du, 0xBDB4F69Du, 0x80D4DF2Du, 0xC774A5FDu, 0xFA148C4Du, 0x78441B9Cu, 0x4524322Cu, 0x028448FCu, 0x3FE4614Cu, 0x8DC4BD5Cu, 0xB0A494ECu, 0xF704EE3Cu, 0xCA64C78Cu }; private static readonly uint[] s_crcTable_5 = new uint[256] { 0x00000000u, 0xCB5CD3A5u, 0x4DC8A10Bu, 0x869472AEu, 0x9B914216u, 0x50CD91B3u, 0xD659E31Du, 0x1D0530B8u, 0xEC53826Du, 0x270F51C8u, 0xA19B2366u, 0x6AC7F0C3u, 0x77C2C07Bu, 0xBC9E13DEu, 0x3A0A6170u, 0xF156B2D5u, 0x03D6029Bu, 0xC88AD13Eu, 0x4E1EA390u, 0x85427035u, 0x9847408Du, 0x531B9328u, 0xD58FE186u, 0x1ED33223u, 0xEF8580F6u, 0x24D95353u, 0xA24D21FDu, 0x6911F258u, 0x7414C2E0u, 0xBF481145u, 0x39DC63EBu, 0xF280B04Eu, 0x07AC0536u, 0xCCF0D693u, 0x4A64A43Du, 0x81387798u, 0x9C3D4720u, 0x57619485u, 0xD1F5E62Bu, 0x1AA9358Eu, 0xEBFF875Bu, 0x20A354FEu, 0xA6372650u, 0x6D6BF5F5u, 0x706EC54Du, 0xBB3216E8u, 0x3DA66446u, 0xF6FAB7E3u, 0x047A07ADu, 0xCF26D408u, 0x49B2A6A6u, 0x82EE7503u, 0x9FEB45BBu, 0x54B7961Eu, 0xD223E4B0u, 0x197F3715u, 0xE82985C0u, 0x23755665u, 0xA5E124CBu, 0x6EBDF76Eu, 0x73B8C7D6u, 0xB8E41473u, 0x3E7066DDu, 0xF52CB578u, 0x0F580A6Cu, 0xC404D9C9u, 0x4290AB67u, 0x89CC78C2u, 0x94C9487Au, 0x5F959BDFu, 0xD901E971u, 0x125D3AD4u, 0xE30B8801u, 0x28575BA4u, 0xAEC3290Au, 0x659FFAAFu, 0x789ACA17u, 0xB3C619B2u, 0x35526B1Cu, 0xFE0EB8B9u, 0x0C8E08F7u, 0xC7D2DB52u, 0x4146A9FCu, 0x8A1A7A59u, 0x971F4AE1u, 0x5C439944u, 0xDAD7EBEAu, 0x118B384Fu, 0xE0DD8A9Au, 0x2B81593Fu, 0xAD152B91u, 0x6649F834u, 0x7B4CC88Cu, 0xB0101B29u, 0x36846987u, 0xFDD8BA22u, 0x08F40F5Au, 0xC3A8DCFFu, 0x453CAE51u, 0x8E607DF4u, 0x93654D4Cu, 0x58399EE9u, 0xDEADEC47u, 0x15F13FE2u, 0xE4A78D37u, 0x2FFB5E92u, 0xA96F2C3Cu, 0x6233FF99u, 0x7F36CF21u, 0xB46A1C84u, 0x32FE6E2Au, 0xF9A2BD8Fu, 0x0B220DC1u, 0xC07EDE64u, 0x46EAACCAu, 0x8DB67F6Fu, 0x90B34FD7u, 0x5BEF9C72u, 0xDD7BEEDCu, 0x16273D79u, 0xE7718FACu, 0x2C2D5C09u, 0xAAB92EA7u, 0x61E5FD02u, 0x7CE0CDBAu, 0xB7BC1E1Fu, 0x31286CB1u, 0xFA74BF14u, 0x1EB014D8u, 0xD5ECC77Du, 0x5378B5D3u, 0x98246676u, 0x852156CEu, 0x4E7D856Bu, 0xC8E9F7C5u, 0x03B52460u, 0xF2E396B5u, 0x39BF4510u, 0xBF2B37BEu, 0x7477E41Bu, 0x6972D4A3u, 0xA22E0706u, 0x24BA75A8u, 0xEFE6A60Du, 0x1D661643u, 0xD63AC5E6u, 0x50AEB748u, 0x9BF264EDu, 0x86F75455u, 0x4DAB87F0u, 0xCB3FF55Eu, 0x006326FBu, 0xF135942Eu, 0x3A69478Bu, 0xBCFD3525u, 0x77A1E680u, 0x6AA4D638u, 0xA1F8059Du, 0x276C7733u, 0xEC30A496u, 0x191C11EEu, 0xD240C24Bu, 0x54D4B0E5u, 0x9F886340u, 0x828D53F8u, 0x49D1805Du, 0xCF45F2F3u, 0x04192156u, 0xF54F9383u, 0x3E134026u, 0xB8873288u, 0x73DBE12Du, 0x6EDED195u, 0xA5820230u, 0x2316709Eu, 0xE84AA33Bu, 0x1ACA1375u, 0xD196C0D0u, 0x5702B27Eu, 0x9C5E61DBu, 0x815B5163u, 0x4A0782C6u, 0xCC93F068u, 0x07CF23CDu, 0xF6999118u, 0x3DC542BDu, 0xBB513013u, 0x700DE3B6u, 0x6D08D30Eu, 0xA65400ABu, 0x20C07205u, 0xEB9CA1A0u, 0x11E81EB4u, 0xDAB4CD11u, 0x5C20BFBFu, 0x977C6C1Au, 0x8A795CA2u, 0x41258F07u, 0xC7B1FDA9u, 0x0CED2E0Cu, 0xFDBB9CD9u, 0x36E74F7Cu, 0xB0733DD2u, 0x7B2FEE77u, 0x662ADECFu, 0xAD760D6Au, 0x2BE27FC4u, 0xE0BEAC61u, 0x123E1C2Fu, 0xD962CF8Au, 0x5FF6BD24u, 0x94AA6E81u, 0x89AF5E39u, 0x42F38D9Cu, 0xC467FF32u, 0x0F3B2C97u, 0xFE6D9E42u, 0x35314DE7u, 0xB3A53F49u, 0x78F9ECECu, 0x65FCDC54u, 0xAEA00FF1u, 0x28347D5Fu, 0xE368AEFAu, 0x16441B82u, 0xDD18C827u, 0x5B8CBA89u, 0x90D0692Cu, 0x8DD55994u, 0x46898A31u, 0xC01DF89Fu, 0x0B412B3Au, 0xFA1799EFu, 0x314B4A4Au, 0xB7DF38E4u, 0x7C83EB41u, 0x6186DBF9u, 0xAADA085Cu, 0x2C4E7AF2u, 0xE712A957u, 0x15921919u, 0xDECECABCu, 0x585AB812u, 0x93066BB7u, 0x8E035B0Fu, 0x455F88AAu, 0xC3CBFA04u, 0x089729A1u, 0xF9C19B74u, 0x329D48D1u, 0xB4093A7Fu, 0x7F55E9DAu, 0x6250D962u, 0xA90C0AC7u, 0x2F987869u, 0xE4C4ABCCu }; private static readonly uint[] s_crcTable_6 = new uint[256] { 0x00000000u, 0xA6770BB4u, 0x979F1129u, 0x31E81A9Du, 0xF44F2413u, 0x52382FA7u, 0x63D0353Au, 0xC5A73E8Eu, 0x33EF4E67u, 0x959845D3u, 0xA4705F4Eu, 0x020754FAu, 0xC7A06A74u, 0x61D761C0u, 0x503F7B5Du, 0xF64870E9u, 0x67DE9CCEu, 0xC1A9977Au, 0xF0418DE7u, 0x56368653u, 0x9391B8DDu, 0x35E6B369u, 0x040EA9F4u, 0xA279A240u, 0x5431D2A9u, 0xF246D91Du, 0xC3AEC380u, 0x65D9C834u, 0xA07EF6BAu, 0x0609FD0Eu, 0x37E1E793u, 0x9196EC27u, 0xCFBD399Cu, 0x69CA3228u, 0x582228B5u, 0xFE552301u, 0x3BF21D8Fu, 0x9D85163Bu, 0xAC6D0CA6u, 0x0A1A0712u, 0xFC5277FBu, 0x5A257C4Fu, 0x6BCD66D2u, 0xCDBA6D66u, 0x081D53E8u, 0xAE6A585Cu, 0x9F8242C1u, 0x39F54975u, 0xA863A552u, 0x0E14AEE6u, 0x3FFCB47Bu, 0x998BBFCFu, 0x5C2C8141u, 0xFA5B8AF5u, 0xCBB39068u, 0x6DC49BDCu, 0x9B8CEB35u, 0x3DFBE081u, 0x0C13FA1Cu, 0xAA64F1A8u, 0x6FC3CF26u, 0xC9B4C492u, 0xF85CDE0Fu, 0x5E2BD5BBu, 0x440B7579u, 0xE27C7ECDu, 0xD3946450u, 0x75E36FE4u, 0xB044516Au, 0x16335ADEu, 0x27DB4043u, 0x81AC4BF7u, 0x77E43B1Eu, 0xD19330AAu, 0xE07B2A37u, 0x460C2183u, 0x83AB1F0Du, 0x25DC14B9u, 0x14340E24u, 0xB2430590u, 0x23D5E9B7u, 0x85A2E203u, 0xB44AF89Eu, 0x123DF32Au, 0xD79ACDA4u, 0x71EDC610u, 0x4005DC8Du, 0xE672D739u, 0x103AA7D0u, 0xB64DAC64u, 0x87A5B6F9u, 0x21D2BD4Du, 0xE47583C3u, 0x42028877u, 0x73EA92EAu, 0xD59D995Eu, 0x8BB64CE5u, 0x2DC14751u, 0x1C295DCCu, 0xBA5E5678u, 0x7FF968F6u, 0xD98E6342u, 0xE86679DFu, 0x4E11726Bu, 0xB8590282u, 0x1E2E0936u, 0x2FC613ABu, 0x89B1181Fu, 0x4C162691u, 0xEA612D25u, 0xDB8937B8u, 0x7DFE3C0Cu, 0xEC68D02Bu, 0x4A1FDB9Fu, 0x7BF7C102u, 0xDD80CAB6u, 0x1827F438u, 0xBE50FF8Cu, 0x8FB8E511u, 0x29CFEEA5u, 0xDF879E4Cu, 0x79F095F8u, 0x48188F65u, 0xEE6F84D1u, 0x2BC8BA5Fu, 0x8DBFB1EBu, 0xBC57AB76u, 0x1A20A0C2u, 0x8816EAF2u, 0x2E61E146u, 0x1F89FBDBu, 0xB9FEF06Fu, 0x7C59CEE1u, 0xDA2EC555u, 0xEBC6DFC8u, 0x4DB1D47Cu, 0xBBF9A495u, 0x1D8EAF21u, 0x2C66B5BCu, 0x8A11BE08u, 0x4FB68086u, 0xE9C18B32u, 0xD82991AFu, 0x7E5E9A1Bu, 0xEFC8763Cu, 0x49BF7D88u, 0x78576715u, 0xDE206CA1u, 0x1B87522Fu, 0xBDF0599Bu, 0x8C184306u, 0x2A6F48B2u, 0xDC27385Bu, 0x7A5033EFu, 0x4BB82972u, 0xEDCF22C6u, 0x28681C48u, 0x8E1F17FCu, 0xBFF70D61u, 0x198006D5u, 0x47ABD36Eu, 0xE1DCD8DAu, 0xD034C247u, 0x7643C9F3u, 0xB3E4F77Du, 0x1593FCC9u, 0x247BE654u, 0x820CEDE0u, 0x74449D09u, 0xD23396BDu, 0xE3DB8C20u, 0x45AC8794u, 0x800BB91Au, 0x267CB2AEu, 0x1794A833u, 0xB1E3A387u, 0x20754FA0u, 0x86024414u, 0xB7EA5E89u, 0x119D553Du, 0xD43A6BB3u, 0x724D6007u, 0x43A57A9Au, 0xE5D2712Eu, 0x139A01C7u, 0xB5ED0A73u, 0x840510EEu, 0x22721B5Au, 0xE7D525D4u, 0x41A22E60u, 0x704A34FDu, 0xD63D3F49u, 0xCC1D9F8Bu, 0x6A6A943Fu, 0x5B828EA2u, 0xFDF58516u, 0x3852BB98u, 0x9E25B02Cu, 0xAFCDAAB1u, 0x09BAA105u, 0xFFF2D1ECu, 0x5985DA58u, 0x686DC0C5u, 0xCE1ACB71u, 0x0BBDF5FFu, 0xADCAFE4Bu, 0x9C22E4D6u, 0x3A55EF62u, 0xABC30345u, 0x0DB408F1u, 0x3C5C126Cu, 0x9A2B19D8u, 0x5F8C2756u, 0xF9FB2CE2u, 0xC813367Fu, 0x6E643DCBu, 0x982C4D22u, 0x3E5B4696u, 0x0FB35C0Bu, 0xA9C457BFu, 0x6C636931u, 0xCA146285u, 0xFBFC7818u, 0x5D8B73ACu, 0x03A0A617u, 0xA5D7ADA3u, 0x943FB73Eu, 0x3248BC8Au, 0xF7EF8204u, 0x519889B0u, 0x6070932Du, 0xC6079899u, 0x304FE870u, 0x9638E3C4u, 0xA7D0F959u, 0x01A7F2EDu, 0xC400CC63u, 0x6277C7D7u, 0x539FDD4Au, 0xF5E8D6FEu, 0x647E3AD9u, 0xC209316Du, 0xF3E12BF0u, 0x55962044u, 0x90311ECAu, 0x3646157Eu, 0x07AE0FE3u, 0xA1D90457u, 0x579174BEu, 0xF1E67F0Au, 0xC00E6597u, 0x66796E23u, 0xA3DE50ADu, 0x05A95B19u, 0x34414184u, 0x92364A30u }; private static readonly uint[] s_crcTable_7 = new uint[256] { 0x00000000u, 0xCCAA009Eu, 0x4225077Du, 0x8E8F07E3u, 0x844A0EFAu, 0x48E00E64u, 0xC66F0987u, 0x0AC50919u, 0xD3E51BB5u, 0x1F4F1B2Bu, 0x91C01CC8u, 0x5D6A1C56u, 0x57AF154Fu, 0x9B0515D1u, 0x158A1232u, 0xD92012ACu, 0x7CBB312Bu, 0xB01131B5u, 0x3E9E3656u, 0xF23436C8u, 0xF8F13FD1u, 0x345B3F4Fu, 0xBAD438ACu, 0x767E3832u, 0xAF5E2A9Eu, 0x63F42A00u, 0xED7B2DE3u, 0x21D12D7Du, 0x2B142464u, 0xE7BE24FAu, 0x69312319u, 0xA59B2387u, 0xF9766256u, 0x35DC62C8u, 0xBB53652Bu, 0x77F965B5u, 0x7D3C6CACu, 0xB1966C32u, 0x3F196BD1u, 0xF3B36B4Fu, 0x2A9379E3u, 0xE639797Du, 0x68B67E9Eu, 0xA41C7E00u, 0xAED97719u, 0x62737787u, 0xECFC7064u, 0x205670FAu, 0x85CD537Du, 0x496753E3u, 0xC7E85400u, 0x0B42549Eu, 0x01875D87u, 0xCD2D5D19u, 0x43A25AFAu, 0x8F085A64u, 0x562848C8u, 0x9A824856u, 0x140D4FB5u, 0xD8A74F2Bu, 0xD2624632u, 0x1EC846ACu, 0x9047414Fu, 0x5CED41D1u, 0x299DC2EDu, 0xE537C273u, 0x6BB8C590u, 0xA712C50Eu, 0xADD7CC17u, 0x617DCC89u, 0xEFF2CB6Au, 0x2358CBF4u, 0xFA78D958u, 0x36D2D9C6u, 0xB85DDE25u, 0x74F7DEBBu, 0x7E32D7A2u, 0xB298D73Cu, 0x3C17D0DFu, 0xF0BDD041u, 0x5526F3C6u, 0x998CF358u, 0x1703F4BBu, 0xDBA9F425u, 0xD16CFD3Cu, 0x1DC6FDA2u, 0x9349FA41u, 0x5FE3FADFu, 0x86C3E873u, 0x4A69E8EDu, 0xC4E6EF0Eu, 0x084CEF90u, 0x0289E689u, 0xCE23E617u, 0x40ACE1F4u, 0x8C06E16Au, 0xD0EBA0BBu, 0x1C41A025u, 0x92CEA7C6u, 0x5E64A758u, 0x54A1AE41u, 0x980BAEDFu, 0x1684A93Cu, 0xDA2EA9A2u, 0x030EBB0Eu, 0xCFA4BB90u, 0x412BBC73u, 0x8D81BCEDu, 0x8744B5F4u, 0x4BEEB56Au, 0xC561B289u, 0x09CBB217u, 0xAC509190u, 0x60FA910Eu, 0xEE7596EDu, 0x22DF9673u, 0x281A9F6Au, 0xE4B09FF4u, 0x6A3F9817u, 0xA6959889u, 0x7FB58A25u, 0xB31F8ABBu, 0x3D908D58u, 0xF13A8DC6u, 0xFBFF84DFu, 0x37558441u, 0xB9DA83A2u, 0x7570833Cu, 0x533B85DAu, 0x9F918544u, 0x111E82A7u, 0xDDB48239u, 0xD7718B20u, 0x1BDB8BBEu, 0x95548C5Du, 0x59FE8CC3u, 0x80DE9E6Fu, 0x4C749EF1u, 0xC2FB9912u, 0x0E51998Cu, 0x04949095u, 0xC83E900Bu, 0x46B197E8u, 0x8A1B9776u, 0x2F80B4F1u, 0xE32AB46Fu, 0x6DA5B38Cu, 0xA10FB312u, 0xABCABA0Bu, 0x6760BA95u, 0xE9EFBD76u, 0x2545BDE8u, 0xFC65AF44u, 0x30CFAFDAu, 0xBE40A839u, 0x72EAA8A7u, 0x782FA1BEu, 0xB485A120u, 0x3A0AA6C3u, 0xF6A0A65Du, 0xAA4DE78Cu, 0x66E7E712u, 0xE868E0F1u, 0x24C2E06Fu, 0x2E07E976u, 0xE2ADE9E8u, 0x6C22EE0Bu, 0xA088EE95u, 0x79A8FC39u, 0xB502FCA7u, 0x3B8DFB44u, 0xF727FBDAu, 0xFDE2F2C3u, 0x3148F25Du, 0xBFC7F5BEu, 0x736DF520u, 0xD6F6D6A7u, 0x1A5CD639u, 0x94D3D1DAu, 0x5879D144u, 0x52BCD85Du, 0x9E16D8C3u, 0x1099DF20u, 0xDC33DFBEu, 0x0513CD12u, 0xC9B9CD8Cu, 0x4736CA6Fu, 0x8B9CCAF1u, 0x8159C3E8u, 0x4DF3C376u, 0xC37CC495u, 0x0FD6C40Bu, 0x7AA64737u, 0xB60C47A9u, 0x3883404Au, 0xF42940D4u, 0xFEEC49CDu, 0x32464953u, 0xBCC94EB0u, 0x70634E2Eu, 0xA9435C82u, 0x65E95C1Cu, 0xEB665BFFu, 0x27CC5B61u, 0x2D095278u, 0xE1A352E6u, 0x6F2C5505u, 0xA386559Bu, 0x061D761Cu, 0xCAB77682u, 0x44387161u, 0x889271FFu, 0x825778E6u, 0x4EFD7878u, 0xC0727F9Bu, 0x0CD87F05u, 0xD5F86DA9u, 0x19526D37u, 0x97DD6AD4u, 0x5B776A4Au, 0x51B26353u, 0x9D1863CDu, 0x1397642Eu, 0xDF3D64B0u, 0x83D02561u, 0x4F7A25FFu, 0xC1F5221Cu, 0x0D5F2282u, 0x079A2B9Bu, 0xCB302B05u, 0x45BF2CE6u, 0x89152C78u, 0x50353ED4u, 0x9C9F3E4Au, 0x121039A9u, 0xDEBA3937u, 0xD47F302Eu, 0x18D530B0u, 0x965A3753u, 0x5AF037CDu, 0xFF6B144Au, 0x33C114D4u, 0xBD4E1337u, 0x71E413A9u, 0x7B211AB0u, 0xB78B1A2Eu, 0x39041DCDu, 0xF5AE1D53u, 0x2C8E0FFFu, 0xE0240F61u, 0x6EAB0882u, 0xA201081Cu, 0xA8C40105u, 0x646E019Bu, 0xEAE10678u, 0x264B06E6u }; // Calculate CRC based on the old CRC and the new bytes // See RFC1952 for details. static public uint UpdateCrc32(uint crc32, byte[] buffer, int offset, int length) { Debug.Assert((buffer != null) && (offset >= 0) && (length >= 0) && (offset <= buffer.Length - length), "check the caller"); Debug.Assert(BitConverter.IsLittleEndian, "UpdateCrc32 Expects Little Endian"); uint term1, term2, term3 = 0; crc32 ^= 0xFFFFFFFFU; int runningLength = (length / 8) * 8; int endBytes = length - runningLength; for (int i = 0; i < runningLength / 8; i++) { crc32 ^= (uint)(buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24); offset += 4; term1 = s_crcTable_7[crc32 & 0x000000FF] ^ s_crcTable_6[(crc32 >> 8) & 0x000000FF]; term2 = crc32 >> 16; crc32 = term1 ^ s_crcTable_5[term2 & 0x000000FF] ^ s_crcTable_4[(term2 >> 8) & 0x000000FF]; term3 = (uint)(buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24); offset += 4; term1 = s_crcTable_3[term3 & 0x000000FF] ^ s_crcTable_2[(term3 >> 8) & 0x000000FF]; term2 = term3 >> 16; crc32 ^= term1 ^ s_crcTable_1[term2 & 0x000000FF] ^ s_crcTable_0[(term2 >> 8) & 0x000000FF]; } for (int i = 0; i < endBytes; i++) { crc32 = s_crcTable_0[(crc32 ^ buffer[offset++]) & 0x000000FF] ^ (crc32 >> 8); } crc32 ^= 0xFFFFFFFFU; return crc32; } } }
using System; using System.Drawing; #if __UNIFIED__ using UIKit; using Foundation; using CoreGraphics; using RectangleF = CoreGraphics.CGRect; using SizeF = CoreGraphics.CGSize; using PointF = CoreGraphics.CGPoint; #else using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreGraphics; using nfloat = global::System.Single; using nint = global::System.Int32; using nuint = global::System.UInt32; #endif namespace SidebarNavigation { public class SidebarController : UIViewController { private Sidebar _sidebar; /// <summary> /// Required contructor. /// </summary> public SidebarController(IntPtr handle) : base(handle) { } /// <summary> /// Contructor. /// </summary> /// <param name="rootViewController"> /// The view controller that the Sidebar is being added to. /// </param> /// <param name="contentViewController"> /// The view controller for the content area. /// </param> /// <param name="navigationViewController"> /// The view controller for the side menu. /// </param> public SidebarController( UIViewController rootViewController, UIViewController contentViewController, UIViewController menuViewController) { _sidebar = new Sidebar(rootViewController, contentViewController, menuViewController); _sidebar.StateChangeHandler += (sender, e) => { if (StateChangeHandler != null) StateChangeHandler.Invoke(sender, e); }; ChangeMenuView(menuViewController); ChangeContentView(contentViewController); AttachSidebarControllerToRootController(rootViewController); } /// <summary> /// This Event will be called when the Sidebar menu is Opened/Closed (at the end of the animation). /// The Event Arg is a Boolean = isOpen. /// </summary> public event EventHandler<bool> StateChangeHandler; /// <summary> /// The view controller shown in the content area. /// </summary> public UIViewController ContentAreaController { get { return _sidebar.ContentViewController; } } /// <summary> /// The view controller for the side menu. /// This is what will be shown when the menu is displayed. /// </summary> public UIViewController MenuAreaController { get { return _sidebar.MenuViewController; } } /// <summary> /// Determines the percent of width to complete slide action. /// </summary> public float FlingPercentage { get { return _sidebar.FlingPercentage; } set { _sidebar.FlingPercentage = value; } } /// <summary> /// Determines the minimum velocity considered a "fling" to complete slide action. /// </summary> public float FlingVelocity { get { return _sidebar.FlingVelocity; } set { _sidebar.FlingVelocity = value; } } /// <summary> /// Active area where the Pan gesture is intercepted. /// </summary> public float GestureActiveArea { get { return _sidebar.GestureActiveArea; } set { _sidebar.GestureActiveArea = value; } } /// <summary> /// Gets or sets a value indicating whether there should be shadowing effects on the content view. /// </summary> public bool HasShadowing { get { return _sidebar.HasShadowing; } set { _sidebar.HasShadowing = value; } } /// <summary> /// Determines if the menu should be reopened after the screen is roated. /// </summary> public bool ReopenOnRotate { get { return _sidebar.ReopenOnRotate; } set { _sidebar.ReopenOnRotate = value; } } /// <summary> /// Determines the width of the menu when open. /// </summary> public int MenuWidth { get { return _sidebar.MenuWidth; } set { _sidebar.MenuWidth = value; } } /// <summary> /// Determines if the menu is on the left or right of the screen. /// </summary> public MenuLocations MenuLocation { get { return _sidebar.MenuLocation; } set { _sidebar.MenuLocation = value; } } /// <summary> /// Disables all open/close actions when set to true. /// </summary> public bool Disabled { get { return _sidebar.Disabled; } set { _sidebar.Disabled = value; } } /// <summary> /// Gets the current state of the menu. /// Setting this property will open/close the menu respectively. /// </summary> public bool IsOpen { get { return _sidebar.IsOpen; } set { _sidebar.IsOpen = value; if (_sidebar.IsOpen) CloseMenu(); else OpenMenu(); } } /// <summary> /// Toggles the menu open or closed. /// </summary> public void ToggleMenu() { if (IsOpen) _sidebar.CloseMenu(); else _sidebar.OpenMenu(); } /// <summary> /// Shows the slideout navigation menu. /// </summary> public void OpenMenu() { _sidebar.OpenMenu(); } /// <summary> /// Hides the slideout navigation menu. /// </summary> public void CloseMenu(bool animate = true) { _sidebar.CloseMenu(animate); } /// <summary> /// Replaces the content area view controller with the specified view controller. /// </summary> /// <param name="newContentView"> /// New content view. /// </param> public void ChangeContentView(UIViewController newContentView) { _sidebar.ChangeContentView(newContentView); AddContentViewToSidebar(); CloseMenu(); } /// <summary> /// Replaces the menu area view controller with the specified view controller. /// </summary> /// <param name="newMenuView"> /// New menu view. /// </param> public void ChangeMenuView(UIViewController newMenuView) { _sidebar.ChangeMenuView(newMenuView); AddMenuViewToSidebar(); } private void AddContentViewToSidebar() { SetContentViewBounds(); SetContentViewPosition(); View.AddSubview(ContentAreaController.View); AddChildViewController(ContentAreaController); } private void SetContentViewBounds() { var sidebarBounds = View.Bounds; if (ContentAreaController.View.Bounds.Equals(sidebarBounds)) return; ContentAreaController.View.Bounds = sidebarBounds; } private void SetContentViewPosition() { var sidebarBounds = View.Bounds; if (IsOpen) sidebarBounds.X = MenuWidth; ContentAreaController.View.Layer.AnchorPoint = new PointF(.5f, .5f); if (ContentAreaController.View.Frame.Location.Equals(sidebarBounds.Location)) return; var sidebarCenter = new PointF(sidebarBounds.Left + sidebarBounds.Width / 2, sidebarBounds.Top + sidebarBounds.Height / 2); ContentAreaController.View.Center = sidebarCenter; } private void AddMenuViewToSidebar() { SetMenuViewPosition(); View.AddSubview(MenuAreaController.View); View.SendSubviewToBack(MenuAreaController.View); } private void SetMenuViewPosition() { var menuFrame = MenuAreaController.View.Frame; menuFrame.X = MenuLocation == MenuLocations.Left ? 0 : View.Frame.Width - MenuWidth; menuFrame.Width = MenuWidth; MenuAreaController.View.Frame = menuFrame; } private void AttachSidebarControllerToRootController(UIViewController rootViewController) { rootViewController.AddChildViewController(this); rootViewController.View.AddSubview(this.View); this.DidMoveToParentViewController(rootViewController); } /// <summary> /// Ensures that the menu view gets properly positioned. /// </summary> public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); SetMenuViewPosition(); } /// <summary> /// Ensures that the menu view gets properly positioned. /// </summary> public override void ViewWillAppear(bool animated) { View.SetNeedsLayout(); base.ViewWillAppear(animated); } private bool _openWhenRotated = false; /// <summary> /// Overridden to handle reopening the menu after rotation. /// </summary> public override void WillRotate(UIInterfaceOrientation toInterfaceOrientation, double duration) { base.WillRotate(toInterfaceOrientation, duration); if (IsOpen) _openWhenRotated = true; _sidebar.CloseMenu(false); } /// <summary> /// Overridden to handle reopening the menu after rotation. /// </summary> public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation) { base.DidRotate(fromInterfaceOrientation); if (_openWhenRotated && ReopenOnRotate) _sidebar.OpenMenu(); _openWhenRotated = false; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Factotum { public partial class ComponentTypeView : Form { // ---------------------------------------------------------------------- // Initialization // ---------------------------------------------------------------------- ESiteCollection sites; // Form constructor public ComponentTypeView() { InitializeComponent(); // Take care of settings that are not easily managed in the designer. InitializeControls(); } // Take care of settings that are not easily managed in the designer. private void InitializeControls() { sites = ESite.ListByName(true, false, false); cboSiteFilter.DataSource = sites; cboSiteFilter.DisplayMember = "SiteName"; cboSiteFilter.ValueMember = "ID"; HandleEnablingForPropertySettings(); } // Set the status filter to show active tools by default // and update the tool selector combo box private void ComponentTypeView_Load(object sender, EventArgs e) { if (sites.Count == 0) { MessageBox.Show("Can't Add Component Types until there is at Least one Site", "Factotum"); btnAdd.Enabled = false; btnEdit.Enabled = false; btnDelete.Enabled = false; return; } // Set the status combo first. The selector DataGridView depends on it. cboStatusFilter.SelectedIndex = (int)FilterActiveStatus.ShowActive; // Apply the current filters and set the selector row. // Passing a null selects the first row if there are any rows. UpdateSelector(null); // Now that we have some rows and columns, we can do some customization. CustomizeGrid(); // Need to do this because the customization clears the row selection. SelectGridRow(null); this.cboSiteFilter.SelectedIndexChanged += new System.EventHandler(this.cboStatus_SelectedIndexChanged); EComponentType.Changed += new EventHandler<EntityChangedEventArgs>(EComponentType_Changed); Globals.CurrentOutageChanged += new EventHandler(Globals_CurrentOutageChanged); } private void ComponentTypeView_FormClosed(object sender, FormClosedEventArgs e) { this.cboSiteFilter.SelectedIndexChanged -= new System.EventHandler(this.cboStatus_SelectedIndexChanged); EComponentType.Changed -= new EventHandler<EntityChangedEventArgs>(EComponentType_Changed); Globals.CurrentOutageChanged -= new EventHandler(Globals_CurrentOutageChanged); } // ---------------------------------------------------------------------- // Event Handlers // ---------------------------------------------------------------------- // If any of this type of entity object was saved or deleted, we want to update the selector // The event args contain the ID of the entity that was added, mofified or deleted. void EComponentType_Changed(object sender, EntityChangedEventArgs e) { UpdateSelector(e.ID); } void Globals_CurrentOutageChanged(object sender, EventArgs e) { HandleEnablingForPropertySettings(); } // Handle the user's decision to edit the current tool private void EditCurrentSelection() { // Make sure there's a row selected if (dgvComponentTypeList.SelectedRows.Count != 1) return; Guid? currentEditItem = (Guid?)(dgvComponentTypeList.SelectedRows[0].Cells["ID"].Value); // First check to see if an instance of the form set to the selected ID already exists if (!Globals.CanActivateForm(this, "ComponentTypeEdit", currentEditItem)) { // Open the edit form with the currently selected ID. ComponentTypeEdit frm = new ComponentTypeEdit(currentEditItem); frm.MdiParent = this.MdiParent; frm.Show(); } } // This handles the datagridview double-click as well as button click void btnEdit_Click(object sender, System.EventArgs e) { EditCurrentSelection(); } private void dgvComponentTypeList_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) EditCurrentSelection(); } // Handle the user's decision to add a new tool private void btnAdd_Click(object sender, EventArgs e) { ComponentTypeEdit frm = new ComponentTypeEdit(null, new Guid(cboSiteFilter.SelectedValue.ToString())); frm.MdiParent = this.MdiParent; frm.Show(); } // Handle the user's decision to delete the selected tool private void btnDelete_Click(object sender, EventArgs e) { if (dgvComponentTypeList.SelectedRows.Count != 1) { MessageBox.Show("Please select a Component Type to delete first.", "Factotum"); return; } Guid? currentEditItem = (Guid?)(dgvComponentTypeList.SelectedRows[0].Cells["ID"].Value); if (Globals.IsFormOpen(this, "ComponentTypeEdit", currentEditItem)) { MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum"); return; } EComponentType ComponentType = new EComponentType(currentEditItem); ComponentType.Delete(true); if (ComponentType.ComponentTypeErrMsg != null) { MessageBox.Show(ComponentType.ComponentTypeErrMsg, "Factotum"); ComponentType.ComponentTypeErrMsg = null; } } // The user changed the status filter setting, so update the selector combo. private void cboStatus_SelectedIndexChanged(object sender, EventArgs e) { ApplyFilters(); } private void btnClose_Click(object sender, EventArgs e) { Close(); } // ---------------------------------------------------------------------- // Private utilities // ---------------------------------------------------------------------- // Update the tool selector combo box by filling its items based on current data and filters. // Then set the currently displayed item to that of the supplied ID. // If the supplied ID isn't on the list because of the current filter state, just show the // first item if there is one. private void UpdateSelector(Guid? id) { // Save the sort specs if there are any, so we can re-apply them SortOrder sortOrder = dgvComponentTypeList.SortOrder; int sortCol = -1; if (sortOrder != SortOrder.None) sortCol = dgvComponentTypeList.SortedColumn.Index; // Update the grid view selector DataView dv = EComponentType.GetDefaultDataView(); dgvComponentTypeList.DataSource = dv; ApplyFilters(); // Re-apply the sort specs if (sortOrder == SortOrder.Ascending) dgvComponentTypeList.Sort(dgvComponentTypeList.Columns[sortCol], ListSortDirection.Ascending); else if (sortOrder == SortOrder.Descending) dgvComponentTypeList.Sort(dgvComponentTypeList.Columns[sortCol], ListSortDirection.Descending); // Select the current row SelectGridRow(id); } private void CustomizeGrid() { // Apply a default sort dgvComponentTypeList.Sort(dgvComponentTypeList.Columns["ComponentTypeName"], ListSortDirection.Ascending); // Fix up the column headings dgvComponentTypeList.Columns["ComponentTypeName"].HeaderText = "Component Type"; dgvComponentTypeList.Columns["ComponentTypeIsActive"].HeaderText = "Active"; // Hide some columns dgvComponentTypeList.Columns["ID"].Visible = false; dgvComponentTypeList.Columns["ComponentTypeIsActive"].Visible = false; dgvComponentTypeList.Columns["ComponentTypeIsLclChg"].Visible = false; dgvComponentTypeList.Columns["ComponentTypeSitID"].Visible = false; dgvComponentTypeList.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); } // Apply the current filters to the DataView. The DataGridView will auto-refresh. private void ApplyFilters() { if (dgvComponentTypeList.DataSource == null) return; StringBuilder sb = new StringBuilder("ComponentTypeIsActive = ", 255); sb.Append(cboStatusFilter.SelectedIndex == (int)FilterActiveStatus.ShowActive ? "'Yes'" : "'No'"); sb.Append(" And ComponentTypeSitID = '" + cboSiteFilter.SelectedValue +"'"); if (txtNameFilter.Text.Length > 0) sb.Append(" And ComponentTypeName Like '" + txtNameFilter.Text + "*'"); DataView dv = (DataView)dgvComponentTypeList.DataSource; dv.RowFilter = sb.ToString(); } // Select the row with the specified ID if it is currently displayed and scroll to it. // If the ID is not in the list, private void SelectGridRow(Guid? id) { bool found = false; int rows = dgvComponentTypeList.Rows.Count; if (rows == 0) return; int r = 0; DataGridViewCell firstCell = dgvComponentTypeList.FirstDisplayedCell; // Find the row with the specified key id and select it. if (id != null) { for (r = 0; r < rows; r++) { if ((Guid?)dgvComponentTypeList.Rows[r].Cells["ID"].Value == id) { dgvComponentTypeList.CurrentCell = dgvComponentTypeList[firstCell.ColumnIndex, r]; dgvComponentTypeList.Rows[r].Selected = true; found = true; break; } } } if (found) { if (!dgvComponentTypeList.Rows[r].Displayed) { // Scroll to the selected row if the ID was in the list. dgvComponentTypeList.FirstDisplayedScrollingRowIndex = r; } } else { // Select the first item dgvComponentTypeList.CurrentCell = firstCell; dgvComponentTypeList.Rows[0].Selected = true; } } private void txtNameFilter_TextChanged(object sender, EventArgs e) { ApplyFilters(); } private void cboSiteFilter_SelectedIndexChanged(object sender, EventArgs e) { ApplyFilters(); } private void HandleEnablingForPropertySettings() { if (Globals.CurrentOutageID != null) { Guid OutageID = (Guid)Globals.CurrentOutageID; EOutage outage = new EOutage(OutageID); EUnit unit = new EUnit(outage.OutageUntID); if (unit.UnitSitID != (Guid)cboSiteFilter.SelectedValue) cboSiteFilter.SelectedValue = unit.UnitSitID; } cboSiteFilter.Enabled = (Globals.IsMasterDB); } } }
using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace TwainLib { public class TwProtocol { // TWON_PROTOCOL... public const short Major = 1; public const short Minor = 9; } [Flags] internal enum TwDG : short { // DG_..... Control = 0x0001, Image = 0x0002, Audio = 0x0004 } internal enum TwDAT : short { // DAT_.... Null = 0x0000, Capability = 0x0001, Event = 0x0002, Identity = 0x0003, Parent = 0x0004, PendingXfers = 0x0005, SetupMemXfer = 0x0006, SetupFileXfer = 0x0007, Status = 0x0008, UserInterface = 0x0009, XferGroup = 0x000a, TwunkIdentity = 0x000b, CustomDSData = 0x000c, DeviceEvent = 0x000d, FileSystem = 0x000e, PassThru = 0x000f, ImageInfo = 0x0101, ImageLayout = 0x0102, ImageMemXfer = 0x0103, ImageNativeXfer = 0x0104, ImageFileXfer = 0x0105, CieColor = 0x0106, GrayResponse = 0x0107, RGBResponse = 0x0108, JpegCompression = 0x0109, Palette8 = 0x010a, ExtImageInfo = 0x010b, SetupFileXfer2 = 0x0301 } internal enum TwMSG : short { // MSG_..... Null = 0x0000, Get = 0x0001, GetCurrent = 0x0002, GetDefault = 0x0003, GetFirst = 0x0004, GetNext = 0x0005, Set = 0x0006, Reset = 0x0007, QuerySupport = 0x0008, XFerReady = 0x0101, CloseDSReq = 0x0102, CloseDSOK = 0x0103, DeviceEvent = 0x0104, CheckStatus = 0x0201, OpenDSM = 0x0301, CloseDSM = 0x0302, OpenDS = 0x0401, CloseDS = 0x0402, UserSelect = 0x0403, DisableDS = 0x0501, EnableDS = 0x0502, EnableDSUIOnly = 0x0503, ProcessEvent = 0x0601, EndXfer = 0x0701, StopFeeder = 0x0702, ChangeDirectory = 0x0801, CreateDirectory = 0x0802, Delete = 0x0803, FormatMedia = 0x0804, GetClose = 0x0805, GetFirstFile = 0x0806, GetInfo = 0x0807, GetNextFile = 0x0808, Rename = 0x0809, Copy = 0x080A, AutoCaptureDir = 0x080B, PassThru = 0x0901 } internal enum TwRC : short { // TWRC_.... Success = 0x0000, Failure = 0x0001, CheckStatus = 0x0002, Cancel = 0x0003, DSEvent = 0x0004, NotDSEvent = 0x0005, XferDone = 0x0006, EndOfList = 0x0007, InfoNotSupported = 0x0008, DataNotAvailable = 0x0009 } internal enum TwCC : short { // TWCC_.... Success = 0x0000, Bummer = 0x0001, LowMemory = 0x0002, NoDS = 0x0003, MaxConnections = 0x0004, OperationError = 0x0005, BadCap = 0x0006, BadProtocol = 0x0009, BadValue = 0x000a, SeqError = 0x000b, BadDest = 0x000c, CapUnsupported = 0x000d, CapBadOperation = 0x000e, CapSeqError = 0x000f, Denied = 0x0010, FileExists = 0x0011, FileNotFound = 0x0012, NotEmpty = 0x0013, PaperJam = 0x0014, PaperDoubleFeed = 0x0015, FileWriteError = 0x0016, CheckDeviceOnline = 0x0017 } internal enum TwOn : short { // TWON_.... Array = 0x0003, Enum = 0x0004, One = 0x0005, Range = 0x0006, DontCare = -1 } internal enum TwType : short { // TWTY_.... Int8 = 0x0000, Int16 = 0x0001, Int32 = 0x0002, UInt8 = 0x0003, UInt16 = 0x0004, UInt32 = 0x0005, Bool = 0x0006, Fix32 = 0x0007, Frame = 0x0008, Str32 = 0x0009, Str64 = 0x000a, Str128 = 0x000b, Str255 = 0x000c, Str1024 = 0x000d, Str512 = 0x000e } internal enum TwCap : short { XferCount = 0x0001, // CAP_XFERCOUNT ICompression = 0x0100, // ICAP_... IPixelType = 0x0101, IUnits = 0x0102, IXferMech = 0x0103 } // ------------------- STRUCTS -------------------------------------------- [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] internal class TwIdentity { // TW_IDENTITY public IntPtr Id; public TwVersion Version; public short ProtocolMajor; public short ProtocolMinor; public int SupportedGroups; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 34)] public string Manufacturer; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 34)] public string ProductFamily; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 34)] public string ProductName; } [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] internal struct TwVersion { // TW_VERSION public short MajorNum; public short MinorNum; public short Language; public short Country; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 34)] public string Info; } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal class TwUserInterface { // TW_USERINTERFACE public short ShowUI; // bool is strictly 32 bit, so use short public short ModalUI; public IntPtr ParentHand; } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal class TwStatus { // TW_STATUS public short ConditionCode; // TwCC public short Reserved; } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal struct TwEvent { // TW_EVENT public IntPtr EventPtr; public short Message; } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal class TwImageInfo { // TW_IMAGEINFO public int XResolution; public int YResolution; public int ImageWidth; public int ImageLength; public short SamplesPerPixel; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public short[] BitsPerSample; public short BitsPerPixel; public short Planar; public short PixelType; public short Compression; } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal class TwPendingXfers { // TW_PENDINGXFERS public short Count; public int EOJ; } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal struct TwFix32 { // TW_FIX32 public short Whole; public ushort Frac; public float ToFloat() { return (float)Whole + ((float)Frac / 65536.0f); } public void FromFloat(float f) { int i = (int)((f * 65536.0f) + 0.5f); Whole = (short)(i >> 16); Frac = (ushort)(i & 0x0000ffff); } } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal class TwCapability { // TW_CAPABILITY public TwCapability(TwCap cap) { Cap = (short)cap; ConType = -1; } public TwCapability(TwCap cap, short sval) { Cap = (short)cap; ConType = (short)TwOn.One; Handle = Twain.GlobalAlloc(0x42, 6); IntPtr pv = Twain.GlobalLock(Handle); Marshal.WriteInt16(pv, 0, (short)TwType.Int16); Marshal.WriteInt32(pv, 2, (int)sval); Twain.GlobalUnlock(Handle); } ~TwCapability() { if (Handle != IntPtr.Zero) Twain.GlobalFree(Handle); } public short Cap; public short ConType; public IntPtr Handle; } } // namespace TwainLib
using System; using UnityEngine; namespace UnityEditor { public class StandardShaderVCGUI : ShaderGUI { private enum WorkflowMode { Specular, Metallic, Dielectric } public enum BlendMode { Opaque, Cutout, Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply } private static class Styles { public static GUIStyle optionsButton = "PaneOptions"; public static GUIContent uvSetLabel = new GUIContent("UV Set"); public static GUIContent[] uvSetOptions = new GUIContent[] { new GUIContent("UV channel 0"), new GUIContent("UV channel 1") }; public static string emptyTootip = ""; public static GUIContent albedoText = new GUIContent("Albedo", "Albedo (RGB) and Transparency (A)"); public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff"); public static GUIContent specularMapText = new GUIContent("Specular", "Specular (RGB) and Smoothness (A)"); public static GUIContent metallicMapText = new GUIContent("Metallic", "Metallic (R) and Smoothness (A)"); public static GUIContent smoothnessText = new GUIContent("Smoothness", ""); public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map"); public static GUIContent heightMapText = new GUIContent("Height Map", "Height Map (G)"); public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (G)"); public static GUIContent emissionText = new GUIContent("Emission", "Emission (RGB)"); public static GUIContent detailMaskText = new GUIContent("Detail Mask", "Mask for Secondary Maps (A)"); public static GUIContent detailAlbedoText = new GUIContent("Detail Albedo x2", "Albedo (RGB) multiplied by 2"); public static GUIContent detailNormalMapText = new GUIContent("Normal Map", "Normal Map"); public static string whiteSpaceString = " "; public static string primaryMapsText = "Main Maps"; public static string secondaryMapsText = "Secondary Maps"; public static string renderingMode = "Rendering Mode"; public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive."); public static GUIContent emissiveColorWarning = new GUIContent("Ensure emissive color is non-black for emission to have effect."); public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode)); public static GUIContent vcLabel = new GUIContent("Vertex Color", "Vertex Color Intensity"); } MaterialProperty blendMode = null; MaterialProperty albedoMap = null; MaterialProperty albedoColor = null; MaterialProperty alphaCutoff = null; MaterialProperty specularMap = null; MaterialProperty specularColor = null; MaterialProperty metallicMap = null; MaterialProperty metallic = null; MaterialProperty smoothness = null; MaterialProperty bumpScale = null; MaterialProperty bumpMap = null; MaterialProperty occlusionStrength = null; MaterialProperty occlusionMap = null; MaterialProperty heigtMapScale = null; MaterialProperty heightMap = null; MaterialProperty emissionScaleUI = null; MaterialProperty emissionColorUI = null; MaterialProperty emissionColorForRendering = null; MaterialProperty emissionMap = null; MaterialProperty detailMask = null; MaterialProperty detailAlbedoMap = null; MaterialProperty detailNormalMapScale = null; MaterialProperty detailNormalMap = null; MaterialProperty uvSetSecondary = null; MaterialProperty vertexColor = null; MaterialEditor m_MaterialEditor; WorkflowMode m_WorkflowMode = WorkflowMode.Specular; bool m_FirstTimeApply = true; public void FindProperties(MaterialProperty[] props) { blendMode = FindProperty("_Mode", props); albedoMap = FindProperty("_MainTex", props); albedoColor = FindProperty("_Color", props); alphaCutoff = FindProperty("_Cutoff", props); specularMap = FindProperty("_SpecGlossMap", props, false); specularColor = FindProperty("_SpecColor", props, false); metallicMap = FindProperty("_MetallicGlossMap", props, false); metallic = FindProperty("_Metallic", props, false); if (specularMap != null && specularColor != null) m_WorkflowMode = WorkflowMode.Specular; else if (metallicMap != null && metallic != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; smoothness = FindProperty("_Glossiness", props); bumpScale = FindProperty("_BumpScale", props); bumpMap = FindProperty("_BumpMap", props); heigtMapScale = FindProperty("_Parallax", props); heightMap = FindProperty("_ParallaxMap", props); occlusionStrength = FindProperty("_OcclusionStrength", props); occlusionMap = FindProperty("_OcclusionMap", props); emissionScaleUI = FindProperty("_EmissionScaleUI", props); emissionColorUI = FindProperty("_EmissionColorUI", props); emissionColorForRendering = FindProperty("_EmissionColor", props); emissionMap = FindProperty("_EmissionMap", props); detailMask = FindProperty("_DetailMask", props); detailAlbedoMap = FindProperty("_DetailAlbedoMap", props); detailNormalMapScale = FindProperty("_DetailNormalMapScale", props); detailNormalMap = FindProperty("_DetailNormalMap", props); uvSetSecondary = FindProperty("_UVSec", props); vertexColor = FindProperty("_IntensityVC", props); } public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) { FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly m_MaterialEditor = materialEditor; Material material = materialEditor.target as Material; ShaderPropertiesGUI(material); // Make sure that needed keywords are set up if we're switching some existing // material to a standard shader. if (m_FirstTimeApply) { SetMaterialKeywords(material, m_WorkflowMode); m_FirstTimeApply = false; } } public void ShaderPropertiesGUI(Material material) { // Use default labelWidth EditorGUIUtility.labelWidth = 0f; // Detect any changes to the material EditorGUI.BeginChangeCheck(); { BlendModePopup(); // Primary properties GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel); DoAlbedoArea(material); DoSpecularMetallicArea(); m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap, heightMap.textureValue != null ? heigtMapScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null); DoEmissionArea(material); m_MaterialEditor.TexturePropertySingleLine(Styles.detailMaskText, detailMask); EditorGUI.BeginChangeCheck(); m_MaterialEditor.TextureScaleOffsetProperty(albedoMap); if (EditorGUI.EndChangeCheck()) emissionMap.textureScaleAndOffset = albedoMap.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake EditorGUILayout.Space(); // Secondary properties GUILayout.Label(Styles.secondaryMapsText, EditorStyles.boldLabel); m_MaterialEditor.TexturePropertySingleLine(Styles.detailAlbedoText, detailAlbedoMap); m_MaterialEditor.TexturePropertySingleLine(Styles.detailNormalMapText, detailNormalMap, detailNormalMapScale); m_MaterialEditor.TextureScaleOffsetProperty(detailAlbedoMap); m_MaterialEditor.ShaderProperty(uvSetSecondary, Styles.uvSetLabel.text); EditorGUILayout.Space(); m_MaterialEditor.ShaderProperty(vertexColor, "Vertex Color"); } if (EditorGUI.EndChangeCheck()) { foreach (var obj in blendMode.targets) MaterialChanged((Material)obj, m_WorkflowMode); } } internal void DetermineWorkflow(MaterialProperty[] props) { if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null) m_WorkflowMode = WorkflowMode.Specular; else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; } void BlendModePopup() { EditorGUI.showMixedValue = blendMode.hasMixedValue; var mode = (BlendMode)blendMode.floatValue; EditorGUI.BeginChangeCheck(); mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode"); blendMode.floatValue = (float)mode; } EditorGUI.showMixedValue = false; } void DoAlbedoArea(Material material) { m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor); if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout)) { m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1); } } void DoEmissionArea(Material material) { bool showEmissionColorAndGIControls = emissionScaleUI.floatValue > 0f; bool hadEmissionTexture = emissionMap.textureValue != null; // Do controls m_MaterialEditor.TexturePropertySingleLine(Styles.emissionText, emissionMap, showEmissionColorAndGIControls ? emissionColorUI : null, emissionScaleUI); // Set default emissionScaleUI if texture was assigned if (emissionMap.textureValue != null && !hadEmissionTexture && emissionScaleUI.floatValue <= 0f) emissionScaleUI.floatValue = 1.0f; // Dynamic Lightmapping mode if (showEmissionColorAndGIControls) { bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled(EvalFinalEmissionColor(material)); EditorGUI.BeginDisabledGroup(!shouldEmissionBeEnabled); m_MaterialEditor.LightmapEmissionProperty(MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1); EditorGUI.EndDisabledGroup(); } if (!HasValidEmissiveKeyword(material)) { EditorGUILayout.HelpBox(Styles.emissiveWarning.text, MessageType.Warning); } } void DoSpecularMetallicArea() { if (m_WorkflowMode == WorkflowMode.Specular) { if (specularMap.textureValue == null) m_MaterialEditor.TexturePropertyTwoLines(Styles.specularMapText, specularMap, specularColor, Styles.smoothnessText, smoothness); else m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap); } else if (m_WorkflowMode == WorkflowMode.Metallic) { if (metallicMap.textureValue == null) m_MaterialEditor.TexturePropertyTwoLines(Styles.metallicMapText, metallicMap, metallic, Styles.smoothnessText, smoothness); else m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap); } } public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode) { switch (blendMode) { case BlendMode.Opaque: material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; break; case BlendMode.Cutout: material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 2450; break; case BlendMode.Fade: material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 3000; break; case BlendMode.Transparent: material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 3000; break; } } // Calculate final HDR _EmissionColor (gamma space) from _EmissionColorUI (LDR, gamma) & _EmissionScaleUI (gamma) static Color EvalFinalEmissionColor(Material material) { return material.GetColor("_EmissionColorUI") * material.GetFloat("_EmissionScaleUI"); } static bool ShouldEmissionBeEnabled(Color color) { return color.grayscale > (0.1f / 255.0f); } static void SetMaterialKeywords(Material material, WorkflowMode workflowMode) { // Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation // (MaterialProperty value might come from renderer material property block) SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap") || material.GetTexture("_DetailNormalMap")); if (workflowMode == WorkflowMode.Specular) SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap")); else if (workflowMode == WorkflowMode.Metallic) SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap")); SetKeyword(material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap")); SetKeyword(material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap")); bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled(material.GetColor("_EmissionColor")); SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled); // Setup lightmap emissive flags MaterialGlobalIlluminationFlags flags = material.globalIlluminationFlags; if ((flags & (MaterialGlobalIlluminationFlags.BakedEmissive | MaterialGlobalIlluminationFlags.RealtimeEmissive)) != 0) { flags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; if (!shouldEmissionBeEnabled) flags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack; material.globalIlluminationFlags = flags; } SetKeyword(material, "_VERTEXCOLOR", material.GetFloat("_IntensityVC") > 0f); } bool HasValidEmissiveKeyword(Material material) { // Material animation might be out of sync with the material keyword. // So if the emission support is disabled on the material, but the property blocks have a value that requires it, then we need to show a warning. // (note: (Renderer MaterialPropertyBlock applies its values to emissionColorForRendering)) bool hasEmissionKeyword = material.IsKeywordEnabled("_EMISSION"); if (!hasEmissionKeyword && ShouldEmissionBeEnabled(emissionColorForRendering.colorValue)) return false; else return true; } static void MaterialChanged(Material material, WorkflowMode workflowMode) { // Clamp EmissionScale to always positive if (material.GetFloat("_EmissionScaleUI") < 0.0f) material.SetFloat("_EmissionScaleUI", 0.0f); // Apply combined emission value Color emissionColorOut = EvalFinalEmissionColor(material); material.SetColor("_EmissionColor", emissionColorOut); // Handle Blending modes SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode")); SetMaterialKeywords(material, workflowMode); } static void SetKeyword(Material m, string keyword, bool state) { if (state) m.EnableKeyword(keyword); else m.DisableKeyword(keyword); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.CalendarsTests { //System.Globalization.KoreanCalendar.IsLeapDay(System.Int32,System.Int32,System.Int32,System.Int32) public class KoreanCalendarIsLeapDay { #region Positive Test Logic // PosTest1:Invoke the method with min date time [Fact] public void PosTest1() { System.Globalization.Calendar kC = new KoreanCalendar(); System.Globalization.Calendar gC = new GregorianCalendar(); DateTime dateTime = gC.ToDateTime(1, 1, 1, 0, 0, 0, 0); int year = dateTime.Year; int month = dateTime.Month; int day = dateTime.Day; int era = gC.GetEra(dateTime); bool expectedValue = gC.IsLeapDay(year, month, day, era); bool actualValue; actualValue = kC.IsLeapDay(year + 2333, month, day, kC.GetEra(dateTime)); Assert.Equal(expectedValue, actualValue); } // PosTest2:Invoke the method with max date time [Fact] public void PosTest2() { System.Globalization.Calendar kC = new KoreanCalendar(); System.Globalization.Calendar gC = new GregorianCalendar(); DateTime dateTime = gC.ToDateTime(9999, 12, 31, 0, 0, 0, 0); int year = dateTime.Year; int month = dateTime.Month; int day = dateTime.Day; int era = gC.GetEra(dateTime); bool expectedValue = gC.IsLeapDay(year, month, day, era); bool actualValue; actualValue = kC.IsLeapDay(year + 2333, month, day, kC.GetEra(dateTime)); Assert.Equal(expectedValue, actualValue); } // PosTest3:Invoke the method with normal date time [Fact] public void PosTest3() { System.Globalization.Calendar kC = new KoreanCalendar(); System.Globalization.Calendar gC = new GregorianCalendar(); DateTime dateTime = gC.ToDateTime(1900, 2, 28, 0, 0, 0, 0); int year = dateTime.Year; int month = dateTime.Month; int day = dateTime.Day; int era = gC.GetEra(dateTime); bool expectedValue = gC.IsLeapDay(year, month, day, era); bool actualValue; actualValue = kC.IsLeapDay(year + 2333, month, day, kC.GetEra(dateTime)); Assert.Equal(expectedValue, actualValue); } // PosTest4:Invoke the method with leap day date time [Fact] public void PosTest4() { System.Globalization.Calendar kC = new KoreanCalendar(); System.Globalization.Calendar gC = new GregorianCalendar(); DateTime dateTime = gC.ToDateTime(1200, 2, 29, 0, 0, 0, 0); int year = dateTime.Year; int month = dateTime.Month; int day = dateTime.Day; int era = gC.GetEra(dateTime); bool expectedValue = gC.IsLeapDay(year, month, day, era); bool actualValue; actualValue = kC.IsLeapDay(year + 2333, month, day, kC.GetEra(dateTime)); Assert.Equal(expectedValue, actualValue); } #endregion #region Negative Test Logic // NegTest1:Invoke the method with the year outside the lower supported range [Fact] public void NegTest1() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = 2333; int month = TestLibrary.Generator.GetInt16(-55) % 12 + 1; int day = TestLibrary.Generator.GetInt16(-55) % 28 + 1; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } // NegTest2:Invoke the method with the year outside the lower supported range [Fact] public void NegTest2() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = 0; int month = TestLibrary.Generator.GetInt16(-55) % 12 + 1; int day = TestLibrary.Generator.GetInt16(-55) % 28 + 1; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } // NegTest3:Invoke the method with the year outside the upper supported range [Fact] public void NegTest3() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = 2333; int month = TestLibrary.Generator.GetInt16(-55) % 12 + 1; int day = TestLibrary.Generator.GetInt16(-55) % 28 + 1; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } // NegTest4:Invoke the method with the month outside the lower supported range [Fact] public void NegTest4() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = TestLibrary.Generator.GetInt16(-55) % 9999 + 2334; int month = 0; int day = TestLibrary.Generator.GetInt16(-55) % 28 + 1; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } // NegTest5:Invoke the method with the month outside the upper supported range [Fact] public void NegTest5() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = TestLibrary.Generator.GetInt16(-55) % 9999 + 2334; int month = 13; int day = TestLibrary.Generator.GetInt16(-55) % 28 + 1; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } // NegTest6:Invoke the method with the day outside the lower supported range [Fact] public void NegTest6() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = TestLibrary.Generator.GetInt16(-55) % 9999 + 2334; int month = TestLibrary.Generator.GetInt16(-55) % 12 + 1; int day = 0; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } // NegTest7:Invoke the method with the wrong leap day [Fact] public void NegTest7() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = 4004; int month = 2; int day = 29; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } // NegTest8:Invoke the method with the day outside the upper supported range [Fact] public void NegTest8() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = TestLibrary.Generator.GetInt16(-55) % 9999 + 2334; int month = TestLibrary.Generator.GetInt16(-55) % 12 + 1; int day = 32; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } // NegTest9:Invoke the method with the era outside the lower supported range [Fact] public void NegTest9() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = TestLibrary.Generator.GetInt16(-55) % 9999 + 2334; int month = TestLibrary.Generator.GetInt16(-55) % 12 + 1; int day = TestLibrary.Generator.GetInt16(-55) % 28 + 1; // The KoreanEra is 1, however using an Era value of 0 defaults to "current era" for the calendar being used. In order to force // the ArgumentOutOfRangeException the era must not be 0 or 1 int era = -1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } // NegTest10:Invoke the method with the era outside the upper supported range [Fact] public void NegTest10() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = TestLibrary.Generator.GetInt16(-55) % 9999 + 2334; int month = TestLibrary.Generator.GetInt16(-55) % 12 + 1; int day = TestLibrary.Generator.GetInt16(-55) % 28 + 1; int era = 2; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapDay(year, month, day, era); }); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Xunit; using System.Threading.Tasks; using Proto.Remote.Tests.Messages; namespace Proto.Remote.Tests { [Collection("RemoteTests"), Trait("Category", "Remote")] public class RemoteTests { private static readonly RootContext Context = new RootContext(); private readonly RemoteManager _remoteManager; public RemoteTests(RemoteManager remoteManager) { _remoteManager = remoteManager; } [Fact, DisplayTestMethodName] public void CanSerializeAndDeserializeJsonPID() { var typeName = "actor.PID"; var json = new JsonMessage(typeName, "{ \"Address\":\"123\", \"Id\":\"456\"}"); var bytes = Serialization.Serialize(json, 1); var deserialized = Serialization.Deserialize(typeName, bytes, 1) as PID; Assert.Equal("123", deserialized.Address); Assert.Equal("456", deserialized.Id); } [Fact, DisplayTestMethodName] public void CanSerializeAndDeserializeJson() { var typeName = "remote_test_messages.Ping"; var json = new JsonMessage(typeName, "{ \"message\":\"Hello\"}"); var bytes = Serialization.Serialize(json, 1); var deserialized = Serialization.Deserialize(typeName, bytes, 1) as Ping; Assert.Equal("Hello",deserialized.Message); } [Fact, DisplayTestMethodName] public async void CanSendJsonAndReceiveToExistingRemote() { var remoteActor = new PID(_remoteManager.DefaultNode.Address, "EchoActorInstance"); var ct = new CancellationTokenSource(3000); var tcs = new TaskCompletionSource<bool>(); ct.Token.Register(() => { tcs.TrySetCanceled(); }); var localActor = Context.Spawn(Props.FromFunc(ctx => { if (ctx.Message is Pong) { tcs.SetResult(true); ctx.Self.Stop(); } return Actor.Done; })); var json = new JsonMessage("remote_test_messages.Ping", "{ \"message\":\"Hello\"}"); var envelope = new Proto.MessageEnvelope(json, localActor, Proto.MessageHeader.Empty); Remote.SendMessage(remoteActor, envelope, 1); await tcs.Task; } [Fact, DisplayTestMethodName] public async void CanSendAndReceiveToExistingRemote() { var remoteActor = new PID(_remoteManager.DefaultNode.Address, "EchoActorInstance"); var pong = await Context.RequestAsync<Pong>(remoteActor, new Ping { Message = "Hello" }, TimeSpan.FromMilliseconds(5000)); Assert.Equal($"{_remoteManager.DefaultNode.Address} Hello", pong.Message); } [Fact, DisplayTestMethodName] public async void WhenRemoteActorNotFound_RequestAsyncTimesout() { var unknownRemoteActor = new PID(_remoteManager.DefaultNode.Address, "doesn't exist"); await Assert.ThrowsAsync<TimeoutException>(async () => { await Context.RequestAsync<Pong>(unknownRemoteActor, new Ping { Message = "Hello" }, TimeSpan.FromMilliseconds(2000)); }); } [Fact, DisplayTestMethodName] public async void CanSpawnRemoteActor() { var remoteActorName = Guid.NewGuid().ToString(); var remoteActorResp = await Remote.SpawnNamedAsync(_remoteManager.DefaultNode.Address, remoteActorName, "EchoActor", TimeSpan.FromSeconds(5)); var remoteActor = remoteActorResp.Pid; var pong = await Context.RequestAsync<Pong>(remoteActor, new Ping{Message="Hello"}, TimeSpan.FromMilliseconds(5000)); Assert.Equal($"{_remoteManager.DefaultNode.Address} Hello", pong.Message); } [Fact, DisplayTestMethodName] public async void CanWatchRemoteActor() { var remoteActor = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var localActor = await SpawnLocalActorAndWatch(remoteActor); remoteActor.Stop(); Assert.True(await PollUntilTrue(() => Context.RequestAsync<bool>(localActor, new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); } [Fact, DisplayTestMethodName] public async void CanWatchMultipleRemoteActors() { var remoteActor1 = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var remoteActor2 = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var localActor = await SpawnLocalActorAndWatch(remoteActor1, remoteActor2); remoteActor1.Stop(); remoteActor2.Stop(); Assert.True(await PollUntilTrue(() => Context.RequestAsync<bool>(localActor, new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor1.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); Assert.True(await PollUntilTrue(() => Context.RequestAsync<bool>(localActor, new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor2.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); } [Fact, DisplayTestMethodName] public async void MultipleLocalActorsCanWatchRemoteActor() { var remoteActor = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var localActor1 = await SpawnLocalActorAndWatch(remoteActor); var localActor2 = await SpawnLocalActorAndWatch(remoteActor); remoteActor.Stop(); Assert.True(await PollUntilTrue(() => Context.RequestAsync<bool>(localActor1, new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); Assert.True(await PollUntilTrue(() => Context.RequestAsync<bool>(localActor2, new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); } [Fact, DisplayTestMethodName] public async void CanUnwatchRemoteActor() { var remoteActor = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var localActor1 = await SpawnLocalActorAndWatch(remoteActor); var localActor2 = await SpawnLocalActorAndWatch(remoteActor); Context.Send(localActor2, new Unwatch(remoteActor)); await Task.Delay(TimeSpan.FromSeconds(3)); // wait for unwatch to propagate... remoteActor.Stop(); // localActor1 is still watching so should get notified Assert.True(await PollUntilTrue(() => Context.RequestAsync<bool>(localActor1, new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); // localActor2 is NOT watching so should not get notified Assert.False(await Context.RequestAsync<bool>(localActor2, new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5)), "Unwatch did not succeed."); } [Fact, DisplayTestMethodName] public async void WhenRemoteTerminated_LocalWatcherReceivesNotification() { var (address, process) = _remoteManager.ProvisionNode("127.0.0.1", 12002); var remoteActor = await SpawnRemoteActor(address); var localActor = await SpawnLocalActorAndWatch(remoteActor); Console.WriteLine($"Killing remote process {address}!"); process.Kill(); Assert.True(await PollUntilTrue(() => Context.RequestAsync<bool>(localActor, new TerminatedMessageReceived(address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); Assert.Equal(1, await Context.RequestAsync<int>(localActor, new GetTerminatedMessagesCount(), TimeSpan.FromSeconds(5))); } private static async Task<PID> SpawnRemoteActor(string address) { var remoteActorName = Guid.NewGuid().ToString(); var remoteActorResp = await Remote.SpawnNamedAsync(address, remoteActorName, "EchoActor", TimeSpan.FromSeconds(5)); return remoteActorResp.Pid; } private async Task<PID> SpawnLocalActorAndWatch(params PID[] remoteActors) { var props = Props.FromProducer(() => new LocalActor(remoteActors)); var actor = Context.Spawn(props); // The local actor watches the remote one - we wait here for the RemoteWatch // message to propagate to the remote actor Console.WriteLine("Waiting for RemoteWatch to propagate..."); await Task.Delay(2000); return actor; } private Task<bool> PollUntilTrue(Func<Task<bool>> predicate) { return PollUntilTrue(predicate, 10, TimeSpan.FromMilliseconds(500)); } private async Task<bool> PollUntilTrue(Func<Task<bool>> predicate, int attempts, TimeSpan interval) { var attempt = 1; while (attempt <= attempts) { Console.WriteLine($"Attempting assertion (attempt {attempt} of {attempts})"); if (await predicate()) { Console.WriteLine($"Passed!"); return true; } attempt++; await Task.Delay(interval); } return false; } } public class TerminatedMessageReceived { public TerminatedMessageReceived(string address, string actorId) { Address = address; ActorId = actorId; } public string Address { get; } public string ActorId { get; } } public class GetTerminatedMessagesCount { } public class LocalActor : IActor { private readonly List<PID> _remoteActors = new List<PID>(); private readonly List<Terminated> _terminatedMessages = new List<Terminated>(); public LocalActor(params PID[] remoteActors) { _remoteActors.AddRange(remoteActors); } public Task ReceiveAsync(IContext context) { switch (context.Message) { case Started _: HandleStarted(context); break; case Unwatch msg: HandleUnwatch(context, msg); break; case TerminatedMessageReceived msg: HandleTerminatedMessageReceived(context, msg); break; case GetTerminatedMessagesCount _: HandleCountOfMessagesReceived(context); break; case Terminated msg: HandleTerminated(msg); break; } return Actor.Done; } private void HandleCountOfMessagesReceived(IContext context) { context.Respond(_terminatedMessages.Count); } private void HandleTerminatedMessageReceived(IContext context, TerminatedMessageReceived msg) { var messageReceived = _terminatedMessages.Any(tm => tm.Who.Address == msg.Address && tm.Who.Id == msg.ActorId); context.Respond(messageReceived); } private void HandleTerminated(Terminated msg) { Console.WriteLine($"Received Terminated message for {msg.Who.Address}: {msg.Who.Id}. Address terminated? {msg.AddressTerminated}"); _terminatedMessages.Add(msg); } private void HandleUnwatch(IContext context, Unwatch msg) { var remoteActor =_remoteActors.Single(ra => ra.Id == msg.Watcher.Id && ra.Address == msg.Watcher.Address); context.Unwatch(remoteActor); } private void HandleStarted(IContext context) { foreach (var remoteActor in _remoteActors) { context.Watch(remoteActor); } } } }
#region license // Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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 Rodrigo B. de Oliveira 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. #endregion using System; using System.Collections.Generic; using Boo.Lang.Compiler.TypeSystem.Generics; namespace Boo.Lang.Compiler.TypeSystem.Generics { /// <summary> /// Maps entities onto their constructed counterparts, substituting type arguments for generic parameters. /// </summary> public abstract class GenericMapping : TypeMapper { IDictionary<IGenericParameter, IType> _map = new Dictionary<IGenericParameter, IType>(); IDictionary<IMember, IMember> _memberCache = new Dictionary<IMember, IMember>(); IEntity _constructedOwner = null; IEntity _genericSource = null; /// <summary> /// Constructs a new generic mapping between a generic type and one of its constructed types. /// </summary> public GenericMapping(IType constructedType, IType[] arguments) : this(constructedType.ConstructedInfo.GenericDefinition.GenericInfo.GenericParameters, arguments) { _constructedOwner = constructedType; _genericSource = constructedType.ConstructedInfo.GenericDefinition; } /// <summary> /// Constructs a new generic mapping between a generic method and one of its constructed methods. /// </summary> public GenericMapping(IMethod constructedMethod, IType[] arguments) : this(constructedMethod.ConstructedInfo.GenericDefinition.GenericInfo.GenericParameters, arguments) { _constructedOwner = constructedMethod; _genericSource = constructedMethod.ConstructedInfo.GenericDefinition; } /// <summary> /// Constrcuts a new GenericMapping for a specific mapping of generic parameters to type arguments. /// </summary> /// <param name="parameters">The generic parameters that should be mapped.</param> /// <param name="arguments">The type arguments to map generic parameters to.</param> protected GenericMapping(IGenericParameter[] parameters, IType[] arguments) { for (int i = 0; i < parameters.Length; i++) { _map.Add(parameters[i], arguments[i]); } } /// <summary> /// Maps a type involving generic parameters to the corresponding type after substituting concrete /// arguments for generic parameters. /// </summary> /// <remarks> /// If the source type is a generic parameter, it is mapped to the corresponding argument. /// If the source type is an open generic type using any of the specified generic parameters, it /// is mapped to a closed constructed type based on the specified arguments. /// </remarks> override public IType MapType(IType sourceType) { if (sourceType == _genericSource) return _constructedOwner as IType; IGenericParameter gp = sourceType as IGenericParameter; if (gp != null) { // Map type parameters declared on our source if (_map.ContainsKey(gp)) return _map[gp]; // Map type parameters declared on members of our source (methods / nested types) return GenericsServices.GetGenericParameters(Map(gp.DeclaringEntity))[gp.GenericParameterPosition]; } // TODO: Map nested types // GenericType[of T].NestedType => GenericType[of int].NestedType return base.MapType(sourceType); } /// <summary> /// Maps a type member involving generic arguments to its constructed counterpart, after substituting /// concrete types for generic arguments. /// </summary> public IEntity Map(IEntity source) { if (source == null) return null; // Map generic source to the constructed owner of this mapping if (source == _genericSource) return _constructedOwner; Ambiguous ambiguous = source as Ambiguous; if (ambiguous != null) return MapAmbiguousEntity(ambiguous); IMember member = source as IMember; if (member != null) return MapMember(member); IType type = source as IType; if (type != null) return MapType(type); return source; } private IMember MapMember(IMember source) { // Use cached mapped member if available if (_memberCache.ContainsKey(source)) return _memberCache[source]; // Map members declared on our source if (source.DeclaringType == _genericSource) { return CacheMember(source, CreateMappedMember(source)); } // If member is declared on a basetype of our source, that is itself constructed, let its own mapper map it IType declaringType = source.DeclaringType; if (declaringType.ConstructedInfo != null) { source = declaringType.ConstructedInfo.UnMap(source); } IType mappedDeclaringType = MapType(declaringType); if (mappedDeclaringType.ConstructedInfo != null) { return mappedDeclaringType.ConstructedInfo.Map(source); } return source; } abstract protected IMember CreateMappedMember(IMember source); public IConstructor Map(IConstructor source) { return (IConstructor)Map((IEntity)source); } public IMethod Map(IMethod source) { return (IMethod)Map((IEntity)source); } public IField Map(IField source) { return (IField)Map((IEntity)source); } public IProperty Map(IProperty source) { return (IProperty)Map((IEntity)source); } public IEvent Map(IEvent source) { return (IEvent)Map((IEntity)source); } internal IGenericParameter MapGenericParameter(IGenericParameter source) { return Cache<IGenericParameter>(source, new GenericMappedTypeParameter(TypeSystemServices, source, this)); } private IEntity MapAmbiguousEntity(Ambiguous source) { // Map each individual entity in the ambiguous list return new Ambiguous(Array.ConvertAll<IEntity, IEntity>(source.Entities, Map)); } /// <summary> /// Gets the method from which the specified method was mapped. /// </summary> public virtual IMember UnMap(IMember mapped) { foreach (KeyValuePair<IMember, IMember> kvp in _memberCache) { if (kvp.Value == mapped) return kvp.Key; } return null; } private IMember CacheMember(IMember source, IMember mapped) { _memberCache[source] = mapped; return mapped; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Reflection; using System.Text; using System.Web.Http; using Autofac; using ReMi.BusinessEntities.Api; using ReMi.BusinessLogic.Api; using ReMi.Common.Cqrs; using ReMi.Contracts.Cqrs; using ReMi.Contracts.Cqrs.Commands; namespace ReMi.Api.Insfrastructure { public class ApiDescriptionBuilder : IApiDescriptionBuilder { public const String IncorrectRoute = "Incorrect"; private readonly IEnumerable<Type> _controllerTypes; private readonly IEnumerable<Type> _commandTypes; public ApiDescriptionBuilder(IEnumerable<Type> controllerTypes, IEnumerable<Type> commandTypes) { _controllerTypes = controllerTypes; _commandTypes = commandTypes; } public IEnumerable<ApiDescription> GetApiDescriptions() { var descriptions = new List<ApiDescription>(); foreach (var controller in _controllerTypes) { var route = GetRoutePrefix(controller); var methods = controller.GetMethods().Where(m => m.IsPublic).ToList(); descriptions.AddRange( FillApiDescriptions(methods, route, _commandTypes.ToList())); } return descriptions .Where(o => !string.IsNullOrWhiteSpace(o.Name)) .OrderBy(o => o.Method) .ThenBy(o => o.Name) .ToList(); } public String FormatType(Type type, int recursionLevel, Dictionary<int, String> levels) { if (type == null) { return String.Empty; } var isEnumerable = IsEnumerable(type); levels = ManageLevels(levels, isEnumerable, recursionLevel, type); var props = GetProperties(isEnumerable, type).ToList(); if ((!isEnumerable && (!props.Any() || type.FullName.StartsWith("System."))) || type.IsEnum) { var value = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>) ? FormatNullable(type) : type.Name; return String.Format("\"{0}\"", value); } var result = new StringBuilder(); recursionLevel++; result.Append(isEnumerable ? "[ {" : "{"); result.Append( FormatProperties(props, levels, recursionLevel)); result.Append(isEnumerable ? "} ]" : "}"); return result.ToString(); } private static String FormatNullable(Type type) { return type.GetGenericArguments()[0].Name + "?"; } private static bool CheckNestingTree(String typeName, int recursionLevel, Dictionary<int, String> levels) { for (var counter = 0; counter < recursionLevel; counter++) { if (levels[counter] == typeName) { return false; } } return true; } private static bool IsEnumerable(Type type) { return type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IEnumerable<>) || type.GetInterfaces().Any(t => t.GetGenericTypeDefinition() == typeof(IEnumerable<>))); } private static String GetRouteAttribute(MethodInfo method, String route) { var actionRoute = method.GetCustomAttributesData() .FirstOrDefault(z => z.AttributeType == typeof(RouteAttribute)); if (actionRoute == null) return IncorrectRoute; return actionRoute.ConstructorArguments.Count == 0 ? route : String.Format("{0}{1}/", route, actionRoute.ConstructorArguments.First().Value); } private ApiDescription CreateCommandDescription(String url, Type type) { if (type != null) { var commandAttrs = type.GetCustomAttributes(typeof(CommandAttribute)).ToArray(); if (commandAttrs.Any()) { if (((CommandAttribute)commandAttrs[0]).IsBackground) return null; } } var desc = new ApiDescription { Url = url, Name = type == null ? string.Empty : type.Name, Method = HttpMethod.Post.Method, InputFormat = FormatType(type, 0, null) }; return desc; } private static String GetRoutePrefix(Type type) { var routePrefix = type.GetCustomAttributesData() .FirstOrDefault(z => z.AttributeType == typeof(RoutePrefixAttribute)); var route = "/"; if (routePrefix != null) { route += String.Format("{0}/", routePrefix.ConstructorArguments.First().Value); } return route; } private ApiDescription CreateQueryApiDescription(String url, MethodInfo method) { var inputFormat = String.Join(", ", method.GetParameters() .Select( p => String.Format("\"{0}\" : \"{1}\"", p.Name, p.ParameterType.Name))); if (!string.IsNullOrWhiteSpace(inputFormat)) inputFormat = "{" + inputFormat + "}"; var desc = new ApiDescription { OutputFormat = FormatType(method.ReturnType, 0, null), Method = HttpMethod.Get.Method, Name = method.ReturnType.Name.Replace("Response", string.Empty), Url = url, InputFormat = inputFormat, }; return desc; } private static Dictionary<int, String> ManageLevels(Dictionary<int, String> levels, bool isEnumerable, int recursionLevel, Type type) { if (levels == null) { levels = new Dictionary<int, String>(); } while (levels.Count > recursionLevel) { levels.Remove(levels.Last().Key); } levels.Add(recursionLevel, isEnumerable ? type.GetGenericArguments()[0].FullName : type.FullName); return levels; } private string FormatDictionary(PropertyInfo prop, Type type) { var genericArguments = prop.PropertyType.GetGenericArguments(); if (genericArguments == null || genericArguments.Length < 2) throw new ArgumentException("Generic arguments are invalid", "prop"); var value = !string.IsNullOrEmpty(genericArguments[1].Namespace) && genericArguments[1].Namespace.StartsWith("System.") && !IsEnumerable(type.GetGenericArguments()[1]) ? genericArguments[1].FullName : FormatType(genericArguments[1], 0, null); return String.Format("\"Key\" : \"{0}\", \"Value\" : {1}", genericArguments[0].Name, value); } private static bool SimpleTypeCheck(PropertyInfo prop, Dictionary<int, String> levels, int recursionLevel) { return !prop.PropertyType.IsEnum && !CheckNestingTree( IsEnumerable(prop.PropertyType) ? prop.PropertyType.GetGenericArguments()[0].FullName : prop.PropertyType.FullName, recursionLevel, levels) && (!prop.PropertyType.FullName.StartsWith("System.") || IsEnumerable(prop.PropertyType)); } private static IEnumerable<PropertyInfo> GetProperties(bool isEnumerable, Type type) { return isEnumerable ? type.GetGenericArguments()[0].GetProperties(BindingFlags.Public | BindingFlags.Instance) : type.GetProperties(BindingFlags.Public | BindingFlags.Instance); } private IEnumerable<ApiDescription> FillApiDescriptions(IEnumerable<MethodInfo> methods, String route, IList<Type> commandTypes) { var result = new List<ApiDescription>(); foreach (var method in methods) { var url = GetRouteAttribute(method, route); if (url == IncorrectRoute) { continue; } if (method.GetCustomAttributes(typeof(HttpGetAttribute)).Any()) { result.Add(CreateQueryApiDescription(url, method)); continue; } if (method.GetCustomAttributes(typeof(HttpPostAttribute)).Any()) { if (url.Contains("deliver/{commandName}")) { result.AddRange( commandTypes .Select(t => CreateCommandDescription(url.Replace("{commandName}", t.Name), t)) .Where(t => t != null) .ToList()); } else { var arguments = method.GetParameters(); var commandDescription = CreateCommandDescription(url, arguments.Length > 0 ? arguments[0].ParameterType : null); if (commandDescription != null) result.Add(commandDescription); } } } return result; } private string FormatProperties(IEnumerable<PropertyInfo> props, Dictionary<int, String> levels, int recursionLevel) { var propertyLines = new List<string>(); foreach (var prop in props) { if (prop.PropertyType.IsAssignableTo<BaseContext>()) { continue; } if ((typeof(IDictionary<,>)).IsAssignableFrom(prop.PropertyType) || (typeof(IDictionary<,>)).Name == prop.PropertyType.Name) { propertyLines.Add( String.Format("\"{0}\" : [ {{{1}}} ]", prop.Name, FormatDictionary(prop, prop.PropertyType)) ); continue; } if (SimpleTypeCheck(prop, levels, recursionLevel)) { propertyLines.Add( String.Format("\"{0}\" : {1}", prop.Name, IsEnumerable(prop.PropertyType) ? String.Format("[ {{ \"{0}\" : \"{0}\" }} ]", prop.PropertyType.GetGenericArguments()[0].Name) : String.Format("\"{0}\"", prop.PropertyType.Name))); continue; } propertyLines.Add( String.Format("\"{0}\" : {1}", prop.Name, FormatType(prop.PropertyType, recursionLevel, levels) ) ); } return string.Join(", ", propertyLines); } } }
using System; using System.Drawing; using System.Windows.Forms; using Microsoft.DirectX.DirectInput; namespace Voyage.Terraingine.DXViewport { /// <summary> /// Summary description for Mouse. /// </summary> public class Mouse { #region Data Members private Form _window; private MouseState _state; private bool[] _buttons; private Microsoft.DirectX.DirectInput.Device _device; #endregion #region Properties /// <summary> /// Gets or sets the window to poll mouse from. /// </summary> public Form Window { get { return _window; } set { Initialize( value ); } } /// <summary> /// Gets the last polled state of the mouse. /// </summary> public MouseState State { get { return _state; } } /// <summary> /// Gets the last polled location of the mouse. /// </summary> public Point Location { get { Point p = Point.Empty; p.X = _state.X; p.Y = _state.Y; return p; } } /// <summary> /// Gets the current polled location of the mouse. /// </summary> public Point CurrentLocation { get { Point p = Point.Empty; Update(); p.X = _state.X; p.Y = _state.Y; return p; } } /// <summary> /// Gets the last polled state of the mouse buttons. /// </summary> public bool[] Buttons { get { return _buttons; } } /// <summary> /// Gets the current state of the mouse buttons. /// </summary> public bool[] CurrentButtons { get { Update(); return _buttons; } } /// <summary> /// Gets the input device used to grab mouse information. /// </summary> public Microsoft.DirectX.DirectInput.Device Device { get { return _device; } } /// <summary> /// Gets whether the input device has been properly initialized. /// </summary> public bool Initialized { get { if ( _device != null ) return true; else return false; } } /// <summary> /// Gets if the left mouse button is pressed. /// </summary> public bool LeftButton { get { return _buttons[0]; } } /// <summary> /// Gets if the right mouse button is pressed. /// </summary> public bool RightButton { get { return _buttons[1]; } } #endregion #region Methods /// <summary> /// Creates an object for polling the system mouse. /// </summary> public Mouse() { } /// <summary> /// Creates an object for polling the system mouse. /// </summary> /// <param name="window">Window to poll mouse from.</param> public Mouse( Form window ) { Initialize( window ); } /// <summary> /// Disposes of the mouse device. /// </summary> public void Dispose() { if ( _device != null ) { _device.Dispose(); _device = null; } } /// <summary> /// Initializes the mouse device to poll from. /// </summary> /// <param name="window">Window to poll mouse from.</param> public void Initialize( Form window ) { Dispose(); _window = window; _device = new Device( SystemGuid.Mouse ); if ( _device != null ) { _device.Properties.AxisModeAbsolute = false; _device.SetCooperativeLevel( window.Handle, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background ); _device.Acquire(); } } /// <summary> /// Updates the mouse device. /// </summary> public void Update() { _state = _device.CurrentMouseState; _buttons = new bool[_state.GetMouseButtons().Length]; UpdatePressedButtons(); } /// <summary> /// Updates the state of the which buttons are pressed. /// </summary> protected void UpdatePressedButtons() { byte[] buttons = _state.GetMouseButtons(); for ( int i = 0; i < buttons.Length; i++ ) { if ( buttons[i] != 0 ) _buttons[i] = true; else _buttons[i] = false; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; public static partial class DeploymentsOperationsExtensions { /// <summary> /// Delete deployment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment to be deleted. /// </param> public static void Delete(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName) { Task.Factory.StartNew(s => ((IDeploymentsOperations)s).DeleteAsync(resourceGroupName, deploymentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete deployment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment to be deleted. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync( this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete deployment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment to be deleted. /// </param> public static void BeginDelete(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName) { Task.Factory.StartNew(s => ((IDeploymentsOperations)s).BeginDeleteAsync(resourceGroupName, deploymentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete deployment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment to be deleted. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync( this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Checks whether deployment exists. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to check. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> public static bool? CheckExistence(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName) { return Task.Factory.StartNew(s => ((IDeploymentsOperations)s).CheckExistenceAsync(resourceGroupName, deploymentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks whether deployment exists. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to check. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<bool?> CheckExistenceAsync( this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckExistenceWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a named template deployment using a template. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Additional parameters supplied to the operation. /// </param> public static DeploymentExtended CreateOrUpdate(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters) { return Task.Factory.StartNew(s => ((IDeploymentsOperations)s).CreateOrUpdateAsync(resourceGroupName, deploymentName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a named template deployment using a template. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Additional parameters supplied to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DeploymentExtended> CreateOrUpdateAsync( this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, deploymentName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a named template deployment using a template. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Additional parameters supplied to the operation. /// </param> public static DeploymentExtended BeginCreateOrUpdate(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters) { return Task.Factory.StartNew(s => ((IDeploymentsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, deploymentName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a named template deployment using a template. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Additional parameters supplied to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DeploymentExtended> BeginCreateOrUpdateAsync( this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, deploymentName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get a deployment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> public static DeploymentExtended Get(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName) { return Task.Factory.StartNew(s => ((IDeploymentsOperations)s).GetAsync(resourceGroupName, deploymentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a deployment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DeploymentExtended> GetAsync( this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Cancel a currently running template deployment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> public static void Cancel(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName) { Task.Factory.StartNew(s => ((IDeploymentsOperations)s).CancelAsync(resourceGroupName, deploymentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Cancel a currently running template deployment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CancelAsync( this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CancelWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Validate a deployment template. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Deployment to validate. /// </param> public static DeploymentValidateResult Validate(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters) { return Task.Factory.StartNew(s => ((IDeploymentsOperations)s).ValidateAsync(resourceGroupName, deploymentName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Validate a deployment template. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='parameters'> /// Deployment to validate. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DeploymentValidateResult> ValidateAsync( this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, Deployment parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ValidateWithHttpMessagesAsync(resourceGroupName, deploymentName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Exports a deployment template. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> public static DeploymentExportResult ExportTemplate(this IDeploymentsOperations operations, string resourceGroupName, string deploymentName) { return Task.Factory.StartNew(s => ((IDeploymentsOperations)s).ExportTemplateAsync(resourceGroupName, deploymentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Exports a deployment template. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DeploymentExportResult> ExportTemplateAsync( this IDeploymentsOperations operations, string resourceGroupName, string deploymentName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ExportTemplateWithHttpMessagesAsync(resourceGroupName, deploymentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to filter by. The name is case insensitive. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<DeploymentExtended> List(this IDeploymentsOperations operations, string resourceGroupName, ODataQuery<DeploymentExtendedFilter> odataQuery = default(ODataQuery<DeploymentExtendedFilter>)) { return Task.Factory.StartNew(s => ((IDeploymentsOperations)s).ListAsync(resourceGroupName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to filter by. The name is case insensitive. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<DeploymentExtended>> ListAsync( this IDeploymentsOperations operations, string resourceGroupName, ODataQuery<DeploymentExtendedFilter> odataQuery = default(ODataQuery<DeploymentExtendedFilter>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<DeploymentExtended> ListNext(this IDeploymentsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IDeploymentsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<DeploymentExtended>> ListNextAsync( this IDeploymentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.Msagl.Drawing; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.DataStructures; using MsaglRectangle = Microsoft.Msagl.Core.Geometry.Rectangle; using Color = System.Windows.Media.Color; using DrawingGraph = Microsoft.Msagl.Drawing.Graph; using GeometryEdge = Microsoft.Msagl.Core.Layout.Edge; using GeometryNode = Microsoft.Msagl.Core.Layout.Node; using DrawingEdge = Microsoft.Msagl.Drawing.Edge; using DrawingNode = Microsoft.Msagl.Drawing.Node; using MsaglPoint = Microsoft.Msagl.Core.Geometry.Point; using WinPoint = System.Windows.Point; using MsaglStyle = Microsoft.Msagl.Drawing.Style; using MsaglLineSegment = Microsoft.Msagl.Core.Geometry.Curves.LineSegment; using WinLineSegment = System.Windows.Media.LineSegment; using WinSize = System.Windows.Size; namespace Microsoft.Msagl.GraphControlSilverlight { /// <summary> /// exposes some drawing functionality /// </summary> public sealed class Draw { /// <summary> /// private constructor /// </summary> Draw() { } static double doubleCircleOffsetRatio = 0.9; internal static double DoubleCircleOffsetRatio { get { return doubleCircleOffsetRatio; } } internal static float dashSize = 0.05f; //inches /// <summary> /// A color converter /// </summary> /// <param name="gleeColor"></param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msagl")] public static Color MsaglColorToDrawingColor(Drawing.Color gleeColor) { return Color.FromArgb(gleeColor.A, gleeColor.R, gleeColor.G, gleeColor.B); } internal static void AddStyleForPen(DObject dObj, Brush myPen, MsaglStyle style) { if (style == MsaglStyle.Dashed) { throw new NotImplementedException(); /* myPen.DashStyle = DashStyle.Dash; if (dObj.DashPatternArray == null) { float f = dObj.DashSize(); dObj.DashPatternArray = new[] { f, f }; } myPen.DashPattern = dObj.DashPatternArray; myPen.DashOffset = dObj.DashPatternArray[0]; */ } else if (style == MsaglStyle.Dotted) { throw new NotImplementedException(); /* myPen.DashStyle = DashStyle.Dash; if (dObj.DashPatternArray == null) { float f = dObj.DashSize(); dObj.DashPatternArray = new[] { 1, f }; } myPen.DashPattern = dObj.DashPatternArray; */ } } internal static void DrawUnderlyingPolyline(PathGeometry pg, DEdge edge) { IEnumerable<WinPoint> points = edge.GeometryEdge.UnderlyingPolyline.Select(p => WinPoint(p)); PathFigure pf = new PathFigure() { IsFilled = false, IsClosed = false, StartPoint = points.First() }; foreach (WinPoint p in points) { if (p != points.First()) pf.Segments.Add(new WinLineSegment() { Point = p }); PathFigure circle = new PathFigure() { IsFilled = false, IsClosed = true, StartPoint = new WinPoint(p.X - edge.RadiusOfPolylineCorner, p.Y) }; circle.Segments.Add( new ArcSegment() { Size = new WinSize(edge.RadiusOfPolylineCorner, edge.RadiusOfPolylineCorner), SweepDirection = SweepDirection.Clockwise, Point = new WinPoint(p.X + edge.RadiusOfPolylineCorner, p.Y) }); circle.Segments.Add( new ArcSegment() { Size = new WinSize(edge.RadiusOfPolylineCorner, edge.RadiusOfPolylineCorner), SweepDirection = SweepDirection.Clockwise, Point = new WinPoint(p.X - edge.RadiusOfPolylineCorner, p.Y) }); pg.Figures.Add(circle); } pg.Figures.Add(pf); } internal static void DrawEdgeArrows(PathGeometry pg, DrawingEdge edge, bool fillAtSource, bool fillAtTarget) { ArrowAtTheEnd(pg, edge, fillAtTarget); ArrowAtTheBeginning(pg, edge, fillAtSource); } private static void ArrowAtTheBeginning(PathGeometry pg, DrawingEdge edge, bool fill) { if (edge.GeometryEdge != null && edge.Attr.ArrowAtSource) DrawArrowAtTheBeginningWithControlPoints(pg, edge, fill); } private static void DrawArrowAtTheBeginningWithControlPoints(PathGeometry pg, DrawingEdge edge, bool fill) { if (edge.EdgeCurve != null) if (edge.Attr.ArrowheadAtSource == ArrowStyle.None) DrawLine(pg, edge.EdgeCurve.Start, edge.ArrowAtSourcePosition); else DrawArrow(pg, edge.EdgeCurve.Start, edge.ArrowAtSourcePosition, edge.Attr.LineWidth, edge.Attr.ArrowheadAtSource, fill); } private static void ArrowAtTheEnd(PathGeometry pg, DrawingEdge edge, bool fill) { if (edge.GeometryEdge != null && edge.Attr.ArrowAtTarget) DrawArrowAtTheEndWithControlPoints(pg, edge, fill); } const float toDegrees = 180 / (float)Math.PI; static void DrawArrowAtTheEndWithControlPoints(PathGeometry pg, DrawingEdge edge, bool fill) { if (edge.EdgeCurve != null) if (edge.Attr.ArrowheadAtTarget == ArrowStyle.None) DrawLine(pg, edge.EdgeCurve.End, edge.ArrowAtTargetPosition); else DrawArrow(pg, edge.EdgeCurve.End, edge.ArrowAtTargetPosition, edge.Attr.LineWidth, edge.Attr.ArrowheadAtTarget, fill); } internal static WinPoint WinPoint(MsaglPoint p) { return new WinPoint(p.X, p.Y); } internal static void CreateGraphicsPathFromCurve(PathFigure pathFigure, Curve curve) { foreach (var seg in curve.Segments) { var bezSeg = seg as CubicBezierSegment; if (bezSeg != null) pathFigure.Segments.Add(new BezierSegment { Point1 = WinPoint(bezSeg.B(1)), Point2 = WinPoint(bezSeg.B(2)), Point3 = WinPoint(bezSeg.B(3)) }); else { var ls = seg as MsaglLineSegment; if (ls != null) pathFigure.Segments.Add(new WinLineSegment() { Point = WinPoint(ls.End) }); else { var ellipse = seg as Ellipse; if (ellipse != null) pathFigure.Segments.Add( new ArcSegment() { Size = new WinSize(ellipse.AxisA.Length, ellipse.AxisB.Length), SweepDirection = SweepDirection.Clockwise, Point = WinPoint(ellipse.End) }); else throw new InvalidOperationException(); } } } } internal static PathFigure CreateGraphicsPath(ICurve iCurve) { var pathFigure = new PathFigure { StartPoint = WinPoint(iCurve.Start), IsFilled = false, IsClosed = false }; if (iCurve is Curve) { CreateGraphicsPathFromCurve(pathFigure, iCurve as Curve); } else if (iCurve is CubicBezierSegment) { var bezSeg = iCurve as CubicBezierSegment; pathFigure.Segments.Add(new BezierSegment { Point1 = WinPoint(bezSeg.B(1)), Point2 = WinPoint(bezSeg.B(2)), Point3 = WinPoint(bezSeg.B(3)) }); } else if (iCurve is MsaglLineSegment) { var segment = iCurve as MsaglLineSegment; pathFigure.Segments.Add( new WinLineSegment() { Point = WinPoint(segment.End) }); } else if (iCurve is Ellipse) { var ellipse = iCurve as Ellipse; pathFigure.Segments.Add( new ArcSegment() { Size = new WinSize(ellipse.BoundingBox.Width / 2, ellipse.BoundingBox.Height / 2), SweepDirection = SweepDirection.Clockwise, Point = WinPoint(ellipse[Math.PI]) }); pathFigure.Segments.Add( new ArcSegment() { Size = new WinSize(ellipse.BoundingBox.Width / 2, ellipse.BoundingBox.Height / 2), SweepDirection = SweepDirection.Clockwise, Point = WinPoint(ellipse.Start) }); } else if (iCurve is RoundedRect) { CreateGraphicsPathFromCurve(pathFigure, (iCurve as RoundedRect).Curve); } return pathFigure; /* var graphicsPath = new GraphicsPath(); if (iCurve == null) return null; var c = iCurve as Curve; if (c != null) { foreach (ICurve seg in c.Segments) { var cubic = seg as CubicBezierSegment; if (cubic != null) graphicsPath.AddBezier(PointF(cubic.B(0)), PointF(cubic.B(1)), PointF(cubic.B(2)), PointF(cubic.B(3))); else { var ls = seg as LineSegment; if (ls != null) graphicsPath.AddLine(PointF(ls.Start), PointF(ls.End)); else { var el = seg as Ellipse; // double del = (el.ParEnd - el.ParStart)/11.0; // graphicsPath.AddLines(Enumerable.Range(1, 10).Select(i => el[el.ParStart + del*i]). // Select(p => new PointF((float) p.X, (float) p.Y)).ToArray()); Rectangle box = el.BoundingBox; float startAngle = EllipseStandardAngle(el, el.ParStart); float sweepAngle = EllipseSweepAngle(el); graphicsPath.AddArc((float)box.Left, (float)box.Bottom, (float)box.Width, (float)box.Height, startAngle, sweepAngle); } } } } else { var ls = iCurve as LineSegment; if (ls != null) graphicsPath.AddLine(PointF(ls.Start), PointF(ls.End)); else { var seg = (CubicBezierSegment)iCurve; graphicsPath.AddBezier(PointF(seg.B(0)), PointF(seg.B(1)), PointF(seg.B(2)), PointF(seg.B(3))); } } return graphicsPath; */ } static float EllipseSweepAngle(Ellipse el) { float sweepAngle = (float)(el.ParEnd - el.ParStart) * toDegrees; if (!OrientedCounterClockwise(el)) sweepAngle = -sweepAngle; return sweepAngle; } static bool OrientedCounterClockwise(Ellipse ellipse) { return ellipse.AxisA.X * ellipse.AxisB.Y - ellipse.AxisB.X * ellipse.AxisA.Y > 0; } static float EllipseStandardAngle(Ellipse ellipse, double angle) { MsaglPoint p = Math.Cos(angle) * ellipse.AxisA + Math.Sin(angle) * ellipse.AxisB; return (float)Math.Atan2(p.Y, p.X) * toDegrees; } static PathGeometry CreateControlPointPolygon(Tuple<double, double> t, CubicBezierSegment cubic) { throw new NotImplementedException(); /* var gp = new GraphicsPath(); gp.AddLines(new[] { PP(cubic.B(0)), PP(cubic.B(1)), PP(cubic.B(2)), PP(cubic.B(3)) }); return gp; */ } static WinPoint PP(Point point) { return new WinPoint(point.X, point.Y); } static PathGeometry CreatePathOnCurvaturePoint(Tuple<double, double> t, CubicBezierSegment cubic) { throw new NotImplementedException(); /* var gp = new GraphicsPath(); Point center = cubic[t.First]; int radius = 10; gp.AddEllipse((float)(center.X - radius), (float)(center.Y - radius), (2 * radius), (2 * radius)); return gp; //*/ } static bool NeedToFill(Color fillColor) { return fillColor.A != 0; //the color is not transparent } internal static void DrawDoubleCircle(Canvas g, Brush pen, DNode dNode) { throw new NotImplementedException(); /* NodeAttr nodeAttr = dNode.DrawingNode.Attr; double x = nodeAttr.Pos.X - nodeAttr.Width / 2.0f; double y = nodeAttr.Pos.Y - nodeAttr.Height / 2.0f; if (NeedToFill(dNode.FillColor)) { g.FillEllipse(new SolidBrush(dNode.FillColor), (float)x, (float)y, (float)nodeAttr.Width, (float)nodeAttr.Height); } g.DrawEllipse(pen, (float)x, (float)y, (float)nodeAttr.Width, (float)nodeAttr.Height); var w = (float)nodeAttr.Width; var h = (float)nodeAttr.Height; float m = Math.Max(w, h); float coeff = (float)1.0 - (float)(DoubleCircleOffsetRatio); x += coeff * m / 2.0; y += coeff * m / 2.0; g.DrawEllipse(pen, (float)x, (float)y, w - coeff * m, h - coeff * m); * */ } static Color FillColor(NodeAttr nodeAttr) { return MsaglColorToDrawingColor(nodeAttr.FillColor); } const double arrowAngle = 25.0; //degrees internal static void DrawArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end, double thickness, ArrowStyle arrowStyle, bool fill) { switch (arrowStyle) { case ArrowStyle.NonSpecified: case ArrowStyle.Normal: DrawNormalArrow(pg, start, end, thickness, fill); break; case ArrowStyle.Tee: DrawTeeArrow(pg, start, end, fill); break; case ArrowStyle.Diamond: DrawDiamondArrow(pg, start, end); break; case ArrowStyle.ODiamond: DrawODiamondArrow(pg, start, end); break; case ArrowStyle.Generalization: DrawGeneralizationArrow(pg, start, end); break; default: throw new InvalidOperationException(); } } internal static void DrawNormalArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end, double thickness, bool fill) { MsaglPoint dir = end - start; MsaglPoint h = dir; dir /= dir.Length; // compensate for line thickness end -= dir * thickness / ((double)Math.Tan(arrowAngle * (Math.PI / 180.0))); var s = new MsaglPoint(-dir.Y, dir.X); s *= h.Length * ((double)Math.Tan(arrowAngle * 0.5 * (Math.PI / 180.0))); PathFigure pf = new PathFigure() { IsFilled = fill, IsClosed=true }; pf.StartPoint = WinPoint(start + s); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) }); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(start - s) }); pg.Figures.Add(pf); /*pf = new PathFigure(); pf.StartPoint = WinPoint(start); pf.Segments.Add(new System.Windows.Media.LineSegment() { Point = WinPoint(end) }); pg.Figures.Add(pf);*/ } // For tee arrows, "fill" indicates whether the line should continue up to the node's boundary. static void DrawTeeArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end, bool fill) { MsaglPoint dir = end - start; MsaglPoint h = dir; dir /= dir.Length; if (fill) { PathFigure pf = new PathFigure(); pf.StartPoint = WinPoint(start); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) }); pg.Figures.Add(pf); } var s = new MsaglPoint(-dir.Y, dir.X); s *= 2 * h.Length * ((float)Math.Tan(arrowAngle * 0.5f * (Math.PI / 180.0))); s += s.Normalize(); PathFigure pf2 = new PathFigure(); pf2.StartPoint = WinPoint(start + s); pf2.Segments.Add(new WinLineSegment() { Point = WinPoint(start - s) }); pg.Figures.Add(pf2); } internal static void DrawDiamondArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end) { MsaglPoint dir = end - start; MsaglPoint h = dir; dir /= dir.Length; var s = new MsaglPoint(-dir.Y, dir.X); PathFigure pf = new PathFigure(); pf.StartPoint = WinPoint(start - dir); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(start + (h / 2) + s * (h.Length / 3)) }); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) }); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(start + (h / 2) - s * (h.Length / 3)) }); pf.IsClosed = true; pg.Figures.Add(pf); } internal static void DrawODiamondArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end) { throw new NotImplementedException(); /* double lw = lineWidth == -1 ? 1 : lineWidth; using (var p = new Pen(brush, (float)lw)) { Point dir = end - start; Point h = dir; dir /= dir.Length; var s = new Point(-dir.Y, dir.X); var points = new[]{ PointF(start - dir), PointF(start + (h/2) + s*(h.Length/3)), PointF(end), PointF(start + (h/2) - s*(h.Length/3)) }; g.DrawPolygon(p, points); }*/ } internal static void DrawGeneralizationArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end) { throw new NotImplementedException(); /* double lw = lineWidth == -1 ? 1 : lineWidth; using (var p = new Pen(brush, (float)lw)) { Point dir = end - start; Point h = dir; dir /= dir.Length; var s = new Point(-dir.Y, dir.X); var points = new[]{ PointF(start), PointF(start + s*(h.Length/2)), PointF(end), PointF(start - s*(h.Length/2)) }; // g.FillPolygon(p.Brush, points); g.DrawPolygon(p, points); }*/ } internal static void DrawLine(PathGeometry pg, MsaglPoint start, MsaglPoint end) { PathFigure pf = new PathFigure() { StartPoint = WinPoint(start) }; pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) }); pg.Figures.Add(pf); } internal static void DrawBox(PathGeometry pg, DNode dNode) { throw new NotImplementedException(); /* NodeAttr nodeAttr = dNode.DrawingNode.Attr; if (nodeAttr.XRadius == 0 || nodeAttr.YRadius == 0) { double x = nodeAttr.Pos.X - nodeAttr.Width / 2.0f; double y = nodeAttr.Pos.Y - nodeAttr.Height / 2.0f; if (NeedToFill(dNode.FillColor)) { Color fc = FillColor(nodeAttr); g.FillRectangle(new SolidBrush(fc), (float)x, (float)y, (float)nodeAttr.Width, (float)nodeAttr.Height); } g.DrawRectangle(pen, (float)x, (float)y, (float)nodeAttr.Width, (float)nodeAttr.Height); } else { var width = (float)nodeAttr.Width; var height = (float)nodeAttr.Height; var xRadius = (float)nodeAttr.XRadius; var yRadius = (float)nodeAttr.YRadius; using (var path = new GraphicsPath()) { FillTheGraphicsPath(nodeAttr, width, height, ref xRadius, ref yRadius, path); if (NeedToFill(dNode.FillColor)) { g.FillPath(new SolidBrush(dNode.FillColor), path); } g.DrawPath(pen, path); } } * */ } internal static void DrawDiamond(Canvas g, Brush pen, DNode dNode) { throw new NotImplementedException(); /* NodeAttr nodeAttr = dNode.DrawingNode.Attr; double w2 = nodeAttr.Width / 2.0f; double h2 = nodeAttr.Height / 2.0f; double cx = nodeAttr.Pos.X; double cy = nodeAttr.Pos.Y; var ps = new[]{ new PointF((float) cx - (float) w2, (float) cy), new PointF((float) cx, (float) cy + (float) h2), new PointF((float) cx + (float) w2, (float) cy), new PointF((float) cx, (float) cy - (float) h2) }; if (NeedToFill(dNode.FillColor)) { Color fc = FillColor(nodeAttr); g.FillPolygon(new SolidBrush(fc), ps); } g.DrawPolygon(pen, ps); //*/ } internal static void DrawEllipse(Canvas g, Brush pen, DNode dNode) { var node = dNode.DrawingNode; NodeAttr nodeAttr = node.Attr; var x = (float)(node.GeometryNode.Center.X - node.Width / 2.0); var y = (float)(node.GeometryNode.Center.Y - node.Height / 2.0); var width = (float)node.Width; var height = (float)node.Height; DrawEllipseOnPosition(dNode, nodeAttr, g, x, y, width, height, pen); } static void DrawEllipseOnPosition(DNode dNode, NodeAttr nodeAttr, Canvas g, float x, float y, float width, float height, Brush pen) { throw new NotImplementedException(); /* if (NeedToFill(dNode.FillColor)) g.FillEllipse(new SolidBrush(dNode.FillColor), x, y, width, height); if (nodeAttr.Shape == Shape.Point) g.FillEllipse(new SolidBrush(pen.Color), x, y, width, height); g.DrawEllipse(pen, x, y, width, height); //*/ } //don't know what to do about the throw-catch block [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal static void DrawLabel(Canvas g, DLabel label) { if (label == null) return; throw new NotImplementedException(); /* try { DrawStringInRectCenter(g, new SolidBrush(MsaglColorToDrawingColor(label.DrawingLabel.FontColor)), label.Font, label.DrawingLabel.Text, new RectangleF((float)label.DrawingLabel.Left, (float)label.DrawingLabel.Bottom, (float)label.DrawingLabel.Size.Width, (float)label.DrawingLabel.Size.Height)); } catch { } if (label.MarkedForDragging) { var pen = new Pen(MsaglColorToDrawingColor(label.DrawingLabel.FontColor)); pen.DashStyle = DashStyle.Dot; DrawLine(g, pen, label.DrawingLabel.GeometryLabel.AttachmentSegmentStart, label.DrawingLabel.GeometryLabel.AttachmentSegmentEnd); } //*/ } static void DrawStringInRectCenter(Canvas g, Brush brush, /*Font f,*/ string s, Rect r /*, double rectLineWidth*/) { if (String.IsNullOrEmpty(s)) return; throw new NotImplementedException(); /* using (Matrix m = g.Transform) { using (Matrix saveM = m.Clone()) { //rotate the label around its center float c = (r.Bottom + r.Top) / 2; using (var m2 = new Matrix(1, 0, 0, -1, 0, 2 * c)) { m.Multiply(m2); } g.Transform = m; using (StringFormat stringFormat = StringFormat.GenericTypographic) { g.DrawString(s, f, brush, r.Left, r.Top, stringFormat); } g.Transform = saveM; } } */ } internal static WinPoint PointF(MsaglPoint p) { return new WinPoint(p.X, p.Y); } internal static void DrawFromMsaglCurve(Canvas g, Brush pen, DNode dNode) { throw new NotImplementedException(); /* NodeAttr attr = dNode.DrawingNode.Attr; var c = attr.GeometryNode.BoundaryCurve as Curve; if (c != null) { var path = new GraphicsPath(); foreach (ICurve seg in c.Segments) AddSegToPath(seg, ref path); if (NeedToFill(dNode.FillColor)) { g.FillPath(new SolidBrush(dNode.FillColor), path); } g.DrawPath(pen, path); } else { var ellipse = attr.GeometryNode.BoundaryCurve as Ellipse; if (ellipse != null) { double w = ellipse.AxisA.X; double h = ellipse.AxisB.Y; DrawEllipseOnPosition(dNode, dNode.DrawingNode.Attr, g, (float)(ellipse.Center.X - w), (float)(ellipse.Center.Y - h), (float)w * 2, (float)h * 2, pen); } }*/ } static void AddSegToPath(ICurve seg, ref PathGeometry path) { throw new NotImplementedException(); /* var line = seg as LineSegment; if (line != null) path.AddLine(PointF(line.Start), PointF(line.End)); else { var cb = seg as CubicBezierSegment; if (cb != null) path.AddBezier(PointF(cb.B(0)), PointF(cb.B(1)), PointF(cb.B(2)), PointF(cb.B(3))); else { var ellipse = seg as Ellipse; if (ellipse != null) { //we assume that ellipes are going counterclockwise double cx = ellipse.Center.X; double cy = ellipse.Center.Y; double w = ellipse.AxisA.X * 2; double h = ellipse.AxisB.Y * 2; double sweep = ellipse.ParEnd - ellipse.ParStart; if (sweep < 0) sweep += Math.PI * 2; const double toDegree = 180 / Math.PI; path.AddArc((float)(cx - w / 2), (float)(cy - h / 2), (float)w, (float)h, (float)(ellipse.ParStart * toDegree), (float)(sweep * toDegree)); } } }*/ } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Wraps a stream and provides convenient read functionality ** for strings and primitive types. ** ** ============================================================*/ using System; using System.Runtime; using System.Text; using System.Globalization; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; namespace System.IO { public class BinaryReader : IDisposable { private const int MaxCharBytesSize = 128; private Stream m_stream; private byte[] m_buffer; private Decoder m_decoder; private byte[] m_charBytes; private char[] m_singleChar; private char[] m_charBuffer; private int m_maxCharsSize; // From MaxCharBytesSize & Encoding // Performance optimization for Read() w/ Unicode. Speeds us up by ~40% private bool m_2BytesPerChar; private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf private bool m_leaveOpen; public BinaryReader(Stream input) : this(input, Encoding.UTF8, false) { } public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false) { } public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) { if (input == null) { throw new ArgumentNullException(nameof(input)); } if (encoding == null) { throw new ArgumentNullException(nameof(encoding)); } if (!input.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable); Contract.EndContractBlock(); m_stream = input; m_decoder = encoding.GetDecoder(); m_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize); int minBufferSize = encoding.GetMaxByteCount(1); // max bytes per one char if (minBufferSize < 16) minBufferSize = 16; m_buffer = new byte[minBufferSize]; // m_charBuffer and m_charBytes will be left null. // For Encodings that always use 2 bytes per char (or more), // special case them here to make Read() & Peek() faster. m_2BytesPerChar = encoding is UnicodeEncoding; // check if BinaryReader is based on MemoryStream, and keep this for it's life // we cannot use "as" operator, since derived classes are not allowed m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream)); m_leaveOpen = leaveOpen; Debug.Assert(m_decoder != null, "[BinaryReader.ctor]m_decoder!=null"); } public virtual Stream BaseStream { get { return m_stream; } } public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Stream copyOfStream = m_stream; m_stream = null; if (copyOfStream != null && !m_leaveOpen) copyOfStream.Close(); } m_stream = null; m_buffer = null; m_decoder = null; m_charBytes = null; m_singleChar = null; m_charBuffer = null; } public void Dispose() { Dispose(true); } public virtual int PeekChar() { Contract.Ensures(Contract.Result<int>() >= -1); if (m_stream == null) __Error.FileNotOpen(); if (!m_stream.CanSeek) return -1; long origPos = m_stream.Position; int ch = Read(); m_stream.Position = origPos; return ch; } public virtual int Read() { Contract.Ensures(Contract.Result<int>() >= -1); if (m_stream == null) { __Error.FileNotOpen(); } return InternalReadOneChar(); } public virtual bool ReadBoolean() { FillBuffer(1); return (m_buffer[0] != 0); } public virtual byte ReadByte() { // Inlined to avoid some method call overhead with FillBuffer. if (m_stream == null) __Error.FileNotOpen(); int b = m_stream.ReadByte(); if (b == -1) __Error.EndOfFile(); return (byte)b; } [CLSCompliant(false)] public virtual sbyte ReadSByte() { FillBuffer(1); return (sbyte)(m_buffer[0]); } public virtual char ReadChar() { int value = Read(); if (value == -1) { __Error.EndOfFile(); } return (char)value; } public virtual short ReadInt16() { FillBuffer(2); return (short)(m_buffer[0] | m_buffer[1] << 8); } [CLSCompliant(false)] public virtual ushort ReadUInt16() { FillBuffer(2); return (ushort)(m_buffer[0] | m_buffer[1] << 8); } public virtual int ReadInt32() { if (m_isMemoryStream) { if (m_stream == null) __Error.FileNotOpen(); // read directly from MemoryStream buffer MemoryStream mStream = m_stream as MemoryStream; Debug.Assert(mStream != null, "m_stream as MemoryStream != null"); return mStream.InternalReadInt32(); } else { FillBuffer(4); return (int)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); } } [CLSCompliant(false)] public virtual uint ReadUInt32() { FillBuffer(4); return (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); } public virtual long ReadInt64() { FillBuffer(8); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); return (long)((ulong)hi) << 32 | lo; } [CLSCompliant(false)] public virtual ulong ReadUInt64() { FillBuffer(8); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); return ((ulong)hi) << 32 | lo; } public virtual unsafe float ReadSingle() { FillBuffer(4); uint tmpBuffer = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); return *((float*)&tmpBuffer); } public virtual unsafe double ReadDouble() { FillBuffer(8); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); ulong tmpBuffer = ((ulong)hi) << 32 | lo; return *((double*)&tmpBuffer); } public virtual decimal ReadDecimal() { FillBuffer(16); try { return Decimal.ToDecimal(m_buffer); } catch (ArgumentException e) { // ReadDecimal cannot leak out ArgumentException throw new IOException(SR.Arg_DecBitCtor, e); } } public virtual String ReadString() { Contract.Ensures(Contract.Result<String>() != null); if (m_stream == null) __Error.FileNotOpen(); int currPos = 0; int n; int stringLength; int readLength; int charsRead; // Length of the string in bytes, not chars stringLength = Read7BitEncodedInt(); if (stringLength < 0) { throw new IOException(SR.Format(SR.IO_InvalidStringLen_Len, stringLength)); } if (stringLength == 0) { return String.Empty; } if (m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; } if (m_charBuffer == null) { m_charBuffer = new char[m_maxCharsSize]; } StringBuilder sb = null; do { readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos); n = m_stream.Read(m_charBytes, 0, readLength); if (n == 0) { __Error.EndOfFile(); } charsRead = m_decoder.GetChars(m_charBytes, 0, n, m_charBuffer, 0); if (currPos == 0 && n == stringLength) return new String(m_charBuffer, 0, charsRead); if (sb == null) sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller. sb.Append(m_charBuffer, 0, charsRead); currPos += n; } while (currPos < stringLength); return StringBuilderCache.GetStringAndRelease(sb); } public virtual int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= count); Contract.EndContractBlock(); if (m_stream == null) __Error.FileNotOpen(); // SafeCritical: index and count have already been verified to be a valid range for the buffer return InternalReadChars(buffer, index, count); } private int InternalReadChars(char[] buffer, int index, int count) { Contract.Requires(buffer != null); Contract.Requires(index >= 0 && count >= 0); Debug.Assert(m_stream != null); int numBytes = 0; int charsRemaining = count; if (m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; } while (charsRemaining > 0) { int charsRead = 0; // We really want to know what the minimum number of bytes per char // is for our encoding. Otherwise for UnicodeEncoding we'd have to // do ~1+log(n) reads to read n characters. numBytes = charsRemaining; // special case for DecoderNLS subclasses when there is a hanging byte from the previous loop DecoderNLS decoder = m_decoder as DecoderNLS; if (decoder != null && decoder.HasState && numBytes > 1) { numBytes -= 1; } if (m_2BytesPerChar) numBytes <<= 1; if (numBytes > MaxCharBytesSize) numBytes = MaxCharBytesSize; int position = 0; byte[] byteBuffer = null; if (m_isMemoryStream) { MemoryStream mStream = m_stream as MemoryStream; Debug.Assert(mStream != null, "m_stream as MemoryStream != null"); position = mStream.InternalGetPosition(); numBytes = mStream.InternalEmulateRead(numBytes); byteBuffer = mStream.InternalGetBuffer(); } else { numBytes = m_stream.Read(m_charBytes, 0, numBytes); byteBuffer = m_charBytes; } if (numBytes == 0) { return (count - charsRemaining); } Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null"); checked { if (position < 0 || numBytes < 0 || position > byteBuffer.Length - numBytes) { throw new ArgumentOutOfRangeException(nameof(numBytes)); } if (index < 0 || charsRemaining < 0 || index > buffer.Length - charsRemaining) { throw new ArgumentOutOfRangeException(nameof(charsRemaining)); } unsafe { fixed (byte* pBytes = byteBuffer) fixed (char* pChars = buffer) { charsRead = m_decoder.GetChars(pBytes + position, numBytes, pChars + index, charsRemaining, flush: false); } } } charsRemaining -= charsRead; index += charsRead; } // this should never fail Debug.Assert(charsRemaining >= 0, "We read too many characters."); // we may have read fewer than the number of characters requested if end of stream reached // or if the encoding makes the char count too big for the buffer (e.g. fallback sequence) return (count - charsRemaining); } private int InternalReadOneChar() { // I know having a separate InternalReadOneChar method seems a little // redundant, but this makes a scenario like the security parser code // 20% faster, in addition to the optimizations for UnicodeEncoding I // put in InternalReadChars. int charsRead = 0; int numBytes = 0; long posSav = posSav = 0; if (m_stream.CanSeek) posSav = m_stream.Position; if (m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; } if (m_singleChar == null) { m_singleChar = new char[1]; } while (charsRead == 0) { // We really want to know what the minimum number of bytes per char // is for our encoding. Otherwise for UnicodeEncoding we'd have to // do ~1+log(n) reads to read n characters. // Assume 1 byte can be 1 char unless m_2BytesPerChar is true. numBytes = m_2BytesPerChar ? 2 : 1; int r = m_stream.ReadByte(); m_charBytes[0] = (byte)r; if (r == -1) numBytes = 0; if (numBytes == 2) { r = m_stream.ReadByte(); m_charBytes[1] = (byte)r; if (r == -1) numBytes = 1; } if (numBytes == 0) { // Console.WriteLine("Found no bytes. We're outta here."); return -1; } Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only."); try { charsRead = m_decoder.GetChars(m_charBytes, 0, numBytes, m_singleChar, 0); } catch { // Handle surrogate char if (m_stream.CanSeek) m_stream.Seek((posSav - m_stream.Position), SeekOrigin.Current); // else - we can't do much here throw; } Debug.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!"); // Console.WriteLine("That became: " + charsRead + " characters."); } if (charsRead == 0) return -1; return m_singleChar[0]; } public virtual char[] ReadChars(int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.Ensures(Contract.Result<char[]>() != null); Contract.Ensures(Contract.Result<char[]>().Length <= count); Contract.EndContractBlock(); if (m_stream == null) { __Error.FileNotOpen(); } if (count == 0) { return Array.Empty<Char>(); } // SafeCritical: we own the chars buffer, and therefore can guarantee that the index and count are valid char[] chars = new char[count]; int n = InternalReadChars(chars, 0, count); if (n != count) { char[] copy = new char[n]; Buffer.InternalBlockCopy(chars, 0, copy, 0, 2 * n); // sizeof(char) chars = copy; } return chars; } public virtual int Read(byte[] buffer, int index, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= count); Contract.EndContractBlock(); if (m_stream == null) __Error.FileNotOpen(); return m_stream.Read(buffer, index, count); } public virtual byte[] ReadBytes(int count) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count)); Contract.EndContractBlock(); if (m_stream == null) __Error.FileNotOpen(); if (count == 0) { return Array.Empty<Byte>(); } byte[] result = new byte[count]; int numRead = 0; do { int n = m_stream.Read(result, numRead, count); if (n == 0) break; numRead += n; count -= n; } while (count > 0); if (numRead != result.Length) { // Trim array. This should happen on EOF & possibly net streams. byte[] copy = new byte[numRead]; Buffer.InternalBlockCopy(result, 0, copy, 0, numRead); result = copy; } return result; } protected virtual void FillBuffer(int numBytes) { if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length)) { throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_BinaryReaderFillBuffer); } int bytesRead = 0; int n = 0; if (m_stream == null) __Error.FileNotOpen(); // Need to find a good threshold for calling ReadByte() repeatedly // vs. calling Read(byte[], int, int) for both buffered & unbuffered // streams. if (numBytes == 1) { n = m_stream.ReadByte(); if (n == -1) __Error.EndOfFile(); m_buffer[0] = (byte)n; return; } do { n = m_stream.Read(m_buffer, bytesRead, numBytes - bytesRead); if (n == 0) { __Error.EndOfFile(); } bytesRead += n; } while (bytesRead < numBytes); } internal protected int Read7BitEncodedInt() { // Read out an Int32 7 bits at a time. The high bit // of the byte when on means to continue reading more bytes. int count = 0; int shift = 0; byte b; do { // Check for a corrupted stream. Read a max of 5 bytes. // In a future version, add a DataFormatException. if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7 throw new FormatException(SR.Format_Bad7BitInt32); // ReadByte handles end of stream cases for us. b = ReadByte(); count |= (b & 0x7F) << shift; shift += 7; } while ((b & 0x80) != 0); return count; } } }
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.NHibernateIntegration.Saga { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Transactions; using GreenPipes; using Logging; using MassTransit.Saga; using NHibernate; using NHibernate.Exceptions; using Util; public class NHibernateSagaRepository<TSaga> : ISagaRepository<TSaga>, IQuerySagaRepository<TSaga> where TSaga : class, ISaga { static readonly ILog _log = Logger.Get<NHibernateSagaRepository<TSaga>>(); readonly ISessionFactory _sessionFactory; System.Data.IsolationLevel _insertIsolationLevel; public NHibernateSagaRepository(ISessionFactory sessionFactory) { _sessionFactory = sessionFactory; _insertIsolationLevel = System.Data.IsolationLevel.ReadCommitted; } public NHibernateSagaRepository(ISessionFactory sessionFactory, System.Data.IsolationLevel isolationLevel) { _sessionFactory = sessionFactory; _insertIsolationLevel = isolationLevel; } public Task<IEnumerable<Guid>> Find(ISagaQuery<TSaga> query) { using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew)) using (var session = _sessionFactory.OpenSession()) { IList<Guid> result = session.QueryOver<TSaga>() .Where(query.FilterExpression) .Select(x => x.CorrelationId) .List<Guid>(); scope.Complete(); return Task.FromResult<IEnumerable<Guid>>(result); } } void IProbeSite.Probe(ProbeContext context) { var scope = context.CreateScope("sagaRepository"); scope.Set(new { Persistence = "nhibernate", Entities = _sessionFactory.GetAllClassMetadata().Select(x => x.Value.EntityName).ToArray() }); } async Task ISagaRepository<TSaga>.Send<T>(ConsumeContext<T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next) { if (!context.CorrelationId.HasValue) throw new SagaException("The CorrelationId was not specified", typeof(TSaga), typeof(T)); var sagaId = context.CorrelationId.Value; using (var session = _sessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { var inserted = false; TSaga instance; if (policy.PreInsertInstance(context, out instance)) inserted = PreInsertSagaInstance<T>(session, instance); try { if (instance == null) instance = session.Get<TSaga>(sagaId, LockMode.Upgrade); if (instance == null) { var missingSagaPipe = new MissingPipe<T>(session, next); await policy.Missing(context, missingSagaPipe).ConfigureAwait(false); } else { if (_log.IsDebugEnabled) _log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName); var sagaConsumeContext = new NHibernateSagaConsumeContext<TSaga, T>(session, context, instance); await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false); if (inserted && !sagaConsumeContext.IsCompleted) session.Update(instance); } if (transaction.IsActive) transaction.Commit(); } catch (Exception ex) { if (_log.IsErrorEnabled) _log.Error($"SAGA:{TypeMetadataCache<TSaga>.ShortName} Exception {TypeMetadataCache<T>.ShortName}", ex); if (transaction.IsActive) transaction.Rollback(); throw; } } } public async Task SendQuery<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next) where T : class { using (var session = _sessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { try { IList<TSaga> instances = session.QueryOver<TSaga>() .Where(context.Query.FilterExpression) .List<TSaga>(); if (instances.Count == 0) { var missingSagaPipe = new MissingPipe<T>(session, next); await policy.Missing(context, missingSagaPipe).ConfigureAwait(false); } else await Task.WhenAll(instances.Select(instance => SendToInstance(context, policy, instance, next, session))).ConfigureAwait(false); // TODO partial failure should not affect them all if (transaction.IsActive) transaction.Commit(); } catch (SagaException sex) { if (_log.IsErrorEnabled) _log.Error($"SAGA:{TypeMetadataCache<TSaga>.ShortName} Exception {TypeMetadataCache<T>.ShortName}", sex); if (transaction.IsActive) transaction.Rollback(); throw; } catch (Exception ex) { if (_log.IsErrorEnabled) _log.Error($"SAGA:{TypeMetadataCache<TSaga>.ShortName} Exception {TypeMetadataCache<T>.ShortName}", ex); if (transaction.IsActive) transaction.Rollback(); throw new SagaException(ex.Message, typeof(TSaga), typeof(T), Guid.Empty, ex); } } } static bool PreInsertSagaInstance<T>(ISession session, TSaga instance) { bool inserted = false; try { session.Save(instance); session.Flush(); inserted = true; _log.DebugFormat("SAGA:{0}:{1} Insert {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName); } catch (GenericADOException ex) { if (_log.IsDebugEnabled) { _log.DebugFormat("SAGA:{0}:{1} Dupe {2} - {3}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName, ex.Message); } } return inserted; } async Task SendToInstance<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, TSaga instance, IPipe<SagaConsumeContext<TSaga, T>> next, ISession session) where T : class { try { if (_log.IsDebugEnabled) _log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName); var sagaConsumeContext = new NHibernateSagaConsumeContext<TSaga, T>(session, context, instance); await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false); } catch (SagaException) { throw; } catch (Exception ex) { throw new SagaException(ex.Message, typeof(TSaga), typeof(T), instance.CorrelationId, ex); } } /// <summary> /// Once the message pipe has processed the saga instance, add it to the saga repository /// </summary> /// <typeparam name="TMessage"></typeparam> class MissingPipe<TMessage> : IPipe<SagaConsumeContext<TSaga, TMessage>> where TMessage : class { readonly IPipe<SagaConsumeContext<TSaga, TMessage>> _next; readonly ISession _session; public MissingPipe(ISession session, IPipe<SagaConsumeContext<TSaga, TMessage>> next) { _session = session; _next = next; } void IProbeSite.Probe(ProbeContext context) { _next.Probe(context); } public async Task Send(SagaConsumeContext<TSaga, TMessage> context) { if (_log.IsDebugEnabled) { _log.DebugFormat("SAGA:{0}:{1} Added {2}", TypeMetadataCache<TSaga>.ShortName, context.Saga.CorrelationId, TypeMetadataCache<TMessage>.ShortName); } SagaConsumeContext<TSaga, TMessage> proxy = new NHibernateSagaConsumeContext<TSaga, TMessage>(_session, context, context.Saga); await _next.Send(proxy).ConfigureAwait(false); if (!proxy.IsCompleted) _session.Save(context.Saga); } } } }
/* ** $Id: print.c,v 1.55a 2006/05/31 13:30:05 lhf Exp $ ** print bytecodes ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; namespace SharpLua { using TValue = Lua.lua_TValue; using Instruction = System.UInt32; public partial class Lua { public static void luaU_print(Proto f, int full) { PrintFunction(f, full); } //#define Sizeof(x) ((int)sizeof(x)) //#define VOID(p) ((const void*)(p)) public static void PrintString(TString ts) { CharPtr s = getstr(ts); uint i, n = ts.tsv.len; putchar('"'); for (i = 0; i < n; i++) { int c = s[i]; switch (c) { case '"': printf("\\\""); break; case '\\': printf("\\\\"); break; case '\a': printf("\\a"); break; case '\b': printf("\\b"); break; case '\f': printf("\\f"); break; case '\n': printf("\\n"); break; case '\r': printf("\\r"); break; case '\t': printf("\\t"); break; case '\v': printf("\\v"); break; default: if (isprint((byte)c)) putchar(c); else printf("\\%03u", (byte)c); break; } } putchar('"'); } private static void PrintConstant(Proto f, int i) { /*const*/ TValue o = f.k[i]; switch (ttype(o)) { case LUA_TNIL: printf("nil"); break; case LUA_TBOOLEAN: printf(bvalue(o) != 0 ? "true" : "false"); break; case LUA_TNUMBER: printf(LUA_NUMBER_FMT, nvalue(o)); break; case LUA_TSTRING: PrintString(rawtsvalue(o)); break; default: /* cannot happen */ printf("? type=%d", ttype(o)); break; } } private static void PrintCode(Proto f) { Instruction[] code = f.code; int pc, n = f.sizecode; for (pc = 0; pc < n; pc++) { Instruction i = f.code[pc]; OpCode o = GET_OPCODE(i); int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); int bx = GETARG_Bx(i); int sbx = GETARG_sBx(i); int line = getline(f, pc); printf("\t%d\t", pc + 1); if (line > 0) printf("[%d]\t", line); else printf("[-]\t"); printf("%-9s\t", luaP_opnames[(int)o]); switch (getOpMode(o)) { case OpMode.iABC: printf("%d", a); if (getBMode(o) != OpArgMask.OpArgN) printf(" %d", (ISK(b) != 0) ? (-1 - INDEXK(b)) : b); if (getCMode(o) != OpArgMask.OpArgN) printf(" %d", (ISK(c) != 0) ? (-1 - INDEXK(c)) : c); break; case OpMode.iABx: if (getBMode(o) == OpArgMask.OpArgK) printf("%d %d", a, -1 - bx); else printf("%d %d", a, bx); break; case OpMode.iAsBx: if (o == OpCode.OP_JMP) printf("%d", sbx); else printf("%d %d", a, sbx); break; } switch (o) { case OpCode.OP_LOADK: printf("\t; "); PrintConstant(f, bx); break; case OpCode.OP_GETUPVAL: case OpCode.OP_SETUPVAL: printf("\t; %s", (f.sizeupvalues > 0) ? getstr(f.upvalues[b]).ToString() : "-"); break; case OpCode.OP_GETGLOBAL: case OpCode.OP_SETGLOBAL: printf("\t; %s", svalue(f.k[bx])); break; case OpCode.OP_GETTABLE: case OpCode.OP_SELF: if (ISK(c) != 0) { printf("\t; "); PrintConstant(f, INDEXK(c)); } break; case OpCode.OP_SETTABLE: case OpCode.OP_ADD: case OpCode.OP_SUB: case OpCode.OP_MUL: case OpCode.OP_DIV: case OpCode.OP_POW: case OpCode.OP_EQ: case OpCode.OP_LT: case OpCode.OP_LE: if (ISK(b) != 0 || ISK(c) != 0) { printf("\t; "); if (ISK(b) != 0) PrintConstant(f, INDEXK(b)); else printf("-"); printf(" "); if (ISK(c) != 0) PrintConstant(f, INDEXK(c)); else printf("-"); } break; case OpCode.OP_JMP: case OpCode.OP_FORLOOP: case OpCode.OP_FORPREP: printf("\t; to %d", sbx + pc + 2); break; case OpCode.OP_CLOSURE: printf("\t; %p", VOID(f.p[bx])); break; case OpCode.OP_SETLIST: if (c == 0) printf("\t; %d", (int)code[++pc]); else printf("\t; %d", c); break; default: break; } printf("\n"); } } public static string SS(int x) { return (x == 1) ? "" : "s"; } //#define S(x) x,SS(x) private static void PrintHeader(Proto f) { CharPtr s = getstr(f.source); if (s[0] == '@' || s[0] == '=') s = s.next(); else if (s[0] == LUA_SIGNATURE[0]) s = "(bstring)"; else s = "(string)"; printf("\n%s <%s:%d,%d> (%d Instruction%s, %d bytes at %p)\n", (f.linedefined == 0) ? "main" : "function", s, f.linedefined, f.lastlinedefined, f.sizecode, SS(f.sizecode), f.sizecode * GetUnmanagedSize(typeof(Instruction)), VOID(f)); printf("%d%s param%s, %d slot%s, %d upvalue%s, ", f.numparams, (f.is_vararg != 0) ? "+" : "", SS(f.numparams), f.maxstacksize, SS(f.maxstacksize), f.nups, SS(f.nups)); printf("%d local%s, %d constant%s, %d function%s\n", f.sizelocvars, SS(f.sizelocvars), f.sizek, SS(f.sizek), f.sizep, SS(f.sizep)); } private static void PrintConstants(Proto f) { int i, n = f.sizek; printf("constants (%d) for %p:\n", n, VOID(f)); for (i = 0; i < n; i++) { printf("\t%d\t", i + 1); PrintConstant(f, i); printf("\n"); } } private static void PrintLocals(Proto f) { int i, n = f.sizelocvars; printf("locals (%d) for %p:\n", n, VOID(f)); for (i = 0; i < n; i++) { printf("\t%d\t%s\t%d\t%d\n", i, getstr(f.locvars[i].varname), f.locvars[i].startpc + 1, f.locvars[i].endpc + 1); } } private static void PrintUpvalues(Proto f) { int i, n = f.sizeupvalues; printf("upvalues (%d) for %p:\n", n, VOID(f)); if (f.upvalues == null) return; for (i = 0; i < n; i++) { printf("\t%d\t%s\n", i, getstr(f.upvalues[i])); } } public static void PrintFunction(Proto f, int full) { int i, n = f.sizep; PrintHeader(f); PrintCode(f); if (full != 0) { PrintConstants(f); PrintLocals(f); PrintUpvalues(f); } for (i = 0; i < n; i++) PrintFunction(f.p[i], full); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Runtime.InteropServices; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using umbraco.BusinessLogic; using umbraco.BusinessLogic.Actions; using umbraco.cms.businesslogic.cache; using Umbraco.Core.Models; using umbraco.interfaces; using umbraco.DataLayer; using System.Runtime.CompilerServices; using Language = umbraco.cms.businesslogic.language.Language; namespace umbraco.cms.businesslogic.web { /// <summary> /// Summary description for Domain. /// </summary> [Obsolete("Use Umbraco.Core.Models.IDomain and Umbraco.Core.Services.IDomainService instead")] public class Domain { public IDomain DomainEntity { get; set; } /// <summary> /// Empty ctor used for unit tests to create a custom domain /// </summary> internal Domain() { } internal Domain(IDomain domain) { DomainEntity = domain; } public Domain(int Id) { DomainEntity = ApplicationContext.Current.Services.DomainService.GetById(Id); if (DomainEntity == null) { throw new Exception(string.Format("Domain name '{0}' does not exists", Id)); } } public Domain(string DomainName) { DomainEntity = ApplicationContext.Current.Services.DomainService.GetByName(DomainName); if (DomainEntity == null) { throw new Exception(string.Format("Domain name '{0}' does not exists", DomainName)); } } public string Name { get { return DomainEntity.DomainName; } set { DomainEntity.DomainName = value; } } public Language Language { get { return new Language(DomainEntity.Language); } set { DomainEntity.Language = value.LanguageEntity; } } public int RootNodeId { get { return DomainEntity.RootContent.Id; } set { var content = ApplicationContext.Current.Services.ContentService.GetById(value); if (content == null) { throw new NullReferenceException("No content found with id " + value); } DomainEntity.RootContent = content; } } public int Id { get { return DomainEntity.Id; } } public void Delete() { var e = new DeleteEventArgs(); FireBeforeDelete(e); if (!e.Cancel) { ApplicationContext.Current.Services.DomainService.Delete(DomainEntity); FireAfterDelete(e); } } public void Save(){ var e = new SaveEventArgs(); FireBeforeSave(e); if (!e.Cancel) { ApplicationContext.Current.Services.DomainService.Save(DomainEntity); FireAfterSave(e); } } #region Statics public static IEnumerable<Domain> GetDomains() { return GetDomains(false); } public static IEnumerable<Domain> GetDomains(bool includeWildcards) { return ApplicationContext.Current.Services.DomainService.GetAll(includeWildcards) .Select(x => new Domain(x)); } public static Domain GetDomain(string DomainName) { var found = ApplicationContext.Current.Services.DomainService.GetByName(DomainName); return found == null ? null : new Domain(found); } public static int GetRootFromDomain(string DomainName) { var found = ApplicationContext.Current.Services.DomainService.GetByName(DomainName); return found == null ? -1 : found.RootContent.Id; } public static Domain[] GetDomainsById(int nodeId) { return ApplicationContext.Current.Services.DomainService.GetAssignedDomains(nodeId, true) .Select(x => new Domain(x)) .ToArray(); } public static Domain[] GetDomainsById(int nodeId, bool includeWildcards) { return ApplicationContext.Current.Services.DomainService.GetAssignedDomains(nodeId, includeWildcards) .Select(x => new Domain(x)) .ToArray(); } public static bool Exists(string DomainName) { return ApplicationContext.Current.Services.DomainService.Exists(DomainName); } public static void MakeNew(string DomainName, int RootNodeId, int LanguageId) { var content = ApplicationContext.Current.Services.ContentService.GetById(RootNodeId); if (content == null) throw new NullReferenceException("No content exists with id " + RootNodeId); var lang = ApplicationContext.Current.Services.LocalizationService.GetLanguageById(LanguageId); if (lang == null) throw new NullReferenceException("No language exists with id " + LanguageId); var domain = new UmbracoDomain(DomainName) { RootContent = content, Language = lang }; ApplicationContext.Current.Services.DomainService.Save(domain); var e = new NewEventArgs(); var legacyModel = new Domain(domain); legacyModel.OnNew(e); } #endregion //EVENTS public delegate void SaveEventHandler(Domain sender, SaveEventArgs e); public delegate void NewEventHandler(Domain sender, NewEventArgs e); public delegate void DeleteEventHandler(Domain sender, DeleteEventArgs e); /// <summary> /// Occurs when a macro is saved. /// </summary> public static event SaveEventHandler BeforeSave; protected virtual void FireBeforeSave(SaveEventArgs e) { if (BeforeSave != null) BeforeSave(this, e); } public static event SaveEventHandler AfterSave; protected virtual void FireAfterSave(SaveEventArgs e) { if (AfterSave != null) AfterSave(this, e); } public static event NewEventHandler New; protected virtual void OnNew(NewEventArgs e) { if (New != null) New(this, e); } public static event DeleteEventHandler BeforeDelete; protected virtual void FireBeforeDelete(DeleteEventArgs e) { if (BeforeDelete != null) BeforeDelete(this, e); } public static event DeleteEventHandler AfterDelete; protected virtual void FireAfterDelete(DeleteEventArgs e) { if (AfterDelete != null) AfterDelete(this, e); } #region Pipeline Refactoring // NOTE: the wildcard name thing should be managed by the Domain class // internally but that would break too much backward compatibility, so // we don't do it now. Will do it when the Domain class migrates to the // new Core.Models API. /// <summary> /// Gets a value indicating whether the domain is a wildcard domain. /// </summary> /// <returns>A value indicating whether the domain is a wildcard domain.</returns> public bool IsWildcard { get { return DomainEntity.IsWildcard; } } #endregion } }
using System; using System.IO; using System.Reactive; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; using Common.Logging; namespace NuGet.Lucene { public class PackageFileSystemWatcher : IDisposable { private FileSystemWatcher fileWatcher; private IDisposable fileObserver; private IDisposable dirObserver; public ILog Log { get; set; } public IFileSystem FileSystem { get; set; } public ILucenePackageRepository PackageRepository { get; set; } public IPackageIndexer Indexer { get; set; } /// <summary> /// Sets the amount of time to wait after receiving a <c cref="FileSystemWatcher.Changed">Changed</c> /// event before attempting to index a package. This timeout is meant to avoid trying to read a package /// while it is still being built or copied into place. /// </summary> public TimeSpan QuietTime { get; set; } public PackageFileSystemWatcher() { Log = LogManager.GetLogger<PackageFileSystemWatcher>(); QuietTime = TimeSpan.FromSeconds(3); } public void Initialize() { fileWatcher = new FileSystemWatcher(FileSystem.Root, "*.nupkg") { NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite, IncludeSubdirectories = true, }; var modifiedFilesThrottledByPath = ModifiedFiles .Select(args => args.EventArgs.FullPath) .GroupBy(path => path) .Select(groupByPath => groupByPath.Throttle(QuietTime)) .SelectMany(obs => obs); #pragma warning disable 4014 // Because this call is not awaited, execution of the current method continues before the call is completed. fileObserver = modifiedFilesThrottledByPath.Subscribe(path => OnPackageModified(path)); fileWatcher.Deleted += (s, e) => OnPackageDeleted(e.FullPath); fileWatcher.Renamed += (s, e) => OnPackageRenamed(e.OldFullPath, e.FullPath); #pragma warning restore 4014 fileWatcher.EnableRaisingEvents = true; dirObserver = MovedDirectories.Select(args => args.EventArgs.FullPath).Throttle(QuietTime).Subscribe(OnDirectoryMoved); } public void Dispose() { fileObserver.Dispose(); fileWatcher.Dispose(); dirObserver.Dispose(); } public void OnDirectoryMoved(string fullPath) { try { if (FileSystem.GetFiles(fullPath, "*.nupkg", true).IsEmpty()) return; } catch (IOException ex) { Log.Error(ex); return; } Indexer.SynchronizeIndexWithFileSystem(CancellationToken.None); } public async Task OnPackageModified(string fullPath) { Log.Info(m => m("Indexing modified package " + fullPath)); await AddToIndex(fullPath).ContinueWith(LogOnFault); } public async Task OnPackageRenamed(string oldFullPath, string fullPath) { Log.Info(m => m("Package path {0} renamed to {1}.", oldFullPath, fullPath)); var task = RemoveFromIndex(oldFullPath).ContinueWith(LogOnFault); if (fullPath.EndsWith(Constants.PackageExtension)) { var addToIndex = AddToIndex(fullPath).ContinueWith(LogOnFault); await Task.WhenAll(addToIndex, task); return; } await task; } public async Task OnPackageDeleted(string fullPath) { Log.Info(m => m("Package path {0} deleted.", fullPath)); await RemoveFromIndex(fullPath).ContinueWith(LogOnFault); } private async Task AddToIndex(string fullPath) { LucenePackage package = null; Action checkTimestampAndLoadPackage = () => { var existingPackage = PackageRepository.LoadFromIndex(fullPath); var flag = (existingPackage == null || IndexDifferenceCalculator.TimestampsMismatch(existingPackage, FileSystem.GetLastModified(fullPath))); if (!flag) return; package = PackageRepository.LoadFromFileSystem(fullPath); }; await Task.Factory.StartNew(checkTimestampAndLoadPackage); if (package != null) { await Indexer.AddPackage(package); } } private async Task RemoveFromIndex(string fullPath) { var package = PackageRepository.LoadFromIndex(fullPath); if (package != null) { await Indexer.RemovePackage(package); } } private void LogOnFault(Task task) { if (task.IsFaulted) { task.Exception.Handle(ex => { Log.Error(ex); return true; }); } } private IObservable<EventPattern<FileSystemEventArgs>> ModifiedFiles { get { var created = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( eh => eh.Invoke, eh => fileWatcher.Created += eh, eh => fileWatcher.Created -= eh); var changed = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( eh => eh.Invoke, eh => fileWatcher.Changed += eh, eh => fileWatcher.Changed -= eh); return created.Merge(changed); } } private IObservable<EventPattern<FileSystemEventArgs>> MovedDirectories { get { Func<FileSystemWatcher> createDirWatcher = () => new FileSystemWatcher(FileSystem.Root) { NotifyFilter = NotifyFilters.DirectoryName, IncludeSubdirectories = true, EnableRaisingEvents = true }; Func<FileSystemWatcher, IObservable<EventPattern<FileSystemEventArgs>>> createObservable = dirWatcher => { var created = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( eh => eh.Invoke, eh => dirWatcher.Created += eh, eh => dirWatcher.Created -= eh); var renamed = Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>( eh => eh.Invoke, eh => dirWatcher.Renamed += eh, eh => dirWatcher.Renamed -= eh); return created.Merge(renamed.Select(re => new EventPattern<FileSystemEventArgs>(re.Sender, re.EventArgs))); }; return Observable.Using(createDirWatcher, createObservable); } } } }
using J2N.Runtime.CompilerServices; using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Codecs.Pulsing { /* * 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. */ /// <summary> /// Concrete class that reads the current doc/freq/skip postings format. /// <para/> /// @lucene.experimental /// </summary> // TODO: -- should we switch "hasProx" higher up? and // create two separate docs readers, one that also reads // prox and one that doesn't? public class PulsingPostingsReader : PostingsReaderBase { // Fallback reader for non-pulsed terms: private readonly PostingsReaderBase _wrappedPostingsReader; private readonly SegmentReadState _segmentState; private int _maxPositions; private int _version; private IDictionary<int, int> _fields; public PulsingPostingsReader(SegmentReadState state, PostingsReaderBase wrappedPostingsReader) { _wrappedPostingsReader = wrappedPostingsReader; _segmentState = state; } public override void Init(IndexInput termsIn) { _version = CodecUtil.CheckHeader(termsIn, PulsingPostingsWriter.CODEC, PulsingPostingsWriter.VERSION_START, PulsingPostingsWriter.VERSION_CURRENT); _maxPositions = termsIn.ReadVInt32(); _wrappedPostingsReader.Init(termsIn); if (_wrappedPostingsReader is PulsingPostingsReader || _version < PulsingPostingsWriter.VERSION_META_ARRAY) { _fields = null; } else { _fields = new JCG.SortedDictionary<int, int>(); var summaryFileName = IndexFileNames.SegmentFileName(_segmentState.SegmentInfo.Name, _segmentState.SegmentSuffix, PulsingPostingsWriter.SUMMARY_EXTENSION); IndexInput input = null; try { input = _segmentState.Directory.OpenInput(summaryFileName, _segmentState.Context); CodecUtil.CheckHeader(input, PulsingPostingsWriter.CODEC, _version, PulsingPostingsWriter.VERSION_CURRENT); var numField = input.ReadVInt32(); for (var i = 0; i < numField; i++) { var fieldNum = input.ReadVInt32(); var longsSize = input.ReadVInt32(); _fields.Add(fieldNum, longsSize); } } finally { IOUtils.DisposeWhileHandlingException(input); } } } internal class PulsingTermState : BlockTermState { internal bool Absolute { get; set; } /// <summary> /// NOTE: This was longs (field) in Lucene /// </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] internal long[] Int64s { get; set; } [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] internal byte[] Postings { get; set; } internal int PostingsSize { get; set; } // -1 if this term was not inlined internal BlockTermState WrappedTermState { get; set; } public override object Clone() { var clone = (PulsingTermState)base.Clone(); if (PostingsSize != -1) { clone.Postings = new byte[PostingsSize]; Array.Copy(Postings, 0, clone.Postings, 0, PostingsSize); } else { if (Debugging.AssertsEnabled) Debugging.Assert(WrappedTermState != null); clone.WrappedTermState = (BlockTermState)WrappedTermState.Clone(); clone.Absolute = Absolute; if (Int64s == null) return clone; clone.Int64s = new long[Int64s.Length]; Array.Copy(Int64s, 0, clone.Int64s, 0, Int64s.Length); } return clone; } public override void CopyFrom(TermState other) { base.CopyFrom(other); var _other = (PulsingTermState)other; PostingsSize = _other.PostingsSize; if (_other.PostingsSize != -1) { if (Postings == null || Postings.Length < _other.PostingsSize) { Postings = new byte[ArrayUtil.Oversize(_other.PostingsSize, 1)]; } Array.Copy(_other.Postings, 0, Postings, 0, _other.PostingsSize); } else { WrappedTermState.CopyFrom(_other.WrappedTermState); } } public override string ToString() { if (PostingsSize == -1) return "PulsingTermState: not inlined: wrapped=" + WrappedTermState; return "PulsingTermState: inlined size=" + PostingsSize + " " + base.ToString(); } } public override BlockTermState NewTermState() { return new PulsingTermState {WrappedTermState = _wrappedPostingsReader.NewTermState()}; } public override void DecodeTerm(long[] empty, DataInput input, FieldInfo fieldInfo, BlockTermState termState, bool absolute) { var termState2 = (PulsingTermState) termState; if (Debugging.AssertsEnabled) Debugging.Assert(empty.Length == 0); termState2.Absolute = termState2.Absolute || absolute; // if we have positions, its total TF, otherwise its computed based on docFreq. // TODO Double check this is right.. long count = fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 ? termState2.TotalTermFreq : termState2.DocFreq; if (count <= _maxPositions) { // Inlined into terms dict -- just read the byte[] blob in, // but don't decode it now (we only decode when a DocsEnum // or D&PEnum is pulled): termState2.PostingsSize = input.ReadVInt32(); if (termState2.Postings == null || termState2.Postings.Length < termState2.PostingsSize) { termState2.Postings = new byte[ArrayUtil.Oversize(termState2.PostingsSize, 1)]; } // TODO: sort of silly to copy from one big byte[] // (the blob holding all inlined terms' blobs for // current term block) into another byte[] (just the // blob for this term)... input.ReadBytes(termState2.Postings, 0, termState2.PostingsSize); //System.out.println(" inlined bytes=" + termState.postingsSize); termState2.Absolute = termState2.Absolute || absolute; } else { //System.out.println(" not inlined"); var longsSize = _fields == null ? 0 : _fields[fieldInfo.Number]; if (termState2.Int64s == null) { termState2.Int64s = new long[longsSize]; } for (var i = 0; i < longsSize; i++) { termState2.Int64s[i] = input.ReadVInt64(); } termState2.PostingsSize = -1; termState2.WrappedTermState.DocFreq = termState2.DocFreq; termState2.WrappedTermState.TotalTermFreq = termState2.TotalTermFreq; _wrappedPostingsReader.DecodeTerm(termState2.Int64s, input, fieldInfo, termState2.WrappedTermState, termState2.Absolute); termState2.Absolute = false; } } public override DocsEnum Docs(FieldInfo field, BlockTermState termState, IBits liveDocs, DocsEnum reuse, DocsFlags flags) { var termState2 = (PulsingTermState) termState; if (termState2.PostingsSize != -1) { PulsingDocsEnum postings; if (reuse is PulsingDocsEnum) { postings = (PulsingDocsEnum) reuse; if (!postings.CanReuse(field)) { postings = new PulsingDocsEnum(field); } } else { // the 'reuse' is actually the wrapped enum var previous = (PulsingDocsEnum) GetOther(reuse); if (previous != null && previous.CanReuse(field)) { postings = previous; } else { postings = new PulsingDocsEnum(field); } } if (reuse != postings) SetOther(postings, reuse); // postings.other = reuse return postings.Reset(liveDocs, termState2); } if (!(reuse is PulsingDocsEnum)) return _wrappedPostingsReader.Docs(field, termState2.WrappedTermState, liveDocs, reuse, flags); var wrapped = _wrappedPostingsReader.Docs(field, termState2.WrappedTermState, liveDocs, GetOther(reuse), flags); SetOther(wrapped, reuse); // wrapped.other = reuse return wrapped; } public override DocsAndPositionsEnum DocsAndPositions(FieldInfo field, BlockTermState termState, IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { var termState2 = (PulsingTermState) termState; if (termState2.PostingsSize != -1) { PulsingDocsAndPositionsEnum postings; if (reuse is PulsingDocsAndPositionsEnum) { postings = (PulsingDocsAndPositionsEnum) reuse; if (!postings.CanReuse(field)) { postings = new PulsingDocsAndPositionsEnum(field); } } else { // the 'reuse' is actually the wrapped enum var previous = (PulsingDocsAndPositionsEnum) GetOther(reuse); if (previous != null && previous.CanReuse(field)) { postings = previous; } else { postings = new PulsingDocsAndPositionsEnum(field); } } if (reuse != postings) { SetOther(postings, reuse); // postings.other = reuse } return postings.Reset(liveDocs, termState2); } if (!(reuse is PulsingDocsAndPositionsEnum)) return _wrappedPostingsReader.DocsAndPositions(field, termState2.WrappedTermState, liveDocs, reuse, flags); var wrapped = _wrappedPostingsReader.DocsAndPositions(field, termState2.WrappedTermState, liveDocs, (DocsAndPositionsEnum) GetOther(reuse), flags); SetOther(wrapped, reuse); // wrapped.other = reuse return wrapped; } private class PulsingDocsEnum : DocsEnum { private byte[] _postingsBytes; private readonly ByteArrayDataInput _postings = new ByteArrayDataInput(); private readonly IndexOptions _indexOptions; private readonly bool _storePayloads; private readonly bool _storeOffsets; private IBits _liveDocs; private int _docId = -1; private int _accum; private int _freq; private int _payloadLength; private int _cost; public PulsingDocsEnum(FieldInfo fieldInfo) { _indexOptions = fieldInfo.IndexOptions; _storePayloads = fieldInfo.HasPayloads; _storeOffsets = _indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; } public virtual PulsingDocsEnum Reset(IBits liveDocs, PulsingTermState termState) { if (Debugging.AssertsEnabled) Debugging.Assert(termState.PostingsSize != -1); // Must make a copy of termState's byte[] so that if // app does TermsEnum.next(), this DocsEnum is not affected if (_postingsBytes == null) { _postingsBytes = new byte[termState.PostingsSize]; } else if (_postingsBytes.Length < termState.PostingsSize) { _postingsBytes = ArrayUtil.Grow(_postingsBytes, termState.PostingsSize); } System.Array.Copy(termState.Postings, 0, _postingsBytes, 0, termState.PostingsSize); _postings.Reset(_postingsBytes, 0, termState.PostingsSize); _docId = -1; _accum = 0; _freq = 1; _cost = termState.DocFreq; _payloadLength = 0; this._liveDocs = liveDocs; return this; } internal bool CanReuse(FieldInfo fieldInfo) { return _indexOptions == fieldInfo.IndexOptions && _storePayloads == fieldInfo.HasPayloads; } public override int NextDoc() { while (true) { if (_postings.Eof) return _docId = NO_MORE_DOCS; var code = _postings.ReadVInt32(); if (_indexOptions == IndexOptions.DOCS_ONLY) { _accum += code; } else { _accum += (int)((uint)code >> 1); ; // shift off low bit _freq = (code & 1) != 0 ? 1 : _postings.ReadVInt32(); if (_indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) { // Skip positions if (_storePayloads) { for (var pos = 0; pos < _freq; pos++) { var posCode = _postings.ReadVInt32(); if ((posCode & 1) != 0) { _payloadLength = _postings.ReadVInt32(); } if (_storeOffsets && (_postings.ReadVInt32() & 1) != 0) { // new offset length _postings.ReadVInt32(); } if (_payloadLength != 0) { _postings.SkipBytes(_payloadLength); } } } else { for (var pos = 0; pos < _freq; pos++) { // TODO: skipVInt _postings.ReadVInt32(); if (_storeOffsets && (_postings.ReadVInt32() & 1) != 0) { // new offset length _postings.ReadVInt32(); } } } } } if (_liveDocs == null || _liveDocs.Get(_accum)) return (_docId = _accum); } } public override int Freq => _freq; public override int DocID => _docId; public override int Advance(int target) { return _docId = SlowAdvance(target); } public override long GetCost() { return _cost; } } private class PulsingDocsAndPositionsEnum : DocsAndPositionsEnum { private byte[] _postingsBytes; private readonly ByteArrayDataInput _postings = new ByteArrayDataInput(); private readonly bool _storePayloads; private readonly bool _storeOffsets; // note: we could actually reuse across different options, if we passed this to reset() // and re-init'ed storeOffsets accordingly (made it non-final) private readonly IndexOptions _indexOptions; private IBits _liveDocs; private int _docId = -1; private int _accum; private int _freq; private int _posPending; private int _position; private int _payloadLength; private BytesRef _payload; private int _startOffset; private int _offsetLength; private bool _payloadRetrieved; private int _cost; public PulsingDocsAndPositionsEnum(FieldInfo fieldInfo) { _indexOptions = fieldInfo.IndexOptions; _storePayloads = fieldInfo.HasPayloads; _storeOffsets = _indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; } internal bool CanReuse(FieldInfo fieldInfo) { return _indexOptions == fieldInfo.IndexOptions && _storePayloads == fieldInfo.HasPayloads; } public virtual PulsingDocsAndPositionsEnum Reset(IBits liveDocs, PulsingTermState termState) { if (Debugging.AssertsEnabled) Debugging.Assert(termState.PostingsSize != -1); if (_postingsBytes == null) { _postingsBytes = new byte[termState.PostingsSize]; } else if (_postingsBytes.Length < termState.PostingsSize) { _postingsBytes = ArrayUtil.Grow(_postingsBytes, termState.PostingsSize); } Array.Copy(termState.Postings, 0, _postingsBytes, 0, termState.PostingsSize); _postings.Reset(_postingsBytes, 0, termState.PostingsSize); this._liveDocs = liveDocs; _payloadLength = 0; _posPending = 0; _docId = -1; _accum = 0; _cost = termState.DocFreq; _startOffset = _storeOffsets ? 0 : -1; // always return -1 if no offsets are stored _offsetLength = 0; //System.out.println("PR d&p reset storesPayloads=" + storePayloads + " bytes=" + bytes.length + " this=" + this); return this; } public override int NextDoc() { while (true) { SkipPositions(); if (_postings.Eof) { return _docId = NO_MORE_DOCS; } var code = _postings.ReadVInt32(); _accum += (int)((uint)code >> 1); // shift off low bit _freq = (code & 1) != 0 ? 1 : _postings.ReadVInt32(); _posPending = _freq; _startOffset = _storeOffsets ? 0 : -1; // always return -1 if no offsets are stored if (_liveDocs != null && !_liveDocs.Get(_accum)) continue; _position = 0; return (_docId = _accum); } } public override int Freq => _freq; public override int DocID => _docId; public override int Advance(int target) { return _docId = SlowAdvance(target); } public override int NextPosition() { if (Debugging.AssertsEnabled) Debugging.Assert(_posPending > 0); _posPending--; if (_storePayloads) { if (!_payloadRetrieved) { _postings.SkipBytes(_payloadLength); } int code = _postings.ReadVInt32(); if ((code & 1) != 0) { _payloadLength = _postings.ReadVInt32(); } _position += (int)((uint)code >> 1); _payloadRetrieved = false; } else { _position += _postings.ReadVInt32(); } if (_storeOffsets) { int offsetCode = _postings.ReadVInt32(); if ((offsetCode & 1) != 0) { // new offset length _offsetLength = _postings.ReadVInt32(); } _startOffset += (int)((uint)offsetCode >> 1); } return _position; } public override int StartOffset => _startOffset; public override int EndOffset => _startOffset + _offsetLength; private void SkipPositions() { while (_posPending != 0) { NextPosition(); } if (_storePayloads && !_payloadRetrieved) { _postings.SkipBytes(_payloadLength); _payloadRetrieved = true; } } public override BytesRef GetPayload() { if (_payloadRetrieved) return _payload; if (_storePayloads && _payloadLength > 0) { _payloadRetrieved = true; if (_payload == null) { _payload = new BytesRef(_payloadLength); } else { _payload.Grow(_payloadLength); } _postings.ReadBytes(_payload.Bytes, 0, _payloadLength); _payload.Length = _payloadLength; return _payload; } return null; } public override long GetCost() { return _cost; } } protected override void Dispose(bool disposing) { if (disposing) { _wrappedPostingsReader.Dispose(); } } /// <summary> /// For a docsenum, gets the 'other' reused enum. /// Example: Pulsing(Standard). /// When doing a term range query you are switching back and forth /// between Pulsing and Standard. /// <para/> /// The way the reuse works is that Pulsing.other = Standard and /// Standard.other = Pulsing. /// </summary> private DocsEnum GetOther(DocsEnum de) { if (de == null) return null; var atts = de.Attributes; DocsEnum result; atts.AddAttribute<IPulsingEnumAttribute>().Enums.TryGetValue(this, out result); return result; } /// <summary> /// For a docsenum, sets the 'other' reused enum. /// see <see cref="GetOther(DocsEnum)"/> for an example. /// </summary> private DocsEnum SetOther(DocsEnum de, DocsEnum other) { var atts = de.Attributes; return atts.AddAttribute<IPulsingEnumAttribute>().Enums[this] = other; } ///<summary> /// A per-docsenum attribute that stores additional reuse information /// so that pulsing enums can keep a reference to their wrapped enums, /// and vice versa. this way we can always reuse. /// <para/> /// @lucene.internal /// </summary> public interface IPulsingEnumAttribute : IAttribute { IDictionary<PulsingPostingsReader, DocsEnum> Enums { get; } } /// <summary> /// Implementation of <see cref="PulsingEnumAttribute"/> for reuse of /// wrapped postings readers underneath pulsing. /// <para/> /// @lucene.internal /// </summary> public sealed class PulsingEnumAttribute : Util.Attribute, IPulsingEnumAttribute { // we could store 'other', but what if someone 'chained' multiple postings readers, // this could cause problems? // TODO: we should consider nuking this map and just making it so if you do this, // you don't reuse? and maybe pulsingPostingsReader should throw an exc if it wraps // another pulsing, because this is just stupid and wasteful. // we still have to be careful in case someone does Pulsing(Stomping(Pulsing(... private readonly IDictionary<PulsingPostingsReader, DocsEnum> _enums = new JCG.Dictionary<PulsingPostingsReader, DocsEnum>(IdentityEqualityComparer<PulsingPostingsReader>.Default); public IDictionary<PulsingPostingsReader, DocsEnum> Enums => _enums; public override void Clear() { // our state is per-docsenum, so this makes no sense. // its best not to clear, in case a wrapped enum has a per-doc attribute or something // and is calling clearAttributes(), so they don't nuke the reuse information! } public override void CopyTo(Util.IAttribute target) { // this makes no sense for us, because our state is per-docsenum. // we don't want to copy any stuff over to another docsenum ever! } } public override long RamBytesUsed() { return ((_wrappedPostingsReader != null) ? _wrappedPostingsReader.RamBytesUsed() : 0); } public override void CheckIntegrity() { _wrappedPostingsReader.CheckIntegrity(); } } }
/**************************************************************************** Tilde Copyright (c) 2008 Tantalus Media Pty Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections; using System.Diagnostics; using System.Windows.Forms; namespace Tilde.Framework.View { public class PersistWindowComponent : System.ComponentModel.Component { #region Declarations // event info that allows form to persist extra window state data public delegate void WindowStateDelegate(object sender, WindowStateInfo WindowInfo); public event WindowStateDelegate LoadStateEvent; public event WindowStateDelegate SaveStateEvent; private Form mParentForm; private WindowStateInfo mWindowInfo = new WindowStateInfo(); private PersistMethods mPersistMethod = PersistMethods.Registry; private string mRegistryPath = ""; private string mRegistryKey = ""; public enum PersistMethods { Registry, Custom } private System.ComponentModel.Container components = null; #endregion #region Public Properties [DefaultValue(PersistMethods.Registry)] [Description("Method of persisting window state information."), Category("Persist Configuration")] public PersistMethods PersistMethod { get { return this.mPersistMethod; } set { this.mPersistMethod = value; } } [DefaultValue("")] [Description("Key for saving info to registry."), Category("Persist Configuration")] public string RegistryKey { get { return this.mRegistryKey; } set { this.mRegistryKey=value; } } [Browsable(false)] public Form Form { get { if (this.mParentForm == null) { if (this.Site.DesignMode) { IDesignerHost dh = (IDesignerHost)this.GetService(typeof(IDesignerHost)); if (dh != null) { Object obj = dh.RootComponent; if (obj != null) { this.mParentForm = (Form)obj; } } } } return this.mParentForm; } set { if (this.mParentForm != null) return; if (value != null) { this.mParentForm = value; // subscribe to parent form's events mParentForm.Closing += new System.ComponentModel.CancelEventHandler(OnClosing); mParentForm.Resize += new System.EventHandler(OnResize); mParentForm.Move += new System.EventHandler(OnMove); mParentForm.Load += new System.EventHandler(OnLoad); // get initial width and height in case form is never resized mWindowInfo.Width = mParentForm.Width; mWindowInfo.Height = mParentForm.Height; mRegistryPath = "Software\\" + this.mParentForm.CompanyName + "\\" + System.Reflection.Assembly.GetEntryAssembly().GetName().Name + "\\WindowPositions"; } } } #endregion #region Public Methods public void SetWindowInfo(WindowStateInfo WindowInfo) { this.mWindowInfo = WindowInfo; mParentForm.Location = new System.Drawing.Point(mWindowInfo.Left, mWindowInfo.Top); mParentForm.Size = new System.Drawing.Size(mWindowInfo.Width, mWindowInfo.Height); mParentForm.WindowState = mWindowInfo.WindowState; } #endregion #region Private Form Event Handlers private void OnResize(object sender, System.EventArgs e) { // save width and height if(mParentForm.WindowState == FormWindowState.Normal) { mWindowInfo.Width = mParentForm.Width; mWindowInfo.Height = mParentForm.Height; } } private void OnMove(object sender, System.EventArgs e) { // save position if(mParentForm.WindowState == FormWindowState.Normal) { mWindowInfo.Left = mParentForm.Left; mWindowInfo.Top= mParentForm.Top; } // save state mWindowInfo.WindowState = mParentForm.WindowState; } private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e) { // check if we are allowed to save the state as minimized (not normally) if(! mWindowInfo.AllowSaveMinimised) { if(mWindowInfo.WindowState == FormWindowState.Minimized) mWindowInfo.WindowState= FormWindowState.Normal; } switch (this.mPersistMethod) { case PersistMethods.Registry: if (this.mRegistryPath == "" || this.mRegistryKey == "") throw new Exception("Registry File path is empty"); this.SaveInfoToRegistry(); break; case PersistMethods.Custom: // fire SaveState event if(SaveStateEvent != null) SaveStateEvent(this, this.mWindowInfo); break; } } private void OnLoad(object sender, System.EventArgs e) { switch (this.mPersistMethod) { case PersistMethods.Registry: if (this.mRegistryPath == "" || this.mRegistryKey == "") throw new Exception("Registry File path is empty"); this.LoadInfoFromRegistry(); break; case PersistMethods.Custom: // fire LoadState event if(LoadStateEvent != null) LoadStateEvent(this, this.mWindowInfo); break; } } #endregion #region Private Support Functions private void LoadInfoFromRegistry() { // attempt to read state from registry Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(this.mRegistryPath); if(key != null) { string data = (string)key.GetValue(mRegistryKey); if (data != null) { string[] windowpos = data.Split(new char[] { ',' }); FormWindowState windowState = (FormWindowState)Enum.Parse(typeof(FormWindowState), windowpos[0]); int left = (int)Decimal.Parse(windowpos[1]); int top = (int)Decimal.Parse(windowpos[2]); int width = (int)Decimal.Parse(windowpos[3]); int height = (int)Decimal.Parse(windowpos[4]); mParentForm.Location = new System.Drawing.Point(left, top); mParentForm.Size = new System.Drawing.Size(width, height); mParentForm.WindowState = windowState; this.mWindowInfo.Left = mParentForm.Left; this.mWindowInfo.Top = mParentForm.Top; this.mWindowInfo.Height = mParentForm.Height; this.mWindowInfo.Width = mParentForm.Width; this.mWindowInfo.WindowState = mParentForm.WindowState; } } } private void SaveInfoToRegistry() { // save position, size and state Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(this.mRegistryPath); key.SetValue(mRegistryKey, String.Join(",", new String[] { mWindowInfo.WindowState.ToString(), mWindowInfo.Left.ToString(), mWindowInfo.Top.ToString(), mWindowInfo.Width.ToString(), mWindowInfo.Height.ToString() })); } #endregion #region Creator public PersistWindowComponent(System.ComponentModel.IContainer container) { container.Add(this); InitializeComponent(); } public PersistWindowComponent() { InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion #endregion } #region WindowStateInfo public class WindowStateInfo { public Int32 Top; public Int32 Left; public Int32 Height; public Int32 Width; public FormWindowState WindowState; public bool AllowSaveMinimised = false; } #endregion }
using UnityEngine; namespace UnitySampleAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent(typeof (Camera))] [AddComponentMenu("Image Effects/Bloom (4.0, HDR, Lens Flares)")] public class Bloom : PostEffectsBase { public enum LensFlareStyle { Ghosting = 0, Anamorphic = 1, Combined = 2, } public enum TweakMode { Basic = 0, Complex = 1, } public enum HDRBloomMode { Auto = 0, On = 1, Off = 2, } public enum BloomScreenBlendMode { Screen = 0, Add = 1, } public enum BloomQuality { Cheap = 0, High = 1, } public TweakMode tweakMode = 0; public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add; public HDRBloomMode hdr = HDRBloomMode.Auto; private bool doHdr = false; public float sepBlurSpread = 2.5f; public BloomQuality quality = BloomQuality.High; public float bloomIntensity = 0.5f; public float bloomThreshhold = 0.5f; public Color bloomThreshholdColor = Color.white; public int bloomBlurIterations = 2; public int hollywoodFlareBlurIterations = 2; public float flareRotation = 0.0f; public LensFlareStyle lensflareMode = LensFlareStyle.Anamorphic; public float hollyStretchWidth = 2.5f; public float lensflareIntensity = 0.0f; public float lensflareThreshhold = 0.3f; public float lensFlareSaturation = 0.75f; public Color flareColorA = new Color(0.4f, 0.4f, 0.8f, 0.75f); public Color flareColorB = new Color(0.4f, 0.8f, 0.8f, 0.75f); public Color flareColorC = new Color(0.8f, 0.4f, 0.8f, 0.75f); public Color flareColorD = new Color(0.8f, 0.4f, 0.0f, 0.75f); public float blurWidth = 1.0f; public Texture2D lensFlareVignetteMask; public Shader lensFlareShader; private Material lensFlareMaterial; public Shader screenBlendShader; private Material screenBlend; public Shader blurAndFlaresShader; private Material blurAndFlaresMaterial; public Shader brightPassFilterShader; private Material brightPassFilterMaterial; protected override bool CheckResources() { CheckSupport(false); screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend); lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial); blurAndFlaresMaterial = CheckShaderAndCreateMaterial(blurAndFlaresShader, blurAndFlaresMaterial); brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial); if (!isSupported) ReportAutoDisable(); return isSupported; } private void OnRenderImage(RenderTexture source, RenderTexture destination) { if (CheckResources() == false) { Graphics.Blit(source, destination); return; } // screen blend is not supported when HDR is enabled (will cap values) doHdr = false; if (hdr == HDRBloomMode.Auto) doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr; else { doHdr = hdr == HDRBloomMode.On; } doHdr = doHdr && supportHDRTextures; BloomScreenBlendMode realBlendMode = screenBlendMode; if (doHdr) realBlendMode = BloomScreenBlendMode.Add; var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; RenderTexture halfRezColor = RenderTexture.GetTemporary(source.width/2, source.height/2, 0, rtFormat); RenderTexture quarterRezColor = RenderTexture.GetTemporary(source.width/4, source.height/4, 0, rtFormat); RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary(source.width/4, source.height/4, 0, rtFormat); RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary(source.width/4, source.height/4, 0, rtFormat); float widthOverHeight = (1.0f*source.width)/(1.0f*source.height); float oneOverBaseSize = 1.0f/512.0f; // downsample if (quality > BloomQuality.Cheap) { Graphics.Blit(source, halfRezColor, screenBlend, 2); Graphics.Blit(halfRezColor, secondQuarterRezColor, screenBlend, 2); Graphics.Blit(secondQuarterRezColor, quarterRezColor, screenBlend, 6); } else { Graphics.Blit(source, halfRezColor); Graphics.Blit(halfRezColor, quarterRezColor, screenBlend, 6); } // cut colors (threshholding) BrightFilter(bloomThreshhold*bloomThreshholdColor, quarterRezColor, secondQuarterRezColor); // blurring if (bloomBlurIterations < 1) bloomBlurIterations = 1; else if (bloomBlurIterations > 10) bloomBlurIterations = 10; for (int iter = 0; iter < bloomBlurIterations; iter++) { float spreadForPass = (1.0f + (iter*0.25f))*sepBlurSpread; blurAndFlaresMaterial.SetVector("_Offsets", new Vector4(0.0f, spreadForPass*oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, blurAndFlaresMaterial, 4); if (quality > BloomQuality.Cheap) { blurAndFlaresMaterial.SetVector("_Offsets", new Vector4((spreadForPass/widthOverHeight)*oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, blurAndFlaresMaterial, 4); if (iter == 0) Graphics.Blit(secondQuarterRezColor, quarterRezColor); else Graphics.Blit(secondQuarterRezColor, quarterRezColor, screenBlend, 10); } else { blurAndFlaresMaterial.SetVector("_Offsets", new Vector4((spreadForPass/widthOverHeight)*oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, blurAndFlaresMaterial, 4); } } if (quality > BloomQuality.Cheap) Graphics.Blit(quarterRezColor, secondQuarterRezColor, screenBlend, 6); // lens flares: ghosting, anamorphic or both (ghosted anamorphic flares) if (lensflareIntensity > Mathf.Epsilon) { if (lensflareMode == 0) { BrightFilter(lensflareThreshhold, secondQuarterRezColor, thirdQuarterRezColor); if (quality > BloomQuality.Cheap) { // smooth a little blurAndFlaresMaterial.SetVector("_Offsets", new Vector4(0.0f, (1.5f)/(1.0f*quarterRezColor.height), 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, quarterRezColor, blurAndFlaresMaterial, 4); blurAndFlaresMaterial.SetVector("_Offsets", new Vector4((1.5f)/(1.0f*quarterRezColor.width), 0.0f, 0.0f, 0.0f)); Graphics.Blit(quarterRezColor, thirdQuarterRezColor, blurAndFlaresMaterial, 4); } // no ugly edges! Vignette(0.975f, thirdQuarterRezColor, thirdQuarterRezColor); BlendFlares(thirdQuarterRezColor, secondQuarterRezColor); } else { //Vignette (0.975f, thirdQuarterRezColor, thirdQuarterRezColor); //DrawBorder(thirdQuarterRezColor, screenBlend, 8); float flareXRot = 1.0f*Mathf.Cos(flareRotation); float flareyRot = 1.0f*Mathf.Sin(flareRotation); float stretchWidth = (hollyStretchWidth*1.0f/widthOverHeight)*oneOverBaseSize; blurAndFlaresMaterial.SetVector("_Offsets", new Vector4(flareXRot, flareyRot, 0.0f, 0.0f)); blurAndFlaresMaterial.SetVector("_Threshhold", new Vector4(lensflareThreshhold, 1.0f, 0.0f, 0.0f)); blurAndFlaresMaterial.SetVector("_TintColor", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a)*flareColorA.a*lensflareIntensity); blurAndFlaresMaterial.SetFloat("_Saturation", lensFlareSaturation); Graphics.Blit(thirdQuarterRezColor, quarterRezColor, blurAndFlaresMaterial, 2); Graphics.Blit(quarterRezColor, thirdQuarterRezColor, blurAndFlaresMaterial, 3); blurAndFlaresMaterial.SetVector("_Offsets", new Vector4(flareXRot*stretchWidth, flareyRot*stretchWidth, 0.0f, 0.0f)); blurAndFlaresMaterial.SetFloat("_StretchWidth", hollyStretchWidth); Graphics.Blit(thirdQuarterRezColor, quarterRezColor, blurAndFlaresMaterial, 1); blurAndFlaresMaterial.SetFloat("_StretchWidth", hollyStretchWidth*2.0f); Graphics.Blit(quarterRezColor, thirdQuarterRezColor, blurAndFlaresMaterial, 1); blurAndFlaresMaterial.SetFloat("_StretchWidth", hollyStretchWidth*4.0f); Graphics.Blit(thirdQuarterRezColor, quarterRezColor, blurAndFlaresMaterial, 1); for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++) { stretchWidth = (hollyStretchWidth*2.0f/widthOverHeight)*oneOverBaseSize; blurAndFlaresMaterial.SetVector("_Offsets", new Vector4(stretchWidth*flareXRot, stretchWidth*flareyRot, 0.0f, 0.0f)); Graphics.Blit(quarterRezColor, thirdQuarterRezColor, blurAndFlaresMaterial, 4); blurAndFlaresMaterial.SetVector("_Offsets", new Vector4(stretchWidth*flareXRot, stretchWidth*flareyRot, 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, quarterRezColor, blurAndFlaresMaterial, 4); } if (lensflareMode == (LensFlareStyle) 1) AddTo(1.0f, quarterRezColor, secondQuarterRezColor); else { // "combined" lens flares Vignette(1.0f, quarterRezColor, thirdQuarterRezColor); BlendFlares(thirdQuarterRezColor, quarterRezColor); AddTo(1.0f, quarterRezColor, secondQuarterRezColor); } } } int blendPass = (int) realBlendMode; //if(Mathf.Abs(chromaticBloom) < Mathf.Epsilon) // blendPass += 4; screenBlend.SetFloat("_Intensity", bloomIntensity); screenBlend.SetTexture("_ColorBuffer", source); if (quality > BloomQuality.Cheap) { Graphics.Blit(secondQuarterRezColor, halfRezColor); Graphics.Blit(halfRezColor, destination, screenBlend, blendPass); } else Graphics.Blit(secondQuarterRezColor, destination, screenBlend, blendPass); RenderTexture.ReleaseTemporary(halfRezColor); RenderTexture.ReleaseTemporary(quarterRezColor); RenderTexture.ReleaseTemporary(secondQuarterRezColor); RenderTexture.ReleaseTemporary(thirdQuarterRezColor); } private void AddTo(float intensity_, RenderTexture from, RenderTexture to) { screenBlend.SetFloat("_Intensity", intensity_); Graphics.Blit(from, to, screenBlend, 9); } private void BlendFlares(RenderTexture from, RenderTexture to) { lensFlareMaterial.SetVector("colorA", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a)* lensflareIntensity); lensFlareMaterial.SetVector("colorB", new Vector4(flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a)* lensflareIntensity); lensFlareMaterial.SetVector("colorC", new Vector4(flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a)* lensflareIntensity); lensFlareMaterial.SetVector("colorD", new Vector4(flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a)* lensflareIntensity); Graphics.Blit(from, to, lensFlareMaterial); } private void BrightFilter(float thresh, RenderTexture from, RenderTexture to) { brightPassFilterMaterial.SetVector("_Threshhold", new Vector4(thresh, thresh, thresh, thresh)); Graphics.Blit(from, to, brightPassFilterMaterial, 0); } private void BrightFilter(Color threshColor, RenderTexture from, RenderTexture to) { brightPassFilterMaterial.SetVector("_Threshhold", threshColor); Graphics.Blit(from, to, brightPassFilterMaterial, 1); } private void Vignette(float amount, RenderTexture from, RenderTexture to) { if (lensFlareVignetteMask) { screenBlend.SetTexture("_ColorBuffer", lensFlareVignetteMask); Graphics.Blit(from == to ? null : from, to, screenBlend, from == to ? 7 : 3); } else if (from != to) Graphics.Blit(from, to); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using Azure; using DataLake; using Management; using Azure; using Management; using DataLake; using Models; using Newtonsoft.Json; using Rest; using Rest.Azure; using Rest.Serialization; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Creates an Azure Data Lake Analytics job client. /// </summary> public partial class DataLakeAnalyticsJobManagementClient : ServiceClient<DataLakeAnalyticsJobManagementClient>, IDataLakeAnalyticsJobManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> internal string BaseUri {get; set;} /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets the DNS suffix used as the base for all Azure Data Lake Analytics Job /// service requests. /// </summary> public string AdlaJobDnsSuffix { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IJobOperations. /// </summary> public virtual IJobOperations Job { get; private set; } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsJobManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataLakeAnalyticsJobManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsJobManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataLakeAnalyticsJobManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsJobManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeAnalyticsJobManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataLakeAnalyticsJobManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeAnalyticsJobManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Job = new JobOperations(this); BaseUri = "https://{accountName}.{adlaJobDnsSuffix}"; ApiVersion = "2016-11-01"; AdlaJobDnsSuffix = "azuredatalakeanalytics.net"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<JobProperties>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<JobProperties>("type")); CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
/* * Velcro Physics: * Copyright (c) 2017 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System.Diagnostics; using Microsoft.Xna.Framework; using VelcroPhysics.Dynamics.Solver; using VelcroPhysics.Shared; using VelcroPhysics.Utilities; namespace VelcroPhysics.Dynamics.Joints { /// <summary> /// A motor joint is used to control the relative motion /// between two bodies. A typical usage is to control the movement /// of a dynamic body with respect to the ground. /// </summary> public class MotorJoint : Joint { private float _angularError; private float _angularImpulse; private float _angularMass; private float _angularOffset; // Solver temp private int _indexA; private int _indexB; private float _invIA; private float _invIB; private float _invMassA; private float _invMassB; private Vector2 _linearError; private Vector2 _linearImpulse; private Mat22 _linearMass; // Solver shared private Vector2 _linearOffset; private Vector2 _localCenterA; private Vector2 _localCenterB; private float _maxForce; private float _maxTorque; private Vector2 _rA; private Vector2 _rB; internal MotorJoint() { JointType = JointType.Motor; } /// <summary> /// Constructor for MotorJoint. /// </summary> /// <param name="bodyA">The first body</param> /// <param name="bodyB">The second body</param> /// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param> public MotorJoint(Body bodyA, Body bodyB, bool useWorldCoordinates = false) : base(bodyA, bodyB) { JointType = JointType.Motor; Vector2 xB = BodyB.Position; if (useWorldCoordinates) _linearOffset = BodyA.GetLocalPoint(xB); else _linearOffset = xB; //Defaults //_angularOffset = 0.0f; _maxForce = 1.0f; _maxTorque = 1.0f; CorrectionFactor = 0.3f; _angularOffset = BodyB.Rotation - BodyA.Rotation; } public override Vector2 WorldAnchorA { get { return BodyA.Position; } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } public override Vector2 WorldAnchorB { get { return BodyB.Position; } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } /// <summary> /// The maximum amount of force that can be applied to BodyA /// </summary> public float MaxForce { set { Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f); _maxForce = value; } get { return _maxForce; } } /// <summary> /// The maximum amount of torque that can be applied to BodyA /// </summary> public float MaxTorque { set { Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f); _maxTorque = value; } get { return _maxTorque; } } /// <summary> /// The linear (translation) offset. /// </summary> public Vector2 LinearOffset { set { if (_linearOffset.X != value.X || _linearOffset.Y != value.Y) { WakeBodies(); _linearOffset = value; } } get { return _linearOffset; } } /// <summary> /// Get or set the angular offset. /// </summary> public float AngularOffset { set { if (_angularOffset != value) { WakeBodies(); _angularOffset = value; } } get { return _angularOffset; } } //Velcro note: Used for serialization. internal float CorrectionFactor { get; set; } public override Vector2 GetReactionForce(float invDt) { return invDt * _linearImpulse; } public override float GetReactionTorque(float invDt) { return invDt * _angularImpulse; } internal override void InitVelocityConstraints(ref SolverData data) { _indexA = BodyA.IslandIndex; _indexB = BodyB.IslandIndex; _localCenterA = BodyA._sweep.LocalCenter; _localCenterB = BodyB._sweep.LocalCenter; _invMassA = BodyA._invMass; _invMassB = BodyB._invMass; _invIA = BodyA._invI; _invIB = BodyB._invI; Vector2 cA = data.Positions[_indexA].C; float aA = data.Positions[_indexA].A; Vector2 vA = data.Velocities[_indexA].V; float wA = data.Velocities[_indexA].W; Vector2 cB = data.Positions[_indexB].C; float aB = data.Positions[_indexB].A; Vector2 vB = data.Velocities[_indexB].V; float wB = data.Velocities[_indexB].W; Rot qA = new Rot(aA); Rot qB = new Rot(aB); // Compute the effective mass matrix. _rA = MathUtils.Mul(qA, -_localCenterA); _rB = MathUtils.Mul(qB, -_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; Mat22 K = new Mat22(); K.ex.X = mA + mB + iA * _rA.Y * _rA.Y + iB * _rB.Y * _rB.Y; K.ex.Y = -iA * _rA.X * _rA.Y - iB * _rB.X * _rB.Y; K.ey.X = K.ex.Y; K.ey.Y = mA + mB + iA * _rA.X * _rA.X + iB * _rB.X * _rB.X; _linearMass = K.Inverse; _angularMass = iA + iB; if (_angularMass > 0.0f) { _angularMass = 1.0f / _angularMass; } _linearError = cB + _rB - cA - _rA - MathUtils.Mul(qA, _linearOffset); _angularError = aB - aA - _angularOffset; if (Settings.EnableWarmstarting) { // Scale impulses to support a variable time step. _linearImpulse *= data.Step.dtRatio; _angularImpulse *= data.Step.dtRatio; Vector2 P = new Vector2(_linearImpulse.X, _linearImpulse.Y); vA -= mA * P; wA -= iA * (MathUtils.Cross(_rA, P) + _angularImpulse); vB += mB * P; wB += iB * (MathUtils.Cross(_rB, P) + _angularImpulse); } else { _linearImpulse = Vector2.Zero; _angularImpulse = 0.0f; } data.Velocities[_indexA].V = vA; data.Velocities[_indexA].W = wA; data.Velocities[_indexB].V = vB; data.Velocities[_indexB].W = wB; } internal override void SolveVelocityConstraints(ref SolverData data) { Vector2 vA = data.Velocities[_indexA].V; float wA = data.Velocities[_indexA].W; Vector2 vB = data.Velocities[_indexB].V; float wB = data.Velocities[_indexB].W; float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; float h = data.Step.dt; float inv_h = data.Step.inv_dt; // Solve angular friction { float Cdot = wB - wA + inv_h * CorrectionFactor * _angularError; float impulse = -_angularMass * Cdot; float oldImpulse = _angularImpulse; float maxImpulse = h * _maxTorque; _angularImpulse = MathUtils.Clamp(_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = _angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve linear friction { Vector2 Cdot = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA) + inv_h * CorrectionFactor * _linearError; Vector2 impulse = -MathUtils.Mul(ref _linearMass, ref Cdot); Vector2 oldImpulse = _linearImpulse; _linearImpulse += impulse; float maxImpulse = h * _maxForce; if (_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { _linearImpulse.Normalize(); _linearImpulse *= maxImpulse; } impulse = _linearImpulse - oldImpulse; vA -= mA * impulse; wA -= iA * MathUtils.Cross(_rA, impulse); vB += mB * impulse; wB += iB * MathUtils.Cross(_rB, impulse); } data.Velocities[_indexA].V = vA; data.Velocities[_indexA].W = wA; data.Velocities[_indexB].V = vB; data.Velocities[_indexB].W = wB; } internal override bool SolvePositionConstraints(ref SolverData data) { return true; } } }
// 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 sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>FeedMapping</c> resource.</summary> public sealed partial class FeedMappingName : gax::IResourceName, sys::IEquatable<FeedMappingName> { /// <summary>The possible contents of <see cref="FeedMappingName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c>. /// </summary> CustomerFeedFeedMapping = 1, } private static gax::PathTemplate s_customerFeedFeedMapping = new gax::PathTemplate("customers/{customer_id}/feedMappings/{feed_id_feed_mapping_id}"); /// <summary>Creates a <see cref="FeedMappingName"/> 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="FeedMappingName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static FeedMappingName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new FeedMappingName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="FeedMappingName"/> with the pattern /// <c>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedMappingId">The <c>FeedMapping</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="FeedMappingName"/> constructed from the provided ids.</returns> public static FeedMappingName FromCustomerFeedFeedMapping(string customerId, string feedId, string feedMappingId) => new FeedMappingName(ResourceNameType.CustomerFeedFeedMapping, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedMappingId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedMappingId, nameof(feedMappingId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedMappingName"/> with pattern /// <c>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedMappingId">The <c>FeedMapping</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedMappingName"/> with pattern /// <c>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c>. /// </returns> public static string Format(string customerId, string feedId, string feedMappingId) => FormatCustomerFeedFeedMapping(customerId, feedId, feedMappingId); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedMappingName"/> with pattern /// <c>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedMappingId">The <c>FeedMapping</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedMappingName"/> with pattern /// <c>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c>. /// </returns> public static string FormatCustomerFeedFeedMapping(string customerId, string feedId, string feedMappingId) => s_customerFeedFeedMapping.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedMappingId, nameof(feedMappingId)))}"); /// <summary>Parses the given resource name string into a new <see cref="FeedMappingName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="feedMappingName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="FeedMappingName"/> if successful.</returns> public static FeedMappingName Parse(string feedMappingName) => Parse(feedMappingName, false); /// <summary> /// Parses the given resource name string into a new <see cref="FeedMappingName"/> 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>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedMappingName">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="FeedMappingName"/> if successful.</returns> public static FeedMappingName Parse(string feedMappingName, bool allowUnparsed) => TryParse(feedMappingName, allowUnparsed, out FeedMappingName 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="FeedMappingName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="feedMappingName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeedMappingName"/>, 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 feedMappingName, out FeedMappingName result) => TryParse(feedMappingName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeedMappingName"/> 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>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedMappingName">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="FeedMappingName"/>, 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 feedMappingName, bool allowUnparsed, out FeedMappingName result) { gax::GaxPreconditions.CheckNotNull(feedMappingName, nameof(feedMappingName)); gax::TemplatedResourceName resourceName; if (s_customerFeedFeedMapping.TryParseName(feedMappingName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerFeedFeedMapping(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(feedMappingName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private FeedMappingName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedId = null, string feedMappingId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; FeedId = feedId; FeedMappingId = feedMappingId; } /// <summary> /// Constructs a new instance of a <see cref="FeedMappingName"/> class from the component parts of pattern /// <c>customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedMappingId">The <c>FeedMapping</c> ID. Must not be <c>null</c> or empty.</param> public FeedMappingName(string customerId, string feedId, string feedMappingId) : this(ResourceNameType.CustomerFeedFeedMapping, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedMappingId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedMappingId, nameof(feedMappingId))) { } /// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedId { get; } /// <summary> /// The <c>FeedMapping</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedMappingId { 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.CustomerFeedFeedMapping: return s_customerFeedFeedMapping.Expand(CustomerId, $"{FeedId}~{FeedMappingId}"); 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 FeedMappingName); /// <inheritdoc/> public bool Equals(FeedMappingName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(FeedMappingName a, FeedMappingName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(FeedMappingName a, FeedMappingName b) => !(a == b); } public partial class FeedMapping { /// <summary> /// <see cref="FeedMappingName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal FeedMappingName ResourceNameAsFeedMappingName { get => string.IsNullOrEmpty(ResourceName) ? null : FeedMappingName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary> internal FeedName FeedAsFeedName { get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true); set => Feed = value?.ToString() ?? ""; } } }
using System.Diagnostics; using Moritz.Globals; using Moritz.Xml; using System.Collections.Generic; namespace Moritz.Spec { /// <summary> /// TrkOptions define how trks react to incoming performed information. /// The following SVG elements (their corresponding Moritz classes) can have a trkOptions attribute: /// inputChord (InputChordDef) /// inputNote (InputNoteDef) /// noteOn or noteOff (NoteTrigger) /// seq (Seq) /// trkRef (TrkRef) /// The Assistant Performer uses these values as follows: /// 1. A TrkOptions element attached to an inputChord persists to the following inputChords until a /// further inputChord.trkOptions element is encountered. /// 2. The settings then cascade (individually) according to the above hierarchy. /// /// The default options are: /// velocity="inherit" -- not written to scores. Means "keep the current setting" /// pedal="inherit" -- not written to scores. Means "keep the current setting" /// speed=-1 -- (N.B. minus 1) not written to scores. Means "keep the current setting" /// trkOff="inherit" -- not written to scores. Means "keep the current setting" /// To turn an option off at some point in a score, use the enum "disabled" setting, or set the speed to 1. /// The Assistant Performer's default settings are: /// velocity="undefined" -- input midi noteOn velocities are ignored (velocities are performed as written in the score.) /// pedal="undefined" -- noteOffs in the trk are performed as written in the score /// speed=1 -- performed durations are the msDurations written in the score. /// trkOff="undefined" -- performed noteOff messages have no affect on the trk (trks play to completion, as written in the score). /// /// See also: https://james-ingram-act-two.de/open-source/svgScoreExtensions.html /// </summary> public sealed class TrkOptions { public TrkOptions(TrkOption trkOption) { AddList(new List<TrkOption>() { trkOption }); } public TrkOptions(List<TrkOption> optList) { AddList(optList); } public void WriteSVG(SvgWriter w, bool writeScoreNamespace) { if(writeScoreNamespace) { w.WriteStartElement("score", "trkOptions", null); } else { w.WriteStartElement("trkOptions"); } if(_velocityOption != VelocityOption.inherit) { w.WriteAttributeString("velocity", _velocityOption.ToString()); if(_velocityOption != VelocityOption.undefined) { if(_minimumVelocity == null || _minimumVelocity < 1 || _minimumVelocity > 127) { Debug.Assert(false, "If the VelocityOption is being used, then\n" + "MinimumVelocity must be set to a value in range [1..127]"); } w.WriteAttributeString("minVelocity", _minimumVelocity.ToString()); } } if(PedalOption != PedalOption.inherit) { w.WriteAttributeString("pedal", PedalOption.ToString()); } if(SpeedOption > 0) { w.WriteAttributeString("speed", SpeedOption.ToString(M.En_USNumberFormat)); } if(TrkOffOption != TrkOffOption.inherit) { w.WriteAttributeString("trkOff", TrkOffOption.ToString()); } w.WriteEndElement(); // score:trkOptions } public void AddList(List<TrkOption> optList) { foreach(TrkOption opt in optList) { if(opt is PedalControl pto) { Add(pto); } if(opt is SpeedControl sc) { Add(sc); } if(opt is TrkOffControl toto) { Add(toto); } if(opt is VelocityTrkOption vto) { Add(vto); } } } public void Add(PedalControl pedalTrkOption) { _pedalOption = pedalTrkOption.PedalOption; } public void Add(SpeedControl speedControl) { _speedOption = speedControl.SpeedFactor; } public void Add(TrkOffControl trkOffTrkOption) { _trkOffOption = trkOffTrkOption.TrkOffOption; } public void Add(VelocityTrkOption velocityTrkOption) { _velocityOption = velocityTrkOption.VelocityOption; _minimumVelocity = velocityTrkOption.MinimumVelocity; } /* * These default values are not written to score files. */ public PedalOption PedalOption { get { return _pedalOption; } } private PedalOption _pedalOption = PedalOption.inherit; public float SpeedOption { get { return _speedOption; } } private float _speedOption = -1; public TrkOffOption TrkOffOption { get { return _trkOffOption; } } private TrkOffOption _trkOffOption = TrkOffOption.inherit; public VelocityOption VelocityOption { get { return _velocityOption; } } private VelocityOption _velocityOption = VelocityOption.inherit; public byte? MinimumVelocity { get { return _minimumVelocity; } } private byte? _minimumVelocity = null; // must be set if a velocity option is being used } public class TrkOption { protected TrkOption() { } } public enum PedalOption { inherit, undefined, // the trk will play as written in the score holdLast, // remove noteOffs from trk's last moment that contains any, and don't send allNotesOff holdAll, // remove all noteOff messages from the trk, and don't send allNotesOff holdAllStop // like holdAll, but sends AllNotesOff when the trk stops (or is stopped) }; public class PedalControl: TrkOption { public PedalControl(PedalOption pedalOption) { _pedalOption = pedalOption; } public PedalOption PedalOption {get{return _pedalOption;}} private readonly PedalOption _pedalOption; } public class SpeedControl:TrkOption { /// <param name="speedFactor">A value greater than zero. Greater values mean greater speed.</param> public SpeedControl(float speedFactor) { Debug.Assert(speedFactor > 0, "Error: speedFactor must be greater than zero."); _speedFactor = speedFactor; } public float SpeedFactor { get { return _speedFactor; } } private readonly float _speedFactor; } public enum TrkOffOption { inherit, undefined, // the trk will ignore an incoming noteOff event, and play to its end (as written in the score). stopChord, // stop when the current midiChord or midiRest completes stopNow, // stop immediately, even inside a midiChord fade // fade velocity to end of trk }; public class TrkOffControl : TrkOption { public TrkOffControl(TrkOffOption trkOffOption) { _trkOffOption = trkOffOption; } public TrkOffOption TrkOffOption { get { return _trkOffOption; } } private readonly TrkOffOption _trkOffOption; } public enum VelocityOption { inherit, undefined, // the velocity written in the score will be played. scaled, shared, overridden }; public class VelocityTrkOption :TrkOption { protected VelocityTrkOption(VelocityOption velocityOption, byte minVelocity) { Debug.Assert(minVelocity > 0 && minVelocity < 128); _minVelocity = minVelocity; _velocityOption = velocityOption; } public VelocityOption VelocityOption { get { return _velocityOption; } } private readonly VelocityOption _velocityOption; public byte MinimumVelocity { get { return _minVelocity; } } private readonly byte _minVelocity; } public class VelocityScaledControl : VelocityTrkOption { public VelocityScaledControl(byte minVelocity) : base(VelocityOption.scaled, minVelocity) { } } public class VelocitySharedControl : VelocityTrkOption { public VelocitySharedControl(byte minVelocity) : base(VelocityOption.shared, minVelocity) { } } public class VelocityOverriddenControl : VelocityTrkOption { public VelocityOverriddenControl(byte minVelocity) : base(VelocityOption.overridden, minVelocity) { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// SoftwareUpdateConfigurationRunsOperations operations. /// </summary> internal partial class SoftwareUpdateConfigurationRunsOperations : IServiceOperations<AutomationClient>, ISoftwareUpdateConfigurationRunsOperations { /// <summary> /// Initializes a new instance of the SoftwareUpdateConfigurationRunsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SoftwareUpdateConfigurationRunsOperations(AutomationClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutomationClient /// </summary> public AutomationClient Client { get; private set; } /// <summary> /// Get a single software update configuration Run by Id. /// <see href="http://aka.ms/azureautomationsdk/softwareupdateconfigurationrunoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within user's subscription. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SoftwareUpdateConfigurationRun>> GetByIdWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2017-05-15-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetById", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/softwareUpdateConfigurationRuns/{softwareUpdateConfigurationRunId}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(Client.SubscriptionId, Client.SerializationSettings).Trim('"'))); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AutomationAccountName, Client.SerializationSettings).Trim('"'))); _url = _url.Replace("{softwareUpdateConfigurationRunId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(Client.SoftwareUpdateConfigurationRunId, Client.SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.ClientRequestId != null) { if (_httpRequest.Headers.Contains("clientRequestId")) { _httpRequest.Headers.Remove("clientRequestId"); } _httpRequest.Headers.TryAddWithoutValidation("clientRequestId", Client.ClientRequestId); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 404) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SoftwareUpdateConfigurationRun>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SoftwareUpdateConfigurationRun>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return list of software update configuration runs /// <see href="http://aka.ms/azureautomationsdk/softwareupdateconfigurationoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within user's subscription. /// </param> /// <param name='skip'> /// number of entries you skip before returning results /// </param> /// <param name='top'> /// Maximum number of entries returned in the results collection /// </param> /// <param name='filter'> /// The filter to apply on the operation. You can use the following filters: /// 'properties/osType', 'properties/status', 'properties/startTime', and /// 'properties/softwareUpdateConfiguration/name' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SoftwareUpdateConfigurationRunListResult>> ListWithHttpMessagesAsync(string resourceGroupName, string skip = default(string), string top = default(string), string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2017-05-15-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("skip", skip); tracingParameters.Add("top", top); tracingParameters.Add("filter", filter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/softwareUpdateConfigurationRuns").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(Client.SubscriptionId, Client.SerializationSettings).Trim('"'))); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AutomationAccountName, Client.SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (skip != null) { _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(skip))); } if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(top))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.ClientRequestId != null) { if (_httpRequest.Headers.Contains("clientRequestId")) { _httpRequest.Headers.Remove("clientRequestId"); } _httpRequest.Headers.TryAddWithoutValidation("clientRequestId", Client.ClientRequestId); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 404) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SoftwareUpdateConfigurationRunListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SoftwareUpdateConfigurationRunListResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// 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.MirrorRecursiveTypes { 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> /// Some cool documentation. /// </summary> public partial class RecursiveTypesAPI : ServiceClient<RecursiveTypesAPI>, IRecursiveTypesAPI { /// <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 RecursiveTypesAPI class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public RecursiveTypesAPI(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the RecursiveTypesAPI 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 RecursiveTypesAPI(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the RecursiveTypesAPI 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 RecursiveTypesAPI(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the RecursiveTypesAPI 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 RecursiveTypesAPI(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("https://management.azure.com/"); 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> /// Products /// </summary> /// The Products endpoint returns information about the Uber products offered /// at a given location. The response includes the display name and other /// details about each product, and lists the products in the proper display /// order. /// <param name='subscriptionId'> /// Subscription Id. /// </param> /// <param name='resourceGroupName'> /// Resource Group Id. /// </param> /// <param name='apiVersion'> /// API Id. /// </param> /// <param name='body'> /// API body mody. /// </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> /// <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<Product>> PostWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, string apiVersion, Product body = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (apiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{apiVersion}", Uri.EscapeDataString(apiVersion)); // 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(body != null) { _requestContent = SafeJsonConvert.SerializeObject(body, 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_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<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Data.ProviderBase; using System.Diagnostics; using System.Globalization; namespace System.Data.Common { public class DataAdapter : Component, IDataAdapter { private static readonly object s_eventFillError = new object(); private bool _acceptChangesDuringUpdate = true; private bool _acceptChangesDuringUpdateAfterInsert = true; private bool _continueUpdateOnError = false; private bool _hasFillErrorHandler = false; private bool _returnProviderSpecificTypes = false; private bool _acceptChangesDuringFill = true; private LoadOption _fillLoadOption; private MissingMappingAction _missingMappingAction = System.Data.MissingMappingAction.Passthrough; private MissingSchemaAction _missingSchemaAction = System.Data.MissingSchemaAction.Add; private DataTableMappingCollection _tableMappings; private static int s_objectTypeCount; // Bid counter internal readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); #if DEBUG // if true, we are asserting that the caller has provided a select command // which should not return an empty result set private bool _debugHookNonEmptySelectCommand = false; #endif [Conditional("DEBUG")] private void AssertReaderHandleFieldCount(DataReaderContainer readerHandler) { #if DEBUG Debug.Assert(!_debugHookNonEmptySelectCommand || readerHandler.FieldCount > 0, "Scenario expects non-empty results but no fields reported by reader"); #endif } [Conditional("DEBUG")] private void AssertSchemaMapping(SchemaMapping mapping) { #if DEBUG if (_debugHookNonEmptySelectCommand) { Debug.Assert(mapping != null && mapping.DataValues != null && mapping.DataTable != null, "Debug hook specifies that non-empty results are not expected"); } #endif } protected DataAdapter() : base() { GC.SuppressFinalize(this); } protected DataAdapter(DataAdapter from) : base() { CloneFrom(from); } [DefaultValue(true)] public bool AcceptChangesDuringFill { get { return _acceptChangesDuringFill; } set { _acceptChangesDuringFill = value; } } [EditorBrowsable(EditorBrowsableState.Never)] public virtual bool ShouldSerializeAcceptChangesDuringFill() { return (0 == _fillLoadOption); } [DefaultValue(true)] public bool AcceptChangesDuringUpdate { get { return _acceptChangesDuringUpdate; } set { _acceptChangesDuringUpdate = value; } } [DefaultValue(false)] public bool ContinueUpdateOnError { get { return _continueUpdateOnError; } set { _continueUpdateOnError = value; } } [RefreshProperties(RefreshProperties.All)] public LoadOption FillLoadOption { get { LoadOption fillLoadOption = _fillLoadOption; return ((0 != fillLoadOption) ? _fillLoadOption : LoadOption.OverwriteChanges); } set { switch (value) { case 0: // to allow simple resetting case LoadOption.OverwriteChanges: case LoadOption.PreserveChanges: case LoadOption.Upsert: _fillLoadOption = value; break; default: throw ADP.InvalidLoadOption(value); } } } [EditorBrowsable(EditorBrowsableState.Never)] public void ResetFillLoadOption() { _fillLoadOption = 0; } [EditorBrowsable(EditorBrowsableState.Never)] public virtual bool ShouldSerializeFillLoadOption() => 0 != _fillLoadOption; [DefaultValue(System.Data.MissingMappingAction.Passthrough)] public MissingMappingAction MissingMappingAction { get { return _missingMappingAction; } set { switch (value) { case MissingMappingAction.Passthrough: case MissingMappingAction.Ignore: case MissingMappingAction.Error: _missingMappingAction = value; break; default: throw ADP.InvalidMissingMappingAction(value); } } } [DefaultValue(Data.MissingSchemaAction.Add)] public MissingSchemaAction MissingSchemaAction { get { return _missingSchemaAction; } set { switch (value) { case MissingSchemaAction.Add: case MissingSchemaAction.Ignore: case MissingSchemaAction.Error: case MissingSchemaAction.AddWithKey: _missingSchemaAction = value; break; default: throw ADP.InvalidMissingSchemaAction(value); } } } internal int ObjectID => _objectID; [DefaultValue(false)] public virtual bool ReturnProviderSpecificTypes { get { return _returnProviderSpecificTypes; } set { _returnProviderSpecificTypes = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DataTableMappingCollection TableMappings { get { DataTableMappingCollection mappings = _tableMappings; if (null == mappings) { mappings = CreateTableMappings(); if (null == mappings) { mappings = new DataTableMappingCollection(); } _tableMappings = mappings; } return mappings; // constructed by base class } } ITableMappingCollection IDataAdapter.TableMappings => TableMappings; protected virtual bool ShouldSerializeTableMappings() => true; protected bool HasTableMappings() => ((null != _tableMappings) && (0 < TableMappings.Count)); public event FillErrorEventHandler FillError { add { _hasFillErrorHandler = true; Events.AddHandler(s_eventFillError, value); } remove { Events.RemoveHandler(s_eventFillError, value); } } [Obsolete("CloneInternals() has been deprecated. Use the DataAdapter(DataAdapter from) constructor. http://go.microsoft.com/fwlink/?linkid=14202")] protected virtual DataAdapter CloneInternals() { DataAdapter clone = (DataAdapter)Activator.CreateInstance(GetType(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); clone.CloneFrom(this); return clone; } private void CloneFrom(DataAdapter from) { _acceptChangesDuringUpdate = from._acceptChangesDuringUpdate; _acceptChangesDuringUpdateAfterInsert = from._acceptChangesDuringUpdateAfterInsert; _continueUpdateOnError = from._continueUpdateOnError; _returnProviderSpecificTypes = from._returnProviderSpecificTypes; _acceptChangesDuringFill = from._acceptChangesDuringFill; _fillLoadOption = from._fillLoadOption; _missingMappingAction = from._missingMappingAction; _missingSchemaAction = from._missingSchemaAction; if ((null != from._tableMappings) && (0 < from.TableMappings.Count)) { DataTableMappingCollection parameters = TableMappings; foreach (object parameter in from.TableMappings) { parameters.Add((parameter is ICloneable) ? ((ICloneable)parameter).Clone() : parameter); } } } protected virtual DataTableMappingCollection CreateTableMappings() { DataCommonEventSource.Log.Trace("<comm.DataAdapter.CreateTableMappings|API> {0}", ObjectID); return new DataTableMappingCollection(); } protected override void Dispose(bool disposing) { if (disposing) { // release mananged objects _tableMappings = null; } // release unmanaged objects base.Dispose(disposing); // notify base classes } public virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType) { throw ADP.NotSupported(); } protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, string srcTable, IDataReader dataReader) { long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DataAdapter.FillSchema|API> {0}, dataSet, schemaType={1}, srcTable, dataReader", ObjectID, schemaType); try { if (null == dataSet) { throw ADP.ArgumentNull(nameof(dataSet)); } if ((SchemaType.Source != schemaType) && (SchemaType.Mapped != schemaType)) { throw ADP.InvalidSchemaType(schemaType); } if (string.IsNullOrEmpty(srcTable)) { throw ADP.FillSchemaRequiresSourceTableName(nameof(srcTable)); } if ((null == dataReader) || dataReader.IsClosed) { throw ADP.FillRequires(nameof(dataReader)); } // user must Close/Dispose of the dataReader object value = FillSchemaFromReader(dataSet, null, schemaType, srcTable, dataReader); return (DataTable[])value; } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } protected virtual DataTable FillSchema(DataTable dataTable, SchemaType schemaType, IDataReader dataReader) { long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DataAdapter.FillSchema|API> {0}, dataTable, schemaType, dataReader", ObjectID); try { if (null == dataTable) { throw ADP.ArgumentNull(nameof(dataTable)); } if ((SchemaType.Source != schemaType) && (SchemaType.Mapped != schemaType)) { throw ADP.InvalidSchemaType(schemaType); } if ((null == dataReader) || dataReader.IsClosed) { throw ADP.FillRequires(nameof(dataReader)); } // user must Close/Dispose of the dataReader // user will have to call NextResult to access remaining results object value = FillSchemaFromReader(null, dataTable, schemaType, null, dataReader); return (DataTable)value; } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } internal object FillSchemaFromReader(DataSet dataset, DataTable datatable, SchemaType schemaType, string srcTable, IDataReader dataReader) { DataTable[] dataTables = null; int schemaCount = 0; do { DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes); AssertReaderHandleFieldCount(readerHandler); if (0 >= readerHandler.FieldCount) { continue; } string tmp = null; if (null != dataset) { tmp = DataAdapter.GetSourceTableName(srcTable, schemaCount); schemaCount++; // don't increment if no SchemaTable ( a non-row returning result ) } SchemaMapping mapping = new SchemaMapping(this, dataset, datatable, readerHandler, true, schemaType, tmp, false, null, null); if (null != datatable) { // do not read remaining results in single DataTable case return mapping.DataTable; } else if (null != mapping.DataTable) { if (null == dataTables) { dataTables = new DataTable[1] { mapping.DataTable }; } else { dataTables = DataAdapter.AddDataTableToArray(dataTables, mapping.DataTable); } } } while (dataReader.NextResult()); // FillSchema does not capture errors for FillError event object value = dataTables; if ((null == value) && (null == datatable)) { value = Array.Empty<DataTable>(); } return value; // null if datatable had no results } public virtual int Fill(DataSet dataSet) { throw ADP.NotSupported(); } protected virtual int Fill(DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords) { long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DataAdapter.Fill|API> {0}, dataSet, srcTable, dataReader, startRecord, maxRecords", ObjectID); try { if (null == dataSet) { throw ADP.FillRequires(nameof(dataSet)); } if (string.IsNullOrEmpty(srcTable)) { throw ADP.FillRequiresSourceTableName(nameof(srcTable)); } if (null == dataReader) { throw ADP.FillRequires(nameof(dataReader)); } if (startRecord < 0) { throw ADP.InvalidStartRecord(nameof(startRecord), startRecord); } if (maxRecords < 0) { throw ADP.InvalidMaxRecords(nameof(maxRecords), maxRecords); } if (dataReader.IsClosed) { return 0; } // user must Close/Dispose of the dataReader DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes); return FillFromReader(dataSet, null, srcTable, readerHandler, startRecord, maxRecords, null, null); } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } protected virtual int Fill(DataTable dataTable, IDataReader dataReader) { DataTable[] dataTables = new DataTable[] { dataTable }; return Fill(dataTables, dataReader, 0, 0); } protected virtual int Fill(DataTable[] dataTables, IDataReader dataReader, int startRecord, int maxRecords) { long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DataAdapter.Fill|API> {0}, dataTables[], dataReader, startRecord, maxRecords", ObjectID); try { ADP.CheckArgumentLength(dataTables, nameof(dataTables)); if ((null == dataTables) || (0 == dataTables.Length) || (null == dataTables[0])) { throw ADP.FillRequires("dataTable"); } if (null == dataReader) { throw ADP.FillRequires(nameof(dataReader)); } if ((1 < dataTables.Length) && ((0 != startRecord) || (0 != maxRecords))) { throw ADP.NotSupported(); // FillChildren is not supported with FillPage } int result = 0; bool enforceContraints = false; DataSet commonDataSet = dataTables[0].DataSet; try { if (null != commonDataSet) { enforceContraints = commonDataSet.EnforceConstraints; commonDataSet.EnforceConstraints = false; } for (int i = 0; i < dataTables.Length; ++i) { Debug.Assert(null != dataTables[i], "null DataTable Fill"); if (dataReader.IsClosed) { #if DEBUG Debug.Assert(!_debugHookNonEmptySelectCommand, "Debug hook asserts data reader should be open"); #endif break; } DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes); AssertReaderHandleFieldCount(readerHandler); if (readerHandler.FieldCount <= 0) { if (i == 0) { bool lastFillNextResult; do { lastFillNextResult = FillNextResult(readerHandler); } while (lastFillNextResult && readerHandler.FieldCount <= 0); if (!lastFillNextResult) { break; } } else { continue; } } if ((0 < i) && !FillNextResult(readerHandler)) { break; } // user must Close/Dispose of the dataReader // user will have to call NextResult to access remaining results int count = FillFromReader(null, dataTables[i], null, readerHandler, startRecord, maxRecords, null, null); if (0 == i) { result = count; } } } catch (ConstraintException) { enforceContraints = false; throw; } finally { if (enforceContraints) { commonDataSet.EnforceConstraints = true; } } return result; } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } internal int FillFromReader(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int startRecord, int maxRecords, DataColumn parentChapterColumn, object parentChapterValue) { int rowsAddedToDataSet = 0; int schemaCount = 0; do { AssertReaderHandleFieldCount(dataReader); if (0 >= dataReader.FieldCount) { continue; // loop to next result } SchemaMapping mapping = FillMapping(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue); schemaCount++; // don't increment if no SchemaTable ( a non-row returning result ) AssertSchemaMapping(mapping); if (null == mapping) { continue; // loop to next result } if (null == mapping.DataValues) { continue; // loop to next result } if (null == mapping.DataTable) { continue; // loop to next result } mapping.DataTable.BeginLoadData(); try { // startRecord and maxRecords only apply to the first resultset if ((1 == schemaCount) && ((0 < startRecord) || (0 < maxRecords))) { rowsAddedToDataSet = FillLoadDataRowChunk(mapping, startRecord, maxRecords); } else { int count = FillLoadDataRow(mapping); if (1 == schemaCount) { // only return LoadDataRow count for first resultset // not secondary or chaptered results rowsAddedToDataSet = count; } } } finally { mapping.DataTable.EndLoadData(); } if (null != datatable) { break; // do not read remaining results in single DataTable case } } while (FillNextResult(dataReader)); return rowsAddedToDataSet; } private int FillLoadDataRowChunk(SchemaMapping mapping, int startRecord, int maxRecords) { DataReaderContainer dataReader = mapping.DataReader; while (0 < startRecord) { if (!dataReader.Read()) { // there are no more rows on first resultset return 0; } --startRecord; } int rowsAddedToDataSet = 0; if (0 < maxRecords) { while ((rowsAddedToDataSet < maxRecords) && dataReader.Read()) { if (_hasFillErrorHandler) { try { mapping.LoadDataRowWithClear(); rowsAddedToDataSet++; } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ADP.TraceExceptionForCapture(e); OnFillErrorHandler(e, mapping.DataTable, mapping.DataValues); } } else { mapping.LoadDataRow(); rowsAddedToDataSet++; } } // skip remaining rows of the first resultset } else { rowsAddedToDataSet = FillLoadDataRow(mapping); } return rowsAddedToDataSet; } private int FillLoadDataRow(SchemaMapping mapping) { int rowsAddedToDataSet = 0; DataReaderContainer dataReader = mapping.DataReader; if (_hasFillErrorHandler) { while (dataReader.Read()) { // read remaining rows of first and subsequent resultsets try { // only try-catch if a FillErrorEventHandler is registered so that // in the default case we get the full callstack from users mapping.LoadDataRowWithClear(); rowsAddedToDataSet++; } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ADP.TraceExceptionForCapture(e); OnFillErrorHandler(e, mapping.DataTable, mapping.DataValues); } } } else { while (dataReader.Read()) { // read remaining rows of first and subsequent resultset mapping.LoadDataRow(); rowsAddedToDataSet++; } } return rowsAddedToDataSet; } private SchemaMapping FillMappingInternal(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn parentChapterColumn, object parentChapterValue) { bool withKeyInfo = (Data.MissingSchemaAction.AddWithKey == MissingSchemaAction); string tmp = null; if (null != dataset) { tmp = DataAdapter.GetSourceTableName(srcTable, schemaCount); } return new SchemaMapping(this, dataset, datatable, dataReader, withKeyInfo, SchemaType.Mapped, tmp, true, parentChapterColumn, parentChapterValue); } private SchemaMapping FillMapping(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn parentChapterColumn, object parentChapterValue) { SchemaMapping mapping = null; if (_hasFillErrorHandler) { try { // only try-catch if a FillErrorEventHandler is registered so that // in the default case we get the full callstack from users mapping = FillMappingInternal(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue); } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ADP.TraceExceptionForCapture(e); OnFillErrorHandler(e, null, null); } } else { mapping = FillMappingInternal(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue); } return mapping; } private bool FillNextResult(DataReaderContainer dataReader) { bool result = true; if (_hasFillErrorHandler) { try { // only try-catch if a FillErrorEventHandler is registered so that // in the default case we get the full callstack from users result = dataReader.NextResult(); } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ADP.TraceExceptionForCapture(e); OnFillErrorHandler(e, null, null); } } else { result = dataReader.NextResult(); } return result; } [EditorBrowsable(EditorBrowsableState.Advanced)] public virtual IDataParameter[] GetFillParameters() => Array.Empty<IDataParameter>(); internal DataTableMapping GetTableMappingBySchemaAction(string sourceTableName, string dataSetTableName, MissingMappingAction mappingAction) { return DataTableMappingCollection.GetTableMappingBySchemaAction(_tableMappings, sourceTableName, dataSetTableName, mappingAction); } internal int IndexOfDataSetTable(string dataSetTable) { if (null != _tableMappings) { return TableMappings.IndexOfDataSetTable(dataSetTable); } return -1; } protected virtual void OnFillError(FillErrorEventArgs value) { ((FillErrorEventHandler)Events[s_eventFillError])?.Invoke(this, value); } private void OnFillErrorHandler(Exception e, DataTable dataTable, object[] dataValues) { FillErrorEventArgs fillErrorEvent = new FillErrorEventArgs(dataTable, dataValues); fillErrorEvent.Errors = e; OnFillError(fillErrorEvent); if (!fillErrorEvent.Continue) { if (null != fillErrorEvent.Errors) { throw fillErrorEvent.Errors; } throw e; } } public virtual int Update(DataSet dataSet) { throw ADP.NotSupported(); } // used by FillSchema which returns an array of datatables added to the dataset private static DataTable[] AddDataTableToArray(DataTable[] tables, DataTable newTable) { for (int i = 0; i < tables.Length; ++i) { // search for duplicates if (tables[i] == newTable) { return tables; // duplicate found } } DataTable[] newTables = new DataTable[tables.Length + 1]; // add unique data table for (int i = 0; i < tables.Length; ++i) { newTables[i] = tables[i]; } newTables[tables.Length] = newTable; return newTables; } // dynamically generate source table names private static string GetSourceTableName(string srcTable, int index) { //if ((null != srcTable) && (0 <= index) && (index < srcTable.Length)) { if (0 == index) { return srcTable; //[index]; } return srcTable + index.ToString(System.Globalization.CultureInfo.InvariantCulture); } } internal sealed class LoadAdapter : DataAdapter { internal LoadAdapter() { } internal int FillFromReader(DataTable[] dataTables, IDataReader dataReader, int startRecord, int maxRecords) { return Fill(dataTables, dataReader, startRecord, maxRecords); } } }
// 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 Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed partial class ExpressionBinder { // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- private sealed class ExplicitConversion { private readonly ExpressionBinder _binder; private EXPR _exprSrc; private readonly CType _typeSrc; private readonly CType _typeDest; private readonly EXPRTYPEORNAMESPACE _exprTypeDest; // This is for lambda error reporting. The reason we have this is because we // store errors for lambda conversions, and then we don't bind the conversion // again to report errors. Consider the following case: // // int? x = () => null; // // When we try to convert the lambda to the nullable type int?, we first // attempt the conversion to int. If that fails, then we know there is no // conversion to int?, since int is a predef type. We then look for UserDefined // conversions, and fail. When we report the errors, we ask the lambda for its // conversion errors. But since we attempted its conversion to int and not int?, // we report the wrong error. This field is to keep track of the right type // to report the error on, so that when the lambda conversion fails, it reports // errors on the correct type. private readonly CType _pDestinationTypeForLambdaErrorReporting; private EXPR _exprDest; private readonly bool _needsExprDest; private readonly CONVERTTYPE _flags; // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- public ExplicitConversion(ExpressionBinder binder, EXPR exprSrc, CType typeSrc, EXPRTYPEORNAMESPACE typeDest, CType pDestinationTypeForLambdaErrorReporting, bool needsExprDest, CONVERTTYPE flags) { _binder = binder; _exprSrc = exprSrc; _typeSrc = typeSrc; _typeDest = typeDest.TypeOrNamespace.AsType(); _pDestinationTypeForLambdaErrorReporting = pDestinationTypeForLambdaErrorReporting; _exprTypeDest = typeDest; _needsExprDest = needsExprDest; _flags = flags; _exprDest = null; } public EXPR ExprDest { get { return _exprDest; } } /* * BindExplicitConversion * * This is a complex routine with complex parameter. Generally, this should * be called through one of the helper methods that insulates you * from the complexity of the interface. This routine handles all the logic * associated with explicit conversions. * * Note that this function calls BindImplicitConversion first, so the main * logic is only concerned with conversions that can be made explicitly, but * not implicitly. */ public bool Bind() { // To test for a standard conversion, call canConvert(exprSrc, typeDest, STANDARDANDCONVERTTYPE.NOUDC) and // canConvert(typeDest, typeSrc, STANDARDANDCONVERTTYPE.NOUDC). Debug.Assert((_flags & CONVERTTYPE.STANDARD) == 0); // 13.2 Explicit conversions // // The following conversions are classified as explicit conversions: // // * All implicit conversions // * Explicit numeric conversions // * Explicit enumeration conversions // * Explicit reference conversions // * Explicit interface conversions // * Unboxing conversions // * Explicit type parameter conversions // * User-defined explicit conversions // * Explicit nullable conversions // * Lifted user-defined explicit conversions // // Explicit conversions can occur in cast expressions (14.6.6). // // The explicit conversions that are not implicit conversions are conversions that cannot be // proven always to succeed, conversions that are known possibly to lose information, and // conversions across domains of types sufficiently different to merit explicit notation. // The set of explicit conversions includes all implicit conversions. // Don't try user-defined conversions now because we'll try them again later. if (_binder.BindImplicitConversion(_exprSrc, _typeSrc, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.ISEXPLICIT)) { return true; } if (_typeSrc == null || _typeDest == null || _typeSrc.IsErrorType() || _typeDest.IsErrorType() || _typeDest.IsNeverSameType()) { return false; } if (_typeDest.IsNullableType()) { // This is handled completely by BindImplicitConversion. return false; } if (_typeSrc.IsNullableType()) { return bindExplicitConversionFromNub(); } if (bindExplicitConversionFromArrayToIList()) { return true; } // if we were casting an integral constant to another constant type, // then, if the constant were in range, then the above call would have succeeded. // But it failed, and so we know that the constant is not in range switch (_typeDest.GetTypeKind()) { default: VSFAIL("Bad type kind"); return false; case TypeKind.TK_VoidType: return false; // Can't convert to a method group or anon method. case TypeKind.TK_NullType: return false; // Can never convert TO the null type. case TypeKind.TK_TypeParameterType: if (bindExplicitConversionToTypeVar()) { return true; } break; case TypeKind.TK_ArrayType: if (bindExplicitConversionToArray(_typeDest.AsArrayType())) { return true; } break; case TypeKind.TK_PointerType: if (bindExplicitConversionToPointer()) { return true; } break; case TypeKind.TK_AggregateType: { AggCastResult result = bindExplicitConversionToAggregate(_typeDest.AsAggregateType()); if (result == AggCastResult.Success) { return true; } if (result == AggCastResult.Abort) { return false; } break; } } // No built-in conversion was found. Maybe a user-defined conversion? if (0 == (_flags & CONVERTTYPE.NOUDC)) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromNub() { Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); // If S and T are value types and there is a builtin conversion from S => T then there is an // explicit conversion from S? => T that throws on null. if (_typeDest.IsValType() && _binder.BindExplicitConversion(null, _typeSrc.StripNubs(), _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _flags | CONVERTTYPE.NOUDC)) { if (_needsExprDest) { EXPR valueSrc = _exprSrc; // This is a holdover from the days when you could have nullable of nullable. // Can we remove this loop? while (valueSrc.type.IsNullableType()) { valueSrc = _binder.BindNubValue(valueSrc); } Debug.Assert(valueSrc.type == _typeSrc.StripNubs()); if (!_binder.BindExplicitConversion(valueSrc, valueSrc.type, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.NOUDC)) { VSFAIL("BindExplicitConversion failed unexpectedly"); return false; } if (_exprDest.kind == ExpressionKind.EK_USERDEFINEDCONVERSION) { _exprDest.asUSERDEFINEDCONVERSION().Argument = _exprSrc; } } return true; } if ((_flags & CONVERTTYPE.NOUDC) == 0) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromArrayToIList() { // 13.2.2 // // The explicit reference conversions are: // // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and // their base interfaces, provided there is an explicit reference conversion from S to T. Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); if (!_typeSrc.IsArrayType() || _typeSrc.AsArrayType().rank != 1 || !_typeDest.isInterfaceType() || _typeDest.AsAggregateType().GetTypeArgsAll().Size != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetOptPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetOptPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !GetSymbolLoader().IsBaseAggregate(aggIList, _typeDest.AsAggregateType().getAggregate())) && (aggIReadOnlyList == null || !GetSymbolLoader().IsBaseAggregate(aggIReadOnlyList, _typeDest.AsAggregateType().getAggregate()))) { return false; } CType typeArr = _typeSrc.AsArrayType().GetElementType(); CType typeLst = _typeDest.AsAggregateType().GetTypeArgsAll().Item(0); if (!CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionToTypeVar() { // 13.2.3 Explicit reference conversions // // For a type-parameter T that is known to be a reference type (25.7), the following // explicit reference conversions exist: // // * From the effective base class C of T to T and from any base class of C to T. // * From any interface-type to T. // * From a type-parameter U to T provided that T depends on U (25.7). Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); // NOTE: for the flags, we have to use EXPRFLAG.EXF_FORCE_UNBOX (not EXPRFLAG.EXF_REFCHECK) even when // we know that the type is a reference type. The verifier expects all code for // type parameters to behave as if the type parameter is a value type. // The jitter should be smart about it.... if (_typeSrc.isInterfaceType() || _binder.canConvert(_typeDest, _typeSrc, CONVERTTYPE.NOUDC)) { if (!_needsExprDest) { return true; } // There is an explicit, possibly unboxing, conversion from Object or any interface to // a type variable. This will involve a type check and possibly an unbox. // There is an explicit conversion from non-interface X to the type var iff there is an // implicit conversion from the type var to X. if (_typeSrc.IsTypeParameterType()) { // Need to box first before unboxing. EXPR exprT; EXPRCLASS exprObj = GetExprFactory().MakeClass(_binder.GetReqPDT(PredefinedType.PT_OBJECT)); _binder.bindSimpleCast(_exprSrc, exprObj, out exprT, EXPRFLAG.EXF_FORCE_BOX); _exprSrc = exprT; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX); return true; } return false; } private bool bindExplicitConversionFromIListToArray(ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces // to a one-dimensional array-type S[], provided there is an implicit or explicit reference conversion from // S[] to System.Collections.Generic.IList<T> or System.Collections.Generic.IReadOnlyList<T>. This is precisely when either S and T // are the same type or there is an implicit or explicit reference conversion from S to T. if (arrayDest.rank != 1 || !_typeSrc.isInterfaceType() || _typeSrc.AsAggregateType().GetTypeArgsAll().Size != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetOptPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetOptPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !GetSymbolLoader().IsBaseAggregate(aggIList, _typeSrc.AsAggregateType().getAggregate())) && (aggIReadOnlyList == null || !GetSymbolLoader().IsBaseAggregate(aggIReadOnlyList, _typeSrc.AsAggregateType().getAggregate()))) { return false; } CType typeArr = arrayDest.GetElementType(); CType typeLst = _typeSrc.AsAggregateType().GetTypeArgsAll().Item(0); Debug.Assert(!typeArr.IsNeverSameType()); if (typeArr != typeLst && !CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionFromArrayToArray(ArrayType arraySrc, ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From an array-type S with an element type SE to an array-type T with an element type // TE, provided all of the following are true: // // * S and T differ only in element type. (In other words, S and T have the same number // of dimensions.) // // * An explicit reference conversion exists from SE to TE. if (arraySrc.rank != arrayDest.rank) { return false; // Ranks do not match. } if (CConversions.FExpRefConv(GetSymbolLoader(), arraySrc.GetElementType(), arrayDest.GetElementType())) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToArray(ArrayType arrayDest) { Debug.Assert(_typeSrc != null); Debug.Assert(arrayDest != null); if (_typeSrc.IsArrayType()) { return bindExplicitConversionFromArrayToArray(_typeSrc.AsArrayType(), arrayDest); } if (bindExplicitConversionFromIListToArray(arrayDest)) { return true; } // 13.2.2 // // The explicit reference conversions are: // // * From System.Array and the interfaces it implements, to any array-type. if (_binder.canConvert(_binder.GetReqPDT(PredefinedType.PT_ARRAY), _typeSrc, CONVERTTYPE.NOUDC)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToPointer() { // 27.4 Pointer conversions // // in an unsafe context, the set of available explicit conversions (13.2) is extended to // include the following explicit pointer conversions: // // * From any pointer-type to any other pointer-type. // * From sbyte, byte, short, ushort, int, uint, long, or ulong to any pointer-type. if (_typeSrc.IsPointerType() || _typeSrc.fundType() <= FUNDTYPE.FT_LASTINTEGRAL && _typeSrc.isNumericType()) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } return false; } // 13.2.2 Explicit enumeration conversions // // The explicit enumeration conversions are: // // * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or // decimal to any enum-type. // // * From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, // float, double, or decimal. // // * From any enum-type to any other enum-type. // // * An explicit enumeration conversion between two types is processed by treating any // participating enum-type as the underlying type of that enum-type, and then performing // an implicit or explicit numeric conversion between the resulting types. private AggCastResult bindExplicitConversionFromEnumToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isEnumType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (aggDest.isPredefAgg(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromEnumToDecimal(aggTypeDest); } if (!aggDest.getThisType().isNumericType() && !aggDest.IsEnum() && !(aggDest.IsPredefined() && aggDest.GetPredefType() == PredefinedType.PT_CHAR)) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } else if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionFromDecimalToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)); // There is an explicit conversion from decimal to all integral types. if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // All casts from decimal to integer types are bound as user-defined conversions. bool bIsConversionOK = true; if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. CType underlyingType = aggTypeDest.underlyingType(); bIsConversionOK = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, underlyingType, _needsExprDest, out _exprDest, false); if (bIsConversionOK) { // upcast to the Enum type _binder.bindSimpleCast(_exprDest, _exprTypeDest, out _exprDest); } } return bIsConversionOK ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromEnumToDecimal(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); Debug.Assert(aggTypeDest.isPredefType(PredefinedType.PT_DECIMAL)); AggregateType underlyingType = _typeSrc.underlyingType().AsAggregateType(); // Need to first cast the source expr to its underlying type. EXPR exprCast; if (_exprSrc == null) { exprCast = null; } else { EXPRCLASS underlyingExpr = GetExprFactory().MakeClass(underlyingType); _binder.bindSimpleCast(_exprSrc, underlyingExpr, out exprCast); } // There is always an implicit conversion from any integral type to decimal. if (exprCast.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(exprCast, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // Conversions from integral types to decimal are always bound as a user-defined conversion. if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bool ok = _binder.bindUserDefinedConversion(exprCast, underlyingType, aggTypeDest, _needsExprDest, out _exprDest, false); Debug.Assert(ok); } return AggCastResult.Success; } private AggCastResult bindExplicitConversionToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (!aggDest.IsEnum()) { return AggCastResult.Failure; } if (_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromDecimalToEnum(aggTypeDest); } if (_typeSrc.isNumericType() || (_typeSrc.isPredefined() && _typeSrc.getPredefType() == PredefinedType.PT_CHAR)) { // Transform constant to constant. if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } else if (_typeSrc.isPredefined() && (_typeSrc.isPredefType(PredefinedType.PT_OBJECT) || _typeSrc.isPredefType(PredefinedType.PT_VALUE) || _typeSrc.isPredefType(PredefinedType.PT_ENUM))) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenSimpleTypes(AggregateType aggTypeDest) { // 13.2.1 // // Because the explicit conversions include all implicit and explicit numeric conversions, // it is always possible to convert from any numeric-type to any other numeric-type using // a cast expression (14.6.6). Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isSimpleType() || !aggTypeDest.isSimpleType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); Debug.Assert(_typeSrc.isPredefined() && aggDest.IsPredefined()); PredefinedType ptSrc = _typeSrc.getPredefType(); PredefinedType ptDest = aggDest.GetPredefType(); Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES); ConvKind convertKind = GetConvKind(ptSrc, ptDest); // Identity and implicit conversions should already have been handled. Debug.Assert(convertKind != ConvKind.Implicit); Debug.Assert(convertKind != ConvKind.Identity); if (convertKind != ConvKind.Explicit) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } bool bConversionOk = true; if (_needsExprDest) { // Explicit conversions involving decimals are bound as user-defined conversions. if (isUserDefinedConversion(ptSrc, ptDest)) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bConversionOk = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, aggTypeDest, _needsExprDest, out _exprDest, false); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, (_flags & CONVERTTYPE.CHECKOVERFLOW) != 0 ? EXPRFLAG.EXF_CHECKOVERFLOW : 0); } } return bConversionOk ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenAggregates(AggregateType aggTypeDest) { // 13.2.3 // // The explicit reference conversions are: // // * From object to any reference-type. // * From any class-type S to any class-type T, provided S is a base class of T. // * From any class-type S to any interface-type T, provided S is not sealed and // provided S does not implement T. // * From any interface-type S to any class-type T, provided T is not sealed or provided // T implements S. // * From any interface-type S to any interface-type T, provided S is not derived from T. Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.IsAggregateType()) { return AggCastResult.Failure; } AggregateSymbol aggSrc = _typeSrc.AsAggregateType().getAggregate(); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (GetSymbolLoader().HasBaseConversion(aggTypeDest, _typeSrc.AsAggregateType())) { if (_needsExprDest) { if (aggDest.IsValueType() && aggSrc.getThisType().fundType() == FUNDTYPE.FT_REF) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); } } return AggCastResult.Success; } if ((aggSrc.IsClass() && !aggSrc.IsSealed() && aggDest.IsInterface()) || (aggSrc.IsInterface() && aggDest.IsClass() && !aggDest.IsSealed()) || (aggSrc.IsInterface() && aggDest.IsInterface()) || CConversions.HasGenericDelegateExplicitReferenceConversion(GetSymbolLoader(), _typeSrc, aggTypeDest)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromPointerToInt(AggregateType aggTypeDest) { // 27.4 Pointer conversions // in an unsafe context, the set of available explicit conversions (13.2) is extended to include // the following explicit pointer conversions: // // * From any pointer-type to sbyte, byte, short, ushort, int, uint, long, or ulong. if (!_typeSrc.IsPointerType() || aggTypeDest.fundType() > FUNDTYPE.FT_LASTINTEGRAL || !aggTypeDest.isNumericType()) { return AggCastResult.Failure; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionFromTypeVarToAggregate(AggregateType aggTypeDest) { // 13.2.3 Explicit reference conversions // // For a type-parameter T that is known to be a reference type (25.7), the following // explicit reference conversions exist: // // * From T to any interface-type I provided there isn't already an implicit reference // conversion from T to I. if (!_typeSrc.IsTypeParameterType()) { return AggCastResult.Failure; } #if ! CSEE if (aggTypeDest.getAggregate().IsInterface()) #else if ((exprSrc != null && !exprSrc.eeValue.substType.IsNullableType()) || aggTypeDest.getAggregate().IsInterface()) #endif { // Explicit conversion of type variables to interfaces. if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_BOX | EXPRFLAG.EXF_REFCHECK); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); // TypeReference and ArgIterator can't be boxed (or converted to anything else) if (_typeSrc.isSpecialByRefType()) { return AggCastResult.Abort; } AggCastResult result = bindExplicitConversionFromEnumToAggregate(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionToEnum(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenSimpleTypes(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenAggregates(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionFromPointerToInt(aggTypeDest); if (result != AggCastResult.Failure) { return result; } if (_typeSrc.IsVoidType()) { // No conversion is allowed to or from a void type (user defined or otherwise) // This is most likely the result of a failed anonymous method or member group conversion return AggCastResult.Abort; } result = bindExplicitConversionFromTypeVarToAggregate(aggTypeDest); if (result != AggCastResult.Failure) { return result; } return AggCastResult.Failure; } private SymbolLoader GetSymbolLoader() { return _binder.GetSymbolLoader(); } private ExprFactory GetExprFactory() { return _binder.GetExprFactory(); } } } }
#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 // All code in this file requires .NET Framework 2.0 or later. #if !NET_1_1 && !NET_1_0 [assembly: Elmah.Scc("$Id: SQLiteErrorLog.cs 566 2009-05-11 10:37:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections; using System.Data; using System.Data.SQLite; using System.Globalization; using System.IO; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses SQLite as its backing store. /// </summary> public class SQLiteErrorLog : ErrorLog { private readonly string _connectionString; /// <summary> /// Initializes a new instance of the <see cref="SQLiteErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public SQLiteErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); string connectionString = ConnectionStringHelper.GetConnectionString(config, true); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new ApplicationException("Connection string is missing for the SQLite error log."); _connectionString = connectionString; InitializeDatabase(); ApplicationName = Mask.NullString((string) config["applicationName"]); } /// <summary> /// Initializes a new instance of the <see cref="SQLiteErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public SQLiteErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = ConnectionStringHelper.GetResolvedConnectionString(connectionString); InitializeDatabase(); } private static readonly object _lock = new object(); private void InitializeDatabase() { string connectionString = ConnectionString; Debug.AssertStringNotEmpty(connectionString); string dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString); if (File.Exists(dbFilePath)) return; // // Make sure that we don't have multiple threads all trying to create the database // lock (_lock) { // // Just double check that no other thread has created the database while // we were waiting for the lock // if (File.Exists(dbFilePath)) return; SQLiteConnection.CreateFile(dbFilePath); const string sql = @" CREATE TABLE Error ( ErrorId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Application TEXT NOT NULL, Host TEXT NOT NULL, Type TEXT NOT NULL, Source TEXT NOT NULL, Message TEXT NOT NULL, User TEXT NOT NULL, StatusCode INTEGER NOT NULL, TimeUtc TEXT NOT NULL, AllXml TEXT NOT NULL )"; using (SQLiteConnection connection = new SQLiteConnection(connectionString)) using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { connection.Open(); command.ExecuteNonQuery(); } } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "SQLite Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); const string query = @" INSERT INTO Error ( Application, Host, Type, Source, Message, User, StatusCode, TimeUtc, AllXml) VALUES ( @Application, @Host, @Type, @Source, @Message, @User, @StatusCode, @TimeUtc, @AllXml); SELECT last_insert_rowid();"; using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) using (SQLiteCommand command = new SQLiteCommand(query, connection)) { SQLiteParameterCollection parameters = command.Parameters; parameters.Add("@Application", DbType.String, 60).Value = ApplicationName; parameters.Add("@Host", DbType.String, 30).Value = error.HostName; parameters.Add("@Type", DbType.String, 100).Value = error.Type; parameters.Add("@Source", DbType.String, 60).Value = error.Source; parameters.Add("@Message", DbType.String, 500).Value = error.Message; parameters.Add("@User", DbType.String, 50).Value = error.User; parameters.Add("@StatusCode", DbType.Int64).Value = error.StatusCode; parameters.Add("@TimeUtc", DbType.DateTime).Value = error.Time.ToUniversalTime(); parameters.Add("@AllXml", DbType.String).Value = errorXml; connection.Open(); return Convert.ToInt64(command.ExecuteScalar()).ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); const string sql = @" SELECT ErrorId, Application, Host, Type, Source, Message, User, StatusCode, TimeUtc FROM Error ORDER BY ErrorId DESC LIMIT @PageIndex * @PageSize, @PageSize; SELECT COUNT(*) FROM Error"; using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { SQLiteParameterCollection parameters = command.Parameters; parameters.Add("@PageIndex", DbType.Int16).Value = pageIndex; parameters.Add("@PageSize", DbType.Int16).Value = pageSize; connection.Open(); using (SQLiteDataReader reader = command.ExecuteReader()) { if (errorEntryList != null) { while (reader.Read()) { string id = reader["ErrorId"].ToString(); Error error = new Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["User"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, id, error)); } } // // Get the result of SELECT COUNT(*) FROM Page // reader.NextResult(); reader.Read(); return reader.GetInt32(0); } } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); long key; try { key = long.Parse(id, CultureInfo.InvariantCulture); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } const string sql = @" SELECT AllXml FROM Error WHERE ErrorId = @ErrorId"; using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { SQLiteParameterCollection parameters = command.Parameters; parameters.Add("@ErrorId", DbType.Int64).Value = key; connection.Open(); string errorXml = (string) command.ExecuteScalar(); if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } } } } #endif //!NET_1_1 && !NET_1_0
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Linq; using RazorDBx.C5; using NUnit.Framework; using SCG = System.Collections.Generic; namespace C5UnitTests.hashtable.dictionary { using DictionaryIntToInt = HashDictionary<int, int>; [TestFixture] public class GenericTesters { [Test] public void TestEvents () { Func<DictionaryIntToInt> factory = delegate() { return new DictionaryIntToInt (TenEqualityComparer.Default); }; new C5UnitTests.Templates.Events.DictionaryTester<DictionaryIntToInt> ().Test (factory); } //[Test] //public void TestSerialize() //{ // C5UnitTests.Templates.Extensible.Serialization.DTester<DictionaryIntToInt>(); //} } static class Factory { public static IDictionary<K, V> New<K, V> () { return new HashDictionary<K, V> (); } } [TestFixture] public class Formatting { IDictionary<int, int> coll; IFormatProvider rad16; [SetUp] public void Init () { Debug.UseDeterministicHashing = true; coll = Factory.New<int, int> (); rad16 = new RadixFormatProvider (16); } [TearDown] public void Dispose () { Debug.UseDeterministicHashing = false; coll = null; rad16 = null; } [Test] public void Format () { Assert.AreEqual ("{ }", coll.ToString ()); coll.Add (23, 67); coll.Add (45, 89); Assert.AreEqual ("{ 45 => 89, 23 => 67 }", coll.ToString ()); Assert.AreEqual ("{ 2D => 59, 17 => 43 }", coll.ToString (null, rad16)); Assert.AreEqual ("{ 45 => 89, ... }", coll.ToString ("L14", null)); Assert.AreEqual ("{ 2D => 59, ... }", coll.ToString ("L14", rad16)); } } [TestFixture] public class HashDict { private HashDictionary<string, string> dict; [SetUp] public void Init () { dict = new HashDictionary<string, string> (); //dict = TreeDictionary<string,string>.MakeNaturalO<string,string>(); } [Test] [ExpectedException(typeof(NullReferenceException))] public void NullEqualityComparerinConstructor1 () { new HashDictionary<int, int> (null); } [Test] [ExpectedException(typeof(NullReferenceException))] public void NullEqualityComparerinConstructor2 () { new HashDictionary<int, int> (5, 0.5, null); } [Test] public void Choose () { dict.Add ("ER", "FOO"); Assert.AreEqual (new KeyValuePair<string, string> ("ER", "FOO"), dict.Choose ()); } [Test] [ExpectedException(typeof(NoSuchItemException))] public void BadChoose () { dict.Choose (); } [TearDown] public void Dispose () { dict = null; } [Test] public void Initial () { bool res; Assert.IsFalse (dict.IsReadOnly); Assert.AreEqual (0, dict.Count, "new dict should be empty"); dict.Add ("A", "B"); Assert.AreEqual (1, dict.Count, "bad count"); Assert.AreEqual ("B", dict ["A"], "Wrong value for dict[A]"); dict.Add ("C", "D"); Assert.AreEqual (2, dict.Count, "bad count"); Assert.AreEqual ("B", dict ["A"], "Wrong value"); Assert.AreEqual ("D", dict ["C"], "Wrong value"); res = dict.Remove ("A"); Assert.IsTrue (res, "bad return value from Remove(A)"); Assert.AreEqual (1, dict.Count, "bad count"); Assert.AreEqual ("D", dict ["C"], "Wrong value of dict[C]"); res = dict.Remove ("Z"); Assert.IsFalse (res, "bad return value from Remove(Z)"); Assert.AreEqual (1, dict.Count, "bad count"); Assert.AreEqual ("D", dict ["C"], "Wrong value of dict[C] (2)"); } [Test] public void Contains () { dict.Add ("C", "D"); Assert.IsTrue (dict.Contains ("C")); Assert.IsFalse (dict.Contains ("D")); } [Test] [ExpectedException(typeof(DuplicateNotAllowedException), ExpectedMessage = "Key being added: 'A'")] public void IllegalAdd () { dict.Add ("A", "B"); dict.Add ("A", "B"); } [Test] [ExpectedException(typeof(NoSuchItemException))] public void GettingNonExisting () { Console.WriteLine (dict ["R"]); } [Test] public void Setter () { dict ["R"] = "UYGUY"; Assert.AreEqual ("UYGUY", dict ["R"]); dict ["R"] = "UIII"; Assert.AreEqual ("UIII", dict ["R"]); dict ["S"] = "VVV"; Assert.AreEqual ("UIII", dict ["R"]); Assert.AreEqual ("VVV", dict ["S"]); //dict.dump(); } [Test] public void CombinedOps () { dict ["R"] = "UIII"; dict ["S"] = "VVV"; dict ["T"] = "XYZ"; string s; Assert.IsTrue (dict.Remove ("S", out s)); Assert.AreEqual ("VVV", s); Assert.IsFalse (dict.Contains ("S")); Assert.IsFalse (dict.Remove ("A", out s)); // string t = "T", a = "A"; Assert.IsTrue (dict.Find (ref t, out s)); Assert.AreEqual ("XYZ", s); Assert.IsFalse (dict.Find (ref a, out s)); // Assert.IsTrue (dict.Update ("R", "UHU")); Assert.AreEqual ("UHU", dict ["R"]); Assert.IsFalse (dict.Update ("A", "W")); Assert.IsFalse (dict.Contains ("A")); // s = "KKK"; Assert.IsFalse (dict.FindOrAdd ("B", ref s)); Assert.AreEqual ("KKK", dict ["B"]); Assert.IsTrue (dict.FindOrAdd ("T", ref s)); Assert.AreEqual ("XYZ", s); // s = "LLL"; Assert.IsTrue (dict.UpdateOrAdd ("R", s)); Assert.AreEqual ("LLL", dict ["R"]); s = "MMM"; Assert.IsFalse (dict.UpdateOrAdd ("C", s)); Assert.AreEqual ("MMM", dict ["C"]); // bug20071112 fixed 2008-02-03 s = "NNN"; String old; Assert.IsTrue (dict.UpdateOrAdd ("R", s, out old)); Assert.AreEqual ("NNN", dict ["R"]); Assert.AreEqual ("LLL", old); s = "OOO"; Assert.IsFalse (dict.UpdateOrAdd ("D", s, out old)); Assert.AreEqual ("OOO", dict ["D"]); // Unclear which of these is correct: // Assert.AreEqual(null, old); // Assert.AreEqual("OOO", old); } [Test] public void DeepBucket () { HashDictionary<int, int> dict2 = new HashDictionary<int, int> (); for (int i = 0; i < 5; i++) dict2 [16 * i] = 5 * i; for (int i = 0; i < 5; i++) Assert.AreEqual (5 * i, dict2 [16 * i]); for (int i = 0; i < 5; i++) dict2 [16 * i] = 7 * i + 1; for (int i = 0; i < 5; i++) Assert.AreEqual (7 * i + 1, dict2 [16 * i]); Assert.IsTrue (dict.Check ()); } } [TestFixture] public class Enumerators { private HashDictionary<string, string> _dict; [SetUp] public void Init () { _dict = new HashDictionary<string, string> (); _dict ["S"] = "A"; _dict ["T"] = "B"; _dict ["R"] = "C"; } [TearDown] public void Dispose () { _dict = null; } [Test] public void Keys () { var keys = _dict.Keys.ToArray (); Assert.AreEqual (3, keys.Length); Assert.IsTrue (keys.Contains ("R")); Assert.IsTrue (keys.Contains ("S")); Assert.IsTrue (keys.Contains ("T")); } [Test] public void Values () { var values = _dict.Values.ToArray (); Assert.AreEqual (3, values.Length); Assert.IsTrue (values.Contains ("A")); Assert.IsTrue (values.Contains ("B")); Assert.IsTrue (values.Contains ("C")); } [Test] public void Fun () { Assert.AreEqual ("B", _dict.Func ("T")); } [Test] public void NormalUse () { var pairs = _dict.ToDictionary (pair => pair.Key, pair => pair.Value); Assert.AreEqual (3, pairs.Count); Assert.IsTrue (pairs.Contains (new SCG.KeyValuePair<string, string> ("R", "C"))); Assert.IsTrue (pairs.Contains (new SCG.KeyValuePair<string, string> ("S", "A"))); Assert.IsTrue (pairs.Contains (new SCG.KeyValuePair<string, string> ("T", "B"))); } } }
/* * PrintingPermission.cs - Implementation of the * "System.Drawing.Printing.PrintingPermission" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Drawing.Printing { #if CONFIG_PERMISSIONS using System.Security; using System.Security.Permissions; #if !ECMA_COMPAT [Serializable] #endif public sealed class PrintingPermission : CodeAccessPermission #if !ECMA_COMPAT , IUnrestrictedPermission #endif { // Internal state. private PermissionState state; private PrintingPermissionLevel level; // Constructor. public PrintingPermission(PermissionState state) { this.state = state; this.level = PrintingPermissionLevel.NoPrinting; } public PrintingPermission(PrintingPermissionLevel level) { this.state = PermissionState.None; this.level = level; } // Convert an XML value into a permissions value. public override void FromXml(SecurityElement esd) { String value; if(esd == null) { throw new ArgumentNullException("esd"); } if(esd.Attribute("version") != "1") { throw new ArgumentException(S._("Arg_PermissionVersion")); } value = esd.Attribute("Unrestricted"); if(value != null && Boolean.Parse(value)) { state = PermissionState.Unrestricted; } else { state = PermissionState.None; } value = esd.Attribute("Level"); if(value != null) { level = (PrintingPermissionLevel) Enum.Parse(typeof(PrintingPermissionLevel), value); } else { level = PrintingPermissionLevel.NoPrinting; } } // Convert this permissions object into an XML value. public override SecurityElement ToXml() { SecurityElement element; element = new SecurityElement("IPermission"); element.AddAttribute ("class", SecurityElement.Escape(typeof(PrintingPermission). AssemblyQualifiedName)); element.AddAttribute("version", "1"); if(level != PrintingPermissionLevel.NoPrinting) { element.AddAttribute("Level", level.ToString()); } else if(state == PermissionState.Unrestricted) { element.AddAttribute("Unrestricted", "true"); } return element; } // Implement the IPermission interface. public override IPermission Copy() { if(level != PrintingPermissionLevel.NoPrinting) { return new PrintingPermission(level); } else { return new PrintingPermission(state); } } public override IPermission Intersect(IPermission target) { PrintingPermissionLevel newLevel; if(target == null) { return target; } else if(!(target is PrintingPermission)) { throw new ArgumentException(S._("Arg_PermissionMismatch")); } else if(((PrintingPermission)target).IsUnrestricted()) { if(IsUnrestricted()) { return Copy(); } else { newLevel = level; } } else if(IsUnrestricted()) { newLevel = ((PrintingPermission)target).level; } else { newLevel = ((PrintingPermission)target).level; if(newLevel > level) { newLevel = level; } } if(newLevel == PrintingPermissionLevel.NoPrinting) { return null; } else { return new PrintingPermission(newLevel); } } public override bool IsSubsetOf(IPermission target) { if(target == null) { return (level == PrintingPermissionLevel.NoPrinting); } else if(!(target is PrintingPermission)) { throw new ArgumentException (S._("Arg_PermissionMismatch")); } else if(((PrintingPermission)target).IsUnrestricted()) { return true; } else if(IsUnrestricted()) { return false; } else { return (level <= ((PrintingPermission)target).level); } } public override IPermission Union(IPermission target) { if(target == null) { return Copy(); } else if(!(target is PrintingPermission)) { throw new ArgumentException (S._("Arg_PermissionMismatch")); } else if(IsUnrestricted() || ((PrintingPermission)target).IsUnrestricted()) { return new PrintingPermission (PermissionState.Unrestricted); } else { PrintingPermissionLevel newLevel; newLevel = ((PrintingPermission)target).level; if(newLevel < level) { newLevel = level; } return new PrintingPermission(newLevel); } } // Determine if this object has unrestricted permissions. #if !ECMA_COMPAT public bool IsUnrestricted() { return (state == PermissionState.Unrestricted); } #else private bool IsUnrestricted() { return (state == PermissionState.Unrestricted); } #endif // Get or set the level on this permissions object. public PrintingPermissionLevel Level { get { return level; } set { level = value; } } }; // class PrintingPermission #endif // CONFIG_PERMISSIONS }; // namespace System.Drawing.Printing
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; namespace Orleans.Runtime { internal class MessagingTrace : DiagnosticListener, ILogger { public const string Category = "Orleans.Messaging"; public const string CreateMessageEventName = Category + ".CreateMessage"; public const string SendMessageEventName = Category + ".Outbound.Send"; public const string IncomingMessageAgentReceiveMessageEventName = Category + ".IncomingMessageAgent.Receive"; public const string DispatcherReceiveMessageEventName = Category + ".Dispatcher.Receive"; public const string DropExpiredMessageEventName = Category + ".Drop.Expired"; public const string DropSendingMessageEventName = Category + ".Drop.Sending"; public const string DropBlockedApplicationMessageEventName = Category + ".Drop.Blocked"; public const string EnqueueInboundMessageEventName = Category + ".Inbound.Enqueue"; public const string DequeueInboundMessageEventName = Category + ".Inbound.Dequeue"; public const string ScheduleMessageEventName = Category + ".Schedule"; public const string EnqueueMessageOnActivationEventName = Category + ".Activation.Enqueue"; public const string InvokeMessageEventName = Category + ".Invoke"; public const string RejectSendMessageToDeadSiloEventName = Category + ".Reject.TargetDead"; private static readonly Action<ILogger, Message, MessagingStatisticsGroup.Phase, Exception> LogDropExpiredMessage = LoggerMessage.Define<Message, MessagingStatisticsGroup.Phase>( LogLevel.Warning, new EventId((int)ErrorCode.Messaging_DroppingExpiredMessage, DropExpiredMessageEventName), "Dropping expired message {Message} at phase {Phase}"); private static readonly Action<ILogger, Message, Exception> LogDropBlockedApplicationMessage = LoggerMessage.Define<Message>( LogLevel.Warning, new EventId((int)ErrorCode.Messaging_DroppingBlockedMessage, DropBlockedApplicationMessageEventName), "Dropping message {Message} since this silo is blocking application messages"); private static readonly Action<ILogger, Message, Exception> LogEnqueueInboundMessage = LoggerMessage.Define<Message>( LogLevel.Trace, new EventId((int)ErrorCode.Messaging_Inbound_Enqueue, EnqueueInboundMessageEventName), "Enqueueing inbound message {Message}"); private static readonly Action<ILogger, Message, Exception> LogDequeueInboundMessage = LoggerMessage.Define<Message>( LogLevel.Trace, new EventId((int)ErrorCode.Messaging_Inbound_Dequeue, DequeueInboundMessageEventName), "Dequeueing inbound message {Message}"); private static readonly Action<ILogger, SiloAddress, Message, string, Exception> LogSiloDropSendingMessage = LoggerMessage.Define<SiloAddress, Message, string>( LogLevel.Warning, new EventId((int)ErrorCode.Messaging_OutgoingMS_DroppingMessage, DropSendingMessageEventName), "Silo {SiloAddress} is dropping message {Message}. Reason: {Reason}"); private static readonly Action<ILogger, SiloAddress, SiloAddress, Message, Exception> LogRejectSendMessageToDeadSilo = LoggerMessage.Define<SiloAddress, SiloAddress, Message>( LogLevel.Information, new EventId((int)ErrorCode.MessagingSendingRejection, RejectSendMessageToDeadSiloEventName), "Silo {SiloAddress} is rejecting message to known-dead silo {DeadSilo}: {Message}"); private readonly ILogger log; public MessagingTrace(ILoggerFactory loggerFactory) : base(Category) { this.log = loggerFactory.CreateLogger(Category); } public void OnSendMessage(Message message) { if (this.IsEnabled(SendMessageEventName)) { this.Write(SendMessageEventName, message); } } public void OnIncomingMessageAgentReceiveMessage(Message message) { if (this.IsEnabled(IncomingMessageAgentReceiveMessageEventName)) { this.Write(IncomingMessageAgentReceiveMessageEventName, message); } OrleansIncomingMessageAgentEvent.Log.ReceiveMessage(message); MessagingProcessingStatisticsGroup.OnImaMessageReceived(message); } public void OnDispatcherReceiveMessage(Message message) { if (this.IsEnabled(DispatcherReceiveMessageEventName)) { this.Write(DispatcherReceiveMessageEventName, message); } OrleansDispatcherEvent.Log.ReceiveMessage(message); MessagingProcessingStatisticsGroup.OnDispatcherMessageReceive(message); } internal void OnDropExpiredMessage(Message message, MessagingStatisticsGroup.Phase phase) { if (this.IsEnabled(DropExpiredMessageEventName)) { this.Write(DropExpiredMessageEventName, new { Message = message, Phase = phase }); } MessagingStatisticsGroup.OnMessageExpired(phase); LogDropExpiredMessage(this, message, phase, null); } internal void OnDropBlockedApplicationMessage(Message message) { if (this.IsEnabled(DropBlockedApplicationMessageEventName)) { this.Write(DropBlockedApplicationMessageEventName, message); } LogDropBlockedApplicationMessage(this, message, null); } internal void OnSiloDropSendingMessage(SiloAddress localSiloAddress, Message message, string reason) { MessagingStatisticsGroup.OnDroppedSentMessage(message); LogSiloDropSendingMessage(this, localSiloAddress, message, reason, null); } public void OnEnqueueInboundMessage(Message message) { if (this.IsEnabled(EnqueueInboundMessageEventName)) { this.Write(EnqueueInboundMessageEventName, message); } LogEnqueueInboundMessage(this, message, null); } public void OnDequeueInboundMessage(Message message) { if (this.IsEnabled(DequeueInboundMessageEventName)) { this.Write(DequeueInboundMessageEventName, message); } LogDequeueInboundMessage(this, message, null); } internal void OnCreateMessage(Message message) { if (this.IsEnabled(CreateMessageEventName)) { this.Write(CreateMessageEventName, message); } } public void OnScheduleMessage(Message message) { if (this.IsEnabled(ScheduleMessageEventName)) { this.Write(ScheduleMessageEventName, message); } } public void OnEnqueueMessageOnActivation(Message message, IGrainContext context) { if (this.IsEnabled(EnqueueMessageOnActivationEventName)) { this.Write(EnqueueMessageOnActivationEventName, message); } MessagingProcessingStatisticsGroup.OnImaMessageEnqueued(context); } public void OnInvokeMessage(Message message) { if (this.IsEnabled(InvokeMessageEventName)) { this.Write(InvokeMessageEventName, message); } } public void OnRejectSendMessageToDeadSilo(SiloAddress localSilo, Message message) { MessagingStatisticsGroup.OnFailedSentMessage(message); if (this.IsEnabled(RejectSendMessageToDeadSiloEventName)) { this.Write(RejectSendMessageToDeadSiloEventName, message); } LogRejectSendMessageToDeadSilo( this, localSilo, message.TargetSilo, message, null); } internal void OnSendRequest(Message message) { OrleansInsideRuntimeClientEvent.Log.SendRequest(message); } public IDisposable BeginScope<TState>(TState state) { return this.log.BeginScope(state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsEnabled(LogLevel logLevel) { return this.log.IsEnabled(logLevel); } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { this.log.Log(logLevel, eventId, state, exception, formatter); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// TollFreeResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry { public class TollFreeResource : Resource { private static Request BuildReadRequest(ReadTollFreeOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/AvailablePhoneNumbers/" + options.PathCountryCode + "/TollFree.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read TollFree parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TollFree </returns> public static ResourceSet<TollFreeResource> Read(ReadTollFreeOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<TollFreeResource>.FromJson("available_phone_numbers", response.Content); return new ResourceSet<TollFreeResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read TollFree parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TollFree </returns> public static async System.Threading.Tasks.Task<ResourceSet<TollFreeResource>> ReadAsync(ReadTollFreeOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<TollFreeResource>.FromJson("available_phone_numbers", response.Content); return new ResourceSet<TollFreeResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathCountryCode"> The ISO Country code of the country from which to read phone numbers </param> /// <param name="pathAccountSid"> The SID of the Account requesting the AvailablePhoneNumber resources </param> /// <param name="areaCode"> The area code of the phone numbers to read </param> /// <param name="contains"> The pattern on which to match phone numbers </param> /// <param name="smsEnabled"> Whether the phone numbers can receive text messages </param> /// <param name="mmsEnabled"> Whether the phone numbers can receive MMS messages </param> /// <param name="voiceEnabled"> Whether the phone numbers can receive calls. </param> /// <param name="excludeAllAddressRequired"> Whether to exclude phone numbers that require an Address </param> /// <param name="excludeLocalAddressRequired"> Whether to exclude phone numbers that require a local address </param> /// <param name="excludeForeignAddressRequired"> Whether to exclude phone numbers that require a foreign address /// </param> /// <param name="beta"> Whether to read phone numbers new to the Twilio platform </param> /// <param name="nearNumber"> Given a phone number, find a geographically close number within distance miles. /// (US/Canada only) </param> /// <param name="nearLatLong"> Given a latitude/longitude pair lat,long find geographically close numbers within /// distance miles. (US/Canada only) </param> /// <param name="distance"> The search radius, in miles, for a near_ query. (US/Canada only) </param> /// <param name="inPostalCode"> Limit results to a particular postal code. (US/Canada only) </param> /// <param name="inRegion"> Limit results to a particular region. (US/Canada only) </param> /// <param name="inRateCenter"> Limit results to a specific rate center, or given a phone number search within the same /// rate center as that number. (US/Canada only) </param> /// <param name="inLata"> Limit results to a specific local access and transport area. (US/Canada only) </param> /// <param name="inLocality"> Limit results to a particular locality </param> /// <param name="faxEnabled"> Whether the phone numbers can receive faxes </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TollFree </returns> public static ResourceSet<TollFreeResource> Read(string pathCountryCode, string pathAccountSid = null, int? areaCode = null, string contains = null, bool? smsEnabled = null, bool? mmsEnabled = null, bool? voiceEnabled = null, bool? excludeAllAddressRequired = null, bool? excludeLocalAddressRequired = null, bool? excludeForeignAddressRequired = null, bool? beta = null, Types.PhoneNumber nearNumber = null, string nearLatLong = null, int? distance = null, string inPostalCode = null, string inRegion = null, string inRateCenter = null, string inLata = null, string inLocality = null, bool? faxEnabled = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadTollFreeOptions(pathCountryCode){PathAccountSid = pathAccountSid, AreaCode = areaCode, Contains = contains, SmsEnabled = smsEnabled, MmsEnabled = mmsEnabled, VoiceEnabled = voiceEnabled, ExcludeAllAddressRequired = excludeAllAddressRequired, ExcludeLocalAddressRequired = excludeLocalAddressRequired, ExcludeForeignAddressRequired = excludeForeignAddressRequired, Beta = beta, NearNumber = nearNumber, NearLatLong = nearLatLong, Distance = distance, InPostalCode = inPostalCode, InRegion = inRegion, InRateCenter = inRateCenter, InLata = inLata, InLocality = inLocality, FaxEnabled = faxEnabled, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathCountryCode"> The ISO Country code of the country from which to read phone numbers </param> /// <param name="pathAccountSid"> The SID of the Account requesting the AvailablePhoneNumber resources </param> /// <param name="areaCode"> The area code of the phone numbers to read </param> /// <param name="contains"> The pattern on which to match phone numbers </param> /// <param name="smsEnabled"> Whether the phone numbers can receive text messages </param> /// <param name="mmsEnabled"> Whether the phone numbers can receive MMS messages </param> /// <param name="voiceEnabled"> Whether the phone numbers can receive calls. </param> /// <param name="excludeAllAddressRequired"> Whether to exclude phone numbers that require an Address </param> /// <param name="excludeLocalAddressRequired"> Whether to exclude phone numbers that require a local address </param> /// <param name="excludeForeignAddressRequired"> Whether to exclude phone numbers that require a foreign address /// </param> /// <param name="beta"> Whether to read phone numbers new to the Twilio platform </param> /// <param name="nearNumber"> Given a phone number, find a geographically close number within distance miles. /// (US/Canada only) </param> /// <param name="nearLatLong"> Given a latitude/longitude pair lat,long find geographically close numbers within /// distance miles. (US/Canada only) </param> /// <param name="distance"> The search radius, in miles, for a near_ query. (US/Canada only) </param> /// <param name="inPostalCode"> Limit results to a particular postal code. (US/Canada only) </param> /// <param name="inRegion"> Limit results to a particular region. (US/Canada only) </param> /// <param name="inRateCenter"> Limit results to a specific rate center, or given a phone number search within the same /// rate center as that number. (US/Canada only) </param> /// <param name="inLata"> Limit results to a specific local access and transport area. (US/Canada only) </param> /// <param name="inLocality"> Limit results to a particular locality </param> /// <param name="faxEnabled"> Whether the phone numbers can receive faxes </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TollFree </returns> public static async System.Threading.Tasks.Task<ResourceSet<TollFreeResource>> ReadAsync(string pathCountryCode, string pathAccountSid = null, int? areaCode = null, string contains = null, bool? smsEnabled = null, bool? mmsEnabled = null, bool? voiceEnabled = null, bool? excludeAllAddressRequired = null, bool? excludeLocalAddressRequired = null, bool? excludeForeignAddressRequired = null, bool? beta = null, Types.PhoneNumber nearNumber = null, string nearLatLong = null, int? distance = null, string inPostalCode = null, string inRegion = null, string inRateCenter = null, string inLata = null, string inLocality = null, bool? faxEnabled = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadTollFreeOptions(pathCountryCode){PathAccountSid = pathAccountSid, AreaCode = areaCode, Contains = contains, SmsEnabled = smsEnabled, MmsEnabled = mmsEnabled, VoiceEnabled = voiceEnabled, ExcludeAllAddressRequired = excludeAllAddressRequired, ExcludeLocalAddressRequired = excludeLocalAddressRequired, ExcludeForeignAddressRequired = excludeForeignAddressRequired, Beta = beta, NearNumber = nearNumber, NearLatLong = nearLatLong, Distance = distance, InPostalCode = inPostalCode, InRegion = inRegion, InRateCenter = inRateCenter, InLata = inLata, InLocality = inLocality, FaxEnabled = faxEnabled, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<TollFreeResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<TollFreeResource>.FromJson("available_phone_numbers", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<TollFreeResource> NextPage(Page<TollFreeResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<TollFreeResource>.FromJson("available_phone_numbers", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<TollFreeResource> PreviousPage(Page<TollFreeResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<TollFreeResource>.FromJson("available_phone_numbers", response.Content); } /// <summary> /// Converts a JSON string into a TollFreeResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> TollFreeResource object represented by the provided JSON </returns> public static TollFreeResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<TollFreeResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// A formatted version of the phone number /// </summary> [JsonProperty("friendly_name")] [JsonConverter(typeof(PhoneNumberConverter))] public Types.PhoneNumber FriendlyName { get; private set; } /// <summary> /// The phone number in E.164 format /// </summary> [JsonProperty("phone_number")] [JsonConverter(typeof(PhoneNumberConverter))] public Types.PhoneNumber PhoneNumber { get; private set; } /// <summary> /// The LATA of this phone number /// </summary> [JsonProperty("lata")] public string Lata { get; private set; } /// <summary> /// The locality or city of this phone number's location /// </summary> [JsonProperty("locality")] public string Locality { get; private set; } /// <summary> /// The rate center of this phone number /// </summary> [JsonProperty("rate_center")] public string RateCenter { get; private set; } /// <summary> /// The latitude of this phone number's location /// </summary> [JsonProperty("latitude")] public decimal? Latitude { get; private set; } /// <summary> /// The longitude of this phone number's location /// </summary> [JsonProperty("longitude")] public decimal? Longitude { get; private set; } /// <summary> /// The two-letter state or province abbreviation of this phone number's location /// </summary> [JsonProperty("region")] public string Region { get; private set; } /// <summary> /// The postal or ZIP code of this phone number's location /// </summary> [JsonProperty("postal_code")] public string PostalCode { get; private set; } /// <summary> /// The ISO country code of this phone number /// </summary> [JsonProperty("iso_country")] public string IsoCountry { get; private set; } /// <summary> /// The type of Address resource the phone number requires /// </summary> [JsonProperty("address_requirements")] public string AddressRequirements { get; private set; } /// <summary> /// Whether the phone number is new to the Twilio platform /// </summary> [JsonProperty("beta")] public bool? Beta { get; private set; } /// <summary> /// Whether a phone number can receive calls or messages /// </summary> [JsonProperty("capabilities")] public PhoneNumberCapabilities Capabilities { get; private set; } private TollFreeResource() { } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.IO; #if NETSTANDARD1_3 using System.Reflection; #endif using log4net.Util; namespace log4net.ObjectRenderer { /// <summary> /// Map class objects to an <see cref="IObjectRenderer"/>. /// </summary> /// <remarks> /// <para> /// Maintains a mapping between types that require special /// rendering and the <see cref="IObjectRenderer"/> that /// is used to render them. /// </para> /// <para> /// The <see cref="M:FindAndRender(object)"/> method is used to render an /// <c>object</c> using the appropriate renderers defined in this map. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class RendererMap { private readonly static Type declaringType = typeof(RendererMap); #region Member Variables private System.Collections.Hashtable m_map; private System.Collections.Hashtable m_cache = new System.Collections.Hashtable(); private static IObjectRenderer s_defaultRenderer = new DefaultRenderer(); #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> /// <remarks> /// <para> /// Default constructor. /// </para> /// </remarks> public RendererMap() { m_map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); } #endregion /// <summary> /// Render <paramref name="obj"/> using the appropriate renderer. /// </summary> /// <param name="obj">the object to render to a string</param> /// <returns>the object rendered as a string</returns> /// <remarks> /// <para> /// This is a convenience method used to render an object to a string. /// The alternative method <see cref="M:FindAndRender(object,TextWriter)"/> /// should be used when streaming output to a <see cref="TextWriter"/>. /// </para> /// </remarks> public string FindAndRender(object obj) { // Optimisation for strings string strData = obj as String; if (strData != null) { return strData; } StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); FindAndRender(obj, stringWriter); return stringWriter.ToString(); } /// <summary> /// Render <paramref name="obj"/> using the appropriate renderer. /// </summary> /// <param name="obj">the object to render to a string</param> /// <param name="writer">The writer to render to</param> /// <remarks> /// <para> /// Find the appropriate renderer for the type of the /// <paramref name="obj"/> parameter. This is accomplished by calling the /// <see cref="M:Get(Type)"/> method. Once a renderer is found, it is /// applied on the object <paramref name="obj"/> and the result is returned /// as a <see cref="string"/>. /// </para> /// </remarks> public void FindAndRender(object obj, TextWriter writer) { if (obj == null) { writer.Write(SystemInfo.NullText); } else { // Optimisation for strings string str = obj as string; if (str != null) { writer.Write(str); } else { // Lookup the renderer for the specific type try { Get(obj.GetType()).RenderObject(this, obj, writer); } catch(Exception ex) { // Exception rendering the object log4net.Util.LogLog.Error(declaringType, "Exception while rendering object of type ["+obj.GetType().FullName+"]", ex); // return default message string objectTypeName = ""; if (obj != null && obj.GetType() != null) { objectTypeName = obj.GetType().FullName; } writer.Write("<log4net.Error>Exception rendering object type ["+objectTypeName+"]"); if (ex != null) { string exceptionText = null; try { exceptionText = ex.ToString(); } catch { // Ignore exception } writer.Write("<stackTrace>" + exceptionText + "</stackTrace>"); } writer.Write("</log4net.Error>"); } } } } /// <summary> /// Gets the renderer for the specified object type /// </summary> /// <param name="obj">the object to lookup the renderer for</param> /// <returns>the renderer for <paramref name="obj"/></returns> /// <remarks> /// <param> /// Gets the renderer for the specified object type. /// </param> /// <param> /// Syntactic sugar method that calls <see cref="M:Get(Type)"/> /// with the type of the object parameter. /// </param> /// </remarks> public IObjectRenderer Get(Object obj) { if (obj == null) { return null; } else { return Get(obj.GetType()); } } /// <summary> /// Gets the renderer for the specified type /// </summary> /// <param name="type">the type to lookup the renderer for</param> /// <returns>the renderer for the specified type</returns> /// <remarks> /// <para> /// Returns the renderer for the specified type. /// If no specific renderer has been defined the /// <see cref="DefaultRenderer"/> will be returned. /// </para> /// </remarks> public IObjectRenderer Get(Type type) { if (type == null) { throw new ArgumentNullException("type"); } IObjectRenderer result = null; // Check cache result = (IObjectRenderer)m_cache[type]; if (result == null) { #if NETSTANDARD1_3 for (Type cur = type; cur != null; cur = cur.GetTypeInfo().BaseType) #else for(Type cur = type; cur != null; cur = cur.BaseType) #endif { // Search the type's interfaces result = SearchTypeAndInterfaces(cur); if (result != null) { break; } } // if not set then use the default renderer if (result == null) { result = s_defaultRenderer; } // Add to cache m_cache[type] = result; } return result; } /// <summary> /// Internal function to recursively search interfaces /// </summary> /// <param name="type">the type to lookup the renderer for</param> /// <returns>the renderer for the specified type</returns> private IObjectRenderer SearchTypeAndInterfaces(Type type) { IObjectRenderer r = (IObjectRenderer)m_map[type]; if (r != null) { return r; } else { foreach(Type t in type.GetInterfaces()) { r = SearchTypeAndInterfaces(t); if (r != null) { return r; } } } return null; } /// <summary> /// Get the default renderer instance /// </summary> /// <value>the default renderer</value> /// <remarks> /// <para> /// Get the default renderer /// </para> /// </remarks> public IObjectRenderer DefaultRenderer { get { return s_defaultRenderer; } } /// <summary> /// Clear the map of renderers /// </summary> /// <remarks> /// <para> /// Clear the custom renderers defined by using /// <see cref="Put"/>. The <see cref="DefaultRenderer"/> /// cannot be removed. /// </para> /// </remarks> public void Clear() { m_map.Clear(); m_cache.Clear(); } /// <summary> /// Register an <see cref="IObjectRenderer"/> for <paramref name="typeToRender"/>. /// </summary> /// <param name="typeToRender">the type that will be rendered by <paramref name="renderer"/></param> /// <param name="renderer">the renderer for <paramref name="typeToRender"/></param> /// <remarks> /// <para> /// Register an object renderer for a specific source type. /// This renderer will be returned from a call to <see cref="M:Get(Type)"/> /// specifying the same <paramref name="typeToRender"/> as an argument. /// </para> /// </remarks> public void Put(Type typeToRender, IObjectRenderer renderer) { m_cache.Clear(); if (typeToRender == null) { throw new ArgumentNullException("typeToRender"); } if (renderer == null) { throw new ArgumentNullException("renderer"); } m_map[typeToRender] = renderer; } } }
// 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> /// Dictionary operations. /// </summary> public partial class Dictionary : IServiceOperations<AutoRestComplexTestService>, IDictionary { /// <summary> /// Initializes a new instance of the Dictionary class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Dictionary(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 with dictionary property /// </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<DictionaryWrapper>> 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/dictionary/typed/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<DictionaryWrapper>(); _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<DictionaryWrapper>(_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 with dictionary property /// </summary> /// <param name='defaultProgram'> /// </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(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { DictionaryWrapper complexBody = new DictionaryWrapper(); if (defaultProgram != null) { complexBody.DefaultProgram = defaultProgram; } // 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/dictionary/typed/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; } /// <summary> /// Get complex types with dictionary property which is empty /// </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<DictionaryWrapper>> GetEmptyWithHttpMessagesAsync(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, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new 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<DictionaryWrapper>(); _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<DictionaryWrapper>(_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 with dictionary property which is empty /// </summary> /// <param name='defaultProgram'> /// </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> PutEmptyWithHttpMessagesAsync(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { DictionaryWrapper complexBody = new DictionaryWrapper(); if (defaultProgram != null) { complexBody.DefaultProgram = defaultProgram; } // 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, "PutEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("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; } /// <summary> /// Get complex types with dictionary property which is null /// </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<DictionaryWrapper>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/null").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<DictionaryWrapper>(); _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<DictionaryWrapper>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get complex types with dictionary property while server doesn't provide a /// response payload /// </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<DictionaryWrapper>> GetNotProvidedWithHttpMessagesAsync(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, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/notprovided").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<DictionaryWrapper>(); _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<DictionaryWrapper>(_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; } } }
using System; using System.Xml; using System.Timers; using System.Collections.Generic; namespace SharpVectors.Dom.Svg { /// <summary> /// A key interface definition is the SVGSVGElement interface, which is the interface that corresponds to the 'svg' element. This interface contains various miscellaneous commonly-used utility methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices. /// SVGSVGElement extends ViewCSS and DocumentCSS to provide access to the computed values of properties and the override style sheet as described in DOM2. /// </summary> public sealed class SvgSvgElement : SvgTransformableElement, ISvgSvgElement { #region Private Fields private SvgTests svgTests; private ISvgAnimatedLength x; private ISvgAnimatedLength height; #endregion #region Constructors internal SvgSvgElement(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { svgExternalResourcesRequired = new SvgExternalResourcesRequired(this); svgFitToViewBox = new SvgFitToViewBox(this); svgTests = new SvgTests(this); currentTranslate = new SvgPoint(0, 0); } #endregion #region Public Properties public bool IsOuterMost { get { return (this.ParentNode is SvgDocument); } } #endregion #region Public Methods public void Resize() { // TODO: Invalidate! Fire SVGResize x = null; y = null; width = null; height = null; currentView = null; cachedViewBoxTransform = null; viewport = null; svgFitToViewBox = null; svgFitToViewBox = new SvgFitToViewBox(this); if (this == OwnerDocument.RootElement) { // TODO } else { (OwnerDocument.RootElement as SvgSvgElement).Resize(); } } #endregion #region ISvgElement Members /// <summary> /// Gets a value providing a hint on the rendering defined by this element. /// </summary> /// <value> /// An enumeration of the <see cref="SvgRenderingHint"/> specifying the rendering hint. /// This will always return <see cref="SvgRenderingHint.Containment"/> /// </value> public override SvgRenderingHint RenderingHint { get { return SvgRenderingHint.Containment; } } #endregion #region ISvgZoomAndPan Members public SvgZoomAndPanType ZoomAndPan { get { return CurrentView.ZoomAndPan; } set { } } #endregion #region ISvgSvgElement Members /// <summary> /// Corresponds to attribute x on the given 'svg' element. /// </summary> public ISvgAnimatedLength X { get { if (x == null) { x = new SvgAnimatedLength(this, "x", SvgLengthDirection.Horizontal, "0px"); } return x; } } private ISvgAnimatedLength y; /// <summary> /// Corresponds to attribute y on the given 'svg' element. /// </summary> public ISvgAnimatedLength Y { get { if (y == null) { y = new SvgAnimatedLength(this, "y", SvgLengthDirection.Vertical, "0px"); } return y; } } private string widthAsString { get { SvgWindow ownerWindow = (SvgWindow)((SvgDocument)OwnerDocument).Window; if (ownerWindow.ParentWindow == null) { return GetAttribute("width").Trim(); } else { return String.Empty; } } } private ISvgAnimatedLength width; /// <summary> /// Corresponds to attribute width on the given 'svg' element. /// </summary> public ISvgAnimatedLength Width { get { if (width == null) { width = new SvgAnimatedLength(this, "width", SvgLengthDirection.Horizontal, widthAsString, "100%"); } return width; } } private string heightAsString { get { SvgWindow ownerWindow = (SvgWindow)((SvgDocument)OwnerDocument).Window; if (ownerWindow.ParentWindow == null) { return GetAttribute("height").Trim(); } else { return ""; } } } /// <summary> /// Corresponds to attribute height on the given 'svg' element. /// </summary> public ISvgAnimatedLength Height { get { if (height == null) { height = new SvgAnimatedLength(this, "height", SvgLengthDirection.Vertical, heightAsString, "100%"); } return height; } } /// <summary> /// Corresponds to attribute contentScriptType on the given 'svg' element /// </summary> /// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR: Raised on an attempt to change the value of a readonly attribute.</exception> public string ContentScriptType { get { return GetAttribute("contentScriptType"); } set { SetAttribute("contentScriptType", value); } } /// <summary> /// Corresponds to attribute contentStyleType on the given 'svg' element. /// </summary> /// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR: Raised on an attempt to change the value of a readonly attribute.</exception> public string ContentStyleType { get { return GetAttribute("contentStyleType"); } set { SetAttribute("contentStyleType", value); } } private double getViewportProp(string propertyName, string inValue, double calcParentVP, double defaultValue, SvgLengthDirection dir) { double ret; inValue = inValue.Trim(); if (inValue.Length > 0) { if (inValue.EndsWith("%")) { double perc = SvgNumber.ParseNumber(inValue.Substring(0, inValue.Length - 1)) / 100; ret = calcParentVP * perc; } else { ret = new SvgLength(this, propertyName, dir, inValue, String.Empty).Value; } } else ret = defaultValue; return ret; } private ISvgRect viewport; /// <summary> /// The position and size of the viewport (implicit or explicit) that corresponds to this 'svg' element. When the user agent is actually rendering the content, then the position and size values represent the actual values when rendering. The position and size values are unitless values in the coordinate system of the parent element. If no parent element exists (i.e., 'svg' element represents the root of the document tree), if this SVG document is embedded as part of another document (e.g., via the HTML 'object' element), then the position and size are unitless values in the coordinate system of the parent document. (If the parent uses CSS or XSL layout, then unitless values represent pixel units for the current CSS or XSL viewport, as described in the CSS2 specification.) If the parent element does not have a coordinate system, then the user agent should provide reasonable default values for this attribute. /// The object itself and its contents are both readonly. /// </summary> public ISvgRect Viewport { get { if (viewport == null) { double calcParentVPWidth = (ViewportElement == null) ? OwnerDocument.Window.InnerWidth : ((ISvgFitToViewBox)ViewportElement).ViewBox.AnimVal.Width; double calcParentVPHeight = (ViewportElement == null) ? OwnerDocument.Window.InnerHeight : ((ISvgFitToViewBox)ViewportElement).ViewBox.AnimVal.Height; double x = getViewportProp("x", GetAttribute("x"), calcParentVPWidth, 0, SvgLengthDirection.Horizontal); double y = getViewportProp("y", GetAttribute("y"), calcParentVPHeight, 0, SvgLengthDirection.Vertical); double width = getViewportProp("width", widthAsString, calcParentVPWidth, OwnerDocument.Window.InnerWidth, SvgLengthDirection.Horizontal); double height = getViewportProp("height", heightAsString, calcParentVPHeight, OwnerDocument.Window.InnerHeight, SvgLengthDirection.Vertical); viewport = new SvgRect(x, y, width, height); } return viewport; } } /// <summary> /// Size of a pixel units (as defined by CSS2) along the x-axis of the viewport, which represents a unit somewhere in the range of 70dpi to 120dpi, and, on systems that support this, might actually match the characteristics of the target medium. On systems where it is impossible to know the size of a pixel, a suitable default pixel size is provided. /// </summary> public float PixelUnitToMillimeterX { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Corresponding size of a pixel unit along the y-axis of the viewport. /// </summary> public float PixelUnitToMillimeterY { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// User interface (UI) events in DOM Level 2 indicate the screen positions at which the given UI event occurred. When the user agent actually knows the physical size of a "screen unit", this attribute will express that information; otherwise, user agents will provide a suitable default value such as .28mm. /// </summary> public float ScreenPixelToMillimeterX { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Corresponding size of a screen pixel along the y-axis of the viewport. /// </summary> public float ScreenPixelToMillimeterY { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// The initial view (i.e., before magnification and panning) of the current innermost SVG /// document fragment can be either the "standard" view (i.e., based on attributes on /// the 'svg' element such as fitBoxToViewport) or to a "custom" view (i.e., a hyperlink /// into a particular 'view' or other element - see Linking into SVG content: URI /// fragments and SVG views). If the initial view is the "standard" view, then this /// attribute is false. If the initial view is a "custom" view, then this attribute is /// true. /// </summary> /// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR: Raised on an attempt to change the value of a readonly attribute.</exception> public bool UseCurrentView { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// The definition of the initial view (i.e., before magnification and panning) of the current innermost SVG document fragment. The meaning depends on the situation: /// * If the initial view was a "standard" view, then: /// o the values for viewBox, preserveAspectRatio and zoomAndPan within currentView will match the values for the corresponding DOM attributes that are on SVGSVGElement directly /// o the values for transform and viewTarget within currentView will be null /// * If the initial view was a link into a 'view' element, then: /// o the values for viewBox, preserveAspectRatio and zoomAndPan within currentView will correspond to the corresponding attributes for the given 'view' element /// o the values for transform and viewTarget within currentView will be null /// * If the initial view was a link into another element (i.e., other than a 'view'), then: /// o the values for viewBox, preserveAspectRatio and zoomAndPan within currentView will match the values for the corresponding DOM attributes that are on SVGSVGElement directly for the closest ancestor 'svg' element /// o the values for transform within currentView will be null /// o the viewTarget within currentView will represent the target of the link /// * If the initial view was a link into the SVG document fragment using an SVG view specification fragment identifier (i.e., #svgView(...)), then: /// o the values for viewBox, preserveAspectRatio, zoomAndPan, transform and viewTarget within currentView will correspond to the values from the SVG view specification fragment identifier /// The object itself and its contents are both readonly. /// </summary> private ISvgViewSpec currentView = null; public ISvgViewSpec CurrentView { get { if (currentView == null) currentView = new SvgViewSpec(this) as ISvgViewSpec; // For now, we only return the "standard" view. return currentView; } } private float currentScale = 1; /// <summary> /// This attribute indicates the current scale factor relative to the initial view to take into account user magnification and panning operations, as described under Magnification and panning. DOM attributes currentScale and currentTranslate are equivalent to the 2x3 matrix [a b c d e f] = [currentScale 0 0 currentScale currentTranslate.x currentTranslate.y]. If "magnification" is enabled (i.e., zoomAndPan="magnify"), then the effect is as if an extra transformation were placed at the outermost level on the SVG document fragment (i.e., outside the outermost 'svg' element). /// </summary> /// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR: Raised on an attempt to change the value of a readonly attribute</exception> public float CurrentScale { get { if (this == OwnerDocument.RootElement) return currentScale; else return OwnerDocument.RootElement.CurrentScale; } set { if (this == OwnerDocument.RootElement) { // TODO: Invalidate! Fire OnZoom currentView = null; currentScale = value; cachedViewBoxTransform = null; viewport = null; width = null; height = null; x = null; y = null; svgFitToViewBox = new SvgFitToViewBox(this); } else OwnerDocument.RootElement.CurrentScale = value; } } private ISvgMatrix cachedViewBoxTransform = null; /// <summary> /// This function is super useful, calculates out the transformation matrix /// (i.e., scale and translate) of the viewport to user space. /// </summary> /// <returns>A Matrix which has the translate and scale portions set.</returns> public ISvgMatrix ViewBoxTransform { // TODO: This needs to be cached... need to handle changes to // parent width or height or viewbox changes (in the case of percents) // x,y,width,height,viewBox,preserveAspectRatio changes get { if (cachedViewBoxTransform == null) { ISvgMatrix matrix = CreateSvgMatrix(); SvgDocument doc = (SvgDocument)OwnerDocument; double x = 0; double y = 0; double w = 0; double h = 0; double attrWidth = Width.AnimVal.Value; double attrHeight = Height.AnimVal.Value; if (this != doc.RootElement) { // X and Y on the root <svg> have no meaning matrix = matrix.Translate(X.AnimVal.Value, Y.AnimVal.Value); } // Apply the viewBox viewport if (HasAttribute("viewBox")) { ISvgRect r = CurrentView.ViewBox.AnimVal; x += -r.X; y += -r.Y; w = r.Width; h = r.Height; if (w < 0 || h < 0) throw new SvgException(SvgExceptionType.SvgInvalidValueErr, "Negative values are not permitted for viewbox width or height"); } else { // This will result in a 1/1 scale. w = attrWidth; h = attrHeight; } double x_ratio = attrWidth / w; double y_ratio = attrHeight / h; ISvgPreserveAspectRatio par = CurrentView.PreserveAspectRatio.AnimVal; if (par.Align == SvgPreserveAspectRatioType.None) { matrix = matrix.ScaleNonUniform(x_ratio, y_ratio); } else { // uniform scaling if (par.MeetOrSlice == SvgMeetOrSlice.Meet) x_ratio = Math.Min(x_ratio, y_ratio); else x_ratio = Math.Max(x_ratio, y_ratio); double x_trans = 0; double x_diff = attrWidth - (x_ratio * w); double y_trans = 0; double y_diff = attrHeight - (x_ratio * h); if (par.Align == SvgPreserveAspectRatioType.XMidYMax || par.Align == SvgPreserveAspectRatioType.XMidYMid || par.Align == SvgPreserveAspectRatioType.XMidYMin) { // align to the Middle X x_trans = x_diff / 2; } else if (par.Align == SvgPreserveAspectRatioType.XMaxYMax || par.Align == SvgPreserveAspectRatioType.XMaxYMid || par.Align == SvgPreserveAspectRatioType.XMaxYMin) { // align to the right X x_trans = x_diff; } if (par.Align == SvgPreserveAspectRatioType.XMaxYMid || par.Align == SvgPreserveAspectRatioType.XMidYMid || par.Align == SvgPreserveAspectRatioType.XMinYMid) { // align to the middle Y y_trans = y_diff / 2; } else if (par.Align == SvgPreserveAspectRatioType.XMaxYMax || par.Align == SvgPreserveAspectRatioType.XMidYMax || par.Align == SvgPreserveAspectRatioType.XMinYMax) { // align to the bottom Y y_trans = y_diff; } matrix = matrix.Translate(x_trans, y_trans); matrix = matrix.Scale(x_ratio); } // Translate for min-x and min-y matrix = matrix.Translate(x, y); // Handle currentSranslate and currentScale if (this == OwnerDocument.RootElement) { matrix = matrix.Translate(this.currentTranslate.X, this.currentTranslate.Y); matrix = matrix.Scale(this.currentScale); } // Set the cache cachedViewBoxTransform = matrix; } return cachedViewBoxTransform; } } private ISvgPoint currentTranslate; /// <summary> /// The corresponding translation factor that takes into account user "magnification". /// </summary> public ISvgPoint CurrentTranslate { get { if (this == OwnerDocument.RootElement) { if (currentTranslate == null) { currentTranslate = CreateSvgPoint(); } return currentTranslate; } else return OwnerDocument.RootElement.CurrentTranslate; } } private List<Timer> redrawTimers = new List<Timer>(); public void RedrawTimerElapsed(object source, ElapsedEventArgs args) { UnsuspendRedraw(((Timer)source).GetHashCode()); } /// <summary> /// Takes a time-out value which indicates that redraw shall not occur until: (a) the /// corresponding unsuspendRedraw(suspend_handle_id) call has been made, (b) an /// unsuspendRedrawAll() call has been made, or (c) its timer has timed out. In /// environments that do not support interactivity (e.g., print media), then redraw shall /// not be suspended. suspend_handle_id = suspendRedraw(max_wait_milliseconds) and /// unsuspendRedraw(suspend_handle_id) must be packaged as balanced pairs. When you /// want to suspend redraw actions as a collection of SVG DOM changes occur, then /// precede the changes to the SVG DOM with a method call similar to /// suspend_handle_id = suspendRedraw(max_wait_milliseconds) and follow the changes with /// a method call similar to unsuspendRedraw(suspend_handle_id). Note that multiple /// suspendRedraw calls can be used at once and that each such method call is treated /// independently of the other suspendRedraw method calls. /// </summary> /// <param name="max_wait_milliseconds">The amount of time in milliseconds to hold off /// before redrawing the device. Values greater than 60 seconds will be truncated /// down to 60 seconds.</param> /// <returns>A number which acts as a unique identifier for the given suspendRedraw() call. This value must be passed as the parameter to the corresponding unsuspendRedraw() method call.</returns> public int SuspendRedraw(int maxWaitMilliseconds) { if (maxWaitMilliseconds > 60000) maxWaitMilliseconds = 60000; Timer t = new Timer(maxWaitMilliseconds); t.AutoReset = false; t.Elapsed += new ElapsedEventHandler(this.RedrawTimerElapsed); t.Enabled = true; redrawTimers.Add(t); return t.GetHashCode(); } /// <summary> /// Cancels a specified suspendRedraw() by providing a unique suspend_handle_id. /// </summary> /// <param name="suspend_handle_id">A number which acts as a unique identifier for the desired suspendRedraw() call. The number supplied must be a value returned from a previous call to suspendRedraw()</param> /// <exception cref="DomException">This method will raise a DOMException with value NOT_FOUND_ERR if an invalid value (i.e., no such suspend_handle_id is active) for suspend_handle_id is provided.</exception> public void UnsuspendRedraw(int suspendHandleId) { Timer timer = null; foreach (Timer t in redrawTimers) { if (t.GetHashCode() == suspendHandleId) { timer = t; break; } } if (timer == null) throw new DomException(DomExceptionType.NotFoundErr, "Invalid handle submitted to unsuspendRedraw"); timer.Enabled = false; redrawTimers.Remove(timer); if (OwnerDocument.Window.Renderer.InvalidRect != SvgRectF.Empty) OwnerDocument.Window.Renderer.Render((ISvgDocument)OwnerDocument); } /// <summary> /// Cancels all currently active suspendRedraw() method calls. This method is most /// useful /// at the very end of a set of SVG DOM calls to ensure that all pending suspendRedraw() /// method calls have been cancelled. /// </summary> public void UnsuspendRedrawAll() { foreach (Timer t in redrawTimers) { t.Enabled = false; } redrawTimers.Clear(); if (OwnerDocument.Window.Renderer.InvalidRect != SvgRectF.Empty) OwnerDocument.Window.Renderer.Render((ISvgDocument)OwnerDocument); } /// <summary> /// In rendering environments supporting interactivity, forces the user agent to /// immediately redraw all regions of the viewport that require updating. /// </summary> public void ForceRedraw() { OwnerDocument.Window.Renderer.InvalidRect = SvgRectF.Empty; OwnerDocument.Window.Renderer.Render((ISvgDocument)OwnerDocument); } /// <summary> /// Suspends (i.e., pauses) all currently running animations that are defined within the /// SVG document fragment corresponding to this 'svg' element, causing the animation clock /// corresponding to this document fragment to stand still until it is unpaused. /// </summary> public void PauseAnimations() { throw new NotImplementedException(); } /// <summary> /// Unsuspends (i.e., unpauses) currently running animations that are defined within the /// SVG document fragment, causing the animation clock to continue from the time at which /// it was suspended. /// </summary> public void UnpauseAnimations() { throw new NotImplementedException(); } /// <summary> /// Returns true if this SVG document fragment is in a paused state /// </summary> /// <returns>Boolean indicating whether this SVG document fragment is in a paused /// state.</returns> public bool AnimationsPaused() { throw new NotImplementedException(); } /// <summary> /// The current time in seconds relative to the start time for the current SVG document /// fragment. /// </summary> public float CurrentTime { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Returns the list of graphics elements whose rendered content intersects the supplied /// rectangle, honoring the 'pointer-events' property value on each candidate graphics /// element. /// </summary> /// <param name="rect">The test rectangle. The values are in the initial coordinate /// system for the current 'svg' element.</param> /// <param name="referenceElement">If not null, then only return elements whose drawing /// order has them below the given reference element.</param> /// <returns>A list of Elements whose content intersects the supplied rectangle.</returns> public XmlNodeList GetIntersectionList(ISvgRect rect, ISvgElement referenceElement) { throw new NotImplementedException(); } /// <summary> /// Returns the list of graphics elements whose rendered content is entirely contained /// within the supplied rectangle, honoring the 'pointer-events' property value on each /// candidate graphics element. /// </summary> /// <param name="rect">The test rectangle. The values are in the initial coordinate system /// for the current 'svg' element.</param> /// <param name="referenceElement">If not null, then only return elements whose drawing /// order has them below the given reference element.</param> /// <returns>A list of Elements whose content is enclosed by the supplied /// rectangle.</returns> public XmlNodeList GetEnclosureList(ISvgRect rect, ISvgElement referenceElement) { throw new NotImplementedException(); } /// <summary> /// Returns true if the rendered content of the given element intersects the supplied /// rectangle, honoring the 'pointer-events' property value on each candidate graphics /// element. /// </summary> /// <param name="element">The element on which to perform the given test.</param> /// <param name="rect">The test rectangle. The values are in the initial coordinate system /// for the current 'svg' element.</param> /// <returns>True or false, depending on whether the given element intersects the supplied /// rectangle.</returns> public bool CheckIntersection(ISvgElement element, ISvgRect rect) { throw new NotImplementedException(); } /// <summary> /// Returns true if the rendered content of the given element is entirely contained within /// the supplied rectangle, honoring the 'pointer-events' property value on each candidate /// graphics element. /// </summary> /// <param name="element">The element on which to perform the given test</param> /// <param name="rect">The test rectangle. The values are in the initial coordinate system /// for the current 'svg' element.</param> /// <returns>True or false, depending on whether the given element is enclosed by the /// supplied rectangle.</returns> public bool CheckEnclosure(ISvgElement element, ISvgRect rect) { throw new NotImplementedException(); } /// <summary> /// Unselects any selected objects, including any selections of text strings and type-in /// bars. /// </summary> public void DeselectAll() { throw new NotImplementedException(); } /// <summary> /// Creates an SVGNumber object outside of any document trees. The object is initialized /// to a value of zero. /// </summary> /// <returns>An SVGNumber object.</returns> public ISvgNumber CreateSvgNumber() { return new SvgNumber(0F); } /// <summary> /// Creates an SVGLength object outside of any document trees. The object is initialized /// to the value of 0 user units. /// </summary> /// <returns>An SVGLength object.</returns> public ISvgLength CreateSvgLength() { return new SvgLength(null, string.Empty, SvgLengthSource.String, SvgLengthDirection.Horizontal, "0"); } /// <summary> /// Creates an SVGAngle object outside of any document trees. The object is initialized to /// the value 0 degrees (unitless). /// </summary> /// <returns>An SVGAngle object.</returns> public ISvgAngle CreateSvgAngle() { return new SvgAngle("0", "0", false); } /// <summary> /// Creates an SVGPoint object outside of any document trees. The object is initialized to /// the point (0,0) in the user coordinate system. /// </summary> /// <returns>An SVGPoint object.</returns> public ISvgPoint CreateSvgPoint() { return new SvgPoint(0, 0); } /// <summary> /// Creates an SVGMatrix object outside of any document trees. The object is initialized /// to the identity matrix. /// </summary> /// <returns>An SVGMatrix object.</returns> public ISvgMatrix CreateSvgMatrix() { return new SvgMatrix(); } /// <summary> /// Creates an SVGRect object outside of any document trees. The object is initialized /// such that all values are set to 0 user units. /// </summary> /// <returns>An SVGRect object.</returns> public ISvgRect CreateSvgRect() { return new SvgRect(0, 0, 0, 0); } /// <summary> /// Creates an SVGTransform object outside of any document trees. The object is initialized /// to an identity matrix transform (SVG_TRANSFORM_MATRIX). /// </summary> /// <returns>An SVGTransform object.</returns> public ISvgTransform CreateSvgTransform() { return new SvgTransform(); } /// <summary> /// Creates an SVGTransform object outside of any document trees. The object is /// initialized to the given matrix transform (i.e., SVG_TRANSFORM_MATRIX). /// </summary> /// <param name="matrix">The transform matrix.</param> /// <returns>An SVGTransform object.</returns> public ISvgTransform CreateSvgTransformFromMatrix(ISvgMatrix matrix) { return new SvgTransform(matrix); } /// <summary> /// Searches this SVG document fragment (i.e., the search is restricted to a subset of the /// document tree) for an Element whose id is given by elementId. If an Element is found, /// that Element is returned. If no such element exists, returns null. Behavior is not /// defined if more than one element has this id. /// </summary> /// <param name="elementId">The unique id value for an element.</param> /// <returns>The matching element.</returns> public XmlElement GetElementById(string elementId) { return this.GetElementById(elementId); } #endregion #region ISvgFitToViewBox Members private SvgFitToViewBox svgFitToViewBox; public ISvgAnimatedRect ViewBox { get { return svgFitToViewBox.ViewBox; } } public ISvgAnimatedPreserveAspectRatio PreserveAspectRatio { get { return svgFitToViewBox.PreserveAspectRatio; } } #endregion #region ISvgExternalResourcesRequired Members private SvgExternalResourcesRequired svgExternalResourcesRequired; public ISvgAnimatedBoolean ExternalResourcesRequired { get { return svgExternalResourcesRequired.ExternalResourcesRequired; } } #endregion #region ISvgTests Members public ISvgStringList RequiredFeatures { get { return svgTests.RequiredFeatures; } } public ISvgStringList RequiredExtensions { get { return svgTests.RequiredExtensions; } } public ISvgStringList SystemLanguage { get { return svgTests.SystemLanguage; } } public bool HasExtension(string extension) { return svgTests.HasExtension(extension); } #endregion #region Update handling public override void HandleAttributeChange(XmlAttribute attribute) { if (attribute.NamespaceURI.Length == 0) { switch (attribute.LocalName) { case "x": case "y": case "width": case "height": case "viewBox": case "preserveAspectRatio": Resize(); break; } base.HandleAttributeChange(attribute); } } #endregion } }
namespace StockSharp.Designer { using System; using System.ComponentModel; using System.Linq; using Ecng.ComponentModel; using Ecng.Configuration; using Ecng.Serialization; using StockSharp.Algo.Storages; using StockSharp.Localization; using StockSharp.Studio.Core; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; [ExpandableObject] public class EmulationSettings : NotifiableObject, IPersistable { private MarketDataSettings _marketDataSettings; private DateTime _startDate; private DateTime _stopDate; private MarketDataSource _marketDataSource; private TimeSpan _candlesTimeFrame; private bool _generateDepths; private int _maxDepths; private int _maxVolume; private bool _debugLog; private bool _isSupportAtomicReRegister; private bool _matchOnTouch; private TimeSpan _emulatoinLatency; private bool _useMarketDepths; private StorageFormats _storageFormat; [DisplayNameLoc(LocalizedStrings.MarketDataKey)] [CategoryLoc(LocalizedStrings.Str1174Key)] [DescriptionLoc(LocalizedStrings.MarketDataStorageKey)] [PropertyOrder(11)] [Editor(typeof(MarketDataSettingsEditor), typeof(MarketDataSettingsEditor))] public MarketDataSettings MarketDataSettings { get { return _marketDataSettings; } set { _marketDataSettings = value; NotifyChanged("MarketDataSettings"); } } [DisplayNameLoc(LocalizedStrings.StorageFormatKey)] [CategoryLoc(LocalizedStrings.Str1174Key)] [PropertyOrder(12)] public StorageFormats StorageFormat { get { return _storageFormat; } set { _storageFormat = value; NotifyChanged("StorageFormat"); } } [DisplayNameLoc(LocalizedStrings.Str343Key)] [CategoryLoc(LocalizedStrings.Str1174Key)] [PropertyOrder(20)] public DateTime StartDate { get { return _startDate; } set { _startDate = value; NotifyChanged("StartDate"); } } [DisplayNameLoc(LocalizedStrings.Str345Key)] [CategoryLoc(LocalizedStrings.Str1174Key)] [PropertyOrder(30)] public DateTime StopDate { get { return _stopDate; } set { _stopDate = value; NotifyChanged("StopDate"); } } [DisplayNameLoc(LocalizedStrings.DataTypeKey)] [CategoryLoc(LocalizedStrings.Str1174Key)] [PropertyOrder(40)] public MarketDataSource MarketDataSource { get { return _marketDataSource; } set { _marketDataSource = value; NotifyChanged("MarketDataSource"); } } [DisplayNameLoc(LocalizedStrings.Str1242Key)] [CategoryLoc(LocalizedStrings.Str1174Key)] [DescriptionLoc(LocalizedStrings.Str1188Key)] [PropertyOrder(50)] public TimeSpan CandlesTimeFrame { get { return _candlesTimeFrame; } set { _candlesTimeFrame = value; NotifyChanged("CandlesTimeFrame"); } } [DisplayNameLoc(LocalizedStrings.MarketDepthsKey)] [CategoryLoc(LocalizedStrings.Str1174Key)] [PropertyOrder(60)] public bool UseMarketDepths { get { return _useMarketDepths; } set { _useMarketDepths = value; NotifyChanged("UseMarketDepths"); } } [DisplayNameLoc(LocalizedStrings.XamlStr97Key)] [CategoryLoc(LocalizedStrings.Str1174Key)] [PropertyOrder(61)] public bool GenerateDepths { get { return _generateDepths; } set { _generateDepths = value; NotifyChanged("GenerateDepths"); } } [DisplayNameLoc(LocalizedStrings.Str1197Key)] [CategoryLoc(LocalizedStrings.Str1174Key)] [DescriptionLoc(LocalizedStrings.Str1198Key)] [PropertyOrder(70)] public int MaxDepths { get { return _maxDepths; } set { _maxDepths = value; NotifyChanged("MaxDepths"); } } [DisplayNameLoc(LocalizedStrings.XamlStr293Key)] [CategoryLoc(LocalizedStrings.Str1174Key)] [PropertyOrder(80)] public int MaxVolume { get { return _maxVolume; } set { _maxVolume = value; NotifyChanged("MaxVolume"); } } [DisplayName(@"MOVE")] [CategoryLoc(LocalizedStrings.Str1174Key)] [DescriptionLoc(LocalizedStrings.Str60Key)] [PropertyOrder(90)] public bool IsSupportAtomicReRegister { get { return _isSupportAtomicReRegister; } set { _isSupportAtomicReRegister = value; NotifyChanged("IsSupportAtomicReRegister"); } } [DisplayNameLoc(LocalizedStrings.Str1176Key)] [CategoryLoc(LocalizedStrings.Str1174Key)] [DescriptionLoc(LocalizedStrings.Str1177Key)] [PropertyOrder(91)] public bool MatchOnTouch { get { return _matchOnTouch; } set { _matchOnTouch = value; NotifyChanged("MatchOnTouch"); } } [DisplayNameLoc(LocalizedStrings.Str161Key)] [CategoryLoc(LocalizedStrings.Str1174Key)] [DescriptionLoc(LocalizedStrings.Str1184Key)] [PropertyOrder(92)] public TimeSpan EmulatoinLatency { get { return _emulatoinLatency; } set { _emulatoinLatency = value; NotifyChanged("EmulatoinLatency"); } } [DisplayNameLoc(LocalizedStrings.XamlStr117Key)] [CategoryLoc(LocalizedStrings.Str1174Key)] [PropertyOrder(100)] public bool DebugLog { get { return _debugLog; } set { _debugLog = value; NotifyChanged("DebugLog"); } } public EmulationSettings() { //DataPath = @"..\..\..\..\Samples\Testing\HistoryData\".ToFullPath(); StartDate = new DateTime(2012, 10, 1); StopDate = new DateTime(2012, 10, 25); MarketDataSource = MarketDataSource.Candles; CandlesTimeFrame = TimeSpan.FromMinutes(5); MaxDepths = 5; MaxVolume = 100; IsSupportAtomicReRegister = true; MatchOnTouch = false; EmulatoinLatency = TimeSpan.Zero; StorageFormat = StorageFormats.Binary; } #region IPersistable public void Load(SettingsStorage storage) { StartDate = storage.GetValue("StartDate", StartDate); StopDate = storage.GetValue("StopDate", StopDate); MarketDataSource = storage.GetValue("MarketDataSource", MarketDataSource); CandlesTimeFrame = storage.GetValue("CandlesTimeFrame", CandlesTimeFrame); UseMarketDepths = storage.GetValue("UseMarketDepths", UseMarketDepths); GenerateDepths = storage.GetValue("GenerateDepths", GenerateDepths); MaxDepths = storage.GetValue("MaxDepths", MaxDepths); MaxVolume = storage.GetValue("MaxVolume", MaxVolume); IsSupportAtomicReRegister = storage.GetValue("IsSupportAtomicReRegister", IsSupportAtomicReRegister); MatchOnTouch = storage.GetValue("MatchOnTouch", MatchOnTouch); EmulatoinLatency = storage.GetValue("EmulatoinLatency", EmulatoinLatency); DebugLog = storage.GetValue("DebugLog", DebugLog); var marketDataSettings = storage.GetValue("MarketDataSettings", Guid.Empty); if (marketDataSettings != Guid.Empty) MarketDataSettings = ConfigManager.GetService<MarketDataSettingsCache>().Settings.FirstOrDefault(s => s.Id == marketDataSettings); StorageFormat = storage.GetValue("StorageFormat", StorageFormat); } public void Save(SettingsStorage storage) { storage.SetValue("StartDate", StartDate); storage.SetValue("StopDate", StopDate); storage.SetValue("MarketDataSource", MarketDataSource); storage.SetValue("CandlesTimeFrame", CandlesTimeFrame); storage.SetValue("UseMarketDepths", UseMarketDepths); storage.SetValue("GenerateDepths", GenerateDepths); storage.SetValue("MaxDepths", MaxDepths); storage.SetValue("MaxVolume", MaxVolume); storage.SetValue("IsSupportAtomicReRegister", IsSupportAtomicReRegister); storage.SetValue("MatchOnTouch", MatchOnTouch); storage.SetValue("EmulatoinLatency", EmulatoinLatency); storage.SetValue("DebugLog", DebugLog); if (MarketDataSettings != null) storage.SetValue("MarketDataSettings", MarketDataSettings.Id); storage.SetValue("StorageFormat", StorageFormat); } #endregion public override string ToString() { return string.Empty; } } }
using System; using Windows.UI.Xaml; namespace WinRTXamlToolkit.Controls { /// <summary> /// Transition in which the old page is pushed off the screen by the new page moving into the screen /// </summary> public class PushTransition : PageTransition { private readonly Random _random = new Random(); /// <summary> /// Gets the page transition mode. /// </summary> /// <value> /// The page transition mode. /// </value> protected override PageTransitionMode Mode { get { return PageTransitionMode.Parallel; } } #region ForwardDirection /// <summary> /// ForwardDirection Dependency Property /// </summary> public static readonly DependencyProperty ForwardDirectionProperty = DependencyProperty.Register( "ForwardDirection", typeof(DirectionOfMotion), typeof(PushTransition), new PropertyMetadata(DirectionOfMotion.RightToLeft, OnForwardDirectionChanged)); /// <summary> /// Gets or sets the ForwardDirection property. This dependency property /// indicates the forward transition direction. /// </summary> public DirectionOfMotion ForwardDirection { get { return (DirectionOfMotion)GetValue(ForwardDirectionProperty); } set { SetValue(ForwardDirectionProperty, value); } } /// <summary> /// Handles changes to the ForwardDirection property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnForwardDirectionChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var target = (PushTransition)d; DirectionOfMotion oldForwardDirection = (DirectionOfMotion)e.OldValue; DirectionOfMotion newForwardDirection = target.ForwardDirection; target.OnForwardDirectionChanged(oldForwardDirection, newForwardDirection); } /// <summary> /// Provides derived classes an opportunity to handle changes /// to the ForwardDirection property. /// </summary> /// <param name="oldForwardDirection">The old ForwardDirection value</param> /// <param name="newForwardDirection">The new ForwardDirection value</param> protected virtual void OnForwardDirectionChanged( DirectionOfMotion oldForwardDirection, DirectionOfMotion newForwardDirection) { if (this.ForwardInAnimation != null) { ((SlideAnimation)this.ForwardInAnimation).Direction = newForwardDirection; } if (this.ForwardOutAnimation != null) { ((SlideAnimation)this.ForwardOutAnimation).Direction = newForwardDirection; } } #endregion #region BackwardDirection /// <summary> /// BackwardDirection Dependency Property /// </summary> public static readonly DependencyProperty BackwardDirectionProperty = DependencyProperty.Register( "BackwardDirection", typeof(DirectionOfMotion), typeof(PushTransition), new PropertyMetadata(DirectionOfMotion.LeftToRight, OnBackwardDirectionChanged)); /// <summary> /// Gets or sets the BackwardDirection property. This dependency property /// indicates the backward transition direction. /// </summary> public DirectionOfMotion BackwardDirection { get { return (DirectionOfMotion)GetValue(BackwardDirectionProperty); } set { SetValue(BackwardDirectionProperty, value); } } /// <summary> /// Handles changes to the BackwardDirection property. /// </summary> /// <param name="d"> /// The <see cref="DependencyObject"/> on which /// the property has changed value. /// </param> /// <param name="e"> /// Event data that is issued by any event that /// tracks changes to the effective value of this property. /// </param> private static void OnBackwardDirectionChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var target = (PushTransition)d; DirectionOfMotion oldBackwardDirection = (DirectionOfMotion)e.OldValue; DirectionOfMotion newBackwardDirection = target.BackwardDirection; target.OnBackwardDirectionChanged(oldBackwardDirection, newBackwardDirection); } /// <summary> /// Provides derived classes an opportunity to handle changes /// to the BackwardDirection property. /// </summary> /// <param name="oldBackwardDirection">The old BackwardDirection value</param> /// <param name="newBackwardDirection">The new BackwardDirection value</param> protected virtual void OnBackwardDirectionChanged( DirectionOfMotion oldBackwardDirection, DirectionOfMotion newBackwardDirection) { if (this.BackwardInAnimation != null) { ((SlideAnimation)this.BackwardInAnimation).Direction = newBackwardDirection; } if (this.BackwardOutAnimation != null) { ((SlideAnimation)this.BackwardOutAnimation).Direction = newBackwardDirection; } } #endregion /// <summary> /// Initializes a new instance of the <see cref="PushTransition"/> class. /// </summary> public PushTransition() { this.ForwardOutAnimation = new SlideAnimation { Direction = ForwardDirection, Mode = AnimationMode.Out }; this.ForwardInAnimation = new SlideAnimation { Direction = ForwardDirection, Mode = AnimationMode.In }; this.BackwardOutAnimation = new SlideAnimation { Direction = BackwardDirection, Mode = AnimationMode.Out }; this.BackwardInAnimation = new SlideAnimation { Direction = BackwardDirection, Mode = AnimationMode.In }; } /// <summary> /// Prepares the forward animations. /// </summary> /// <param name="previousPage">The previous page.</param> /// <param name="newPage">The new page.</param> protected override void PrepareForwardAnimations(DependencyObject previousPage, DependencyObject newPage) { base.PrepareForwardAnimations(previousPage, newPage); if (this.ForwardDirection == DirectionOfMotion.Random) { var randomDirection = (DirectionOfMotion)_random.Next(4); if (this.ForwardOutAnimation is SlideAnimation) { ((SlideAnimation)this.ForwardOutAnimation).Direction = randomDirection; } if (this.ForwardInAnimation is SlideAnimation) { ((SlideAnimation)this.ForwardInAnimation).Direction = randomDirection; } } //if (previousPage != null) // FrameworkElementExtensions.SetClipToBounds(previousPage, true); //if (newPage != null) // FrameworkElementExtensions.SetClipToBounds(newPage, true); } /// <summary> /// Prepares the backward animations. /// </summary> /// <param name="previousPage">The previous page.</param> /// <param name="newPage">The new page.</param> protected override void PrepareBackwardAnimations(DependencyObject previousPage, DependencyObject newPage) { base.PrepareBackwardAnimations(previousPage, newPage); if (this.BackwardDirection == DirectionOfMotion.Random) { var randomDirection = (DirectionOfMotion)_random.Next(4); if (this.BackwardOutAnimation is SlideAnimation) { ((SlideAnimation)this.BackwardOutAnimation).Direction = randomDirection; } if (this.BackwardInAnimation is SlideAnimation) { ((SlideAnimation)this.BackwardInAnimation).Direction = randomDirection; } } //if (previousPage != null) // FrameworkElementExtensions.SetClipToBounds(previousPage, true); //if (newPage != null) // FrameworkElementExtensions.SetClipToBounds(newPage, true); } /// <summary> /// Cleans up the backward animations. /// </summary> /// <param name="previousPage">The previous page.</param> /// <param name="newPage">The new page.</param> protected override void CleanupBackwardAnimations(DependencyObject previousPage, DependencyObject newPage) { base.CleanupBackwardAnimations(previousPage, newPage); //if (previousPage != null) // FrameworkElementExtensions.SetClipToBounds(previousPage, false); //if (newPage != null) // FrameworkElementExtensions.SetClipToBounds(newPage, false); } /// <summary> /// Cleans up the forward animations. /// </summary> /// <param name="previousPage">The previous page.</param> /// <param name="newPage">The new page.</param> protected override void CleanupForwardAnimations(DependencyObject previousPage, DependencyObject newPage) { base.CleanupForwardAnimations(previousPage, newPage); //if (previousPage != null) // FrameworkElementExtensions.SetClipToBounds(previousPage, false); //if (newPage != null) // FrameworkElementExtensions.SetClipToBounds(newPage, false); // TODO: Get the transitions container panel and clip that one for push transitions // TODO: Consider adding a fade in/out option to this transition } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Expressions { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; internal class DeserializerTransform<R> { delegate Expression NewObject(Type type, Type schemaType); delegate Expression NewContainer(Type type, Type schemaType, Expression count); readonly NewObject newObject; readonly NewContainer newContainer; readonly bool inlineNested; TypeAlias typeAlias; readonly Expression<Func<R, int, object>> deferredDeserialize; readonly List<Expression<Func<R, object>>> deserializeFuncs = new List<Expression<Func<R, object>>>(); readonly Dictionary<Type, int> deserializeIndex = new Dictionary<Type, int>(); readonly Stack<Type> inProgress = new Stack<Type>(); static readonly MethodInfo bondedConvert = Reflection.GenericMethodInfoOf((IBonded bonded) => bonded.Convert<object>()); static readonly MethodInfo bondedDeserialize = Reflection.GenericMethodInfoOf((IBonded bonded) => bonded.Deserialize<object>()); static readonly MethodInfo arrayResize = Reflection.GenericMethodInfoOf((object[] o) => Array.Resize(ref o, default(int))); static readonly ConstructorInfo arraySegmentCtor = typeof(ArraySegment<byte>).GetConstructor(typeof(byte[]), typeof(int), typeof(int)); static readonly MethodInfo bufferBlockCopy = Reflection.MethodInfoOf((byte[] a) => Buffer.BlockCopy(a, default(int), a, default(int), default(int))); public DeserializerTransform( Expression<Func<R, int, object>> deferredDeserialize, bool inlineNested = true, Expression<Func<Type, Type, object>> createObject = null, Expression<Func<Type, Type, int, object>> createContainer = null) { this.deferredDeserialize = deferredDeserialize; if (createObject != null) { newObject = (t1, t2) => Expression.Convert( Expression.Invoke( createObject, Expression.Constant(t1), Expression.Constant(t2)), t1); } else { newObject = (t1, t2) => New(t1, t2); } if (createContainer != null) { newContainer = (t1, t2, count) => Expression.Convert( Expression.Invoke( createContainer, Expression.Constant(t1), Expression.Constant(t2), count), t1); } else { newContainer = (t1, t2, count) => New(t1, t2, count); } this.inlineNested = inlineNested; } public IEnumerable<Expression<Func<R, object>>> Generate(IParser parser, Type type) { Audit.ArgNotNull(type, "type"); typeAlias = new TypeAlias(type); Deserialize(parser, null, type, type, true); return deserializeFuncs; } Expression Deserialize(IParser parser, Expression var, Type objectType, Type schemaType, bool initialize) { var inline = inlineNested && inProgress.Count != 0 && !inProgress.Contains(schemaType) && var != null; Expression body; inProgress.Push(schemaType); if (inline) { body = Struct(parser, var, schemaType, initialize); if (parser.ReaderParam != parser.ReaderValue) { body = Expression.Block( new[] { parser.ReaderParam }, Expression.Assign(parser.ReaderParam, Expression.Convert(parser.ReaderValue, parser.ReaderParam.Type)), body); } } else { int index; if (!deserializeIndex.TryGetValue(schemaType, out index)) { index = deserializeFuncs.Count; deserializeIndex[schemaType] = index; deserializeFuncs.Add(null); var result = Expression.Variable(objectType, objectType.Name); deserializeFuncs[index] = Expression.Lambda<Func<R, object>>( Expression.Block( new[] { result }, Struct(parser, result, schemaType, true), Expression.Convert(result, typeof(object))), parser.ReaderParam); } if (var == null) body = null; else body = Expression.Assign(var, Expression.Convert( Expression.Invoke( deferredDeserialize, parser.ReaderValue, Expression.Constant(index)), objectType)); } inProgress.Pop(); return body; } Expression Struct(IParser parser, Expression var, Type schemaType, bool initialize) { var body = new List<Expression>(); if (initialize) { body.Add(Expression.Assign(var, newObject(var.Type, schemaType))); } ITransform transform; if (parser.HierarchyDepth > schemaType.GetHierarchyDepth()) { // Parser inheritance hierarchy is deeper than the type we are deserializing. // Recurse until hierarchies align. transform = new Transform( Base: baseParser => Struct(baseParser, var, schemaType, initialize: false)); } else { var baseType = schemaType.GetBaseSchemaType(); transform = new Transform( Fields: from field in schemaType.GetSchemaFields() select new Field( Id: field.Id, Value: (fieldParser, fieldType) => FieldValue( fieldParser, DataExpression.PropertyOrField(var, field.Name), fieldType, field.GetSchemaType(), field.GetDefaultValue() == null), Omitted: () => field.GetModifier() == Modifier.Required ? ThrowExpression.RequiredFieldMissingException( field.DeclaringType.Name, Expression.Constant(field.Name)) : Expression.Empty()), Base: baseParser => baseType != null ? Struct(baseParser, Expression.Convert(var, baseType.GetObjectType()), baseType, initialize: false) : Expression.Empty()); } body.Add(parser.Apply(transform)); return Expression.Block(body); } Expression Nullable(IParser parser, Expression var, Type schemaType, bool initialize) { return parser.Container(schemaType.GetBondDataType(), (valueParser, valueType, next, count) => { var body = new List<Expression>(); if (initialize) body.Add(Expression.Assign(var, Expression.Default(var.Type))); body.Add(ControlExpression.While(next, Value(valueParser, var, valueType, schemaType, initialize: true))); return Expression.Block(body); }); } Expression Container(IParser parser, Expression container, Type schemaType, bool initialize) { var itemSchemaType = schemaType.GetValueType(); return parser.Container(itemSchemaType.GetBondDataType(), (valueParser, elementType, next, count) => { Expression addItem; ParameterExpression[] parameters; Expression beforeLoop = Expression.Empty(); Expression afterLoop = Expression.Empty(); if (schemaType.IsBondBlob()) { var blob = parser.Blob(count); if (blob != null) return typeAlias.Assign(container, blob); // Parser doesn't provide optimized read for blob so we will have to read byte-by-byte. var index = Expression.Variable(typeof(int), "index"); var array = Expression.Variable(typeof(byte[]), "array"); beforeLoop = Expression.Block( Expression.Assign(index, Expression.Constant(0)), Expression.Assign(array, Expression.NewArrayBounds(typeof(byte), count))); // If parser didn't provide real item count we may need to resize the array var newSize = Expression.Condition( Expression.GreaterThan(index, Expression.Constant(512)), Expression.Multiply(index, Expression.Constant(2)), Expression.Constant(1024)); addItem = Expression.Block( Expression.IfThen( Expression.GreaterThanOrEqual(index, Expression.ArrayLength(array)), Expression.Call(null, arrayResize.MakeGenericMethod(typeof(byte)), array, newSize)), valueParser.Scalar(elementType, BondDataType.BT_INT8, value => Expression.Assign( Expression.ArrayAccess(array, Expression.PostIncrementAssign(index)), Expression.Convert(value, typeof(byte))))); afterLoop = typeAlias.Assign( container, Expression.New(arraySegmentCtor, array, Expression.Constant(0), index)); parameters = new[] { index, array }; } else if (container.Type.IsArray) { var arrayElemType = container.Type.GetValueType(); var containerResizeMethod = arrayResize.MakeGenericMethod(arrayElemType); if (initialize) { beforeLoop = Expression.Assign(container, newContainer(container.Type, schemaType, count)); } if (arrayElemType == typeof(byte)) { var parseBlob = parser.Blob(count); if (parseBlob != null) { var blob = Expression.Variable(typeof(ArraySegment<byte>), "blob"); return Expression.Block( new[] { blob }, beforeLoop, Expression.Assign(blob, parseBlob), Expression.Call(null, bufferBlockCopy, new[] { Expression.Property(blob, "Array"), Expression.Property(blob, "Offset"), container, Expression.Constant(0), count })); } } var i = Expression.Variable(typeof(int), "i"); beforeLoop = Expression.Block( beforeLoop, Expression.Assign(i, Expression.Constant(0))); // Resize the array if we've run out of room var maybeResize = Expression.IfThen( Expression.Equal(i, Expression.ArrayLength(container)), Expression.Call( containerResizeMethod, container, Expression.Multiply( Expression.Condition( Expression.LessThan(i, Expression.Constant(32)), Expression.Constant(32), i), Expression.Constant(2)))); // Puts a single element into the array. addItem = Expression.Block( maybeResize, Value( valueParser, Expression.ArrayAccess(container, i), elementType, itemSchemaType, initialize: true), Expression.PostIncrementAssign(i)); // Expanding the array potentially leaves many blank // entries; this resize will get rid of them. afterLoop = Expression.IfThen( Expression.GreaterThan(Expression.ArrayLength(container), i), Expression.Call(containerResizeMethod, container, i)); parameters = new[] { i }; } else { var item = Expression.Variable(container.Type.GetValueType(), container + "_item"); if (initialize) { beforeLoop = Expression.Assign(container, newContainer(container.Type, schemaType, count)); } else { var capacity = container.Type.GetDeclaredProperty("Capacity", count.Type); if (capacity != null) { beforeLoop = Expression.Assign(Expression.Property(container, capacity), count); } } var add = container.Type.GetMethod(typeof(ICollection<>), "Add", item.Type); addItem = Expression.Block( Value(valueParser, item, elementType, itemSchemaType, initialize: true), Expression.Call(container, add, item)); parameters = new[] { item }; } return Expression.Block( parameters, beforeLoop, ControlExpression.While(next, addItem), afterLoop); }); } Expression Map(IParser parser, Expression map, Type schemaType, bool initialize) { var itemSchemaType = schemaType.GetKeyValueType(); return parser.Map(itemSchemaType.Key.GetBondDataType(), itemSchemaType.Value.GetBondDataType(), (keyParser, valueParser, keyType, valueType, nextKey, nextValue, count) => { Expression init = Expression.Empty(); var itemType = map.Type.GetKeyValueType(); var key = Expression.Variable(itemType.Key, map + "_key"); var value = Expression.Variable(itemType.Value, map + "_value"); if (initialize) { // TODO: should we use non-default Comparer init = Expression.Assign(map, newContainer(map.Type, schemaType, count)); } var add = map.Type.GetDeclaredProperty(typeof(IDictionary<,>), "Item", value.Type); Expression addItem = Expression.Block( Value(keyParser, key, keyType, itemSchemaType.Key, initialize: true), nextValue, Value(valueParser, value, valueType, itemSchemaType.Value, initialize: true), Expression.Assign(Expression.Property(map, add, new Expression[] { key }), value)); return Expression.Block( new [] { key, value }, init, ControlExpression.While(nextKey, addItem)); }); } Expression FieldValue(IParser parser, Expression var, Expression valueType, Type schemaType, bool initialize) { Expression body; if (schemaType.IsBondStruct() && var.Type.IsValueType()) { // Special handling for properties of struct types: we deserialize into // a temp variable and then assign the value to the property. var temp = Expression.Variable(var.Type, "temp"); body = Expression.Block( new[] { temp }, Value(parser, temp, valueType, schemaType, true), Expression.Assign(var, temp)); } else { body = Value(parser, var, valueType, schemaType, initialize); } if (schemaType.IsBondContainer() || schemaType.IsBondStruct() || schemaType.IsBondNullable()) { var expectedType = Expression.Constant(schemaType.GetBondDataType()); return PrunedExpression.IfThenElse( Expression.Equal(valueType, expectedType), body, ThrowExpression.InvalidTypeException(expectedType, valueType)); } return body; } Expression Value(IParser parser, Expression var, Expression valueType, Type schemaType, bool initialize) { if (schemaType.IsBondNullable()) return Nullable(parser, var, schemaType.GetValueType(), initialize); if (schemaType.IsBonded()) { var convert = bondedConvert.MakeGenericMethod(var.Type.GetValueType()); return parser.Bonded(value => Expression.Assign(var, Expression.Call(value, convert))); } if (schemaType.IsBondStruct()) { if (parser.IsBonded) { var deserialize = bondedDeserialize.MakeGenericMethod(schemaType); return parser.Bonded(value => Expression.Assign(var, Expression.Call(value, deserialize))); } return Deserialize(parser, var, var.Type, schemaType, initialize); } if (schemaType.IsBondMap()) return Map(parser, var, schemaType, initialize); if (schemaType.IsBondContainer()) return Container(parser, var, schemaType, initialize); return parser.Scalar(valueType, schemaType.GetBondDataType(), value => typeAlias.Assign(var, PrunedExpression.Convert(value, schemaType))); } static Expression New(Type type, Type schemaType, params Expression[] arguments) { if (schemaType.IsGenericType()) { schemaType = schemaType.GetGenericTypeDefinition().MakeGenericType(type.GetGenericArguments()); } else if (schemaType.IsArray) { var rank = schemaType.GetArrayRank(); schemaType = rank == 1 ? type.GetElementType().MakeArrayType() : type.GetElementType().MakeArrayType(rank); } var ctor = schemaType.GetConstructor(arguments.Select(a => a.Type).ToArray()); if (ctor != null) { return Expression.New(ctor, arguments); } return Expression.New(schemaType); } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace Discord { /// <summary> /// Represents a generic channel that can send and receive messages. /// </summary> public interface IMessageChannel : IChannel { /// <summary> /// Sends a message to this message channel. /// </summary> /// <example> /// <para>The following example sends a message with the current system time in RFC 1123 format to the channel and /// deletes itself after 5 seconds.</para> /// <code language="cs" region="SendMessageAsync" /// source="..\..\..\Discord.Net.Examples\Core\Entities\Channels\IMessageChannel.Examples.cs" /> /// </example> /// <param name="text">The message to be sent.</param> /// <param name="isTTS">Determines whether the message should be read aloud by Discord or not.</param> /// <param name="embed">The <see cref="Discord.EmbedType.Rich"/> <see cref="Embed"/> to be sent.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// </returns> Task<IUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null); /// <summary> /// Sends a file to this message channel with an optional caption. /// </summary> /// <example> /// <para>The following example uploads a local file called <c>wumpus.txt</c> along with the text /// <c>good discord boi</c> to the channel.</para> /// <code language="cs" region="SendFileAsync.FilePath" /// source="..\..\..\Discord.Net.Examples\Core\Entities\Channels\IMessageChannel.Examples.cs" /> /// <para>The following example uploads a local image called <c>b1nzy.jpg</c> embedded inside a rich embed to the /// channel.</para> /// <code language="cs" region="SendFileAsync.FilePath.EmbeddedImage" /// source="..\..\..\Discord.Net.Examples\Core\Entities\Channels\IMessageChannel.Examples.cs" /> /// </example> /// <remarks> /// This method sends a file as if you are uploading an attachment directly from your Discord client. /// <note> /// If you wish to upload an image and have it embedded in a <see cref="Discord.EmbedType.Rich"/> embed, /// you may upload the file and refer to the file with "attachment://filename.ext" in the /// <see cref="Discord.EmbedBuilder.ImageUrl"/>. See the example section for its usage. /// </note> /// </remarks> /// <param name="filePath">The file path of the file.</param> /// <param name="text">The message to be sent.</param> /// <param name="isTTS">Whether the message should be read aloud by Discord or not.</param> /// <param name="embed">The <see cref="Discord.EmbedType.Rich" /> <see cref="Embed" /> to be sent.</param> /// <param name="options">The options to be used when sending the request.</param> /// <param name="isSpoiler">Whether the message attachment should be hidden as a spoiler.</param> /// <returns> /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// </returns> Task<IUserMessage> SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false); /// <summary> /// Sends a file to this message channel with an optional caption. /// </summary> /// <example> /// <para>The following example uploads a streamed image that will be called <c>b1nzy.jpg</c> embedded inside a /// rich embed to the channel.</para> /// <code language="cs" region="SendFileAsync.FileStream.EmbeddedImage" /// source="..\..\..\Discord.Net.Examples\Core\Entities\Channels\IMessageChannel.Examples.cs" /> /// </example> /// <remarks> /// This method sends a file as if you are uploading an attachment directly from your Discord client. /// <note> /// If you wish to upload an image and have it embedded in a <see cref="Discord.EmbedType.Rich"/> embed, /// you may upload the file and refer to the file with "attachment://filename.ext" in the /// <see cref="Discord.EmbedBuilder.ImageUrl"/>. See the example section for its usage. /// </note> /// </remarks> /// <param name="stream">The <see cref="Stream" /> of the file to be sent.</param> /// <param name="filename">The name of the attachment.</param> /// <param name="text">The message to be sent.</param> /// <param name="isTTS">Whether the message should be read aloud by Discord or not.</param> /// <param name="embed">The <see cref="Discord.EmbedType.Rich"/> <see cref="Embed"/> to be sent.</param> /// <param name="options">The options to be used when sending the request.</param> /// <param name="isSpoiler">Whether the message attachment should be hidden as a spoiler.</param> /// <returns> /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// </returns> Task<IUserMessage> SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false); /// <summary> /// Gets a message from this message channel. /// </summary> /// <param name="id">The snowflake identifier of the message.</param> /// <param name="mode">The <see cref="CacheMode"/> that determines whether the object should be fetched from cache.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents an asynchronous get operation for retrieving the message. The task result contains /// the retrieved message; <c>null</c> if no message is found with the specified identifier. /// </returns> Task<IMessage> GetMessageAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// <summary> /// Gets the last N messages from this message channel. /// </summary> /// <remarks> /// <note type="important"> /// The returned collection is an asynchronous enumerable object; one must call /// <see cref="AsyncEnumerableExtensions.FlattenAsync{T}"/> to access the individual messages as a /// collection. /// </note> /// <note type="warning"> /// Do not fetch too many messages at once! This may cause unwanted preemptive rate limit or even actual /// rate limit, causing your bot to freeze! /// </note> /// This method will attempt to fetch the number of messages specified under <paramref name="limit"/>. The /// library will attempt to split up the requests according to your <paramref name="limit"/> and /// <see cref="DiscordConfig.MaxMessagesPerBatch"/>. In other words, should the user request 500 messages, /// and the <see cref="Discord.DiscordConfig.MaxMessagesPerBatch"/> constant is <c>100</c>, the request will /// be split into 5 individual requests; thus returning 5 individual asynchronous responses, hence the need /// of flattening. /// </remarks> /// <example> /// <para>The following example downloads 300 messages and gets messages that belong to the user /// <c>53905483156684800</c>.</para> /// <code language="cs" region="GetMessagesAsync.FromLimit.Standard" /// source="..\..\..\Discord.Net.Examples\Core\Entities\Channels\IMessageChannel.Examples.cs" /> /// </example> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="mode">The <see cref="CacheMode" /> that determines whether the object should be fetched from /// cache.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// <summary> /// Gets a collection of messages in this channel. /// </summary> /// <remarks> /// <note type="important"> /// The returned collection is an asynchronous enumerable object; one must call /// <see cref="AsyncEnumerableExtensions.FlattenAsync{T}"/> to access the individual messages as a /// collection. /// </note> /// <note type="warning"> /// Do not fetch too many messages at once! This may cause unwanted preemptive rate limit or even actual /// rate limit, causing your bot to freeze! /// </note> /// This method will attempt to fetch the number of messages specified under <paramref name="limit"/> around /// the message <paramref name="fromMessageId"/> depending on the <paramref name="dir"/>. The library will /// attempt to split up the requests according to your <paramref name="limit"/> and /// <see cref="DiscordConfig.MaxMessagesPerBatch"/>. In other words, should the user request 500 messages, /// and the <see cref="Discord.DiscordConfig.MaxMessagesPerBatch"/> constant is <c>100</c>, the request will /// be split into 5 individual requests; thus returning 5 individual asynchronous responses, hence the need /// of flattening. /// </remarks> /// <example> /// <para>The following example gets 5 message prior to the message identifier <c>442012544660537354</c>.</para> /// <code language="cs" region="GetMessagesAsync.FromId.FromMessage" /// source="..\..\..\Discord.Net.Examples\Core\Entities\Channels\IMessageChannel.Examples.cs" /> /// <para>The following example attempts to retrieve <c>messageCount</c> number of messages from the /// beginning of the channel and prints them to the console.</para> /// <code language="cs" region="GetMessagesAsync.FromId.BeginningMessages" /// source="..\..\..\Discord.Net.Examples\Core\Entities\Channels\IMessageChannel.Examples.cs" /> /// </example> /// <param name="fromMessageId">The ID of the starting message to get the messages from.</param> /// <param name="dir">The direction of the messages to be gotten from.</param> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="mode">The <see cref="CacheMode"/> that determines whether the object should be fetched from /// cache.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// <summary> /// Gets a collection of messages in this channel. /// </summary> /// <remarks> /// <note type="important"> /// The returned collection is an asynchronous enumerable object; one must call /// <see cref="AsyncEnumerableExtensions.FlattenAsync{T}"/> to access the individual messages as a /// collection. /// </note> /// <note type="warning"> /// Do not fetch too many messages at once! This may cause unwanted preemptive rate limit or even actual /// rate limit, causing your bot to freeze! /// </note> /// This method will attempt to fetch the number of messages specified under <paramref name="limit"/> around /// the message <paramref name="fromMessage"/> depending on the <paramref name="dir"/>. The library will /// attempt to split up the requests according to your <paramref name="limit"/> and /// <see cref="DiscordConfig.MaxMessagesPerBatch"/>. In other words, should the user request 500 messages, /// and the <see cref="Discord.DiscordConfig.MaxMessagesPerBatch"/> constant is <c>100</c>, the request will /// be split into 5 individual requests; thus returning 5 individual asynchronous responses, hence the need /// of flattening. /// </remarks> /// <example> /// <para>The following example gets 5 message prior to a specific message, <c>oldMessage</c>.</para> /// <code language="cs" region="GetMessagesAsync.FromMessage" /// source="..\..\..\Discord.Net.Examples\Core\Entities\Channels\IMessageChannel.Examples.cs" /> /// </example> /// <param name="fromMessage">The starting message to get the messages from.</param> /// <param name="dir">The direction of the messages to be gotten from.</param> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="mode">The <see cref="CacheMode"/> that determines whether the object should be fetched from /// cache.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// <summary> /// Gets a collection of pinned messages in this channel. /// </summary> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous get operation for retrieving pinned messages in this channel. /// The task result contains a collection of messages found in the pinned messages. /// </returns> Task<IReadOnlyCollection<IMessage>> GetPinnedMessagesAsync(RequestOptions options = null); /// <summary> /// Deletes a message. /// </summary> /// <param name="messageId">The snowflake identifier of the message that would be removed.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous removal operation. /// </returns> Task DeleteMessageAsync(ulong messageId, RequestOptions options = null); /// <summary> Deletes a message based on the provided message in this channel. </summary> /// <param name="message">The message that would be removed.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous removal operation. /// </returns> Task DeleteMessageAsync(IMessage message, RequestOptions options = null); /// <summary> /// Broadcasts the "user is typing" message to all users in this channel, lasting 10 seconds. /// </summary> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous operation that triggers the broadcast. /// </returns> Task TriggerTypingAsync(RequestOptions options = null); /// <summary> /// Continuously broadcasts the "user is typing" message to all users in this channel until the returned /// object is disposed. /// </summary> /// <example> /// <para>The following example keeps the client in the typing state until <c>LongRunningAsync</c> has finished.</para> /// <code language="cs" region="EnterTypingState" /// source="..\..\..\Discord.Net.Examples\Core\Entities\Channels\IMessageChannel.Examples.cs" /> /// </example> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A disposable object that, upon its disposal, will stop the client from broadcasting its typing state in /// this channel. /// </returns> IDisposable EnterTypingState(RequestOptions options = null); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Settings/GlobalSettings.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.Settings { /// <summary>Holder for reflection information generated from POGOProtos/Settings/GlobalSettings.proto</summary> public static partial class GlobalSettingsReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Settings/GlobalSettings.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GlobalSettingsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CihQT0dPUHJvdG9zL1NldHRpbmdzL0dsb2JhbFNldHRpbmdzLnByb3RvEhNQ", "T0dPUHJvdG9zLlNldHRpbmdzGiZQT0dPUHJvdG9zL1NldHRpbmdzL0ZvcnRT", "ZXR0aW5ncy5wcm90bxolUE9HT1Byb3Rvcy9TZXR0aW5ncy9NYXBTZXR0aW5n", "cy5wcm90bxonUE9HT1Byb3Rvcy9TZXR0aW5ncy9MZXZlbFNldHRpbmdzLnBy", "b3RvGitQT0dPUHJvdG9zL1NldHRpbmdzL0ludmVudG9yeVNldHRpbmdzLnBy", "b3RvGiVQT0dPUHJvdG9zL1NldHRpbmdzL0dwc1NldHRpbmdzLnByb3RvItoC", "Cg5HbG9iYWxTZXR0aW5ncxI4Cg1mb3J0X3NldHRpbmdzGAIgASgLMiEuUE9H", "T1Byb3Rvcy5TZXR0aW5ncy5Gb3J0U2V0dGluZ3MSNgoMbWFwX3NldHRpbmdz", "GAMgASgLMiAuUE9HT1Byb3Rvcy5TZXR0aW5ncy5NYXBTZXR0aW5ncxI6Cg5s", "ZXZlbF9zZXR0aW5ncxgEIAEoCzIiLlBPR09Qcm90b3MuU2V0dGluZ3MuTGV2", "ZWxTZXR0aW5ncxJCChJpbnZlbnRvcnlfc2V0dGluZ3MYBSABKAsyJi5QT0dP", "UHJvdG9zLlNldHRpbmdzLkludmVudG9yeVNldHRpbmdzEh4KFm1pbmltdW1f", "Y2xpZW50X3ZlcnNpb24YBiABKAkSNgoMZ3BzX3NldHRpbmdzGAcgASgLMiAu", "UE9HT1Byb3Rvcy5TZXR0aW5ncy5HcHNTZXR0aW5nc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Settings.FortSettingsReflection.Descriptor, global::POGOProtos.Settings.MapSettingsReflection.Descriptor, global::POGOProtos.Settings.LevelSettingsReflection.Descriptor, global::POGOProtos.Settings.InventorySettingsReflection.Descriptor, global::POGOProtos.Settings.GpsSettingsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.GlobalSettings), global::POGOProtos.Settings.GlobalSettings.Parser, new[]{ "FortSettings", "MapSettings", "LevelSettings", "InventorySettings", "MinimumClientVersion", "GpsSettings" }, null, null, null) })); } #endregion } #region Messages public sealed partial class GlobalSettings : pb::IMessage<GlobalSettings> { private static readonly pb::MessageParser<GlobalSettings> _parser = new pb::MessageParser<GlobalSettings>(() => new GlobalSettings()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GlobalSettings> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Settings.GlobalSettingsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GlobalSettings() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GlobalSettings(GlobalSettings other) : this() { FortSettings = other.fortSettings_ != null ? other.FortSettings.Clone() : null; MapSettings = other.mapSettings_ != null ? other.MapSettings.Clone() : null; LevelSettings = other.levelSettings_ != null ? other.LevelSettings.Clone() : null; InventorySettings = other.inventorySettings_ != null ? other.InventorySettings.Clone() : null; minimumClientVersion_ = other.minimumClientVersion_; GpsSettings = other.gpsSettings_ != null ? other.GpsSettings.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GlobalSettings Clone() { return new GlobalSettings(this); } /// <summary>Field number for the "fort_settings" field.</summary> public const int FortSettingsFieldNumber = 2; private global::POGOProtos.Settings.FortSettings fortSettings_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Settings.FortSettings FortSettings { get { return fortSettings_; } set { fortSettings_ = value; } } /// <summary>Field number for the "map_settings" field.</summary> public const int MapSettingsFieldNumber = 3; private global::POGOProtos.Settings.MapSettings mapSettings_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Settings.MapSettings MapSettings { get { return mapSettings_; } set { mapSettings_ = value; } } /// <summary>Field number for the "level_settings" field.</summary> public const int LevelSettingsFieldNumber = 4; private global::POGOProtos.Settings.LevelSettings levelSettings_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Settings.LevelSettings LevelSettings { get { return levelSettings_; } set { levelSettings_ = value; } } /// <summary>Field number for the "inventory_settings" field.</summary> public const int InventorySettingsFieldNumber = 5; private global::POGOProtos.Settings.InventorySettings inventorySettings_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Settings.InventorySettings InventorySettings { get { return inventorySettings_; } set { inventorySettings_ = value; } } /// <summary>Field number for the "minimum_client_version" field.</summary> public const int MinimumClientVersionFieldNumber = 6; private string minimumClientVersion_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MinimumClientVersion { get { return minimumClientVersion_; } set { minimumClientVersion_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "gps_settings" field.</summary> public const int GpsSettingsFieldNumber = 7; private global::POGOProtos.Settings.GpsSettings gpsSettings_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Settings.GpsSettings GpsSettings { get { return gpsSettings_; } set { gpsSettings_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GlobalSettings); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GlobalSettings other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(FortSettings, other.FortSettings)) return false; if (!object.Equals(MapSettings, other.MapSettings)) return false; if (!object.Equals(LevelSettings, other.LevelSettings)) return false; if (!object.Equals(InventorySettings, other.InventorySettings)) return false; if (MinimumClientVersion != other.MinimumClientVersion) return false; if (!object.Equals(GpsSettings, other.GpsSettings)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (fortSettings_ != null) hash ^= FortSettings.GetHashCode(); if (mapSettings_ != null) hash ^= MapSettings.GetHashCode(); if (levelSettings_ != null) hash ^= LevelSettings.GetHashCode(); if (inventorySettings_ != null) hash ^= InventorySettings.GetHashCode(); if (MinimumClientVersion.Length != 0) hash ^= MinimumClientVersion.GetHashCode(); if (gpsSettings_ != null) hash ^= GpsSettings.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 (fortSettings_ != null) { output.WriteRawTag(18); output.WriteMessage(FortSettings); } if (mapSettings_ != null) { output.WriteRawTag(26); output.WriteMessage(MapSettings); } if (levelSettings_ != null) { output.WriteRawTag(34); output.WriteMessage(LevelSettings); } if (inventorySettings_ != null) { output.WriteRawTag(42); output.WriteMessage(InventorySettings); } if (MinimumClientVersion.Length != 0) { output.WriteRawTag(50); output.WriteString(MinimumClientVersion); } if (gpsSettings_ != null) { output.WriteRawTag(58); output.WriteMessage(GpsSettings); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (fortSettings_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(FortSettings); } if (mapSettings_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MapSettings); } if (levelSettings_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(LevelSettings); } if (inventorySettings_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(InventorySettings); } if (MinimumClientVersion.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MinimumClientVersion); } if (gpsSettings_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(GpsSettings); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GlobalSettings other) { if (other == null) { return; } if (other.fortSettings_ != null) { if (fortSettings_ == null) { fortSettings_ = new global::POGOProtos.Settings.FortSettings(); } FortSettings.MergeFrom(other.FortSettings); } if (other.mapSettings_ != null) { if (mapSettings_ == null) { mapSettings_ = new global::POGOProtos.Settings.MapSettings(); } MapSettings.MergeFrom(other.MapSettings); } if (other.levelSettings_ != null) { if (levelSettings_ == null) { levelSettings_ = new global::POGOProtos.Settings.LevelSettings(); } LevelSettings.MergeFrom(other.LevelSettings); } if (other.inventorySettings_ != null) { if (inventorySettings_ == null) { inventorySettings_ = new global::POGOProtos.Settings.InventorySettings(); } InventorySettings.MergeFrom(other.InventorySettings); } if (other.MinimumClientVersion.Length != 0) { MinimumClientVersion = other.MinimumClientVersion; } if (other.gpsSettings_ != null) { if (gpsSettings_ == null) { gpsSettings_ = new global::POGOProtos.Settings.GpsSettings(); } GpsSettings.MergeFrom(other.GpsSettings); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 18: { if (fortSettings_ == null) { fortSettings_ = new global::POGOProtos.Settings.FortSettings(); } input.ReadMessage(fortSettings_); break; } case 26: { if (mapSettings_ == null) { mapSettings_ = new global::POGOProtos.Settings.MapSettings(); } input.ReadMessage(mapSettings_); break; } case 34: { if (levelSettings_ == null) { levelSettings_ = new global::POGOProtos.Settings.LevelSettings(); } input.ReadMessage(levelSettings_); break; } case 42: { if (inventorySettings_ == null) { inventorySettings_ = new global::POGOProtos.Settings.InventorySettings(); } input.ReadMessage(inventorySettings_); break; } case 50: { MinimumClientVersion = input.ReadString(); break; } case 58: { if (gpsSettings_ == null) { gpsSettings_ = new global::POGOProtos.Settings.GpsSettings(); } input.ReadMessage(gpsSettings_); break; } } } } } #endregion } #endregion Designer generated code
// 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.Contracts; using System.IO; using System.Reflection; using System.Security; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; namespace System { [SecurityCritical] internal class SafeTypeNameParserHandle : SafeHandleZeroOrMinusOneIsInvalid { #region QCalls [SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void _ReleaseTypeNameParser(IntPtr pTypeNameParser); #endregion public SafeTypeNameParserHandle() : base(true) { } [SecurityCritical] protected override bool ReleaseHandle() { _ReleaseTypeNameParser(handle); handle = IntPtr.Zero; return true; } } internal sealed class TypeNameParser : IDisposable { #region QCalls [SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void _CreateTypeNameParser(string typeName, ObjectHandleOnStack retHandle, bool throwOnError); [SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void _GetNames(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray); [SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void _GetTypeArguments(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray); [SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void _GetModifiers(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray); [SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void _GetAssemblyName(SafeTypeNameParserHandle pTypeNameParser, StringHandleOnStack retString); #endregion #region Static Members [SecuritySafeCritical] internal static Type GetType( string typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { if (typeName == null) throw new ArgumentNullException(nameof(typeName)); if (typeName.Length > 0 && typeName[0] == '\0') throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength")); Contract.EndContractBlock(); Type ret = null; SafeTypeNameParserHandle handle = CreateTypeNameParser(typeName, throwOnError); if (handle != null) { // If we get here the typeName must have been successfully parsed. // Let's construct the Type object. using (TypeNameParser parser = new TypeNameParser(handle)) { ret = parser.ConstructType(assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); } } return ret; } #endregion #region Private Data Members [SecurityCritical] private SafeTypeNameParserHandle m_NativeParser; private static readonly char[] SPECIAL_CHARS = {',', '[', ']', '&', '*', '+', '\\'}; /* see typeparse.h */ #endregion #region Constructor and Disposer [SecuritySafeCritical] private TypeNameParser(SafeTypeNameParserHandle handle) { m_NativeParser = handle; } [SecuritySafeCritical] public void Dispose() { m_NativeParser.Dispose(); } #endregion #region private Members [SecuritySafeCritical] private unsafe Type ConstructType( Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { // assembly name Assembly assembly = null; string asmName = GetAssemblyName(); // GetAssemblyName never returns null Contract.Assert(asmName != null); if (asmName.Length > 0) { assembly = ResolveAssembly(asmName, assemblyResolver, throwOnError, ref stackMark); if (assembly == null) { // Cannot resolve the assembly. If throwOnError is true we should have already thrown. return null; } } string[] names = GetNames(); if (names == null) { // This can only happen if the type name is an empty string or if the first char is '\0' if (throwOnError) throw new TypeLoadException(Environment.GetResourceString("Arg_TypeLoadNullStr")); return null; } Type baseType = ResolveType(assembly, names, typeResolver, throwOnError, ignoreCase, ref stackMark); if (baseType == null) { // Cannot resolve the type. If throwOnError is true we should have already thrown. Contract.Assert(throwOnError == false); return null; } SafeTypeNameParserHandle[] typeArguments = GetTypeArguments(); Type[] types = null; if (typeArguments != null) { types = new Type[typeArguments.Length]; for (int i = 0; i < typeArguments.Length; i++) { Contract.Assert(typeArguments[i] != null); using (TypeNameParser argParser = new TypeNameParser(typeArguments[i])) { types[i] = argParser.ConstructType(assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); } if (types[i] == null) { // If throwOnError is true argParser.ConstructType should have already thrown. Contract.Assert(throwOnError == false); return null; } } } int[] modifiers = GetModifiers(); fixed (int* ptr = modifiers) { IntPtr intPtr = new IntPtr(ptr); return RuntimeTypeHandle.GetTypeHelper(baseType, types, intPtr, modifiers == null ? 0 : modifiers.Length); } } [SecuritySafeCritical] private static Assembly ResolveAssembly(string asmName, Func<AssemblyName, Assembly> assemblyResolver, bool throwOnError, ref StackCrawlMark stackMark) { Contract.Requires(asmName != null && asmName.Length > 0); Assembly assembly = null; if (assemblyResolver == null) { if (throwOnError) { assembly = RuntimeAssembly.InternalLoad(asmName, null, ref stackMark, false /*forIntrospection*/); } else { // When throwOnError is false we should only catch FileNotFoundException. // Other exceptions like BadImangeFormatException should still fly. try { assembly = RuntimeAssembly.InternalLoad(asmName, null, ref stackMark, false /*forIntrospection*/); } catch (FileNotFoundException) { return null; } } } else { assembly = assemblyResolver(new AssemblyName(asmName)); if (assembly == null && throwOnError) { throw new FileNotFoundException(Environment.GetResourceString("FileNotFound_ResolveAssembly", asmName)); } } return assembly; } private static Type ResolveType(Assembly assembly, string[] names, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { Contract.Requires(names != null && names.Length > 0); Type type = null; // both the customer provided and the default type resolvers accept escaped type names string OuterMostTypeName = EscapeTypeName(names[0]); // Resolve the top level type. if (typeResolver != null) { type = typeResolver(assembly, OuterMostTypeName, ignoreCase); if (type == null && throwOnError) { string errorString = assembly == null ? Environment.GetResourceString("TypeLoad_ResolveType", OuterMostTypeName) : Environment.GetResourceString("TypeLoad_ResolveTypeFromAssembly", OuterMostTypeName, assembly.FullName); throw new TypeLoadException(errorString); } } else { if (assembly == null) { type = RuntimeType.GetType(OuterMostTypeName, throwOnError, ignoreCase, false, ref stackMark); } else { type = assembly.GetType(OuterMostTypeName, throwOnError, ignoreCase); } } // Resolve nested types. if (type != null) { BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public; if (ignoreCase) bindingFlags |= BindingFlags.IgnoreCase; for (int i = 1; i < names.Length; i++) { type = type.GetNestedType(names[i], bindingFlags); if (type == null) { if (throwOnError) throw new TypeLoadException(Environment.GetResourceString("TypeLoad_ResolveNestedType", names[i], names[i-1])); else break; } } } return type; } private static string EscapeTypeName(string name) { if (name.IndexOfAny(SPECIAL_CHARS) < 0) return name; StringBuilder sb = StringBuilderCache.Acquire(); foreach (char c in name) { if (Array.IndexOf<char>(SPECIAL_CHARS, c) >= 0) sb.Append('\\'); sb.Append(c); } return StringBuilderCache.GetStringAndRelease(sb); } [SecuritySafeCritical] private static SafeTypeNameParserHandle CreateTypeNameParser(string typeName, bool throwOnError) { SafeTypeNameParserHandle retHandle = null; _CreateTypeNameParser(typeName, JitHelpers.GetObjectHandleOnStack(ref retHandle), throwOnError); return retHandle; } [SecuritySafeCritical] private string[] GetNames() { string[] names = null; _GetNames(m_NativeParser, JitHelpers.GetObjectHandleOnStack(ref names)); return names; } [SecuritySafeCritical] private SafeTypeNameParserHandle[] GetTypeArguments() { SafeTypeNameParserHandle[] arguments = null; _GetTypeArguments(m_NativeParser, JitHelpers.GetObjectHandleOnStack(ref arguments)); return arguments; } [SecuritySafeCritical] private int[] GetModifiers() { int[] modifiers = null; _GetModifiers(m_NativeParser, JitHelpers.GetObjectHandleOnStack(ref modifiers)); return modifiers; } [SecuritySafeCritical] private string GetAssemblyName() { string assemblyName = null; _GetAssemblyName(m_NativeParser, JitHelpers.GetStringHandleOnStack(ref assemblyName)); return assemblyName; } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/ml/v1beta1/prediction_service.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Ml.V1Beta1 { /// <summary>Holder for reflection information generated from google/cloud/ml/v1beta1/prediction_service.proto</summary> public static partial class PredictionServiceReflection { #region Descriptor /// <summary>File descriptor for google/cloud/ml/v1beta1/prediction_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PredictionServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjBnb29nbGUvY2xvdWQvbWwvdjFiZXRhMS9wcmVkaWN0aW9uX3NlcnZpY2Uu", "cHJvdG8SF2dvb2dsZS5jbG91ZC5tbC52MWJldGExGhxnb29nbGUvYXBpL2Fu", "bm90YXRpb25zLnByb3RvGhlnb29nbGUvYXBpL2h0dHBib2R5LnByb3RvIkcK", "DlByZWRpY3RSZXF1ZXN0EgwKBG5hbWUYASABKAkSJwoJaHR0cF9ib2R5GAIg", "ASgLMhQuZ29vZ2xlLmFwaS5IdHRwQm9keTKTAQoXT25saW5lUHJlZGljdGlv", "blNlcnZpY2USeAoHUHJlZGljdBInLmdvb2dsZS5jbG91ZC5tbC52MWJldGEx", "LlByZWRpY3RSZXF1ZXN0GhQuZ29vZ2xlLmFwaS5IdHRwQm9keSIugtPkkwIo", "IiMvdjFiZXRhMS97bmFtZT1wcm9qZWN0cy8qKn06cHJlZGljdDoBKkJ2Ch9j", "b20uZ29vZ2xlLmNsb3VkLm1sLmFwaS52MWJldGExQhZQcmVkaWN0aW9uU2Vy", "dmljZVByb3RvUAFaOWdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2ds", "ZWFwaXMvY2xvdWQvbWwvdjFiZXRhMTttbGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.HttpbodyReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Ml.V1Beta1.PredictRequest), global::Google.Cloud.Ml.V1Beta1.PredictRequest.Parser, new[]{ "Name", "HttpBody" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Request for predictions to be issued against a trained model. /// /// The body of the request is a single JSON object with a single top-level /// field: /// /// &lt;dl> /// &lt;dt>instances&lt;/dt> /// &lt;dd>A JSON array containing values representing the instances to use for /// prediction.&lt;/dd> /// &lt;/dl> /// /// The structure of each element of the instances list is determined by your /// model's input definition. Instances can include named inputs or can contain /// only unlabeled values. /// /// Most data does not include named inputs. Some instances will be simple /// JSON values (boolean, number, or string). However, instances are often lists /// of simple values, or complex nested lists. Here are some examples of request /// bodies: /// /// CSV data with each row encoded as a string value: /// &lt;pre> /// {"instances": ["1.0,true,\\"x\\"", "-2.0,false,\\"y\\""]} /// &lt;/pre> /// Plain text: /// &lt;pre> /// {"instances": ["the quick brown fox", "la bruja le dio"]} /// &lt;/pre> /// Sentences encoded as lists of words (vectors of strings): /// &lt;pre> /// {"instances": [["the","quick","brown"], ["la","bruja","le"]]} /// &lt;/pre> /// Floating point scalar values: /// &lt;pre> /// {"instances": [0.0, 1.1, 2.2]} /// &lt;/pre> /// Vectors of integers: /// &lt;pre> /// {"instances": [[0, 1, 2], [3, 4, 5],...]} /// &lt;/pre> /// Tensors (in this case, two-dimensional tensors): /// &lt;pre> /// {"instances": [[[0, 1, 2], [3, 4, 5]], ...]} /// &lt;/pre> /// Images represented as a three-dimensional list. In this encoding scheme the /// first two dimensions represent the rows and columns of the image, and the /// third contains the R, G, and B values for each pixel. /// &lt;pre> /// {"instances": [[[[138, 30, 66], [130, 20, 56], ...]]]]} /// &lt;/pre> /// Data must be encoded as UTF-8. If your data uses another character encoding, /// you must base64 encode the data and mark it as binary. To mark a JSON string /// as binary, replace it with an object with a single attribute named `b`: /// &lt;pre>{"b": "..."} &lt;/pre> /// For example: /// /// Two Serialized tf.Examples (fake data, for illustrative purposes only): /// &lt;pre> /// {"instances": [{"b64": "X5ad6u"}, {"b64": "IA9j4nx"}]} /// &lt;/pre> /// Two JPEG image byte strings (fake data, for illustrative purposes only): /// &lt;pre> /// {"instances": [{"b64": "ASa8asdf"}, {"b64": "JLK7ljk3"}]} /// &lt;/pre> /// If your data includes named references, format each instance as a JSON object /// with the named references as the keys: /// /// JSON input data to be preprocessed: /// &lt;pre> /// {"instances": [{"a": 1.0, "b": true, "c": "x"}, /// {"a": -2.0, "b": false, "c": "y"}]} /// &lt;/pre> /// Some models have an underlying TensorFlow graph that accepts multiple input /// tensors. In this case, you should use the names of JSON name/value pairs to /// identify the input tensors, as shown in the following exmaples: /// /// For a graph with input tensor aliases "tag" (string) and "image" /// (base64-encoded string): /// &lt;pre> /// {"instances": [{"tag": "beach", "image": {"b64": "ASa8asdf"}}, /// {"tag": "car", "image": {"b64": "JLK7ljk3"}}]} /// &lt;/pre> /// For a graph with input tensor aliases "tag" (string) and "image" /// (3-dimensional array of 8-bit ints): /// &lt;pre> /// {"instances": [{"tag": "beach", "image": [[[263, 1, 10], [262, 2, 11], ...]]}, /// {"tag": "car", "image": [[[10, 11, 24], [23, 10, 15], ...]]}]} /// &lt;/pre> /// If the call is successful, the response body will contain one prediction /// entry per instance in the request body. If prediction fails for any /// instance, the response body will contain no predictions and will contian /// a single error entry instead. /// </summary> public sealed partial class PredictRequest : pb::IMessage<PredictRequest> { private static readonly pb::MessageParser<PredictRequest> _parser = new pb::MessageParser<PredictRequest>(() => new PredictRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PredictRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Ml.V1Beta1.PredictionServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PredictRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PredictRequest(PredictRequest other) : this() { name_ = other.name_; HttpBody = other.httpBody_ != null ? other.HttpBody.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PredictRequest Clone() { return new PredictRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. The resource name of a model or a version. /// /// Authorization: requires `Viewer` role on the parent project. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "http_body" field.</summary> public const int HttpBodyFieldNumber = 2; private global::Google.Api.HttpBody httpBody_; /// <summary> /// /// Required. The prediction request body. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.HttpBody HttpBody { get { return httpBody_; } set { httpBody_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PredictRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PredictRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(HttpBody, other.HttpBody)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (httpBody_ != null) hash ^= HttpBody.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (httpBody_ != null) { output.WriteRawTag(18); output.WriteMessage(HttpBody); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (httpBody_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(HttpBody); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PredictRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.httpBody_ != null) { if (httpBody_ == null) { httpBody_ = new global::Google.Api.HttpBody(); } HttpBody.MergeFrom(other.HttpBody); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { if (httpBody_ == null) { httpBody_ = new global::Google.Api.HttpBody(); } input.ReadMessage(httpBody_); break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: This class will encapsulate a long and provide an ** Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] public struct Int64 : IComparable, IFormattable, IConvertible , IComparable<Int64>, IEquatable<Int64> { internal long m_value; public const long MaxValue = 0x7fffffffffffffffL; public const long MinValue = unchecked((long)0x8000000000000000L); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int64, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Int64) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. long i = (long)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException (Environment.GetResourceString("Arg_MustBeInt64")); } public int CompareTo(Int64 value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is Int64)) { return false; } return m_value == ((Int64)obj).m_value; } [System.Runtime.Versioning.NonVersionable] public bool Equals(Int64 obj) { return m_value == obj; } // The value of the lower 32 bits XORed with the uppper 32 bits. public override int GetHashCode() { return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32)); } [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt64(m_value, null, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt64(m_value, null, NumberFormatInfo.GetInstance(provider)); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt64(m_value, format, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt64(m_value, format, NumberFormatInfo.GetInstance(provider)); } public static long Parse(String s) { return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static long Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt64(s, style, NumberFormatInfo.CurrentInfo); } public static long Parse(String s, IFormatProvider provider) { return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses a long from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static long Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider)); } public static Boolean TryParse(String s, out Int64 result) { return Number.TryParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseInt64(s, style, NumberFormatInfo.GetInstance(provider), out result); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int64; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return m_value; } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int64", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
#region License /* * Copyright 2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Threading; using NUnit.Framework; using Spring.Context.Support; using Spring.Util; #endregion namespace Spring.Reflection.Dynamic { /// <summary> /// Unit tests for the DynamicMethod class. /// </summary> /// <author>Aleksandar Seovic</author> [TestFixture] public sealed class DynamicMethodTests { private Inventor tesla; private Inventor pupin; private Society ieee; #region SetUp and TearDown /// <summary> /// The setup logic executed before the execution of each individual test. /// </summary> [SetUp] public void SetUp() { ContextRegistry.Clear(); tesla = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); tesla.Inventions = new string[] { "Telephone repeater", "Rotating magnetic field principle", "Polyphase alternating-current system", "Induction motor", "Alternating-current power transmission", "Tesla coil transformer", "Wireless communication", "Radio", "Fluorescent lights" }; tesla.PlaceOfBirth.City = "Smiljan"; pupin = new Inventor("Mihajlo Pupin", new DateTime(1854, 10, 9), "Serbian"); pupin.Inventions = new string[] { "Long distance telephony & telegraphy", "Secondary X-Ray radiation", "Sonar" }; pupin.PlaceOfBirth.City = "Idvor"; pupin.PlaceOfBirth.Country = "Serbia"; ieee = new Society(); ieee.Members.Add(tesla); ieee.Members.Add(pupin); ieee.Officers["president"] = pupin; ieee.Officers["advisors"] = new Inventor[] { tesla, pupin }; // not historically accurate, but I need an array in the map ;-) } [TestFixtureTearDown] public void TearDown() { //DynamicReflectionManager.SaveAssembly(); } #endregion #if NET_2_0 private string RespectsPermissionsPrivateMethod() { return "Result"; } public void RespectsPermissionsPublicMethod() { } [Test] public void CanCreateWithRestrictedPermissions() { SecurityTemplate.MediumTrustInvoke(new ThreadStart(CanCreateWithRestrictedPermissionsImpl)); } private void CanCreateWithRestrictedPermissionsImpl() { MethodInfo method = this.GetType().GetMethod("RespectsPermissionsPublicMethod"); IDynamicMethod m = DynamicMethod.Create(method); m.Invoke(this, null); } [Test] public void CanCreatePrivateMethodButThrowsOnInvoke() { SecurityTemplate.MediumTrustInvoke(new ThreadStart(CanCreatePrivateMethodButThrowsOnInvokeImpl)); } private void CanCreatePrivateMethodButThrowsOnInvokeImpl() { MethodInfo privateMethod = this.GetType().GetMethod("RespectsPermissionsPrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance); IDynamicMethod m = DynamicMethod.Create(privateMethod); try { object result = m.Invoke(this, null); if (SystemUtils.MonoRuntime) { Assert.AreEqual("Result", result); } else { Assert.Fail("shoud throw a security exception"); } } catch (MethodAccessException) { } } #endif [Test] public void TestInstanceMethods() { IDynamicMethod getAge = DynamicMethod.Create(typeof(Inventor).GetMethod("GetAge")); Assert.AreEqual(tesla.GetAge(DateTime.Today), getAge.Invoke(tesla, new object[] { DateTime.Today })); MethodTarget target = new MethodTarget(); IDynamicMethod test = DynamicMethod.Create(typeof(MethodTarget).GetMethod("MethodReturningString")); Assert.AreEqual(tesla.Name, test.Invoke(target, new object[] { 5, DateTime.Today, new String[] { "xyz", "abc" }, tesla })); ArrayList list = new ArrayList(new string[] { "one", "two", "three" }); IDynamicMethod removeAt = DynamicMethod.Create(typeof(ArrayList).GetMethod("RemoveAt")); removeAt.Invoke(list, new object[] { 1 }); Assert.AreEqual(2, list.Count); Assert.AreEqual("three", list[1]); } [Test] public void TestStaticMethods() { IDynamicMethod isNullOrEmpty = DynamicMethod.Create(typeof(StringUtils).GetMethod("IsNullOrEmpty")); Assert.IsTrue((bool)isNullOrEmpty.Invoke(null, new object[] { null })); Assert.IsTrue((bool)isNullOrEmpty.Invoke(null, new object[] { String.Empty })); Assert.IsFalse((bool)isNullOrEmpty.Invoke(null, new object[] { "Ana Maria" })); } #if NET_2_0 internal class TheClassAsArgument { } internal class TheClassDerivedFromTheArgumentClass : TheClassAsArgument { } internal class TheClassWithMethod { public bool TheMethod(TheClassAsArgument arg) { return true; } } [Test] public void CanAcceptImplicitlyConvertedTypesAsSubstitutesForArguments() { IDynamicMethod method = DynamicMethod.Create(typeof(TheClassWithMethod).GetMethod("TheMethod")); bool ret = (bool)(method.Invoke(new TheClassWithMethod(), new object[] { new TheClassDerivedFromTheArgumentClass() })); Assert.IsTrue(ret); } [Test] public void PassNullableArguments() { IDynamicMethod dm = DynamicMethod.Create(typeof(TestMethods).GetMethod("PassNullableArgumentStatic")); DateTime dt = DateTime.Now; Assert.AreEqual(dt, dm.Invoke(null, dt)); } #endif [Test] public void PassInvalidNumberOfArguments() { IDynamicMethod dm = DynamicMethod.Create(typeof(TestMethods).GetMethod("PassReferenceArgumentStatic")); DateTime dt = DateTime.Now; Assert.IsNull(dm.Invoke(null, null)); // this is ok try { dm.Invoke(null); // this is not ok Assert.Fail(); } catch (ArgumentException) { } try { dm.Invoke(null, null, null); // this is not ok Assert.Fail(); } catch (ArgumentException) { } } [Test] public void TestArgumentTypeCasts() { IDynamicMethod sqrt = DynamicMethod.Create(typeof(Math).GetMethod("Sqrt")); object result = sqrt.Invoke(null, new object[] { 4 }); Assert.AreEqual(Math.Sqrt(4), result); try { sqrt.Invoke(null, new object[] { null }); Assert.Fail(); } catch (InvalidCastException) { } try { sqrt.Invoke(null, new object[] { "4" }); Assert.Fail(); } catch (InvalidCastException) { } } private void CodeForReflection() { object val = 4; Type argType = typeof(double); Math.Sqrt((double)Convert.ChangeType(val, argType)); } [Test] public void TestRefOutMethods() { IDynamicMethod refMethod = DynamicMethod.Create(typeof(MethodTarget).GetMethod("MethodWithRefParameter")); MethodTarget target = new MethodTarget(); object[] args = new object[] { "aleks", 5 }; refMethod.Invoke(target, args); Assert.AreEqual("ALEKS", args[0]); Assert.AreEqual(25, args[1]); IDynamicMethod outMethod = DynamicMethod.Create(typeof(MethodTarget).GetMethod("MethodWithOutParameter")); args = new object[] { "aleks", null }; outMethod.Invoke(target, args); Assert.AreEqual("ALEKS", args[1]); IDynamicMethod refOutMethod = DynamicMethod.Create(typeof(RefOutTestObject).GetMethod("DoIt")); RefOutTestObject refOutTarget = new RefOutTestObject(); args = new object[] { 0, 1, null }; refOutMethod.Invoke(refOutTarget, args); Assert.AreEqual(2, args[1]); Assert.AreEqual("done", args[2]); refOutMethod.Invoke(refOutTarget, args); Assert.AreEqual(3, args[1]); Assert.AreEqual("done", args[2]); int count = 0; string done; target.DoItCaller(0, ref count, out done); Assert.AreEqual(1, count); Assert.AreEqual("done", done); } #region Performance tests private DateTime start, stop; //[Test] public void PerformanceTests() { int n = 10000000; object x = null; // tesla.GetAge start = DateTime.Now; for (int i = 0; i < n; i++) { x = tesla.GetAge(DateTime.Today); } stop = DateTime.Now; PrintTest("tesla.GetAge (direct)", n, Elapsed); start = DateTime.Now; IDynamicMethod getAge = DynamicMethod.Create(typeof(Inventor).GetMethod("GetAge")); for (int i = 0; i < n; i++) { object[] args = new object[] { DateTime.Today }; x = getAge.Invoke(tesla, args); } stop = DateTime.Now; PrintTest("tesla.GetAge (dynamic reflection)", n, Elapsed); start = DateTime.Now; MethodInfo getAgeMi = typeof(Inventor).GetMethod("GetAge"); for (int i = 0; i < n; i++) { object[] args = new object[] { DateTime.Today }; x = getAgeMi.Invoke(tesla, args); } stop = DateTime.Now; PrintTest("tesla.GetAge (standard reflection)", n, Elapsed); } private double Elapsed { get { return (stop.Ticks - start.Ticks) / 10000000f; } } private void PrintTest(string name, int iterations, double duration) { Debug.WriteLine(String.Format("{0,-60} {1,12:#,###} {2,12:##0.000} {3,12:#,###}", name, iterations, duration, iterations / duration)); } #endregion #region Helper Classes public class TestMethods { public static object PassReferenceArgumentStatic(object arg) { return arg; } #if NET_2_0 public static object Invoke(object target, object[] args) { return PassNullableArgumentStatic((DateTime?)(args[0])); } public DateTime? PassNullableArgument(DateTime? arg) { return PassNullableArgumentStatic(arg); } public static DateTime? PassNullableArgumentStatic(DateTime? arg) { return arg; } #endif } #endregion } #region IL generation helper classes (they help if you look at them in Reflector ;-) public class InstanceMethod : IDynamicMethod { public object Invoke(object target, object[] args) { return ((MethodTarget)target).MethodReturningString( (int)args[0], (DateTime)args[1], (string[])args[2], (Inventor)args[3]); } public object InvokeVoid(object target, object[] args) { ((MethodTarget)target).RemoveAt(5); return null; } public object InvokeWithOut(object target, object[] args) { string outVar = null; ((MethodTarget)target).MethodWithOutParameter((string)args[0], out outVar); args[1] = outVar; return null; } public object InvokeWithRef(object target, object[] args) { string refVar1 = (string)args[0]; int refVar2 = (int)args[0]; ((MethodTarget)target).MethodWithRefParameter(ref refVar1, ref refVar2); args[0] = refVar1; args[1] = refVar2; return null; } public object InvokeDoIt(object target, object[] args) { int reference = (int)args[1]; string output; ((RefOutTestObject)target).DoIt((int)args[0], ref reference, out output); args[1] = reference; args[2] = output; return null; } } public class MethodTarget { public string MethodReturningString(int arg1, DateTime arg2, string[] arg3, Inventor arg4) { return arg4.Name; } public void RemoveAt(int index) { } public void MethodWithOutParameter(string lower, out string upper) { upper = lower.ToUpper(); } public void MethodWithRefParameter(ref string lowerUpper, ref int square) { lowerUpper = lowerUpper.ToUpper(); square = square * square; } public void DoItCaller(int count, ref int reference, out string output) { InstanceMethod caller = new InstanceMethod(); RefOutTestObject target = new RefOutTestObject(); object[] args = new object[] { count, reference, null }; caller.InvokeDoIt(target, args); reference = (int)args[1]; output = (string)args[2]; } } public interface IRefOutTestObject { void DoIt(int count, ref int reference, out string output); } public class RefOutTestObject : IRefOutTestObject { public void DoIt(int count, ref int reference, out string output) { output = "done"; reference++; } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Threading.Tasks.Tests { public class YieldAwaitableTests { // awaiting Task.Yield [Fact] public static void RunAsyncYieldAwaiterTests() { // Test direct usage works even though it's not encouraged { for (int i = 0; i < 2; i++) { SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); var ya = i == 0 ? new YieldAwaitable.YieldAwaiter() : new YieldAwaitable().GetAwaiter(); var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, "RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(ValidateCorrectContextSynchronizationContext.t_isPostedInContext, "RunAsyncYieldAwaiterTests > FAILURE. Expected to post in target context."); mres.Set(); }); mres.Wait(); ya.GetResult(); SynchronizationContext.SetSynchronizationContext(null); } } { // Yield when there's a current sync context SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); var ya = Task.Yield().GetAwaiter(); try { ya.GetResult(); } catch { Assert.True(false, string.Format("RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, "RunAsyncYieldAwaiterTests > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(ValidateCorrectContextSynchronizationContext.t_isPostedInContext, " > FAILURE. Expected to post in target context."); mres.Set(); }); mres.Wait(); ya.GetResult(); SynchronizationContext.SetSynchronizationContext(null); } { // Yield when there's a current TaskScheduler Task.Factory.StartNew(() => { try { var ya = Task.Yield().GetAwaiter(); try { ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(TaskScheduler.Current is QUWITaskScheduler, " > FAILURE. Expected to queue into target scheduler."); mres.Set(); }); mres.Wait(); ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. Unexpected exception from Yield")); } }, CancellationToken.None, TaskCreationOptions.None, new QUWITaskScheduler()).Wait(); } { // Yield when there's a current TaskScheduler and SynchronizationContext.Current is the base SynchronizationContext Task.Factory.StartNew(() => { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); try { var ya = Task.Yield().GetAwaiter(); try { ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(TaskScheduler.Current is QUWITaskScheduler, " > FAILURE. Expected to queue into target scheduler."); mres.Set(); }); mres.Wait(); ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. Unexpected exception from Yield")); } SynchronizationContext.SetSynchronizationContext(null); }, CancellationToken.None, TaskCreationOptions.None, new QUWITaskScheduler()).Wait(); } { // OnCompleted grabs the current context, not Task.Yield nor GetAwaiter SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); var ya = Task.Yield().GetAwaiter(); SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); try { ya.GetResult(); } catch { Assert.True(false, string.Format(" > FAILURE. YieldAwaiter.GetResult threw inappropriately")); } var mres = new ManualResetEventSlim(); Assert.False(ya.IsCompleted, " > FAILURE. YieldAwaiter.IsCompleted should always be false."); ya.OnCompleted(() => { Assert.True(ValidateCorrectContextSynchronizationContext.t_isPostedInContext, " > FAILURE. Expected to post in target context."); mres.Set(); }); mres.Wait(); ya.GetResult(); SynchronizationContext.SetSynchronizationContext(null); } } // awaiting Task.Yield [Fact] public static void RunAsyncYieldAwaiterTests_Negative() { // Yield when there's a current sync context SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext()); var ya = Task.Yield().GetAwaiter(); Assert.Throws<ArgumentNullException>(() => { ya.OnCompleted(null); }); } #region Helper Methods / Classes private class ValidateCorrectContextSynchronizationContext : SynchronizationContext { [ThreadStatic] internal static bool t_isPostedInContext; internal int PostCount; internal int SendCount; public override void Post(SendOrPostCallback d, object state) { Interlocked.Increment(ref PostCount); Task.Run(() => { t_isPostedInContext = true; d(state); t_isPostedInContext = false; }); } public override void Send(SendOrPostCallback d, object state) { Interlocked.Increment(ref SendCount); d(state); } } /// <summary>A scheduler that queues to the TP and tracks the number of times QueueTask and TryExecuteTaskInline are invoked.</summary> private class QUWITaskScheduler : TaskScheduler { private int _queueTaskCount; private int _tryExecuteTaskInlineCount; public int QueueTaskCount { get { return _queueTaskCount; } } public int TryExecuteTaskInlineCount { get { return _tryExecuteTaskInlineCount; } } protected override IEnumerable<Task> GetScheduledTasks() { return null; } protected override void QueueTask(Task task) { Interlocked.Increment(ref _queueTaskCount); Task.Run(() => TryExecuteTask(task)); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Interlocked.Increment(ref _tryExecuteTaskInlineCount); return TryExecuteTask(task); } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="WebEventCodes.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Management { using System.Globalization; using System.Collections; using Debug=System.Web.Util.Debug; using System.Security.Permissions; // this class is a container for pre-defined event codes // all APIs will take integers so application defined // codes or new codes added through servicing are supported public sealed class WebEventCodes { private WebEventCodes() { } static WebEventCodes() { InitEventArrayDimensions(); } // (not bit flags) // we're not using an enum for extensibility reasons public const int InvalidEventCode = -1; public const int UndefinedEventCode = 0; public const int UndefinedEventDetailCode = 0; // ---------------------------------- // Application Codes // ---------------------------------- public const int ApplicationCodeBase = 1000; public const int ApplicationStart = ApplicationCodeBase + 1; public const int ApplicationShutdown = ApplicationCodeBase + 2; public const int ApplicationCompilationStart = ApplicationCodeBase + 3; public const int ApplicationCompilationEnd = ApplicationCodeBase + 4; public const int ApplicationHeartbeat = ApplicationCodeBase + 5; internal const int ApplicationCodeBaseLast = ApplicationCodeBase + 5; // ---------------------------------- // Request Codes // ---------------------------------- public const int RequestCodeBase = 2000; public const int RequestTransactionComplete = RequestCodeBase+1; public const int RequestTransactionAbort = RequestCodeBase+2; internal const int RequestCodeBaseLast = RequestCodeBase+2; // ---------------------------------- // Error Codes // ---------------------------------- public const int ErrorCodeBase = 3000; // Errors during request processing related to client input // or behavior public const int RuntimeErrorRequestAbort = ErrorCodeBase + 1; public const int RuntimeErrorViewStateFailure = ErrorCodeBase + 2; public const int RuntimeErrorValidationFailure = ErrorCodeBase + 3; public const int RuntimeErrorPostTooLarge = ErrorCodeBase + 4; public const int RuntimeErrorUnhandledException = ErrorCodeBase + 5; // Errors related to configuration or invalid code public const int WebErrorParserError = ErrorCodeBase + 6; public const int WebErrorCompilationError = ErrorCodeBase + 7; public const int WebErrorConfigurationError = ErrorCodeBase + 8; public const int WebErrorOtherError = ErrorCodeBase + 9; public const int WebErrorPropertyDeserializationError = ErrorCodeBase + 10; public const int WebErrorObjectStateFormatterDeserializationError = ErrorCodeBase + 11; public const int RuntimeErrorWebResourceFailure = ErrorCodeBase + 12; internal const int ErrorCodeBaseLast = ErrorCodeBase + 12; // ---------------------------------- // Audit codes // ---------------------------------- public const int AuditCodeBase = 4000; // success codes public const int AuditFormsAuthenticationSuccess = AuditCodeBase + 1; public const int AuditMembershipAuthenticationSuccess = AuditCodeBase + 2; public const int AuditUrlAuthorizationSuccess = AuditCodeBase + 3; public const int AuditFileAuthorizationSuccess = AuditCodeBase + 4; // failure codes public const int AuditFormsAuthenticationFailure = AuditCodeBase +5; public const int AuditMembershipAuthenticationFailure = AuditCodeBase + 6; public const int AuditUrlAuthorizationFailure = AuditCodeBase + 7; public const int AuditFileAuthorizationFailure = AuditCodeBase + 8; public const int AuditInvalidViewStateFailure = AuditCodeBase + 9; public const int AuditUnhandledSecurityException = AuditCodeBase + 10; public const int AuditUnhandledAccessException = AuditCodeBase + 11; internal const int AuditCodeBaseLast = AuditCodeBase + 11; // Misc events public const int MiscCodeBase = 6000; public const int WebEventProviderInformation = MiscCodeBase + 1; internal const int MiscCodeBaseLast = MiscCodeBase + 1; // Last code base internal const int LastCodeBase = 6000; ///////////////////////////////////////////////////// // Detail Codes ///////////////////////////////////////////////////// public const int ApplicationDetailCodeBase = 50000; public const int ApplicationShutdownUnknown = ApplicationDetailCodeBase + 1; public const int ApplicationShutdownHostingEnvironment = ApplicationDetailCodeBase + 2; public const int ApplicationShutdownChangeInGlobalAsax = ApplicationDetailCodeBase + 3; public const int ApplicationShutdownConfigurationChange = ApplicationDetailCodeBase + 4; public const int ApplicationShutdownUnloadAppDomainCalled = ApplicationDetailCodeBase + 5; public const int ApplicationShutdownChangeInSecurityPolicyFile = ApplicationDetailCodeBase + 6; public const int ApplicationShutdownBinDirChangeOrDirectoryRename = ApplicationDetailCodeBase + 7; public const int ApplicationShutdownBrowsersDirChangeOrDirectoryRename = ApplicationDetailCodeBase + 8; public const int ApplicationShutdownCodeDirChangeOrDirectoryRename = ApplicationDetailCodeBase + 9; public const int ApplicationShutdownResourcesDirChangeOrDirectoryRename = ApplicationDetailCodeBase + 10; public const int ApplicationShutdownIdleTimeout = ApplicationDetailCodeBase + 11; public const int ApplicationShutdownPhysicalApplicationPathChanged = ApplicationDetailCodeBase + 12; public const int ApplicationShutdownHttpRuntimeClose = ApplicationDetailCodeBase + 13; public const int ApplicationShutdownInitializationError = ApplicationDetailCodeBase + 14; public const int ApplicationShutdownMaxRecompilationsReached = ApplicationDetailCodeBase + 15; public const int StateServerConnectionError = ApplicationDetailCodeBase + 16; public const int ApplicationShutdownBuildManagerChange = ApplicationDetailCodeBase + 17; // Audit detail codes public const int AuditDetailCodeBase = 50200; public const int InvalidTicketFailure = AuditDetailCodeBase + 1; public const int ExpiredTicketFailure = AuditDetailCodeBase + 2; public const int InvalidViewStateMac = AuditDetailCodeBase + 3; public const int InvalidViewState = AuditDetailCodeBase + 4; // Web Event provider detail codes public const int WebEventDetailCodeBase = 50300; public const int SqlProviderEventsDropped = WebEventDetailCodeBase + 1; // Application extensions should start from here public const int WebExtendedBase = 100000; internal static string MessageFromEventCode(int eventCode, int eventDetailCode) { string msg = null; string detailMsg = null; if (eventDetailCode != 0) { switch(eventDetailCode) { case ApplicationShutdownUnknown: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownUnknown); break; case ApplicationShutdownHostingEnvironment: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownHostingEnvironment); break; case ApplicationShutdownChangeInGlobalAsax: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownChangeInGlobalAsax); break; case ApplicationShutdownConfigurationChange: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownConfigurationChange); break; case ApplicationShutdownUnloadAppDomainCalled: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownUnloadAppDomainCalled); break; case ApplicationShutdownChangeInSecurityPolicyFile: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownChangeInSecurityPolicyFile); break; case ApplicationShutdownBinDirChangeOrDirectoryRename: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownBinDirChangeOrDirectoryRename); break; case ApplicationShutdownBrowsersDirChangeOrDirectoryRename: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownBrowsersDirChangeOrDirectoryRename); break; case ApplicationShutdownCodeDirChangeOrDirectoryRename: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownCodeDirChangeOrDirectoryRename); break; case ApplicationShutdownResourcesDirChangeOrDirectoryRename: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownResourcesDirChangeOrDirectoryRename); break; case ApplicationShutdownIdleTimeout: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownIdleTimeout); break; case ApplicationShutdownPhysicalApplicationPathChanged: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownPhysicalApplicationPathChanged); break; case ApplicationShutdownHttpRuntimeClose: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownHttpRuntimeClose); break; case ApplicationShutdownInitializationError: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownInitializationError); break; case ApplicationShutdownMaxRecompilationsReached: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownMaxRecompilationsReached); break; case ApplicationShutdownBuildManagerChange: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ApplicationShutdownBuildManagerChange); break; case StateServerConnectionError: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_StateServerConnectionError); break; case InvalidTicketFailure: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_InvalidTicketFailure); break; case ExpiredTicketFailure: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_ExpiredTicketFailure); break; case InvalidViewStateMac: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_InvalidViewStateMac); break; case InvalidViewState: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_InvalidViewState); break; case SqlProviderEventsDropped: detailMsg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_detail_SqlProviderEventsDropped); break; default: break; } } switch(eventCode) { case ApplicationStart: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationStart); break; case ApplicationShutdown: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationShutdown); break; case ApplicationCompilationStart: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationCompilationStart); break; case ApplicationCompilationEnd: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationCompilationEnd); break; case ApplicationHeartbeat: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_ApplicationHeartbeat); break; case RequestTransactionComplete: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RequestTransactionComplete); break; case RequestTransactionAbort: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RequestTransactionAbort); break; case RuntimeErrorRequestAbort: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorRequestAbort); break; case RuntimeErrorViewStateFailure: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorViewStateFailure); break; case RuntimeErrorValidationFailure: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorValidationFailure); break; case RuntimeErrorPostTooLarge: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorPostTooLarge); break; case RuntimeErrorUnhandledException: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_RuntimeErrorUnhandledException); break; case WebErrorParserError: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_WebErrorParserError); break; case WebErrorCompilationError: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_WebErrorCompilationError); break; case WebErrorConfigurationError: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_WebErrorConfigurationError); break; case AuditUnhandledSecurityException: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditUnhandledSecurityException); break; case AuditInvalidViewStateFailure: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditInvalidViewStateFailure); break; case AuditFormsAuthenticationSuccess: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditFormsAuthenticationSuccess); break; case AuditUrlAuthorizationSuccess: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditUrlAuthorizationSuccess); break; case AuditFileAuthorizationFailure: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditFileAuthorizationFailure); break; case AuditFormsAuthenticationFailure: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditFormsAuthenticationFailure); break; case AuditFileAuthorizationSuccess: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditFileAuthorizationSuccess); break; case AuditMembershipAuthenticationSuccess: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditMembershipAuthenticationSuccess); break; case AuditMembershipAuthenticationFailure: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditMembershipAuthenticationFailure); break; case AuditUrlAuthorizationFailure: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditUrlAuthorizationFailure); break; case AuditUnhandledAccessException: msg = WebBaseEvent.FormatResourceStringWithCache(SR.Webevent_msg_AuditUnhandledAccessException); break; default: Debug.Assert(false, "ASP.NET event code " + eventCode.ToString(CultureInfo.InvariantCulture) + " doesn't have message string mapped to it"); return String.Empty; } if (detailMsg != null) { msg += " " + detailMsg; } return msg; } // Both WebBaseEvents and HealthMonitoringSectionHelper has to store information per {event type, event code}. // But for system event type, eventCode and event type has a N:1 relationship. Meaning every event // code can be mapped to one and only one event type. So instead of using {event type, event code} as // the key, we can use just the event code as the key. // The simplest way is to use a hashtable. But in order to boost performance, we store those // information using an array with event code as the key. However, because the event code range is not // continuous, and has large gap between categories, instead we use an NxM array, when N is number // of major event code categories (e.g. ApplicationCodeBase and RequestCodeBase), and M is the // max number of per category event code among all the catogories. // WebBaseEvents and HealthMonitoringSectionHelper will each maintain its own NxM arrays, and it // depends on the following functions to calculate the sizes of the array, and to convert an event // code into a (x,y) coordinate. internal static int[] s_eventArrayDimensionSizes = new int[2]; internal static int GetEventArrayDimensionSize(int dim) { Debug.Assert(dim == 0 || dim == 1, "dim == 0 || dim == 1"); return s_eventArrayDimensionSizes[dim]; } // Convert an event code into a (x,y) coordinate. internal static void GetEventArrayIndexsFromEventCode(int eventCode, out int index0, out int index1) { index0 = eventCode/1000 - 1; index1 = eventCode - (eventCode/1000)*1000 - 1; Debug.Assert(index0 >= 0 && index0 < GetEventArrayDimensionSize(0), "Index0 of system eventCode out of expected range: " + eventCode); Debug.Assert(index1 >= 0 && index1 < GetEventArrayDimensionSize(1), "Index1 of system eventCode out of expected range: " + eventCode); } static void InitEventArrayDimensions() { int sizeOf2ndDim = 0; int size; // Below is the manual way to figure out the size of the 2nd dimension. size = WebEventCodes.ApplicationCodeBaseLast - WebEventCodes.ApplicationCodeBase; if (size > sizeOf2ndDim) { sizeOf2ndDim = size; } size = WebEventCodes.RequestCodeBaseLast - WebEventCodes.RequestCodeBase; if (size > sizeOf2ndDim) { sizeOf2ndDim = size; } size = WebEventCodes.ErrorCodeBaseLast - WebEventCodes.ErrorCodeBase; if (size > sizeOf2ndDim) { sizeOf2ndDim = size; } size = WebEventCodes.AuditCodeBaseLast - WebEventCodes.AuditCodeBase; if (size > sizeOf2ndDim) { sizeOf2ndDim = size; } size = WebEventCodes.MiscCodeBaseLast - WebEventCodes.MiscCodeBase; if (size > sizeOf2ndDim) { sizeOf2ndDim = size; } s_eventArrayDimensionSizes[0] = WebEventCodes.LastCodeBase/1000; s_eventArrayDimensionSizes[1] = sizeOf2ndDim; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Threading; using System.ComponentModel.Design; using System.Drawing.Drawing2D; /* Copyright (c) 2008,2009 DI Zimmermann Stephan (stefan.zimmermann@tele2.at) * * 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. */ namespace GraphLib { public partial class PlotterDisplayEx : UserControl { #region MEMBERS delegate void InvokeVoidFuncDelegate(); PlotterGraphSelectCurvesForm GraphPropertiesForm = null; PrintPreviewForm printPreviewForm = null; private PrecisionTimer.Timer mTimer = null; private float play_speed = 0.5f; private float play_speed_max = 10f; private float play_speed_min = 0.5f; private bool paused = false; private bool isRunning = false; #endregion #region CONSTRUCTOR public PlotterDisplayEx() { InitializeComponent(); mTimer = new PrecisionTimer.Timer(); mTimer.Period = 50; // 20 fps mTimer.Tick += new EventHandler(OnTimerTick); play_speed = 0.5f; // 20x10 = 200 values per second == sample frequency mTimer.Start(); isRunning = false; } void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { String text = e.ClickedItem.Text; foreach (DataSource s in gPane.Sources) { if (s.Name == text) { s.Active ^= true; gPane.Invalidate(); break; } } } #endregion #region PROPERTIES [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [Editor(typeof(System.ComponentModel.Design.CollectionEditor), typeof(System.Drawing.Design.UITypeEditor))] public List<DataSource> DataSources { get { return gPane.Sources; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [Editor(typeof(System.ComponentModel.Design.CollectionEditor), typeof(System.Drawing.Design.UITypeEditor))] public PlotterGraphPaneEx.LayoutMode PanelLayout { get { return gPane.layout; } set { gPane.layout = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [Editor(typeof(System.ComponentModel.Design.CollectionEditor), typeof(System.Drawing.Design.UITypeEditor))] public SmoothingMode Smoothing { get { return gPane.smoothing; } set { gPane.smoothing = value; } } [Category("Playback")] [DefaultValue(typeof(float), "2")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public float PlaySpeed { get { return play_speed; } set { play_speed = value; } } [Category("Playback")] [DefaultValue(typeof(bool), "true")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public bool ShowMovingGrid { get { return gPane.hasMovingGrid; } set { gPane.hasMovingGrid = value; } } [Category("Properties")] [DefaultValue(typeof(Color), "")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Color BackgroundColorTop { get { return gPane.BgndColorTop; } set { gPane.BgndColorTop = value; } } [Category("Properties")] [DefaultValue(typeof(Color), "")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Color BackgroundColorBot { get { return gPane.BgndColorBot; } set { gPane.BgndColorBot = value; } } [Category("Properties")] [DefaultValue(typeof(Color), "")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Color DashedGridColor { get { return gPane.MinorGridColor; } set { gPane.MinorGridColor = value; } } [Category("Properties")] [DefaultValue(typeof(Color), "")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Color SolidGridColor { get { return gPane.MajorGridColor; } set { gPane.MajorGridColor = value; } } public bool DoubleBuffering { get { return gPane.useDoubleBuffer; } set { gPane.useDoubleBuffer = value; } } #endregion #region PUBLIC METHODS public void SetDisplayRangeX(float x_start, float x_end ) { gPane.XD0 = x_start; gPane.XD1 = x_end; gPane.CurXD0 = gPane.XD0; gPane.CurXD1 = gPane.XD1; } public void SetGridDistanceX(float grid_dist_x_samples) { gPane.grid_distance_x = grid_dist_x_samples; } public void SetGridOriginX(float off_x) { gPane.grid_off_x = off_x; } #endregion #region PRIVATE METHODS protected override void Dispose(bool disposing) { paused = true; if (mTimer.IsRunning) { mTimer.Stop(); mTimer.Dispose(); } base.Dispose(disposing); } public void Start() { if (isRunning == false && paused == false) { gPane.starting_idx = 0; paused = false; isRunning = true; //mTimer.Start(); tb1.Buttons[0].ImageIndex = 2; } else { if (paused == false) { //mTimer.Stop(); paused = true; } else { // mTimer.Start(); paused = false; } if (paused) { tb1.Buttons[0].ImageIndex = 0; } else { tb1.Buttons[0].ImageIndex = 2; } } } public void Stop() { if (isRunning) { //mTimer.Stop(); isRunning = false; paused = false; hScrollBar1.Value = 0; tb1.Buttons[0].ImageIndex = 0; } } private void tb1_ButtonClick(object sender, ToolBarButtonClickEventArgs e) { bool pushed = e.Button.Pushed; switch (e.Button.Tag.ToString().ToLower()) { case "play": Start(); break; case "stop": Stop(); break; case "print": // // todo implement print preview ShowPrintPreview(); break; } } private void SetPlayPanelVisible() { panel1.Visible = true; tb1.Buttons[0].Visible = true; tb1.Buttons[1].Visible = true; } private void SetPlayPanelInvisible() { panel1.Visible = false; tb1.Buttons[0].Visible = false; tb1.Buttons[1].Visible = false; } private void UpdateControl() { try { bool AllAutoscaled = true; foreach (DataSource s in gPane.Sources) { AllAutoscaled &= s.AutoScaleX; } if (AllAutoscaled == true) { if (panel1.Visible == true) { this.Invoke(new MethodInvoker(SetPlayPanelInvisible)); } } else { if (panel1.Visible == false) { this.Invoke(new MethodInvoker(SetPlayPanelVisible)); } } } catch { } } private void UpdatePlayback() { if (!paused && isRunning == true) { try { gPane.starting_idx += play_speed; UpdateScrollBar(); gPane.Invalidate(); } catch { } } } private void OnTimerTick(object sender, EventArgs e) { UpdateControl(); UpdatePlayback(); } private void UpdateScrollBar() { if (InvokeRequired) { Invoke(new MethodInvoker(UpdateScrollBar)); } else { if (gPane.Sources.Count > 0) { if (gPane.starting_idx > gPane.Sources[0].Length) { hScrollBar1.Value = 10000; } else if (gPane.starting_idx >= 0) { hScrollBar1.Value = 10000 * (int)gPane.starting_idx / gPane.Sources[0].Length; } else { hScrollBar1.Value = 0; } } else { hScrollBar1.Value = 0; } } } private void OnScrollbarScroll(object sender, ScrollEventArgs e) { if (gPane.Sources.Count > 0) { int val = hScrollBar1.Value; gPane.starting_idx = (int)(gPane.Sources[0].Length * (float)val / 10000.0f); gPane.Invalidate(); } } private void OnScrollBarSpeedScroll(object sender, ScrollEventArgs e) { float Percentage = hScrollBar2.Value / 10000.0f; float delta = play_speed_max - play_speed_min; play_speed = play_speed_min + Percentage * delta; } #endregion private void ShowPrintPreview() { if (printPreviewForm == null) { printPreviewForm = new PrintPreviewForm(); } printPreviewForm.GraphPanel = this.gPane; printPreviewForm.Show(); printPreviewForm.TopMost = true; printPreviewForm.Invalidate(); } private void selectGraphsToolStripMenuItem_Click(object sender, EventArgs e) { if (GraphPropertiesForm == null) { GraphPropertiesForm = new PlotterGraphSelectCurvesForm(); } GraphPropertiesForm.GraphPanel = this.gPane; GraphPropertiesForm.Show(); // GraphPropertiesForm.BringToFront(); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Internal; using System.Reflection; using System.Runtime.Loader; using System.Security; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using PathType = System.IO.Path; namespace Microsoft.PowerShell.Commands { /// <summary> /// Languages supported for code generation. /// </summary> public enum Language { /// <summary> /// The C# programming language. /// </summary> CSharp } /// <summary> /// Types supported for the OutputAssembly parameter. /// </summary> public enum OutputAssemblyType { /// <summary> /// A Dynamically linked library (DLL). /// </summary> Library, /// <summary> /// An executable application that targets the console subsystem. /// </summary> ConsoleApplication, /// <summary> /// An executable application that targets the graphical subsystem. /// </summary> WindowsApplication } /// <summary> /// Adds a new type to the Application Domain. /// This version is based on CodeAnalysis (Roslyn). /// </summary> [Cmdlet(VerbsCommon.Add, "Type", DefaultParameterSetName = FromSourceParameterSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096601")] [OutputType(typeof(Type))] public sealed class AddTypeCommand : PSCmdlet { #region Parameters /// <summary> /// The source code of this generated type. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = FromSourceParameterSetName)] [ValidateTrustedData] public string TypeDefinition { get { return _sourceCode; } set { _sourceCode = value; } } /// <summary> /// The name of the type (class) used for auto-generated types. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = FromMemberParameterSetName)] [ValidateTrustedData] public string Name { get; set; } /// <summary> /// The source code of this generated method / member. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = FromMemberParameterSetName)] public string[] MemberDefinition { get { return new string[] { _sourceCode }; } set { _sourceCode = string.Empty; if (value != null) { _sourceCode = string.Join("\n", value); } } } private string _sourceCode; /// <summary> /// The namespace used for the auto-generated type. /// </summary> [Parameter(ParameterSetName = FromMemberParameterSetName)] [AllowNull] [Alias("NS")] public string Namespace { get; set; } = "Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes"; /// <summary> /// Any using statements required by the auto-generated type. /// </summary> [Parameter(ParameterSetName = FromMemberParameterSetName)] [ValidateNotNull()] [Alias("Using")] public string[] UsingNamespace { get; set; } = Array.Empty<string>(); /// <summary> /// The path to the source code or DLL to load. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = FromPathParameterSetName)] [ValidateTrustedData] public string[] Path { get { return _paths; } set { if (value == null) { _paths = null; return; } string[] pathValue = value; List<string> resolvedPaths = new(); // Verify that the paths are resolved and valid foreach (string path in pathValue) { // Try to resolve the path Collection<string> newPaths = SessionState.Path.GetResolvedProviderPathFromPSPath(path, out ProviderInfo _); // If it didn't resolve, add the original back // for a better error message. if (newPaths.Count == 0) { resolvedPaths.Add(path); } else { resolvedPaths.AddRange(newPaths); } } ProcessPaths(resolvedPaths); } } /// <summary> /// The literal path to the source code or DLL to load. /// </summary> [Parameter(Mandatory = true, ParameterSetName = FromLiteralPathParameterSetName)] [Alias("PSPath", "LP")] [ValidateTrustedData] public string[] LiteralPath { get { return _paths; } set { if (value == null) { _paths = null; return; } List<string> resolvedPaths = new(); foreach (string path in value) { string literalPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); resolvedPaths.Add(literalPath); } ProcessPaths(resolvedPaths); } } private void ProcessPaths(List<string> resolvedPaths) { // Validate file extensions. // Make sure we don't mix source files from different languages (if we support any other languages in future). string activeExtension = null; foreach (string path in resolvedPaths) { string currentExtension = PathType.GetExtension(path).ToUpperInvariant(); switch (currentExtension) { case ".CS": Language = Language.CSharp; break; case ".DLL": _loadAssembly = true; break; // Throw an error if it is an unrecognized extension default: ErrorRecord errorRecord = new( new Exception( StringUtil.Format(AddTypeStrings.FileExtensionNotSupported, currentExtension)), "EXTENSION_NOT_SUPPORTED", ErrorCategory.InvalidArgument, currentExtension); ThrowTerminatingError(errorRecord); break; } if (activeExtension == null) { activeExtension = currentExtension; } else if (!string.Equals(activeExtension, currentExtension, StringComparison.OrdinalIgnoreCase)) { // All files must have the same extension otherwise throw. ErrorRecord errorRecord = new( new Exception( StringUtil.Format(AddTypeStrings.MultipleExtensionsNotSupported)), "MULTIPLE_EXTENSION_NOT_SUPPORTED", ErrorCategory.InvalidArgument, currentExtension); ThrowTerminatingError(errorRecord); } } _paths = resolvedPaths.ToArray(); } private string[] _paths; /// <summary> /// The name of the assembly to load. /// </summary> [Parameter(Mandatory = true, ParameterSetName = FromAssemblyNameParameterSetName)] [Alias("AN")] [ValidateTrustedData] public string[] AssemblyName { get; set; } private bool _loadAssembly = false; /// <summary> /// The language used to compile the source code. /// Default is C#. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] public Language Language { get; set; } = Language.CSharp; /// <summary> /// Any reference DLLs to use in the compilation. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] [Alias("RA")] public string[] ReferencedAssemblies { get { return _referencedAssemblies; } set { if (value != null) { _referencedAssemblies = value; } } } private string[] _referencedAssemblies = Array.Empty<string>(); /// <summary> /// The path to the output assembly. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] [Alias("OA")] public string OutputAssembly { get { return _outputAssembly; } set { _outputAssembly = value; if (_outputAssembly != null) { _outputAssembly = _outputAssembly.Trim(); // Try to resolve the path ProviderInfo provider = null; Collection<string> newPaths = new(); try { newPaths = SessionState.Path.GetResolvedProviderPathFromPSPath(_outputAssembly, out provider); } // Ignore the ItemNotFound -- we handle it. catch (ItemNotFoundException) { } ErrorRecord errorRecord = new( new Exception( StringUtil.Format(AddTypeStrings.OutputAssemblyDidNotResolve, _outputAssembly)), "INVALID_OUTPUT_ASSEMBLY", ErrorCategory.InvalidArgument, _outputAssembly); // If it resolved to a non-standard provider, // generate an error. if (!string.Equals("FileSystem", provider.Name, StringComparison.OrdinalIgnoreCase)) { ThrowTerminatingError(errorRecord); return; } // If it resolved to more than one path, // generate an error. if (newPaths.Count > 1) { ThrowTerminatingError(errorRecord); return; } // It didn't resolve to any files. They may // want to create the file. else if (newPaths.Count == 0) { // We can't create one with wildcard characters if (WildcardPattern.ContainsWildcardCharacters(_outputAssembly)) { ThrowTerminatingError(errorRecord); } // Create the file else { _outputAssembly = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_outputAssembly); } } // It resolved to a single file else { _outputAssembly = newPaths[0]; } } } } private string _outputAssembly = null; /// <summary> /// The output type of the assembly. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] [Alias("OT")] public OutputAssemblyType OutputType { get; set; } = OutputAssemblyType.Library; /// <summary> /// Flag to pass the resulting types along. /// </summary> [Parameter()] public SwitchParameter PassThru { get; set; } /// <summary> /// Flag to ignore warnings during compilation. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] public SwitchParameter IgnoreWarnings { get; set; } /// <summary> /// Roslyn command line parameters. /// https://github.com/dotnet/roslyn/blob/master/docs/compilers/CSharp/CommandLine.md /// /// Parser options: /// langversion:string - language version from: /// [enum]::GetNames([Microsoft.CodeAnalysis.CSharp.LanguageVersion]) /// define:symbol list - preprocessor symbols: /// /define:UNIX,DEBUG - CSharp /// /// Compilation options: /// optimize{+|-} - optimization level /// parallel{+|-} - concurrent build /// warnaserror{+|-} - report warnings to errors /// warnaserror{+|-}:strings - report specific warnings to errors /// warn:number - warning level (0-4) for CSharp /// nowarn - disable all warnings /// nowarn:strings - disable a list of individual warnings /// usings:strings - ';'-delimited usings for CSharp /// /// Emit options: /// platform:string - limit which platforms this code can run on; must be x86, x64, Itanium, arm, AnyCPU32BitPreferred or anycpu (default) /// delaysign{+|-} - delay-sign the assembly using only the public portion of the strong name key /// keyfile:file - specifies a strong name key file /// keycontainer:string - specifies a strong name key container /// highentropyva{+|-} - enable high-entropy ASLR. /// </summary> [Parameter(ParameterSetName = FromSourceParameterSetName)] [Parameter(ParameterSetName = FromMemberParameterSetName)] [Parameter(ParameterSetName = FromPathParameterSetName)] [Parameter(ParameterSetName = FromLiteralPathParameterSetName)] [ValidateNotNullOrEmpty] public string[] CompilerOptions { get; set; } #endregion Parameters #region GererateSource private string GenerateTypeSource(string typeNamespace, string typeName, string sourceCodeText, Language language) { string usingSource = string.Format( CultureInfo.InvariantCulture, GetUsingTemplate(language), GetUsingSet(language)); string typeSource = string.Format( CultureInfo.InvariantCulture, GetMethodTemplate(language), typeName, sourceCodeText); if (!string.IsNullOrEmpty(typeNamespace)) { return usingSource + string.Format( CultureInfo.InvariantCulture, GetNamespaceTemplate(language), typeNamespace, typeSource); } else { return usingSource + typeSource; } } // Get the -FromMember template for a given language private static string GetMethodTemplate(Language language) { switch (language) { case Language.CSharp: return " public class {0}\n" + " {{\n" + " {1}\n" + " }}\n"; } throw PSTraceSource.NewNotSupportedException(); } // Get the -FromMember namespace template for a given language private static string GetNamespaceTemplate(Language language) { switch (language) { case Language.CSharp: return "namespace {0}\n" + "{{\n" + "{1}\n" + "}}\n"; } throw PSTraceSource.NewNotSupportedException(); } // Get the -FromMember namespace template for a given language private static string GetUsingTemplate(Language language) { switch (language) { case Language.CSharp: return "using System;\n" + "using System.Runtime.InteropServices;\n" + "{0}" + "\n"; } throw PSTraceSource.NewNotSupportedException(); } // Generate the code for the using statements private string GetUsingSet(Language language) { StringBuilder usingNamespaceSet = new(); switch (language) { case Language.CSharp: foreach (string namespaceValue in UsingNamespace) { usingNamespaceSet.Append("using " + namespaceValue + ";\n"); } break; default: throw PSTraceSource.NewNotSupportedException(); } return usingNamespaceSet.ToString(); } #endregion GererateSource /// <summary> /// Prevent code compilation in ConstrainedLanguage mode. /// </summary> protected override void BeginProcessing() { // Prevent code compilation in ConstrainedLanguage mode if (SessionState.LanguageMode == PSLanguageMode.ConstrainedLanguage) { ThrowTerminatingError( new ErrorRecord( new PSNotSupportedException(AddTypeStrings.CannotDefineNewType), nameof(AddTypeStrings.CannotDefineNewType), ErrorCategory.PermissionDenied, targetObject: null)); } // 'ConsoleApplication' and 'WindowsApplication' types are currently not working in .NET Core if (OutputType != OutputAssemblyType.Library) { ThrowTerminatingError( new ErrorRecord( new PSNotSupportedException(AddTypeStrings.AssemblyTypeNotSupported), nameof(AddTypeStrings.AssemblyTypeNotSupported), ErrorCategory.NotImplemented, targetObject: OutputType)); } } /// <summary> /// Generate and load the type(s). /// </summary> protected override void EndProcessing() { // Generate an error if they've specified an output // assembly type without an output assembly if (string.IsNullOrEmpty(_outputAssembly) && this.MyInvocation.BoundParameters.ContainsKey(nameof(OutputType))) { ErrorRecord errorRecord = new( new Exception( string.Format( CultureInfo.CurrentCulture, AddTypeStrings.OutputTypeRequiresOutputAssembly)), "OUTPUTTYPE_REQUIRES_ASSEMBLY", ErrorCategory.InvalidArgument, OutputType); ThrowTerminatingError(errorRecord); return; } if (_loadAssembly) { // File extension is ".DLL" (ParameterSetName = FromPathParameterSetName or FromLiteralPathParameterSetName). LoadAssemblies(_paths); } else if (ParameterSetName == FromAssemblyNameParameterSetName) { LoadAssemblies(AssemblyName); } else { // Process a source code from files or strings. SourceCodeProcessing(); } } #region LoadAssembly // We now ship .NET Core's reference assemblies with PowerShell, so that Add-Type can work // in a predictable way and won't be broken when we move to newer version of .NET Core. // The reference assemblies are located at '$PSHOME\ref' for pwsh. // // For applications that host PowerShell, the 'ref' folder will be deployed to the 'publish' // folder, not where 'System.Management.Automation.dll' is located. So here we should use // the entry assembly's location to construct the path to the 'ref' folder. // For pwsh, the entry assembly is 'pwsh.dll', so the entry assembly's location is still // $PSHOME. // However, 'Assembly.GetEntryAssembly()' returns null when the managed code is called from // unmanaged code (PowerShell WSMan remoting scenario), so in that case, we continue to use // the location of 'System.Management.Automation.dll'. private static readonly string s_netcoreAppRefFolder = PathType.Combine( PathType.GetDirectoryName( (Assembly.GetEntryAssembly() ?? typeof(PSObject).Assembly).Location), "ref"); // Path to the folder where .NET Core runtime assemblies are located. private static readonly string s_frameworkFolder = PathType.GetDirectoryName(typeof(object).Assembly.Location); // These assemblies are always automatically added to ReferencedAssemblies. private static readonly Lazy<PortableExecutableReference[]> s_autoReferencedAssemblies = new(InitAutoIncludedRefAssemblies); // A HashSet of assembly names to be ignored if they are specified in '-ReferencedAssemblies' private static readonly Lazy<HashSet<string>> s_refAssemblyNamesToIgnore = new(InitRefAssemblyNamesToIgnore); // These assemblies are used, when ReferencedAssemblies parameter is not specified. private static readonly Lazy<IEnumerable<PortableExecutableReference>> s_defaultAssemblies = new(InitDefaultRefAssemblies); private bool InMemory { get { return string.IsNullOrEmpty(_outputAssembly); } } // These dictionaries prevent reloading already loaded and unchanged code. // We don't worry about unbounded growing of the cache because in .Net Core 2.0 we can not unload assemblies. // TODO: review if we will be able to unload assemblies after migrating to .Net Core 2.1. private static readonly HashSet<string> s_sourceTypesCache = new(); private static readonly Dictionary<int, Assembly> s_sourceAssemblyCache = new(); private static readonly string s_defaultSdkDirectory = Utils.DefaultPowerShellAppBase; private const ReportDiagnostic defaultDiagnosticOption = ReportDiagnostic.Error; private static readonly string[] s_writeInformationTags = new string[] { "PSHOST" }; private int _syntaxTreesHash; private const string FromMemberParameterSetName = "FromMember"; private const string FromSourceParameterSetName = "FromSource"; private const string FromPathParameterSetName = "FromPath"; private const string FromLiteralPathParameterSetName = "FromLiteralPath"; private const string FromAssemblyNameParameterSetName = "FromAssemblyName"; private void LoadAssemblies(IEnumerable<string> assemblies) { foreach (string assemblyName in assemblies) { // CoreCLR doesn't allow re-load TPA assemblies with different API (i.e. we load them by name and now want to load by path). // LoadAssemblyHelper helps us avoid re-loading them, if they already loaded. Assembly assembly = LoadAssemblyHelper(assemblyName) ?? Assembly.LoadFrom(ResolveAssemblyName(assemblyName, false)); if (PassThru) { WriteTypes(assembly); } } } /// <summary> /// Initialize the list of reference assemblies that will be used when '-ReferencedAssemblies' is not specified. /// </summary> private static IEnumerable<PortableExecutableReference> InitDefaultRefAssemblies() { // Define number of reference assemblies distributed with PowerShell. const int maxPowershellRefAssemblies = 160; const int capacity = maxPowershellRefAssemblies + 1; var defaultRefAssemblies = new List<PortableExecutableReference>(capacity); foreach (string file in Directory.EnumerateFiles(s_netcoreAppRefFolder, "*.dll", SearchOption.TopDirectoryOnly)) { defaultRefAssemblies.Add(MetadataReference.CreateFromFile(file)); } // Add System.Management.Automation.dll defaultRefAssemblies.Add(MetadataReference.CreateFromFile(typeof(PSObject).Assembly.Location)); // We want to avoid reallocating the internal array, so we assert if the list capacity has increased. Diagnostics.Assert( defaultRefAssemblies.Capacity <= capacity, $"defaultRefAssemblies was resized because of insufficient initial capacity! A capacity of {defaultRefAssemblies.Count} is required."); return defaultRefAssemblies; } /// <summary> /// Initialize the set of assembly names that should be ignored when they are specified in '-ReferencedAssemblies'. /// - System.Private.CoreLib.ni.dll - the runtime dll that contains most core/primitive types /// - System.Private.Uri.dll - the runtime dll that contains 'System.Uri' and related types /// Referencing these runtime dlls may cause ambiguous type identity or other issues. /// - System.Runtime.dll - the corresponding reference dll will be automatically included /// - System.Runtime.InteropServices.dll - the corresponding reference dll will be automatically included. /// </summary> private static HashSet<string> InitRefAssemblyNamesToIgnore() { return new HashSet<string>(StringComparer.OrdinalIgnoreCase) { PathType.GetFileName(typeof(object).Assembly.Location), PathType.GetFileName(typeof(Uri).Assembly.Location), PathType.GetFileName(GetReferenceAssemblyPathBasedOnType(typeof(object))), PathType.GetFileName(GetReferenceAssemblyPathBasedOnType(typeof(SecureString))) }; } /// <summary> /// Initialize the list of reference assemblies that will be automatically added when '-ReferencedAssemblies' is specified. /// </summary> private static PortableExecutableReference[] InitAutoIncludedRefAssemblies() { return new PortableExecutableReference[] { MetadataReference.CreateFromFile(GetReferenceAssemblyPathBasedOnType(typeof(object))), MetadataReference.CreateFromFile(GetReferenceAssemblyPathBasedOnType(typeof(SecureString))) }; } /// <summary> /// Get the path of reference assembly where the type is declared. /// </summary> private static string GetReferenceAssemblyPathBasedOnType(Type type) { string refAsmFileName = PathType.GetFileName(ClrFacade.GetAssemblies(type.FullName).First().Location); return PathType.Combine(s_netcoreAppRefFolder, refAsmFileName); } private string ResolveAssemblyName(string assembly, bool isForReferenceAssembly) { ErrorRecord errorRecord; // if it's a path, resolve it if (assembly.Contains(PathType.DirectorySeparatorChar) || assembly.Contains(PathType.AltDirectorySeparatorChar)) { if (PathType.IsPathRooted(assembly)) { return assembly; } else { var paths = SessionState.Path.GetResolvedPSPathFromPSPath(assembly); if (paths.Count > 0) { return paths[0].Path; } else { errorRecord = new ErrorRecord( new Exception( string.Format(ParserStrings.ErrorLoadingAssembly, assembly)), "ErrorLoadingAssembly", ErrorCategory.InvalidOperation, assembly); ThrowTerminatingError(errorRecord); return null; } } } string refAssemblyDll = assembly; if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { // It could be a short assembly name or a full assembly name, but we // always want the short name to find the corresponding assembly file. var assemblyName = new AssemblyName(assembly); refAssemblyDll = assemblyName.Name + ".dll"; } // We look up in reference/framework only when it's for resolving reference assemblies. // In case of 'Add-Type -AssemblyName' scenario, we don't attempt to resolve against framework assemblies because // 1. Explicitly loading a framework assembly usually is not necessary in PowerShell 6+. // 2. A user should use assembly name instead of path if they want to explicitly load a framework assembly. if (isForReferenceAssembly) { // If it's for resolving a reference assembly, then we look in NetCoreApp ref assemblies first string netcoreAppRefPath = PathType.Combine(s_netcoreAppRefFolder, refAssemblyDll); if (File.Exists(netcoreAppRefPath)) { return netcoreAppRefPath; } // Look up the assembly in the framework folder. This may happen when assembly is not part of // NetCoreApp, but comes from an additional package, such as 'Json.Net'. string frameworkPossiblePath = PathType.Combine(s_frameworkFolder, refAssemblyDll); if (File.Exists(frameworkPossiblePath)) { return frameworkPossiblePath; } // The assembly name may point to a third-party assembly that is already loaded at run time. if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { Assembly result = LoadAssemblyHelper(assembly); if (result != null) { return result.Location; } } } // Look up the assembly in the current folder var resolvedPaths = SessionState.Path.GetResolvedPSPathFromPSPath(refAssemblyDll); if (resolvedPaths.Count > 0) { string currentFolderPath = resolvedPaths[0].Path; if (File.Exists(currentFolderPath)) { return currentFolderPath; } } errorRecord = new ErrorRecord( new Exception( string.Format(ParserStrings.ErrorLoadingAssembly, assembly)), "ErrorLoadingAssembly", ErrorCategory.InvalidOperation, assembly); ThrowTerminatingError(errorRecord); return null; } // LoadWithPartialName is deprecated, so we have to write the closest approximation possible. // However, this does give us a massive usability improvement, as users can just say // Add-Type -AssemblyName Forms (instead of System.Windows.Forms) // This is just long, not unmaintainable. private static Assembly LoadAssemblyHelper(string assemblyName) { Assembly loadedAssembly = null; // First try by strong name try { loadedAssembly = Assembly.Load(new AssemblyName(assemblyName)); } // Generates a FileNotFoundException if you can't load the strong type. // So we'll try from the short name. catch (System.IO.FileNotFoundException) { } // File load exception can happen, when we trying to load from the incorrect assembly name // or file corrupted. catch (System.IO.FileLoadException) { } return loadedAssembly; } private IEnumerable<PortableExecutableReference> GetPortableExecutableReferences() { if (ReferencedAssemblies.Length > 0) { var tempReferences = new List<PortableExecutableReference>(s_autoReferencedAssemblies.Value); foreach (string assembly in ReferencedAssemblies) { if (string.IsNullOrWhiteSpace(assembly)) { continue; } string resolvedAssemblyPath = ResolveAssemblyName(assembly, true); // Ignore some specified reference assemblies string fileName = PathType.GetFileName(resolvedAssemblyPath); if (s_refAssemblyNamesToIgnore.Value.Contains(fileName)) { WriteVerbose(StringUtil.Format(AddTypeStrings.ReferenceAssemblyIgnored, resolvedAssemblyPath)); continue; } tempReferences.Add(MetadataReference.CreateFromFile(resolvedAssemblyPath)); } return tempReferences; } else { return s_defaultAssemblies.Value; } } private void WriteTypes(Assembly assembly) { WriteObject(assembly.GetTypes(), true); } #endregion LoadAssembly #region SourceCodeProcessing private static OutputKind OutputAssemblyTypeToOutputKind(OutputAssemblyType outputType) { switch (outputType) { case OutputAssemblyType.Library: return OutputKind.DynamicallyLinkedLibrary; default: throw PSTraceSource.NewNotSupportedException(); } } private CommandLineArguments ParseCompilerOption(IEnumerable<string> args) { string sdkDirectory = s_defaultSdkDirectory; string baseDirectory = this.SessionState.Path.CurrentLocation.Path; switch (Language) { case Language.CSharp: return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory); default: throw PSTraceSource.NewNotSupportedException(); } } private SyntaxTree ParseSourceText(SourceText sourceText, ParseOptions parseOptions, string path = "") { switch (Language) { case Language.CSharp: return CSharpSyntaxTree.ParseText(sourceText, (CSharpParseOptions)parseOptions, path); default: throw PSTraceSource.NewNotSupportedException(); } } private CompilationOptions GetDefaultCompilationOptions() { switch (Language) { case Language.CSharp: return new CSharpCompilationOptions(OutputAssemblyTypeToOutputKind(OutputType)); default: throw PSTraceSource.NewNotSupportedException(); } } private bool isSourceCodeUpdated(List<SyntaxTree> syntaxTrees, out Assembly assembly) { Diagnostics.Assert(syntaxTrees.Count != 0, "syntaxTrees should contains a source code."); _syntaxTreesHash = SyntaxTreeArrayGetHashCode(syntaxTrees); if (s_sourceAssemblyCache.TryGetValue(_syntaxTreesHash, out Assembly hashedAssembly)) { assembly = hashedAssembly; return false; } else { assembly = null; return true; } } private void SourceCodeProcessing() { ParseOptions parseOptions = null; CompilationOptions compilationOptions = null; EmitOptions emitOptions = null; if (CompilerOptions != null) { var arguments = ParseCompilerOption(CompilerOptions); HandleCompilerErrors(arguments.Errors); parseOptions = arguments.ParseOptions; compilationOptions = arguments.CompilationOptions.WithOutputKind(OutputAssemblyTypeToOutputKind(OutputType)); emitOptions = arguments.EmitOptions; } else { parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); compilationOptions = GetDefaultCompilationOptions(); } if (!IgnoreWarnings.IsPresent) { compilationOptions = compilationOptions.WithGeneralDiagnosticOption(defaultDiagnosticOption); } SourceText sourceText; List<SyntaxTree> syntaxTrees = new(); switch (ParameterSetName) { case FromPathParameterSetName: case FromLiteralPathParameterSetName: foreach (string filePath in _paths) { using (var sourceFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { sourceText = SourceText.From(sourceFile); syntaxTrees.Add(ParseSourceText(sourceText, parseOptions, path: filePath)); } } break; case FromMemberParameterSetName: _sourceCode = GenerateTypeSource(Namespace, Name, _sourceCode, Language); sourceText = SourceText.From(_sourceCode); syntaxTrees.Add(ParseSourceText(sourceText, parseOptions)); break; case FromSourceParameterSetName: sourceText = SourceText.From(_sourceCode); syntaxTrees.Add(ParseSourceText(sourceText, parseOptions)); break; default: Diagnostics.Assert(false, "Invalid parameter set: {0}", this.ParameterSetName); break; } if (!string.IsNullOrEmpty(_outputAssembly) && !PassThru.IsPresent) { CompileToAssembly(syntaxTrees, compilationOptions, emitOptions); } else { // if the source code was already compiled and loaded and not changed // we get the assembly from the cache. if (isSourceCodeUpdated(syntaxTrees, out Assembly assembly)) { CompileToAssembly(syntaxTrees, compilationOptions, emitOptions); } else { WriteVerbose(AddTypeStrings.AlreadyCompiledandLoaded); if (PassThru) { WriteTypes(assembly); } } } } private void CompileToAssembly(List<SyntaxTree> syntaxTrees, CompilationOptions compilationOptions, EmitOptions emitOptions) { IEnumerable<PortableExecutableReference> references = GetPortableExecutableReferences(); Compilation compilation = null; switch (Language) { case Language.CSharp: compilation = CSharpCompilation.Create( PathType.GetRandomFileName(), syntaxTrees: syntaxTrees, references: references, options: (CSharpCompilationOptions)compilationOptions); break; default: throw PSTraceSource.NewNotSupportedException(); } DoEmitAndLoadAssembly(compilation, emitOptions); } private void CheckDuplicateTypes(Compilation compilation, out ConcurrentBag<string> newTypes) { AllNamedTypeSymbolsVisitor visitor = new(); visitor.Visit(compilation.Assembly.GlobalNamespace); foreach (var symbolName in visitor.DuplicateSymbols) { ErrorRecord errorRecord = new( new Exception( string.Format(AddTypeStrings.TypeAlreadyExists, symbolName)), "TYPE_ALREADY_EXISTS", ErrorCategory.InvalidOperation, symbolName); WriteError(errorRecord); } if (!visitor.DuplicateSymbols.IsEmpty) { ErrorRecord errorRecord = new( new InvalidOperationException(AddTypeStrings.CompilerErrors), "COMPILER_ERRORS", ErrorCategory.InvalidData, null); ThrowTerminatingError(errorRecord); } newTypes = visitor.UniqueSymbols; return; } // Visit symbols in all namespaces and collect duplicates. private sealed class AllNamedTypeSymbolsVisitor : SymbolVisitor { public readonly ConcurrentBag<string> DuplicateSymbols = new(); public readonly ConcurrentBag<string> UniqueSymbols = new(); public override void VisitNamespace(INamespaceSymbol symbol) { // Main cycle. // For large files we could use symbol.GetMembers().AsParallel().ForAll(s => s.Accept(this)); foreach (var member in symbol.GetMembers()) { member.Accept(this); } } public override void VisitNamedType(INamedTypeSymbol symbol) { // It is namespace-fully-qualified name var symbolFullName = symbol.ToString(); if (s_sourceTypesCache.TryGetValue(symbolFullName, out _)) { DuplicateSymbols.Add(symbolFullName); } else { UniqueSymbols.Add(symbolFullName); } } } private static void CacheNewTypes(ConcurrentBag<string> newTypes) { foreach (var typeName in newTypes) { s_sourceTypesCache.Add(typeName); } } private void CacheAssembly(Assembly assembly) { s_sourceAssemblyCache.Add(_syntaxTreesHash, assembly); } private void DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOptions) { EmitResult emitResult; CheckDuplicateTypes(compilation, out ConcurrentBag<string> newTypes); if (InMemory) { using (var ms = new MemoryStream()) { emitResult = compilation.Emit(peStream: ms, options: emitOptions); HandleCompilerErrors(emitResult.Diagnostics); if (emitResult.Success) { // TODO: We could use Assembly.LoadFromStream() in future. // See https://github.com/dotnet/corefx/issues/26994 ms.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); CacheNewTypes(newTypes); CacheAssembly(assembly); if (PassThru) { WriteTypes(assembly); } } } } else { using (var fs = new FileStream(_outputAssembly, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) { emitResult = compilation.Emit(peStream: fs, options: emitOptions); } HandleCompilerErrors(emitResult.Diagnostics); if (emitResult.Success && PassThru) { Assembly assembly = Assembly.LoadFrom(_outputAssembly); CacheNewTypes(newTypes); CacheAssembly(assembly); WriteTypes(assembly); } } } private void HandleCompilerErrors(ImmutableArray<Diagnostic> compilerDiagnostics) { if (compilerDiagnostics.Length > 0) { bool IsError = false; foreach (var diagnisticRecord in compilerDiagnostics) { // We shouldn't specify input and output files in CompilerOptions parameter // so suppress errors from Roslyn default command line parser: // CS1562: Outputs without source must have the /out option specified // CS2008: No inputs specified // BC2008: No inputs specified // // On emit phase some warnings (like CS8019/BS50001) don't suppressed // and present in diagnostic report with DefaultSeverity equal to Hidden // so we skip them explicitly here too. if (diagnisticRecord.IsSuppressed || diagnisticRecord.DefaultSeverity == DiagnosticSeverity.Hidden || string.Equals(diagnisticRecord.Id, "CS2008", StringComparison.InvariantCulture) || string.Equals(diagnisticRecord.Id, "CS1562", StringComparison.InvariantCulture) || string.Equals(diagnisticRecord.Id, "BC2008", StringComparison.InvariantCulture)) { continue; } if (!IsError) { IsError = diagnisticRecord.Severity == DiagnosticSeverity.Error || (diagnisticRecord.IsWarningAsError && diagnisticRecord.Severity == DiagnosticSeverity.Warning); } string errorText = BuildErrorMessage(diagnisticRecord); if (diagnisticRecord.Severity == DiagnosticSeverity.Warning) { WriteWarning(errorText); } else if (diagnisticRecord.Severity == DiagnosticSeverity.Info) { WriteInformation(errorText, s_writeInformationTags); } else { ErrorRecord errorRecord = new( new Exception(errorText), "SOURCE_CODE_ERROR", ErrorCategory.InvalidData, diagnisticRecord); WriteError(errorRecord); } } if (IsError) { ErrorRecord errorRecord = new( new InvalidOperationException(AddTypeStrings.CompilerErrors), "COMPILER_ERRORS", ErrorCategory.InvalidData, null); ThrowTerminatingError(errorRecord); } } } private static string BuildErrorMessage(Diagnostic diagnisticRecord) { var location = diagnisticRecord.Location; if (location.SourceTree == null) { // For some error types (linker?) we don't have related source code. return diagnisticRecord.ToString(); } else { var text = location.SourceTree.GetText(); var textLines = text.Lines; var lineSpan = location.GetLineSpan(); // FileLinePositionSpan type. var errorLineNumber = lineSpan.StartLinePosition.Line; // This is typical Roslyn diagnostic message which contains // a message number, a source context and an error position. var diagnisticMessage = diagnisticRecord.ToString(); var errorLineString = textLines[errorLineNumber].ToString(); var errorPosition = lineSpan.StartLinePosition.Character; StringBuilder sb = new(diagnisticMessage.Length + errorLineString.Length * 2 + 4); sb.AppendLine(diagnisticMessage); sb.AppendLine(errorLineString); for (var i = 0; i < errorLineString.Length; i++) { if (!char.IsWhiteSpace(errorLineString[i])) { // We copy white chars from the source string. sb.Append(errorLineString, 0, i); // then pad up to the error position. sb.Append(' ', Math.Max(0, errorPosition - i)); // then put "^" into the error position. sb.AppendLine("^"); break; } } return sb.ToString(); } } private static int SyntaxTreeArrayGetHashCode(IEnumerable<SyntaxTree> sts) { // We use our extension method EnumerableExtensions.SequenceGetHashCode<T>(). List<int> stHashes = new(); foreach (var st in sts) { stHashes.Add(SyntaxTreeGetHashCode(st)); } return stHashes.SequenceGetHashCode<int>(); } private static int SyntaxTreeGetHashCode(SyntaxTree st) { int hash; if (string.IsNullOrEmpty(st.FilePath)) { // If the file name does not exist, the source text is set by the user using parameters. // In this case, we assume that the source text is of a small size and we can re-allocate by ToString(). hash = st.ToString().GetHashCode(); } else { // If the file was modified, the write time stamp was also modified // so we do not need to calculate the entire file hash. var updateTime = File.GetLastWriteTimeUtc(st.FilePath); hash = Utils.CombineHashCodes(st.FilePath.GetHashCode(), updateTime.GetHashCode()); } return hash; } #endregion SourceCodeProcessing } }
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> /// A tire shop. /// </summary> public class TireShop_Core : TypeCore, IStore { public TireShop_Core() { this._TypeId = 267; this._Id = "TireShop"; this._Schema_Org_Url = "http://schema.org/TireShop"; string label = ""; GetLabel(out label, "TireShop", typeof(TireShop_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,252}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{252}; 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); } } } }
using DevExpress.Mvvm.Native; using DevExpress.Mvvm.UI.Interactivity; using DevExpress.Mvvm.UI.Native; using System; using System.Collections.Specialized; using System.Reflection; using System.Windows; using System.Windows.Data; using System.Windows.Input; using System.Windows.Markup; namespace DevExpress.Mvvm.UI { [ContentProperty("Commands")] public class CompositeCommandBehavior : Behavior<DependencyObject> { #region Static public static readonly DependencyProperty CommandPropertyNameProperty; [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Code Defects", "DXCA001")] [IgnoreDependencyPropertiesConsistencyChecker] static readonly DependencyProperty CanExecuteProperty; [IgnoreDependencyPropertiesConsistencyChecker] static readonly DependencyProperty InternalItemsProperty; static CompositeCommandBehavior() { Type owner = typeof(CompositeCommandBehavior); CommandPropertyNameProperty = DependencyProperty.Register("CommandPropertyName", typeof(string), owner, new PropertyMetadata("Command", (d, e) => ((CompositeCommandBehavior)d).OnCommandPropertyNameChanged(e))); CanExecuteProperty = DependencyProperty.Register("CanExecute", typeof(bool), owner, new PropertyMetadata(false, (d, e) => ((CompositeCommandBehavior)d).OnCanExecuteChanged(e))); InternalItemsProperty = DependencyProperty.RegisterAttached("InternalItems", typeof(CommandsCollection), owner, new PropertyMetadata(null)); } #endregion #region Dependency Properties public string CommandPropertyName { get { return (string)GetValue(CommandPropertyNameProperty); } set { SetValue(CommandPropertyNameProperty, value); } } bool CanExecute { get { return (bool)GetValue(CanExecuteProperty); } set { SetValue(CanExecuteProperty, value); } } #endregion #region Props public DelegateCommand<object> CompositeCommand { get; private set; } public CommandsCollection Commands { get; private set; } #endregion public CompositeCommandBehavior() { CompositeCommand = new DelegateCommand<object>(CompositeCommandExecute, CompositeCommandCanExecute, false); Commands = new CommandsCollection(); ((INotifyCollectionChanged)Commands).CollectionChanged += OnCommandsChanged; } #region Commands void OnCommandsChanged(object sender, NotifyCollectionChangedEventArgs e) { UpdateCanExecuteBinding(); } void OnCommandsSourceItemsChanged(object sender, NotifyCollectionChangedEventArgs e) { UpdateCanExecuteBinding(); } void UpdateCanExecuteBinding() { MultiBinding multiBinding = new MultiBinding() { Converter = new BooleanMultiValueConverter() }; for(int i = 0; i < Commands.Count; i++) { multiBinding.Bindings.Add(new Binding("CanExecute") { Mode = BindingMode.OneWay, Source = Commands[i] }); } BindingOperations.SetBinding(this, CanExecuteProperty, multiBinding); } void CompositeCommandExecute(object parameter) { if(!CanExecute) return; foreach(CommandItem item in Commands) item.ExecuteCommand(); } bool CompositeCommandCanExecute(object parameter) { return CanExecute; } void RaiseCompositeCommandCanExecuteChanged() { CompositeCommand.RaiseCanExecuteChanged(); } void OnCanExecuteChanged(DependencyPropertyChangedEventArgs e) { RaiseCompositeCommandCanExecuteChanged(); } #endregion #region Attach|Detach command protected override void OnAttached() { base.OnAttached(); SetAssociatedObjectCommandProperty(CommandPropertyName); AssociatedObject.SetValue(InternalItemsProperty, Commands); } protected override void OnDetaching() { ReleaseAssociatedObjectCommandProperty(CommandPropertyName); AssociatedObject.SetValue(InternalItemsProperty, null); base.OnDetaching(); } void OnCommandPropertyNameChanged(DependencyPropertyChangedEventArgs e) { if(!IsAttached) return; ReleaseAssociatedObjectCommandProperty(e.OldValue as string); SetAssociatedObjectCommandProperty(e.NewValue as string); } PropertyInfo GetCommandProperty(string propName) { return ObjectPropertyHelper.GetPropertyInfoSetter(AssociatedObject, propName); } DependencyProperty GetCommandDependencyProperty(string propName) { return ObjectPropertyHelper.GetDependencyProperty(AssociatedObject, propName); } void SetAssociatedObjectCommandProperty(string propName) { var pi = GetCommandProperty(propName); if(pi != null) pi.SetValue(AssociatedObject, CompositeCommand, null); else GetCommandDependencyProperty(propName).Do(x => AssociatedObject.SetValue(x, CompositeCommand)); } void ReleaseAssociatedObjectCommandProperty(string propName) { var pi = GetCommandProperty(propName); if(pi != null) { if(pi.GetValue(AssociatedObject, null) == CompositeCommand) pi.SetValue(AssociatedObject, null, null); } else { DependencyProperty commandProperty = GetCommandDependencyProperty(propName); if(commandProperty != null && AssociatedObject.GetValue(commandProperty) == CompositeCommand) AssociatedObject.SetValue(commandProperty, null); } } #endregion } public class CommandsCollection : FreezableCollection<CommandItem> { } public class CommandItem : DependencyObjectExt { #region Static public static readonly DependencyProperty CommandProperty; public static readonly DependencyProperty CommandParameterProperty; public static readonly DependencyProperty CheckCanExecuteProperty; public static readonly DependencyProperty CanExecuteProperty; static readonly DependencyPropertyKey CanExecutePropertyKey; static CommandItem() { Type owner = typeof(CommandItem); CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), owner, new PropertyMetadata(null, (d, e) => ((CommandItem)d).OnCommandChanged(e))); CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), owner, new PropertyMetadata(null, (d, e) => ((CommandItem)d).UpdateCanExecute())); CheckCanExecuteProperty = DependencyProperty.Register("CheckCanExecute", typeof(bool), owner, new PropertyMetadata(true, (d, e) => ((CommandItem)d).UpdateCanExecute())); CanExecutePropertyKey = DependencyProperty.RegisterReadOnly("CanExecute", typeof(bool), owner, new PropertyMetadata(false)); CanExecuteProperty = CanExecutePropertyKey.DependencyProperty; } #endregion #region Dependency Properties public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } } public object CommandParameter { get { return GetValue(CommandParameterProperty); } set { SetValue(CommandParameterProperty, value); } } public bool CheckCanExecute { get { return (bool)GetValue(CheckCanExecuteProperty); } set { SetValue(CheckCanExecuteProperty, value); } } public bool CanExecute { get { return (bool)GetValue(CanExecuteProperty); } private set { SetValue(CanExecutePropertyKey, value); } } #endregion public bool ExecuteCommand() { if(!CanExecute) return false; Command.Execute(CommandParameter); return true; } void OnCommandChanged(DependencyPropertyChangedEventArgs e) { e.OldValue.With(x => x as ICommand).Do(o => o.CanExecuteChanged -= OnCommandCanExecuteChanged); e.NewValue.With(x => x as ICommand).Do(o => o.CanExecuteChanged += OnCommandCanExecuteChanged); UpdateCanExecute(); } void OnCommandCanExecuteChanged(object sender, EventArgs e) { UpdateCanExecute(); } void UpdateCanExecute() { CanExecute = Command != null && (!CheckCanExecute || Command.CanExecute(CommandParameter)); } } class BooleanMultiValueConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if(values == null || values.Length == 0) return false; foreach(bool value in values) if(!value) return false; return true; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Azure.Core; using Azure.Messaging.ServiceBus.Primitives; namespace Azure.Messaging.ServiceBus.Administration { /// <summary> /// Represents the correlation rule filter expression. /// </summary> /// <remarks> /// <para> /// A CorrelationRuleFilter holds a set of conditions that are matched against one of more of an arriving message's user and system properties. /// A common use is a match against the <see cref="ServiceBusMessage.CorrelationId"/> property, but the application can also choose to match against /// <see cref="ServiceBusMessage.ContentType"/>, <see cref="ServiceBusMessage.Subject"/>, <see cref="ServiceBusMessage.MessageId"/>, <see cref="ServiceBusMessage.ReplyTo"/>, /// <see cref="ServiceBusMessage.ReplyToSessionId"/>, <see cref="ServiceBusMessage.SessionId"/>, <see cref="ServiceBusMessage.To"/>, and any user-defined properties. /// A match exists when an arriving message's value for a property is equal to the value specified in the correlation filter. For string expressions, /// the comparison is case-sensitive. When specifying multiple match properties, the filter combines them as a logical AND condition, /// meaning all conditions must match for the filter to match. /// </para> /// <para> /// The CorrelationRuleFilter provides an efficient shortcut for declarations of filters that deal only with correlation equality. /// In this case the cost of the lexicographical analysis of the expression can be avoided. /// Not only will correlation filters be optimized at declaration time, but they will also be optimized at runtime. /// Correlation filter matching can be reduced to a hashtable lookup, which aggregates the complexity of the set of defined correlation filters to O(1). /// </para> /// </remarks> public sealed class CorrelationRuleFilter : RuleFilter { /// <summary> /// Initializes a new instance of the <see cref="CorrelationRuleFilter" /> class with default values. /// </summary> public CorrelationRuleFilter() { } /// <summary> /// Initializes a new instance of the <see cref="CorrelationRuleFilter" /> class with the specified correlation identifier. /// </summary> /// <param name="correlationId">The identifier for the correlation.</param> /// <exception cref="System.ArgumentException">Thrown when the <paramref name="correlationId" /> is null or empty.</exception> public CorrelationRuleFilter(string correlationId) : this() { Argument.AssertNotNullOrWhiteSpace(correlationId, nameof(correlationId)); CorrelationId = correlationId; } internal override RuleFilter Clone() => new CorrelationRuleFilter { CorrelationId = CorrelationId, MessageId = MessageId, To = To, ReplyTo = ReplyTo, Subject = Subject, SessionId = SessionId, ReplyToSessionId = ReplyToSessionId, ContentType = ContentType, ApplicationProperties = (ApplicationProperties as PropertyDictionary).Clone() }; /// <summary> /// Identifier of the correlation. /// </summary> /// <value>The identifier of the correlation.</value> public string CorrelationId { get; set; } /// <summary> /// Identifier of the message. /// </summary> /// <value>The identifier of the message.</value> /// <remarks>Max MessageId size is 128 chars.</remarks> public string MessageId { get; set; } /// <summary> /// Address to send to. /// </summary> /// <value>The address to send to.</value> public string To { get; set; } /// <summary> /// Address of the queue to reply to. /// </summary> /// <value>The address of the queue to reply to.</value> public string ReplyTo { get; set; } /// <summary> /// Application specific subject. /// </summary> /// <value>The application specific subject.</value> public string Subject { get; set; } /// <summary> /// Session identifier. /// </summary> /// <value>The session identifier.</value> /// <remarks>Max size of sessionId is 128 chars.</remarks> public string SessionId { get; set; } /// <summary> /// Session identifier to reply to. /// </summary> /// <value>The session identifier to reply to.</value> /// <remarks>Max size of ReplyToSessionId is 128.</remarks> public string ReplyToSessionId { get; set; } /// <summary> /// Content type of the message. /// </summary> /// <value>The content type of the message.</value> public string ContentType { get; set; } /// <summary> /// Application specific properties of the message. /// </summary> /// <value>The application specific properties of the message.</value> /// <remarks> /// Only following value types are supported: /// byte, sbyte, char, short, ushort, int, uint, long, ulong, float, double, decimal, /// bool, Guid, string, Uri, DateTime, DateTimeOffset, TimeSpan, Stream, byte[], /// and IList / IDictionary of supported types /// </remarks> public IDictionary<string, object> ApplicationProperties { get; internal set; } = new PropertyDictionary(); /// <summary> /// Converts the value of the current instance to its equivalent string representation. /// </summary> /// <returns>A string representation of the current instance.</returns> public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.Append("CorrelationRuleFilter: "); var isFirstExpression = true; AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.CorrelationId", CorrelationId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.MessageId", MessageId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.To", To); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyTo", ReplyTo); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.Label", Subject); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.SessionId", SessionId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyToSessionId", ReplyToSessionId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ContentType", ContentType); foreach (var pair in ApplicationProperties) { string propertyName = pair.Key; object propertyValue = pair.Value; AppendPropertyExpression(ref isFirstExpression, stringBuilder, propertyName, propertyValue); } return stringBuilder.ToString(); } private static void AppendPropertyExpression(ref bool firstExpression, StringBuilder builder, string propertyName, object value) { if (value != null) { if (firstExpression) { firstExpression = false; } else { builder.Append(" AND "); } builder.AppendFormat(CultureInfo.InvariantCulture, "{0} = '{1}'", propertyName, value); } } /// <inheritdoc/> public override int GetHashCode() { int hash = 13; unchecked { hash = (hash * 7) + CorrelationId?.GetHashCode() ?? 0; hash = (hash * 7) + MessageId?.GetHashCode() ?? 0; hash = (hash * 7) + SessionId?.GetHashCode() ?? 0; } return hash; } /// <inheritdoc/> public override bool Equals(object obj) { var other = obj as CorrelationRuleFilter; return Equals(other); } /// <inheritdoc/> public override bool Equals(RuleFilter other) { if (other is CorrelationRuleFilter correlationRuleFilter) { if (string.Equals(CorrelationId, correlationRuleFilter.CorrelationId, StringComparison.OrdinalIgnoreCase) && string.Equals(MessageId, correlationRuleFilter.MessageId, StringComparison.OrdinalIgnoreCase) && string.Equals(To, correlationRuleFilter.To, StringComparison.OrdinalIgnoreCase) && string.Equals(ReplyTo, correlationRuleFilter.ReplyTo, StringComparison.OrdinalIgnoreCase) && string.Equals(Subject, correlationRuleFilter.Subject, StringComparison.OrdinalIgnoreCase) && string.Equals(SessionId, correlationRuleFilter.SessionId, StringComparison.OrdinalIgnoreCase) && string.Equals(ReplyToSessionId, correlationRuleFilter.ReplyToSessionId, StringComparison.OrdinalIgnoreCase) && string.Equals(ContentType, correlationRuleFilter.ContentType, StringComparison.OrdinalIgnoreCase)) { if (ApplicationProperties.Count != correlationRuleFilter.ApplicationProperties.Count) { return false; } foreach (var param in ApplicationProperties) { if (!correlationRuleFilter.ApplicationProperties.TryGetValue(param.Key, out var otherParamValue) || (param.Value == null ^ otherParamValue == null) || (param.Value != null && !param.Value.Equals(otherParamValue))) { return false; } } return true; } } return false; } /// <summary>Compares two <see cref="CorrelationRuleFilter"/> values for equality.</summary> public static bool operator ==(CorrelationRuleFilter left, CorrelationRuleFilter right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } return left.Equals(right); } /// <summary>Compares two <see cref="CorrelationRuleFilter"/> values for inequality.</summary> public static bool operator !=(CorrelationRuleFilter left, CorrelationRuleFilter right) { return !(left == right); } } }
using Android.Content; using Android.Graphics; using Android.Runtime; using Android.Text; using Android.Text.Style; using Android.Util; using Android.Views; using Android.Views.InputMethods; using Android.Widget; using Java.Lang; using System; using System.Globalization; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using Toggl.Core; using Toggl.Droid.Extensions; namespace Toggl.Droid.Views.EditDuration { public static class WheelDurationInputExtensions { public static string AsDurationString(this TimeSpan value) => $"{(int)value.TotalHours}:{value.Minutes.ToString("D2", CultureInfo.InvariantCulture)}:{value.Seconds.ToString("D2", CultureInfo.InvariantCulture)}"; } [Register("toggl.droid.views.WheelDurationInput")] public partial class WheelDurationInput : EditText, ITextWatcher, View.IOnTouchListener { private Color fadedTextColor = Color.Gray; private TimeSpan originalDuration; private TimeSpan duration; private DurationFieldInfo input = DurationFieldInfo.Empty; private bool isEditing = false; private readonly ISubject<TimeSpan> durationSubject = new Subject<TimeSpan>(); public IObservable<TimeSpan> Duration { get; private set; } public WheelDurationInput(IntPtr handle, JniHandleOwnership ownership) : base(handle, ownership) { } public WheelDurationInput(Context context) : base(context) { initialize(); } public WheelDurationInput(Context context, IAttributeSet attrs) : base(context, attrs) { initializeAttributeSet(context, attrs); initialize(); } public WheelDurationInput(Context context, IAttributeSet attrs, int defStyleRes) : base(context, attrs, defStyleRes) { initializeAttributeSet(context, attrs, 0, defStyleRes); initialize(); } public WheelDurationInput(Context context, IAttributeSet attrs, int defStyleAttrs, int defStyleRes) : base(context, attrs, defStyleAttrs, defStyleRes) { initializeAttributeSet(context, attrs, defStyleAttrs, defStyleRes); initialize(); } private void initializeAttributeSet(Context context, IAttributeSet attrs, int defStyleAttrs = 0, int defStyleRes = 0) { var customsAttrs = context.ObtainStyledAttributes(attrs, Resource.Styleable.WheelDurationInput, defStyleAttrs, defStyleRes); try { var colorStateList = customsAttrs.GetColorStateList(Resource.Styleable.WheelDurationInput_fadedTextColor); var fadedTextColorRGB = colorStateList.GetColorForState(GetDrawableState(), Color.Gray); fadedTextColor = new Color(fadedTextColorRGB); } finally { customsAttrs.Recycle(); } } public void ApplyDurationIfBeingEdited() { if (!isEditing) return; var actualDuration = input.IsEmpty ? originalDuration : input.ToTimeSpan(); Text = actualDuration.AsDurationString(); durationSubject.OnNext(actualDuration); Focusable = false; } public void SetDuration(TimeSpan duration) { this.duration = duration; input = DurationFieldInfo.FromTimeSpan(duration); Text = duration.AsDurationString(); } public override void OnEditorAction(ImeAction actionCode) { if (actionCode == ImeAction.Done || actionCode == ImeAction.Next) this.RemoveFocus(); } public override bool OnKeyPreIme(Keycode keyCode, KeyEvent e) { if (keyCode == Keycode.Back || keyCode == Keycode.Enter) { this.RemoveFocus(); } return base.OnKeyPreIme(keyCode, e); } protected override void OnSelectionChanged(int selStart, int selEnd) { moveCursorToEnd(); } protected override void OnFocusChanged(bool gainFocus, FocusSearchDirection direction, Android.Graphics.Rect previouslyFocusedRect) { if (gainFocus) { originalDuration = duration; input = DurationFieldInfo.Empty; Text = input.ToString(); moveCursorToEnd(); } else { ApplyDurationIfBeingEdited(); } isEditing = gainFocus; base.OnFocusChanged(gainFocus, direction, previouslyFocusedRect); } private void initialize() { Focusable = false; Duration = durationSubject.DistinctUntilChanged(); AddTextChangedListener(this); SetOnTouchListener(this); TransformationMethod = null; SetFilters( new IInputFilter[] { new InputFilter(onDigitEntered, onDeletionDetected) } ); } private void onDeletionDetected() { var nextInput = input.Pop(); updateDuration(nextInput); } private void onDigitEntered(int digit) { var nextInput = input.Push(digit); updateDuration(nextInput); } private void updateDuration(DurationFieldInfo nextInput) { if (nextInput.Equals(input)) return; input = nextInput; duration = input.ToTimeSpan(); Text = input.ToString(); } private int getFormattingSplitPoint(string text) { var colonCount = text.Count(c => c == ':'); // Text in edit mode always has one colon if (colonCount == 1) return text.TakeWhile(c => c == '0' || c == ':').Count(); // Text in display mode always has two colons if (colonCount == 2) return text.LastIndexOf(':'); return 0; } private void applyFormatting(string text, IEditable editable) { var splitPoint = getFormattingSplitPoint(text); editable.ClearSpans(); if (isEditing) { editable.SetSpan(new TypefaceSpan("sans-serif-medium"), 0, editable.Length(), SpanTypes.InclusiveInclusive); editable.SetSpan(new ForegroundColorSpan(fadedTextColor), 0, splitPoint, SpanTypes.InclusiveInclusive); } else { editable.SetSpan(new TypefaceSpan("sans-serif-medium"), 0, splitPoint, SpanTypes.InclusiveInclusive); } } private void moveCursorToEnd() { if (Text.Length == SelectionEnd && Text.Length == SelectionStart) return; SetSelection(Text.Length); } void ITextWatcher.AfterTextChanged(IEditable editable) { var text = isEditing ? input.ToString() : editable.ToString(); if (Text == text) { applyFormatting(text, editable); moveCursorToEnd(); return; } Text = text; } void ITextWatcher.BeforeTextChanged(ICharSequence s, int start, int count, int after) { } void ITextWatcher.OnTextChanged(ICharSequence s, int start, int before, int count) { moveCursorToEnd(); } public bool OnTouch(View v, MotionEvent e) { FocusableInTouchMode = true; return false; } } }
// // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER // REMAINS UNCHANGED. // // Email: gustavo_franco@hotmail.com // // Copyright (C) 2006 Franco, Gustavo // using System.Collections.Generic; namespace GraphX.Logic.Algorithms.EdgeRouting { #region Interfaces public interface IPriorityQueue<T> { #region Methods int Push(T item); T Pop(); T Peek(); void Update(int i); #endregion } #endregion public class PriorityQueueB<T> : IPriorityQueue<T> { #region Variables Declaration protected List<T> InnerList = new List<T>(); protected IComparer<T> mComparer; #endregion #region Contructors public PriorityQueueB() { mComparer = Comparer<T>.Default; } public PriorityQueueB(IComparer<T> comparer) { mComparer = comparer; } public PriorityQueueB(IComparer<T> comparer, int capacity) { mComparer = comparer; InnerList.Capacity = capacity; } #endregion #region Methods protected void SwitchElements(int i, int j) { T h = InnerList[i]; InnerList[i] = InnerList[j]; InnerList[j] = h; } protected virtual int OnCompare(int i, int j) { return mComparer.Compare(InnerList[i],InnerList[j]); } /// <summary> /// Push an object onto the PQ /// </summary> /// <param name="O">The new object</param> /// <returns>The index in the list where the object is _now_. This will change when objects are taken from or put onto the PQ.</returns> public int Push(T item) { int p = InnerList.Count,p2; InnerList.Add(item); // E[p] = O do { if(p==0) break; p2 = (p-1)/2; if(OnCompare(p,p2)<0) { SwitchElements(p,p2); p = p2; } else break; }while(true); return p; } /// <summary> /// Get the smallest object and remove it. /// </summary> /// <returns>The smallest object</returns> public T Pop() { T result = InnerList[0]; int p = 0,p1,p2,pn; InnerList[0] = InnerList[InnerList.Count-1]; InnerList.RemoveAt(InnerList.Count-1); do { pn = p; p1 = 2*p+1; p2 = 2*p+2; if(InnerList.Count>p1 && OnCompare(p,p1)>0) // links kleiner p = p1; if(InnerList.Count>p2 && OnCompare(p,p2)>0) // rechts noch kleiner p = p2; if(p==pn) break; SwitchElements(p,pn); }while(true); return result; } /// <summary> /// Notify the PQ that the object at position i has changed /// and the PQ needs to restore order. /// Since you dont have access to any indexes (except by using the /// explicit IList.this) you should not call this function without knowing exactly /// what you do. /// </summary> /// <param name="i">The index of the changed object.</param> public void Update(int i) { int p = i,pn; int p1,p2; do // aufsteigen { if(p==0) break; p2 = (p-1)/2; if(OnCompare(p,p2)<0) { SwitchElements(p,p2); p = p2; } else break; }while(true); if(p<i) return; do // absteigen { pn = p; p1 = 2*p+1; p2 = 2*p+2; if(InnerList.Count>p1 && OnCompare(p,p1)>0) // links kleiner p = p1; if(InnerList.Count>p2 && OnCompare(p,p2)>0) // rechts noch kleiner p = p2; if(p==pn) break; SwitchElements(p,pn); }while(true); } /// <summary> /// Get the smallest object without removing it. /// </summary> /// <returns>The smallest object</returns> public T Peek() { if(InnerList.Count>0) return InnerList[0]; return default(T); } public void Clear() { InnerList.Clear(); } public int Count { get{ return InnerList.Count; } } public void RemoveLocation(T item) { int index = -1; for(int i=0; i<InnerList.Count; i++) { if (mComparer.Compare(InnerList[i], item) == 0) index = i; } if (index != -1) InnerList.RemoveAt(index); } public T this[int index] { get { return InnerList[index]; } set { InnerList[index] = value; Update(index); } } #endregion } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using SquabPie.Mono.Cecil.Metadata; namespace SquabPie.Mono.Cecil { public abstract class TypeSystem { sealed class CoreTypeSystem : TypeSystem { public CoreTypeSystem (ModuleDefinition module) : base (module) { } internal override TypeReference LookupType (string @namespace, string name) { var type = LookupTypeDefinition (@namespace, name) ?? LookupTypeForwarded (@namespace, name); if (type != null) return type; throw new NotSupportedException (); } TypeReference LookupTypeDefinition (string @namespace, string name) { var metadata = module.MetadataSystem; if (metadata.Types == null) Initialize (module.Types); return module.Read (new Row<string, string> (@namespace, name), (row, reader) => { var types = reader.metadata.Types; for (int i = 0; i < types.Length; i++) { if (types [i] == null) types [i] = reader.GetTypeDefinition ((uint) i + 1); var type = types [i]; if (type.Name == row.Col2 && type.Namespace == row.Col1) return type; } return null; }); } TypeReference LookupTypeForwarded (string @namespace, string name) { if (!module.HasExportedTypes) return null; var exported_types = module.ExportedTypes; for (int i = 0; i < exported_types.Count; i++) { var exported_type = exported_types [i]; if (exported_type.Name == name && exported_type.Namespace == @namespace) return exported_type.CreateReference (); } return null; } static void Initialize (object obj) { } } sealed class CommonTypeSystem : TypeSystem { AssemblyNameReference core_library; public CommonTypeSystem (ModuleDefinition module) : base (module) { } internal override TypeReference LookupType (string @namespace, string name) { return CreateTypeReference (@namespace, name); } public AssemblyNameReference GetCoreLibraryReference () { if (core_library != null) return core_library; const string mscorlib = "mscorlib"; const string system_runtime = "System.Runtime"; if (TryLookupReference (mscorlib, out core_library)) return core_library; if (TryLookupReference (system_runtime, out core_library)) return core_library; core_library = new AssemblyNameReference { Name = mscorlib, Version = GetCorlibVersion (), PublicKeyToken = new byte [] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 }, }; module.AssemblyReferences.Add (core_library); return core_library; } bool TryLookupReference (string name, out AssemblyNameReference reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { reference = references [i]; if (reference.Name == name) return true; } reference = null; return false; } Version GetCorlibVersion () { switch (module.Runtime) { case TargetRuntime.Net_1_0: case TargetRuntime.Net_1_1: return new Version (1, 0, 0, 0); case TargetRuntime.Net_2_0: return new Version (2, 0, 0, 0); case TargetRuntime.Net_4_0: return new Version (4, 0, 0, 0); default: throw new NotSupportedException (); } } TypeReference CreateTypeReference (string @namespace, string name) { return new TypeReference (@namespace, name, module, GetCoreLibraryReference ()); } } readonly ModuleDefinition module; TypeReference type_object; TypeReference type_void; TypeReference type_bool; TypeReference type_char; TypeReference type_sbyte; TypeReference type_byte; TypeReference type_int16; TypeReference type_uint16; TypeReference type_int32; TypeReference type_uint32; TypeReference type_int64; TypeReference type_uint64; TypeReference type_single; TypeReference type_double; TypeReference type_intptr; TypeReference type_uintptr; TypeReference type_string; TypeReference type_typedref; TypeSystem (ModuleDefinition module) { this.module = module; } internal static TypeSystem CreateTypeSystem (ModuleDefinition module) { if (module.IsCoreLibrary ()) return new CoreTypeSystem (module); return new CommonTypeSystem (module); } internal abstract TypeReference LookupType (string @namespace, string name); TypeReference LookupSystemType (ref TypeReference reference, string name, ElementType element_type) { lock (module.SyncRoot) { if (reference != null) return reference; var type = LookupType ("System", name); type.etype = element_type; return reference = type; } } TypeReference LookupSystemValueType (ref TypeReference typeRef, string name, ElementType element_type) { lock (module.SyncRoot) { if (typeRef != null) return typeRef; var type = LookupType ("System", name); type.etype = element_type; type.IsValueType = true; return typeRef = type; } } [Obsolete ("Use CoreLibrary")] public IMetadataScope Corlib { get { return CoreLibrary; } } public IMetadataScope CoreLibrary { get { var common = this as CommonTypeSystem; if (common == null) return module; return common.GetCoreLibraryReference (); } } public TypeReference Object { get { return type_object ?? (LookupSystemType (ref type_object, "Object", ElementType.Object)); } } public TypeReference Void { get { return type_void ?? (LookupSystemType (ref type_void, "Void", ElementType.Void)); } } public TypeReference Boolean { get { return type_bool ?? (LookupSystemValueType (ref type_bool, "Boolean", ElementType.Boolean)); } } public TypeReference Char { get { return type_char ?? (LookupSystemValueType (ref type_char, "Char", ElementType.Char)); } } public TypeReference SByte { get { return type_sbyte ?? (LookupSystemValueType (ref type_sbyte, "SByte", ElementType.I1)); } } public TypeReference Byte { get { return type_byte ?? (LookupSystemValueType (ref type_byte, "Byte", ElementType.U1)); } } public TypeReference Int16 { get { return type_int16 ?? (LookupSystemValueType (ref type_int16, "Int16", ElementType.I2)); } } public TypeReference UInt16 { get { return type_uint16 ?? (LookupSystemValueType (ref type_uint16, "UInt16", ElementType.U2)); } } public TypeReference Int32 { get { return type_int32 ?? (LookupSystemValueType (ref type_int32, "Int32", ElementType.I4)); } } public TypeReference UInt32 { get { return type_uint32 ?? (LookupSystemValueType (ref type_uint32, "UInt32", ElementType.U4)); } } public TypeReference Int64 { get { return type_int64 ?? (LookupSystemValueType (ref type_int64, "Int64", ElementType.I8)); } } public TypeReference UInt64 { get { return type_uint64 ?? (LookupSystemValueType (ref type_uint64, "UInt64", ElementType.U8)); } } public TypeReference Single { get { return type_single ?? (LookupSystemValueType (ref type_single, "Single", ElementType.R4)); } } public TypeReference Double { get { return type_double ?? (LookupSystemValueType (ref type_double, "Double", ElementType.R8)); } } public TypeReference IntPtr { get { return type_intptr ?? (LookupSystemValueType (ref type_intptr, "IntPtr", ElementType.I)); } } public TypeReference UIntPtr { get { return type_uintptr ?? (LookupSystemValueType (ref type_uintptr, "UIntPtr", ElementType.U)); } } public TypeReference String { get { return type_string ?? (LookupSystemType (ref type_string, "String", ElementType.String)); } } public TypeReference TypedReference { get { return type_typedref ?? (LookupSystemValueType (ref type_typedref, "TypedReference", ElementType.TypedByRef)); } } } }
// 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! using gax = Google.Api.Gax; using gcicv = Google.Cloud.Iam.Credentials.V1; using sys = System; namespace Google.Cloud.Iam.Credentials.V1 { /// <summary>Resource name for the <c>ServiceAccount</c> resource.</summary> public sealed partial class ServiceAccountName : gax::IResourceName, sys::IEquatable<ServiceAccountName> { /// <summary>The possible contents of <see cref="ServiceAccountName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/serviceAccounts/{service_account}</c>. /// </summary> ProjectServiceAccount = 1, } private static gax::PathTemplate s_projectServiceAccount = new gax::PathTemplate("projects/{project}/serviceAccounts/{service_account}"); /// <summary>Creates a <see cref="ServiceAccountName"/> 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="ServiceAccountName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ServiceAccountName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ServiceAccountName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ServiceAccountName"/> with the pattern /// <c>projects/{project}/serviceAccounts/{service_account}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceAccountId">The <c>ServiceAccount</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ServiceAccountName"/> constructed from the provided ids.</returns> public static ServiceAccountName FromProjectServiceAccount(string projectId, string serviceAccountId) => new ServiceAccountName(ResourceNameType.ProjectServiceAccount, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceAccountId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceAccountId, nameof(serviceAccountId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceAccountName"/> with pattern /// <c>projects/{project}/serviceAccounts/{service_account}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceAccountId">The <c>ServiceAccount</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceAccountName"/> with pattern /// <c>projects/{project}/serviceAccounts/{service_account}</c>. /// </returns> public static string Format(string projectId, string serviceAccountId) => FormatProjectServiceAccount(projectId, serviceAccountId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceAccountName"/> with pattern /// <c>projects/{project}/serviceAccounts/{service_account}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceAccountId">The <c>ServiceAccount</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceAccountName"/> with pattern /// <c>projects/{project}/serviceAccounts/{service_account}</c>. /// </returns> public static string FormatProjectServiceAccount(string projectId, string serviceAccountId) => s_projectServiceAccount.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceAccountId, nameof(serviceAccountId))); /// <summary> /// Parses the given resource name string into a new <see cref="ServiceAccountName"/> 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}/serviceAccounts/{service_account}</c></description></item> /// </list> /// </remarks> /// <param name="serviceAccountName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ServiceAccountName"/> if successful.</returns> public static ServiceAccountName Parse(string serviceAccountName) => Parse(serviceAccountName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ServiceAccountName"/> 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}/serviceAccounts/{service_account}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceAccountName">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="ServiceAccountName"/> if successful.</returns> public static ServiceAccountName Parse(string serviceAccountName, bool allowUnparsed) => TryParse(serviceAccountName, allowUnparsed, out ServiceAccountName 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="ServiceAccountName"/> 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}/serviceAccounts/{service_account}</c></description></item> /// </list> /// </remarks> /// <param name="serviceAccountName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ServiceAccountName"/>, 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 serviceAccountName, out ServiceAccountName result) => TryParse(serviceAccountName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ServiceAccountName"/> 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}/serviceAccounts/{service_account}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceAccountName">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="ServiceAccountName"/>, 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 serviceAccountName, bool allowUnparsed, out ServiceAccountName result) { gax::GaxPreconditions.CheckNotNull(serviceAccountName, nameof(serviceAccountName)); gax::TemplatedResourceName resourceName; if (s_projectServiceAccount.TryParseName(serviceAccountName, out resourceName)) { result = FromProjectServiceAccount(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(serviceAccountName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ServiceAccountName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string serviceAccountId = null) { Type = type; UnparsedResource = unparsedResourceName; ProjectId = projectId; ServiceAccountId = serviceAccountId; } /// <summary> /// Constructs a new instance of a <see cref="ServiceAccountName"/> class from the component parts of pattern /// <c>projects/{project}/serviceAccounts/{service_account}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceAccountId">The <c>ServiceAccount</c> ID. Must not be <c>null</c> or empty.</param> public ServiceAccountName(string projectId, string serviceAccountId) : this(ResourceNameType.ProjectServiceAccount, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceAccountId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceAccountId, nameof(serviceAccountId))) { } /// <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>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>ServiceAccount</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string ServiceAccountId { 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.ProjectServiceAccount: return s_projectServiceAccount.Expand(ProjectId, ServiceAccountId); 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 ServiceAccountName); /// <inheritdoc/> public bool Equals(ServiceAccountName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ServiceAccountName a, ServiceAccountName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ServiceAccountName a, ServiceAccountName b) => !(a == b); } public partial class GenerateAccessTokenRequest { /// <summary> /// <see cref="gcicv::ServiceAccountName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcicv::ServiceAccountName ServiceAccountName { get => string.IsNullOrEmpty(Name) ? null : gcicv::ServiceAccountName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class SignBlobRequest { /// <summary> /// <see cref="gcicv::ServiceAccountName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcicv::ServiceAccountName ServiceAccountName { get => string.IsNullOrEmpty(Name) ? null : gcicv::ServiceAccountName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class SignJwtRequest { /// <summary> /// <see cref="gcicv::ServiceAccountName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcicv::ServiceAccountName ServiceAccountName { get => string.IsNullOrEmpty(Name) ? null : gcicv::ServiceAccountName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GenerateIdTokenRequest { /// <summary> /// <see cref="gcicv::ServiceAccountName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcicv::ServiceAccountName ServiceAccountName { get => string.IsNullOrEmpty(Name) ? null : gcicv::ServiceAccountName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using Debug = System.Diagnostics.Debug; using Internal.NativeFormat; namespace Internal.TypeSystem.Ecma { /// <summary> /// Override of MetadataType that uses actual Ecma335 metadata. /// </summary> public sealed partial class EcmaType : MetadataType, EcmaModule.IEntityHandleObject { private EcmaModule _module; private TypeDefinitionHandle _handle; private TypeDefinition _typeDefinition; // Cached values private string _typeName; private string _typeNamespace; private TypeDesc[] _genericParameters; private MetadataType _baseType; private int _hashcode; internal EcmaType(EcmaModule module, TypeDefinitionHandle handle) { _module = module; _handle = handle; _typeDefinition = module.MetadataReader.GetTypeDefinition(handle); _baseType = this; // Not yet initialized flag #if DEBUG // Initialize name eagerly in debug builds for convenience InitializeName(); InitializeNamespace(); #endif } public override int GetHashCode() { if (_hashcode != 0) return _hashcode; return InitializeHashCode(); } private int InitializeHashCode() { TypeDesc containingType = ContainingType; if (containingType == null) { string ns = Namespace; var hashCodeBuilder = new TypeHashingAlgorithms.HashCodeBuilder(ns); if (ns.Length > 0) hashCodeBuilder.Append("."); hashCodeBuilder.Append(Name); _hashcode = hashCodeBuilder.ToHashCode(); } else { _hashcode = TypeHashingAlgorithms.ComputeNestedTypeHashCode( containingType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name)); } return _hashcode; } EntityHandle EcmaModule.IEntityHandleObject.Handle { get { return _handle; } } public override TypeSystemContext Context { get { return _module.Context; } } private void ComputeGenericParameters() { var genericParameterHandles = _typeDefinition.GetGenericParameters(); int count = genericParameterHandles.Count; if (count > 0) { TypeDesc[] genericParameters = new TypeDesc[count]; int i = 0; foreach (var genericParameterHandle in genericParameterHandles) { genericParameters[i++] = new EcmaGenericParameter(_module, genericParameterHandle); } Interlocked.CompareExchange(ref _genericParameters, genericParameters, null); } else { _genericParameters = TypeDesc.EmptyTypes; } } public override Instantiation Instantiation { get { if (_genericParameters == null) ComputeGenericParameters(); return new Instantiation(_genericParameters); } } public override ModuleDesc Module { get { return _module; } } public EcmaModule EcmaModule { get { return _module; } } public MetadataReader MetadataReader { get { return _module.MetadataReader; } } public TypeDefinitionHandle Handle { get { return _handle; } } private MetadataType InitializeBaseType() { var baseTypeHandle = _typeDefinition.BaseType; if (baseTypeHandle.IsNil) { _baseType = null; return null; } var type = _module.GetType(baseTypeHandle) as MetadataType; if (type == null) { // PREFER: "new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadBadFormat, this)" but the metadata is too broken ThrowHelper.ThrowTypeLoadException(Namespace, Name, Module); } _baseType = type; return type; } public override DefType BaseType { get { if (_baseType == this) return InitializeBaseType(); return _baseType; } } public override MetadataType MetadataBaseType { get { if (_baseType == this) return InitializeBaseType(); return _baseType; } } protected override TypeFlags ComputeTypeFlags(TypeFlags mask) { TypeFlags flags = 0; if ((mask & TypeFlags.CategoryMask) != 0) { TypeDesc baseType = this.BaseType; if (baseType != null && baseType.IsWellKnownType(WellKnownType.ValueType)) { flags |= TypeFlags.ValueType; } else if (baseType != null && baseType.IsWellKnownType(WellKnownType.Enum)) { flags |= TypeFlags.Enum; } else { if ((_typeDefinition.Attributes & TypeAttributes.Interface) != 0) flags |= TypeFlags.Interface; else flags |= TypeFlags.Class; } // All other cases are handled during TypeSystemContext intitialization } if ((mask & TypeFlags.HasGenericVarianceComputed) != 0) { flags |= TypeFlags.HasGenericVarianceComputed; foreach (GenericParameterDesc genericParam in Instantiation) { if (genericParam.Variance != GenericVariance.None) { flags |= TypeFlags.HasGenericVariance; break; } } } if ((mask & TypeFlags.HasFinalizerComputed) != 0) { flags |= TypeFlags.HasFinalizerComputed; if (GetFinalizer() != null) flags |= TypeFlags.HasFinalizer; } if ((mask & TypeFlags.AttributeCacheComputed) != 0) { MetadataReader reader = MetadataReader; MetadataStringComparer stringComparer = reader.StringComparer; bool isValueType = IsValueType; flags |= TypeFlags.AttributeCacheComputed; foreach (CustomAttributeHandle attributeHandle in _typeDefinition.GetCustomAttributes()) { if (MetadataReader.GetAttributeNamespaceAndName(attributeHandle, out StringHandle namespaceHandle, out StringHandle nameHandle)) { if (isValueType && stringComparer.Equals(nameHandle, "IsByRefLikeAttribute") && stringComparer.Equals(namespaceHandle, "System.Runtime.CompilerServices")) flags |= TypeFlags.IsByRefLike; if (stringComparer.Equals(nameHandle, "IntrinsicAttribute") && stringComparer.Equals(namespaceHandle, "System.Runtime.CompilerServices")) flags |= TypeFlags.IsIntrinsic; } } } return flags; } private string InitializeName() { var metadataReader = this.MetadataReader; _typeName = metadataReader.GetString(_typeDefinition.Name); return _typeName; } public override string Name { get { if (_typeName == null) return InitializeName(); return _typeName; } } private string InitializeNamespace() { var metadataReader = this.MetadataReader; _typeNamespace = metadataReader.GetString(_typeDefinition.Namespace); return _typeNamespace; } public override string Namespace { get { if (_typeNamespace == null) return InitializeNamespace(); return _typeNamespace; } } public override IEnumerable<MethodDesc> GetMethods() { foreach (var handle in _typeDefinition.GetMethods()) { yield return (MethodDesc)_module.GetObject(handle); } } public override MethodDesc GetMethod(string name, MethodSignature signature) { var metadataReader = this.MetadataReader; var stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetMethods()) { if (stringComparer.Equals(metadataReader.GetMethodDefinition(handle).Name, name)) { MethodDesc method = (MethodDesc)_module.GetObject(handle); if (signature == null || signature.Equals(method.Signature)) return method; } } return null; } public override MethodDesc GetStaticConstructor() { var metadataReader = this.MetadataReader; var stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetMethods()) { var methodDefinition = metadataReader.GetMethodDefinition(handle); if (methodDefinition.Attributes.IsRuntimeSpecialName() && stringComparer.Equals(methodDefinition.Name, ".cctor")) { MethodDesc method = (MethodDesc)_module.GetObject(handle); return method; } } return null; } public override MethodDesc GetDefaultConstructor() { if (IsAbstract) return null; MetadataReader metadataReader = this.MetadataReader; MetadataStringComparer stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetMethods()) { var methodDefinition = metadataReader.GetMethodDefinition(handle); MethodAttributes attributes = methodDefinition.Attributes; if (attributes.IsRuntimeSpecialName() && attributes.IsPublic() && stringComparer.Equals(methodDefinition.Name, ".ctor")) { MethodDesc method = (MethodDesc)_module.GetObject(handle); if (method.Signature.Length != 0) continue; return method; } } return null; } public override MethodDesc GetFinalizer() { // System.Object defines Finalize but doesn't use it, so we can determine that a type has a Finalizer // by checking for a virtual method override that lands anywhere other than Object in the inheritance // chain. if (!HasBaseType) return null; TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object); MethodDesc decl = objectType.GetMethod("Finalize", null); if (decl != null) { MethodDesc impl = this.FindVirtualFunctionTargetMethodOnObjectType(decl); if (impl == null) { // TODO: invalid input: the type doesn't derive from our System.Object throw new TypeLoadException(this.GetFullName()); } if (impl.OwningType != objectType) { return impl; } return null; } // Class library doesn't have finalizers return null; } public override IEnumerable<FieldDesc> GetFields() { foreach (var handle in _typeDefinition.GetFields()) { var field = (EcmaField)_module.GetObject(handle); yield return field; } } public override FieldDesc GetField(string name) { var metadataReader = this.MetadataReader; var stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetFields()) { if (stringComparer.Equals(metadataReader.GetFieldDefinition(handle).Name, name)) { var field = (EcmaField)_module.GetObject(handle); return field; } } return null; } public override IEnumerable<MetadataType> GetNestedTypes() { foreach (var handle in _typeDefinition.GetNestedTypes()) { yield return (MetadataType)_module.GetObject(handle); } } public override MetadataType GetNestedType(string name) { var metadataReader = this.MetadataReader; var stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetNestedTypes()) { bool nameMatched; TypeDefinition type = metadataReader.GetTypeDefinition(handle); if (type.Namespace.IsNil) { nameMatched = stringComparer.Equals(type.Name, name); } else { string typeName = metadataReader.GetString(type.Name); typeName = metadataReader.GetString(type.Namespace) + "." + typeName; nameMatched = typeName == name; } if (nameMatched) return (MetadataType)_module.GetObject(handle); } return null; } public TypeAttributes Attributes { get { return _typeDefinition.Attributes; } } public override DefType ContainingType { get { if (!_typeDefinition.Attributes.IsNested()) return null; var handle = _typeDefinition.GetDeclaringType(); return (DefType)_module.GetType(handle); } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return !MetadataReader.GetCustomAttributeHandle(_typeDefinition.GetCustomAttributes(), attributeNamespace, attributeName).IsNil; } public override ClassLayoutMetadata GetClassLayout() { TypeLayout layout = _typeDefinition.GetLayout(); ClassLayoutMetadata result; result.PackingSize = layout.PackingSize; result.Size = layout.Size; // Skip reading field offsets if this is not explicit layout if (IsExplicitLayout) { var fieldDefinitionHandles = _typeDefinition.GetFields(); var numInstanceFields = 0; foreach (var handle in fieldDefinitionHandles) { var fieldDefinition = MetadataReader.GetFieldDefinition(handle); if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0) continue; numInstanceFields++; } result.Offsets = new FieldAndOffset[numInstanceFields]; int index = 0; foreach (var handle in fieldDefinitionHandles) { var fieldDefinition = MetadataReader.GetFieldDefinition(handle); if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0) continue; // Note: GetOffset() returns -1 when offset was not set in the metadata int specifiedOffset = fieldDefinition.GetOffset(); result.Offsets[index] = new FieldAndOffset((FieldDesc)_module.GetObject(handle), specifiedOffset == -1 ? FieldAndOffset.InvalidOffset : new LayoutInt(specifiedOffset)); index++; } } else result.Offsets = null; return result; } public override MarshalAsDescriptor[] GetFieldMarshalAsDescriptors() { var fieldDefinitionHandles = _typeDefinition.GetFields(); MarshalAsDescriptor[] marshalAsDescriptors = new MarshalAsDescriptor[fieldDefinitionHandles.Count]; int index = 0; foreach (var handle in fieldDefinitionHandles) { var fieldDefinition = MetadataReader.GetFieldDefinition(handle); if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0) continue; MarshalAsDescriptor marshalAsDescriptor = GetMarshalAsDescriptor(fieldDefinition); marshalAsDescriptors[index++] = marshalAsDescriptor; } return marshalAsDescriptors; } private MarshalAsDescriptor GetMarshalAsDescriptor(FieldDefinition fieldDefinition) { if ((fieldDefinition.Attributes & FieldAttributes.HasFieldMarshal) == FieldAttributes.HasFieldMarshal) { MetadataReader metadataReader = MetadataReader; BlobReader marshalAsReader = metadataReader.GetBlobReader(fieldDefinition.GetMarshallingDescriptor()); EcmaSignatureParser parser = new EcmaSignatureParser(EcmaModule, marshalAsReader); MarshalAsDescriptor marshalAs = parser.ParseMarshalAsDescriptor(); Debug.Assert(marshalAs != null); return marshalAs; } return null; } public override bool IsExplicitLayout { get { return (_typeDefinition.Attributes & TypeAttributes.ExplicitLayout) != 0; } } public override bool IsSequentialLayout { get { return (_typeDefinition.Attributes & TypeAttributes.SequentialLayout) != 0; } } public override bool IsBeforeFieldInit { get { return (_typeDefinition.Attributes & TypeAttributes.BeforeFieldInit) != 0; } } public override bool IsModuleType { get { return _handle.Equals(MetadataTokens.TypeDefinitionHandle(0x00000001 /* COR_GLOBAL_PARENT_TOKEN */)); } } public override bool IsSealed { get { return (_typeDefinition.Attributes & TypeAttributes.Sealed) != 0; } } public override bool IsAbstract { get { return (_typeDefinition.Attributes & TypeAttributes.Abstract) != 0; } } public override PInvokeStringFormat PInvokeStringFormat { get { return (PInvokeStringFormat)(_typeDefinition.Attributes & TypeAttributes.StringFormatMask); } } } }
using System; using System.Collections; using System.Diagnostics; namespace OTFontFile { /// <summary> /// Summary description for Table_kern. /// </summary> public class Table_kern : OTTable { /************************ * constructors */ public Table_kern(OTTag tag, MBOBuffer buf) : base(tag, buf) { } /************************ * field offset values */ public enum FieldOffsets { version = 0, nTables = 2, FirstSubTableHeader = 4 } /************************ * internal classes */ public class SubTableHeader { public SubTableHeader(uint offset, MBOBuffer bufTable) { m_offsetSubTableHeader = offset; m_bufTable = bufTable; } public enum FieldOffsets { version = 0, length = 2, coverage = 4 } public ushort version { get {return m_bufTable.GetUshort(m_offsetSubTableHeader + (uint)FieldOffsets.version);} } public ushort length { get {return m_bufTable.GetUshort(m_offsetSubTableHeader + (uint)FieldOffsets.length);} } public ushort coverage { get {return m_bufTable.GetUshort(m_offsetSubTableHeader + (uint)FieldOffsets.coverage);} } public bool GetHorizontalBit() { return ((coverage & 0x0001) == 0x0001); } public bool GetMinimumBit() { return ((coverage & 0x0002) == 0x0002); } public bool GetCrossStreamBit() { return ((coverage & 0x0004) == 0x0004); } public bool GetOverrideBit() { return ((coverage & 0x0008) == 0x0008); } public ushort GetFormat() { return (ushort)(coverage >> 8); } MBOBuffer m_bufTable; uint m_offsetSubTableHeader; } public class SubTable { public SubTable(uint offset, MBOBuffer bufTable) { m_offsetSubTable = offset; m_bufTable = bufTable; } public enum HeaderFieldOffsets { version = 0, length = 2, coverage = 4 } public ushort version { get {return m_bufTable.GetUshort(m_offsetSubTable + (uint)HeaderFieldOffsets.version);} } public ushort length { get {return m_bufTable.GetUshort(m_offsetSubTable + (uint)HeaderFieldOffsets.length);} } public ushort coverage { get {return m_bufTable.GetUshort(m_offsetSubTable + (uint)HeaderFieldOffsets.coverage);} } virtual public ushort CalculatedLength() { return length; // overrides should calculate the correct length, not return the actual length } public ushort GetFormat() { return (ushort)(coverage >> 8); } protected MBOBuffer m_bufTable; protected uint m_offsetSubTable; } public class SubTableFormat0 : SubTable { // constructor public SubTableFormat0(uint offset, MBOBuffer bufTable) : base(offset, bufTable) { } public enum FieldOffsets { nPairs = 6, searchRange = 8, entrySelector = 10, rangeShift = 12, FirstKernPair = 14 } public ushort nPairs { get {return m_bufTable.GetUshort(m_offsetSubTable + (uint)FieldOffsets.nPairs);} } public ushort searchRange { get {return m_bufTable.GetUshort(m_offsetSubTable + (uint)FieldOffsets.searchRange);} } public ushort entrySelector { get {return m_bufTable.GetUshort(m_offsetSubTable + (uint)FieldOffsets.entrySelector);} } public ushort rangeShift { get {return m_bufTable.GetUshort(m_offsetSubTable + (uint)FieldOffsets.rangeShift);} } public void GetKerningPairAndValue(int iPair, ref ushort left, ref ushort right, ref short kernvalue) { if (iPair >= nPairs) { throw new ArgumentOutOfRangeException("iPair"); } uint offset = m_offsetSubTable + (uint)FieldOffsets.FirstKernPair + (uint)iPair*6; left = m_bufTable.GetUshort(offset); right = m_bufTable.GetUshort(offset + 2); kernvalue = m_bufTable.GetShort(offset + 4); } override public ushort CalculatedLength() { return (ushort)(FieldOffsets.FirstKernPair + nPairs*6); } } public class SubTableFormat2 : SubTable { public SubTableFormat2(uint offset, MBOBuffer bufTable) : base(offset, bufTable) { } // NOTE: SubTableFormat2 is not suppported under windows } /************************ * private methods */ private uint GetSubTableHeaderOffset(uint i) { uint sthOffset = (uint)FieldOffsets.FirstSubTableHeader; for (uint n=0; n<i; n++) { sthOffset += m_bufTable.GetUshort(sthOffset + (uint)SubTableHeader.FieldOffsets.length); } return sthOffset; } /************************ * accessors */ public ushort version { get {return m_bufTable.GetUshort((uint)FieldOffsets.version);} } public ushort nTables { get {return m_bufTable.GetUshort((uint)FieldOffsets.nTables);} } public SubTableHeader GetSubTableHeader(uint i) { SubTableHeader sth = null; if (i < nTables) { uint sthOffset = GetSubTableHeaderOffset(i); // check for subtable header extending past end of table if (sthOffset+6 <= m_bufTable.GetLength()) { sth = new SubTableHeader(sthOffset, m_bufTable); } } return sth; } public SubTable GetSubTable(uint i) { SubTable st = null; SubTableHeader sth = GetSubTableHeader(i); if (sth != null) { if (sth.GetFormat() == 0) { uint offsetSubTable = GetSubTableHeaderOffset(i); st = new SubTableFormat0(offsetSubTable, m_bufTable); } else if (sth.GetFormat() == 2) { } } return st; } /************************ * DataCache class */ public override DataCache GetCache() { if (m_cache == null) { m_cache = new kern_cache(this); } return m_cache; } public class kern_cache : DataCache { // the cached data protected ushort m_version; protected ushort m_nTables; ArrayList m_SubTable; // SubTableFormat0[] since we only support format 0 public kern_cache(Table_kern OwnerTable) { m_version = OwnerTable.version; m_nTables = 0; ushort nTablesTemp = OwnerTable.nTables; m_SubTable = new ArrayList( m_nTables ); for( ushort i = 0; i < nTablesTemp; i ++ ) { SubTable SubTableTemp = OwnerTable.GetSubTable( i ); //NOTE: Since these subtables could be Format 2 and we don't support them we will strip them out if( null != SubTableTemp && 0 == SubTableTemp.GetFormat() ) { m_SubTable.Add( SubTableTemp ); m_nTables++; } } } // accessor methods public ushort version { get { return m_version; } set { m_version = value; m_bDirty = true; } } // Cant set number of tables this is done by adding or removing tables public ushort nTables { get { return m_nTables; } } public SubTable getSubTable( ushort nIndex ) { if( nIndex >= m_nTables ) { throw new ArgumentOutOfRangeException( "Index is greater than number of tables." ); } SubTable st = (SubTable)m_SubTable[nIndex]; return st; } public bool setSubTable( ushort nIndex, SubTable st ) { bool bResult = true; if( nIndex >= m_nTables ) { bResult = false; throw new ArgumentOutOfRangeException( "Index is greater than number of tables." ); } else if( null == st ) { bResult = false; throw new ArgumentNullException(); } else if( !(st is SubTableFormat0 )) //NOTE: We only support format0 { bResult = false; throw new ArgumentException( "The SubTable variable needs to SubTableFormat0." ); } m_SubTable[nIndex] = st; m_bDirty = true; return bResult; } public bool addSubTable( ushort nIndex, SubTable st ) { bool bResult = true; if( nIndex > m_nTables ) { bResult = false; throw new ArgumentOutOfRangeException( "Index is greater than number of tables." ); } else if( null == st ) { bResult = false; throw new ArgumentNullException(); } else if( !(st is SubTableFormat0 )) //NOTE: We only support format0 { bResult = false; throw new ArgumentException( "The SubTable variable needs to SubTableFormat0." ); } m_SubTable.Insert( nIndex, st ); m_nTables++; m_bDirty = true; return bResult; } public bool removeSubTable( ushort nIndex ) { bool bResult = true; if( nIndex >= m_nTables ) { bResult = false; throw new ArgumentOutOfRangeException( "Index is greater than number of tables." ); } m_SubTable.RemoveAt( nIndex ); m_nTables--; m_bDirty = true; return bResult; } public override OTTable GenerateTable() { uint iSizeOfTables = 0; ushort nLeft = 0; ushort nRight = 0; short nValue = 0; // Find the sizeof all of the tables for( ushort i = 0; i < m_nTables; i++ ) { iSizeOfTables += (uint)((SubTableFormat0)m_SubTable[i]).CalculatedLength(); } // create a Motorola Byte Order buffer for the new table MBOBuffer newbuf = new MBOBuffer( (uint)FieldOffsets.FirstSubTableHeader + iSizeOfTables ); newbuf.SetUshort( m_version, (uint)FieldOffsets.version ); newbuf.SetUshort( m_nTables, (uint)FieldOffsets.nTables ); uint iOffset = (uint)FieldOffsets.FirstSubTableHeader; //Fill in the tables for( int i = 0; i < m_nTables; i++ ) { newbuf.SetUshort( ((SubTableFormat0)m_SubTable[i]).version, (uint)iOffset ); iOffset += 2; newbuf.SetUshort( ((SubTableFormat0)m_SubTable[i]).length, (uint)iOffset ); iOffset += 2; newbuf.SetUshort( ((SubTableFormat0)m_SubTable[i]).coverage, (uint)iOffset ); iOffset += 2; newbuf.SetUshort( ((SubTableFormat0)m_SubTable[i]).nPairs, (uint)iOffset ); iOffset += 2; newbuf.SetUshort( ((SubTableFormat0)m_SubTable[i]).searchRange, (uint)iOffset ); iOffset += 2; newbuf.SetUshort( ((SubTableFormat0)m_SubTable[i]).entrySelector, (uint)iOffset ); iOffset += 2; newbuf.SetUshort( ((SubTableFormat0)m_SubTable[i]).rangeShift, (uint)iOffset ); iOffset += 2; // Cycle through all of the kerning pairs for( int ii = 0; ii < ((SubTableFormat0)m_SubTable[i]).nPairs; ii++ ) { ((SubTableFormat0)m_SubTable[i]).GetKerningPairAndValue( ii, ref nLeft, ref nRight, ref nValue ); newbuf.SetUshort( nLeft, (uint)iOffset ); iOffset += 2; newbuf.SetUshort( nRight, (uint)iOffset ); iOffset += 2; newbuf.SetShort( nValue, (uint)iOffset ); iOffset += 2; } } // put the buffer into a Table_vhmtx object and return it Table_kern kernTable = new Table_kern("kern", newbuf); return kernTable; } } } }
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 Storymark.Web.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; } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2010 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using OpenTK.Platform; namespace OpenTK.Graphics { /// <summary> /// Represents and provides methods to manipulate an OpenGL render context. /// </summary> public sealed class GraphicsContext : IGraphicsContext, IGraphicsContextInternal { #region --- Fields --- IGraphicsContext implementation; // The actual render context implementation for the underlying platform. bool disposed; // Indicates that this context was created through external means, e.g. Tao.Sdl or GLWidget#. // In this case, We'll assume that the external program will manage the lifetime of this // context - we'll not destroy it manually. readonly bool IsExternal; bool check_errors = true; static bool share_contexts = true; static bool direct_rendering = true; readonly static object SyncRoot = new object(); // Maps OS-specific context handles to GraphicsContext weak references. readonly static Dictionary<ContextHandle, WeakReference> available_contexts = new Dictionary<ContextHandle, WeakReference>(); #endregion #region --- Constructors --- // Necessary to allow creation of dummy GraphicsContexts (see CreateDummyContext static method). GraphicsContext(ContextHandle handle) { implementation = new OpenTK.Platform.Dummy.DummyGLContext(handle); lock (SyncRoot) { available_contexts.Add((implementation as IGraphicsContextInternal).Context, new WeakReference(this)); } } /// <summary> /// Constructs a new GraphicsContext with the specified GraphicsMode and attaches it to the specified window. /// </summary> /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param> /// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param> public GraphicsContext(GraphicsMode mode, IWindowInfo window) : this(mode, window, 1, 0, GraphicsContextFlags.Default) { } /// <summary> /// Constructs a new GraphicsContext with the specified GraphicsMode, version and flags, and attaches it to the specified window. /// </summary> /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param> /// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param> /// <param name="major">The major version of the new GraphicsContext.</param> /// <param name="minor">The minor version of the new GraphicsContext.</param> /// <param name="flags">The GraphicsContextFlags for the GraphicsContext.</param> /// <remarks> /// Different hardware supports different flags, major and minor versions. Invalid parameters will be silently ignored. /// </remarks> public GraphicsContext(GraphicsMode mode, IWindowInfo window, int major, int minor, GraphicsContextFlags flags) { lock (SyncRoot) { bool designMode = false; if (mode == null && window == null) designMode = true; else if (mode == null) throw new ArgumentNullException("mode", "Must be a valid GraphicsMode."); else if (window == null) throw new ArgumentNullException("window", "Must point to a valid window."); // Silently ignore invalid major and minor versions. if (major <= 0) major = 1; if (minor < 0) minor = 0; Debug.Print("Creating GraphicsContext."); try { Debug.Indent(); Debug.Print("GraphicsMode: {0}", mode); Debug.Print("IWindowInfo: {0}", window); Debug.Print("GraphicsContextFlags: {0}", flags); Debug.Print("Requested version: {0}.{1}", major, minor); IGraphicsContext shareContext = shareContext = FindSharedContext(); // Todo: Add a DummyFactory implementing IPlatformFactory. if (designMode) { implementation = new Platform.Dummy.DummyGLContext(); } else { IPlatformFactory factory = null; switch ((flags & GraphicsContextFlags.Embedded) == GraphicsContextFlags.Embedded) { case false: factory = Factory.Default; break; case true: factory = Factory.Embedded; break; } implementation = factory.CreateGLContext(mode, window, shareContext, direct_rendering, major, minor, flags); // Note: this approach does not allow us to mix native and EGL contexts in the same process. // This should not be a problem, as this use-case is not interesting for regular applications. // Note 2: some platforms may not support a direct way of getting the current context // (this happens e.g. with DummyGLContext). In that case, we use a slow fallback which // iterates through all known contexts and checks if any is current (check GetCurrentContext // declaration). if (GetCurrentContext == null) { GetCurrentContextDelegate temp = factory.CreateGetCurrentGraphicsContext(); if (temp != null) { GetCurrentContext = temp; } } } available_contexts.Add((this as IGraphicsContextInternal).Context, new WeakReference(this)); } finally { Debug.Unindent(); } } } /// <summary> /// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK. /// </summary> /// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param> /// <param name="window">The window this context is bound to. This must be a valid window obtained through Utilities.CreateWindowInfo.</param> /// <exception cref="GraphicsContextException">Occurs if handle is identical to a context already registered with OpenTK.</exception> public GraphicsContext(ContextHandle handle, IWindowInfo window) : this(handle, window, null, 1, 0, GraphicsContextFlags.Default) { } /// <summary> /// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK. /// </summary> /// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param> /// <param name="window">The window this context is bound to. This must be a valid window obtained through Utilities.CreateWindowInfo.</param> /// <param name="shareContext">A different context that shares resources with this instance, if any. /// Pass null if the context is not shared or if this is the first GraphicsContext instruct you construct.</param> /// <param name="major">The major version of the context (e.g. "2" for "2.1").</param> /// <param name="minor">The minor version of the context (e.g. "1" for "2.1").</param> /// <param name="flags">A bitwise combination of <see cref="GraphicsContextFlags"/> that describe this context.</param> /// <exception cref="GraphicsContextException">Occurs if handle is identical to a context already registered with OpenTK.</exception> public GraphicsContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, int major, int minor, GraphicsContextFlags flags) { lock (SyncRoot) { IsExternal = true; if (handle == ContextHandle.Zero) { implementation = new OpenTK.Platform.Dummy.DummyGLContext(handle); } else if (available_contexts.ContainsKey(handle)) { throw new GraphicsContextException("Context already exists."); } else { switch ((flags & GraphicsContextFlags.Embedded) == GraphicsContextFlags.Embedded) { case false: implementation = Factory.Default.CreateGLContext(handle, window, shareContext, direct_rendering, major, minor, flags); break; case true: implementation = Factory.Embedded.CreateGLContext(handle, window, shareContext, direct_rendering, major, minor, flags); break; } } available_contexts.Add((implementation as IGraphicsContextInternal).Context, new WeakReference(this)); (this as IGraphicsContextInternal).LoadAll(); } } #endregion #region Public Members /// <summary> /// Returns a <see cref="System.String"/> representing this instance. /// </summary> /// <returns>A <see cref="System.String"/> that contains a string representation of this instance.</returns> public override string ToString() { return (this as IGraphicsContextInternal).Context.ToString(); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A System.Int32 with the hash code of this instance.</returns> public override int GetHashCode() { return (this as IGraphicsContextInternal).Context.GetHashCode(); } /// <summary> /// Compares two instances. /// </summary> /// <param name="obj">The instance to compare to.</param> /// <returns>True, if obj is equal to this instance; false otherwise.</returns> public override bool Equals(object obj) { return (obj is GraphicsContext) && (this as IGraphicsContextInternal).Context == (obj as IGraphicsContextInternal).Context; } #endregion #region Private Members static IGraphicsContext FindSharedContext() { if (GraphicsContext.ShareContexts) { // A small hack to create a shared context with the first available context. foreach (WeakReference r in GraphicsContext.available_contexts.Values) { // Fix for bug 1874: if a GraphicsContext gets finalized // (but not disposed), it won't be removed from available_contexts // making this return null even if another valid context exists. // The workaround is to simply ignore null targets. IGraphicsContext target = r.Target as IGraphicsContext; if (target != null) return target; } } return null; } #endregion #region --- Static Members --- #region public static GraphicsContext CreateDummyContext() /// <summary> /// Creates a dummy GraphicsContext to allow OpenTK to work with contexts created by external libraries. /// </summary> /// <returns>A new, dummy GraphicsContext instance.</returns> /// <remarks> /// <para>Instances created by this method will not be functional. Instance methods will have no effect.</para> /// <para>This method requires that a context is current on the calling thread.</para> /// </remarks> public static GraphicsContext CreateDummyContext() { ContextHandle handle = GetCurrentContext(); if (handle == ContextHandle.Zero) throw new InvalidOperationException("No GraphicsContext is current on the calling thread."); return CreateDummyContext(handle); } /// <summary> /// Creates a dummy GraphicsContext to allow OpenTK to work with contexts created by external libraries. /// </summary> /// <param name="handle">The handle of a context.</param> /// <returns>A new, dummy GraphicsContext instance.</returns> /// <remarks> /// <para>Instances created by this method will not be functional. Instance methods will have no effect.</para> /// </remarks> public static GraphicsContext CreateDummyContext(ContextHandle handle) { if (handle == ContextHandle.Zero) throw new ArgumentOutOfRangeException("handle"); return new GraphicsContext(handle); } #endregion #region public static void Assert() /// <summary> /// Checks if a GraphicsContext exists in the calling thread and throws a GraphicsContextMissingException if it doesn't. /// </summary> /// <exception cref="GraphicsContextMissingException">Generated when no GraphicsContext is current in the calling thread.</exception> public static void Assert() { if (GraphicsContext.CurrentContext == null) throw new GraphicsContextMissingException(); } #endregion #region public static IGraphicsContext CurrentContext internal delegate ContextHandle GetCurrentContextDelegate(); internal static GetCurrentContextDelegate GetCurrentContext = Platform.Factory.Default.CreateGetCurrentGraphicsContext(); /// <summary> /// Gets the GraphicsContext that is current in the calling thread. /// </summary> /// <remarks> /// Note: this property will not function correctly when both desktop and EGL contexts are /// available in the same process. This scenario is very unlikely to appear in practice. /// </remarks> public static IGraphicsContext CurrentContext { get { lock (SyncRoot) { if (available_contexts.Count > 0) { ContextHandle handle = GetCurrentContext(); if (handle.Handle != IntPtr.Zero) return (GraphicsContext)available_contexts[handle].Target; } return null; } } } #endregion #region public static bool ShareContexts /// <summary>Gets or sets a System.Boolean, indicating whether GraphicsContext resources are shared</summary> /// <remarks> /// <para>If ShareContexts is true, new GLContexts will share resources. If this value is /// false, new GLContexts will not share resources.</para> /// <para>Changing this value will not affect already created GLContexts.</para> /// </remarks> public static bool ShareContexts { get { return share_contexts; } set { share_contexts = value; } } #endregion #region public static bool DirectRendering /// <summary>Gets or sets a System.Boolean, indicating whether GraphicsContexts will perform direct rendering.</summary> /// <remarks> /// <para> /// If DirectRendering is true, new contexts will be constructed with direct rendering capabilities, if possible. /// If DirectRendering is false, new contexts will be constructed with indirect rendering capabilities. /// </para> /// <para>This property does not affect existing GraphicsContexts, unless they are recreated.</para> /// <para> /// This property is ignored on Operating Systems without support for indirect rendering, like Windows and OS X. /// </para> /// </remarks> public static bool DirectRendering { get { return direct_rendering; } set { direct_rendering = value; } } #endregion #endregion #region --- IGraphicsContext Members --- /// <summary> /// Gets or sets a System.Boolean, indicating whether automatic error checking should be performed. /// Influences the debug version of OpenTK.dll, only. /// </summary> /// <remarks>Automatic error checking will clear the OpenGL error state. Set CheckErrors to false if you use /// the OpenGL error state in your code flow (e.g. for checking supported texture formats).</remarks> public bool ErrorChecking { get { return check_errors; } set { check_errors = value; } } /// <summary> /// Creates an OpenGL context with the specified direct/indirect rendering mode and sharing state with the /// specified IGraphicsContext. /// </summary> /// <param name="direct">Set to true for direct rendering or false otherwise.</param> /// <param name="source">The source IGraphicsContext to share state from.</param>. /// <remarks> /// <para> /// Direct rendering is the default rendering mode for OpenTK, since it can provide higher performance /// in some circumastances. /// </para> /// <para> /// The 'direct' parameter is a hint, and will ignored if the specified mode is not supported (e.g. setting /// indirect rendering on Windows platforms). /// </para> /// </remarks> void CreateContext(bool direct, IGraphicsContext source) { lock (SyncRoot) { available_contexts.Add((this as IGraphicsContextInternal).Context, new WeakReference(this)); } } /// <summary> /// Swaps buffers on a context. This presents the rendered scene to the user. /// </summary> public void SwapBuffers() { implementation.SwapBuffers(); } /// <summary> /// Makes the GraphicsContext the current rendering target. /// </summary> /// <param name="window">A valid <see cref="OpenTK.Platform.IWindowInfo" /> structure.</param> /// <remarks> /// You can use this method to bind the GraphicsContext to a different window than the one it was created from. /// </remarks> public void MakeCurrent(IWindowInfo window) { implementation.MakeCurrent(window); } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether this instance is current in the calling thread. /// </summary> public bool IsCurrent { get { return implementation.IsCurrent; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether this instance has been disposed. /// It is an error to access any instance methods if this property returns true. /// </summary> public bool IsDisposed { get { return disposed && implementation.IsDisposed; } private set { disposed = value; } } /// <summary> /// Gets or sets a value indicating whether VSync is enabled. /// </summary> public bool VSync { get { return implementation.VSync; } set { implementation.VSync = value; } } /// <summary> /// Updates the graphics context. This must be called when the render target /// is resized for proper behavior on Mac OS X. /// </summary> /// <param name="window"></param> public void Update(IWindowInfo window) { implementation.Update(window); } /// <summary> /// Loads all OpenGL entry points. /// </summary> /// <exception cref="OpenTK.Graphics.GraphicsContextException"> /// Occurs when this instance is not current on the calling thread. /// </exception> public void LoadAll() { if (GraphicsContext.CurrentContext != this) throw new GraphicsContextException(); implementation.LoadAll(); } #endregion #region --- IGraphicsContextInternal Members --- /// <summary> /// Gets the platform-specific implementation of this IGraphicsContext. /// </summary> IGraphicsContext IGraphicsContextInternal.Implementation { get { return implementation; } } /// <summary> /// Gets a handle to the OpenGL rendering context. /// </summary> ContextHandle IGraphicsContextInternal.Context { get { return ((IGraphicsContextInternal)implementation).Context; } } /// <summary> /// Gets the GraphicsMode of the context. /// </summary> public GraphicsMode GraphicsMode { get { return (implementation as IGraphicsContext).GraphicsMode; } } /// <summary> /// Gets the address of an OpenGL extension function. /// </summary> /// <param name="function">The name of the OpenGL function (e.g. "glGetString")</param> /// <returns> /// A pointer to the specified function or IntPtr.Zero if the function isn't /// available in the current opengl context. /// </returns> IntPtr IGraphicsContextInternal.GetAddress(string function) { return (implementation as IGraphicsContextInternal).GetAddress(function); } #endregion #region --- IDisposable Members --- /// <summary> /// Disposes of the GraphicsContext. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool manual) { if (!IsDisposed) { Debug.Print("Disposing context {0}.", (this as IGraphicsContextInternal).Context.ToString()); lock (SyncRoot) { available_contexts.Remove((this as IGraphicsContextInternal).Context); } if (manual && !IsExternal) { if (implementation != null) implementation.Dispose(); } IsDisposed = true; } } #endregion } }