context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Security.Principal { public static class __WindowsIdentity { public static IObservable<System.Security.Principal.WindowsIdentity> GetCurrent() { return ObservableExt.Factory(() => System.Security.Principal.WindowsIdentity.GetCurrent()); } public static IObservable<System.Security.Principal.WindowsIdentity> GetCurrent( IObservable<System.Boolean> ifImpersonating) { return Observable.Select(ifImpersonating, (ifImpersonatingLambda) => System.Security.Principal.WindowsIdentity.GetCurrent(ifImpersonatingLambda)); } public static IObservable<System.Security.Principal.WindowsIdentity> GetCurrent( IObservable<System.Security.Principal.TokenAccessLevels> desiredAccess) { return Observable.Select(desiredAccess, (desiredAccessLambda) => System.Security.Principal.WindowsIdentity.GetCurrent(desiredAccessLambda)); } public static IObservable<System.Security.Principal.WindowsIdentity> GetAnonymous() { return ObservableExt.Factory(() => System.Security.Principal.WindowsIdentity.GetAnonymous()); } public static IObservable<System.Reactive.Unit> RunImpersonated( IObservable<Microsoft.Win32.SafeHandles.SafeAccessTokenHandle> safeAccessTokenHandle, IObservable<System.Action> action) { return ObservableExt.ZipExecute(safeAccessTokenHandle, action, (safeAccessTokenHandleLambda, actionLambda) => System.Security.Principal.WindowsIdentity.RunImpersonated(safeAccessTokenHandleLambda, actionLambda)); } public static IObservable<T> RunImpersonated<T>( IObservable<Microsoft.Win32.SafeHandles.SafeAccessTokenHandle> safeAccessTokenHandle, IObservable<Func<T>> func) { return Observable.Zip(safeAccessTokenHandle, func, (safeAccessTokenHandleLambda, funcLambda) => System.Security.Principal.WindowsIdentity.RunImpersonated(safeAccessTokenHandleLambda, funcLambda)); } public static IObservable<System.Security.Principal.WindowsImpersonationContext> Impersonate( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.Impersonate()); } public static IObservable<System.Security.Principal.WindowsImpersonationContext> Impersonate( IObservable<System.IntPtr> userToken) { return Observable.Select(userToken, (userTokenLambda) => System.Security.Principal.WindowsIdentity.Impersonate(userTokenLambda)); } public static IObservable<System.Reactive.Unit> Dispose( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Do(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.Dispose()) .ToUnit(); } public static IObservable<System.Security.Claims.ClaimsIdentity> Clone( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.Clone()); } public static IObservable<System.String> get_AuthenticationType( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.AuthenticationType); } public static IObservable<System.Security.Principal.TokenImpersonationLevel> get_ImpersonationLevel( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.ImpersonationLevel); } public static IObservable<System.Boolean> get_IsAuthenticated( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.IsAuthenticated); } public static IObservable<System.Boolean> get_IsGuest( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.IsGuest); } public static IObservable<System.Boolean> get_IsSystem( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.IsSystem); } public static IObservable<System.Boolean> get_IsAnonymous( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.IsAnonymous); } public static IObservable<System.String> get_Name( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.Name); } public static IObservable<System.Security.Principal.SecurityIdentifier> get_Owner( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.Owner); } public static IObservable<System.Security.Principal.SecurityIdentifier> get_User( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.User); } public static IObservable<System.Security.Principal.IdentityReferenceCollection> get_Groups( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.Groups); } public static IObservable<System.IntPtr> get_Token( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.Token); } public static IObservable<Microsoft.Win32.SafeHandles.SafeAccessTokenHandle> get_AccessToken( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.AccessToken); } public static IObservable<System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>> get_UserClaims( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.UserClaims); } public static IObservable<System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>> get_DeviceClaims (this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.DeviceClaims); } public static IObservable<System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>> get_Claims( this IObservable<System.Security.Principal.WindowsIdentity> WindowsIdentityValue) { return Observable.Select(WindowsIdentityValue, (WindowsIdentityValueLambda) => WindowsIdentityValueLambda.Claims); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void OrUInt16() { var test = new SimpleBinaryOpTest__OrUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__OrUInt16 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(UInt16); private const int Op2ElementCount = VectorSize / sizeof(UInt16); private const int RetElementCount = VectorSize / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector256<UInt16> _clsVar1; private static Vector256<UInt16> _clsVar2; private Vector256<UInt16> _fld1; private Vector256<UInt16> _fld2; private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable; static SimpleBinaryOpTest__OrUInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__OrUInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Or( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Or( Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Or( Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr); var result = Avx2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__OrUInt16(); var result = Avx2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<UInt16> left, Vector256<UInt16> right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { if ((ushort)(left[0] | right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((ushort)(left[i] | right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Or)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
#if UNITY_EDITOR_WIN using System.Collections; using System.Collections.Generic; using System.IO; using System; using System.Linq; using UnityEngine; using UnityEditor; #if UNITY_2018_1_OR_NEWER using UnityEditor.Build.Reporting; #endif public class OVRBundleManager { public const string TRANSITION_APK_VERSION_NAME = "OVRTransitionAPKVersion"; private const int BUNDLE_CHUNK_SIZE = 30; private const string TRANSITION_SCENE_RELATIVE_PATH = "Scenes/OVRTransitionScene.unity"; private const string BUNDLE_MANAGER_OUTPUT_PATH = "OVRAssetBundles"; private const string BUNDLE_MANAGER_MASTER_BUNDLE = "OVRMasterBundle"; private const string EXTERNAL_STORAGE_PATH = "/sdcard/Android/data"; private const string ADB_TOOL_INITIALIZE_ERROR = "Failed to initialize ADB Tool. Please check Android SDK path in Preferences -> External Tools"; private static string externalSceneCache; private static string transitionScenePath; private static string projectDefaultAppIdentifier; private static string projectDefaultVersion; private static ScriptingImplementation projectScriptImplementation; #if UNITY_2018_3_OR_NEWER private static ManagedStrippingLevel projectManagedStrippingLevel; #else private static StrippingLevel projectStrippingLevel; #endif private static bool projectStripEngineCode; public static void BuildDeployTransitionAPK(bool useOptionalTransitionApkPackage) { OVRBundleTool.PrintLog("Building and deploying transition APK . . . ", true); if (!Directory.Exists(BUNDLE_MANAGER_OUTPUT_PATH)) { Directory.CreateDirectory(BUNDLE_MANAGER_OUTPUT_PATH); } PrebuildProjectSettingUpdate(); if (String.IsNullOrEmpty(transitionScenePath)) { // Get current editor script's directory as base path string[] res = System.IO.Directory.GetFiles(Application.dataPath, "OVRBundleManager.cs", SearchOption.AllDirectories); if (res.Length > 1) { OVRBundleTool.PrintError("More than one OVRBundleManager editor script has been found, please double check your Oculus SDK import."); return; } else { // Append Transition Scene's relative path to base path var OVREditorScript = Path.GetDirectoryName(res[0]); transitionScenePath = Path.Combine(OVREditorScript, TRANSITION_SCENE_RELATIVE_PATH); } } string[] buildScenes = new string[1] { transitionScenePath }; string apkOutputPath = Path.Combine(BUNDLE_MANAGER_OUTPUT_PATH, "OVRTransition.apk"); DateTime apkBuildStart = DateTime.Now; #if UNITY_2018_1_OR_NEWER BuildReport report = BuildPipeline.BuildPlayer(buildScenes, apkOutputPath, BuildTarget.Android, BuildOptions.Development | BuildOptions.AutoRunPlayer); if (report.summary.result == BuildResult.Succeeded) { OVRBundleTool.PrintSuccess(); } else if (report.summary.result == BuildResult.Failed) { OVRBundleTool.PrintError(); } #else string error = BuildPipeline.BuildPlayer(buildScenes, apkOutputPath, BuildTarget.Android, BuildOptions.Development | BuildOptions.AutoRunPlayer); if (string.IsNullOrEmpty(error)) { OVRBundleTool.PrintSuccess(); } else { OVRBundleTool.PrintError(); } #endif OVRPlugin.SendEvent("oculus_bundle_tool", "apk_build_time", (DateTime.Now - apkBuildStart).TotalSeconds.ToString()); PostbuildProjectSettingUpdate(); } private static void PrebuildProjectSettingUpdate() { // Modify application identifier for transition APK projectDefaultAppIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, projectDefaultAppIdentifier + GetTransitionApkOptionalIdentifier()); // Set VersionCode as a unique identifier for transition APK projectDefaultVersion = PlayerSettings.bundleVersion; PlayerSettings.bundleVersion = TRANSITION_APK_VERSION_NAME; // Modify IL2CPP option as it strips script symbols that are necessary for the scenes at runtime projectScriptImplementation = PlayerSettings.GetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup); if (projectScriptImplementation != ScriptingImplementation.Mono2x) { // Show message in console to make it more clear to developers OVRBundleTool.PrintLog("Build will use Mono as scripting backend."); PlayerSettings.SetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup, ScriptingImplementation.Mono2x); } // Avoid stripping managed code that are necessary for the scenes at runtime #if UNITY_2018_3_OR_NEWER projectManagedStrippingLevel = PlayerSettings.GetManagedStrippingLevel(BuildTargetGroup.Android); if (projectManagedStrippingLevel != ManagedStrippingLevel.Disabled) { OVRBundleTool.PrintLog("Build will set Managed Stripping Level to Disabled."); PlayerSettings.SetManagedStrippingLevel(BuildTargetGroup.Android, ManagedStrippingLevel.Disabled); } #else projectStrippingLevel = PlayerSettings.strippingLevel; if (projectStrippingLevel != StrippingLevel.Disabled) { OVRBundleTool.PrintLog("Build will set Stripping Level to Disabled."); PlayerSettings.strippingLevel = StrippingLevel.Disabled; } #endif projectStripEngineCode = PlayerSettings.stripEngineCode; if (projectStripEngineCode) { PlayerSettings.stripEngineCode = false; } } private static void PostbuildProjectSettingUpdate() { // Restore application identifier PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, projectDefaultAppIdentifier); // Restore version setting PlayerSettings.bundleVersion = projectDefaultVersion; // Restore scripting backend option if (PlayerSettings.GetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup) != projectScriptImplementation) { PlayerSettings.SetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup, projectScriptImplementation); } // Restore managed stripping level #if UNITY_2018_3_OR_NEWER if (PlayerSettings.GetManagedStrippingLevel(BuildTargetGroup.Android) != projectManagedStrippingLevel) { PlayerSettings.SetManagedStrippingLevel(BuildTargetGroup.Android, projectManagedStrippingLevel); } #else if (PlayerSettings.strippingLevel != projectStrippingLevel) { PlayerSettings.strippingLevel = projectStrippingLevel; } #endif if (PlayerSettings.stripEngineCode != projectStripEngineCode) { PlayerSettings.stripEngineCode = projectStripEngineCode; } } // Build and deploy a list of scenes. It's suggested to only build and deploy one active scene that's being modified and // its dependencies such as scenes that are loaded additively public static void BuildDeployScenes(List<OVRBundleTool.EditorSceneInfo> sceneList, bool forceRestart) { externalSceneCache = EXTERNAL_STORAGE_PATH + "/" + PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android) + GetTransitionApkOptionalIdentifier() + "/cache/scenes"; BuildSceneBundles(sceneList); if (DeploySceneBundles(sceneList)) { if (forceRestart) { LaunchApplication(); return; } OVRBundleTool.PrintSuccess(); return; } } // Build assets that are used by scenes from the given list. // This function will automatically de-duplicated same asset file being referenced in multiple scenes. // Scene bundles will be created with name pattern: <SceneName>_<AssetTypeExtention><ChunckNumber> private static void BuildSceneBundles(List<OVRBundleTool.EditorSceneInfo> sceneList) { DateTime totalStart = DateTime.Now; // Keeps track of dependent assets across scenes // to ensure each asset is only packaged once in one of the scene bundles. // uniqueAssetInSceneBundle is a map from "asset unique identifier" to the first scene that references the asset. // It supports different assets with same file name as "asset unique identifier" contain full qualified asset file path Dictionary<string, string> uniqueAssetInSceneBundle = new Dictionary<string, string>(); // List of bundle targets for Unity's build pipeline to package List<AssetBundleBuild> assetBundleBuilds = new List<AssetBundleBuild>(); // Map that contains "asset type" to list of assets that are of the asset type Dictionary<string, List<string>> extToAssetList = new Dictionary<string, List<string>>(); // Check if assets in Resources need to be packaged if (CheckForResources()) { var resourceDirectories = Directory.GetDirectories("Assets", "Resources", SearchOption.AllDirectories).ToArray(); // Fetch a list of all files in resource directory string[] resourceAssetPaths = AssetDatabase.FindAssets("", resourceDirectories).Select(x => AssetDatabase.GUIDToAssetPath(x)).ToArray(); ProcessAssets(resourceAssetPaths, "resources", ref uniqueAssetInSceneBundle, ref extToAssetList); AssetBundleBuild resourceBundle = new AssetBundleBuild(); resourceBundle.assetNames = uniqueAssetInSceneBundle.Keys.ToArray(); resourceBundle.assetBundleName = OVRSceneLoader.resourceBundleName; assetBundleBuilds.Add(resourceBundle); } // Create scene bundle output directory string sceneBundleDirectory = Path.Combine(BUNDLE_MANAGER_OUTPUT_PATH, BUNDLE_MANAGER_MASTER_BUNDLE); if (!Directory.Exists(sceneBundleDirectory)) { Directory.CreateDirectory(sceneBundleDirectory); } OVRBundleTool.PrintLog("Building scene bundles . . . "); DateTime labelingStart = DateTime.Now; foreach (var scene in sceneList) { // Get all the assets that the scene depends on and sort them by type DateTime getDepStart = DateTime.Now; string[] assetDependencies = AssetDatabase.GetDependencies(scene.scenePath); Debug.Log("[OVRBundleManager] - " + scene.sceneName + " - Calculated scene asset dependencies in: " + (DateTime.Now - getDepStart).TotalSeconds); ProcessAssets(assetDependencies, scene.sceneName, ref uniqueAssetInSceneBundle, ref extToAssetList); // Add the scene into it's own bundle string[] sceneAsset = new string[1] { scene.scenePath }; AssetBundleBuild sceneBuild = new AssetBundleBuild(); sceneBuild.assetBundleName = "scene_" + scene.sceneName; sceneBuild.assetNames = sceneAsset; assetBundleBuilds.Add(sceneBuild); } // Chunk the asset bundles by number of assets foreach (string ext in extToAssetList.Keys) { int assetCount = extToAssetList[ext].Count; int numChunks = (assetCount + BUNDLE_CHUNK_SIZE - 1) / BUNDLE_CHUNK_SIZE; //Debug.Log(ext + " has " + assetCount + " asset(s) that will be split into " + numChunks + " chunk(s)"); for (int i = 0; i < numChunks; i++) { List<string> assetChunkList; if (i == numChunks - 1) { int size = BUNDLE_CHUNK_SIZE - (numChunks * BUNDLE_CHUNK_SIZE - assetCount); assetChunkList = extToAssetList[ext].GetRange(i * BUNDLE_CHUNK_SIZE, size); } else { assetChunkList = extToAssetList[ext].GetRange(i * BUNDLE_CHUNK_SIZE, BUNDLE_CHUNK_SIZE); } AssetBundleBuild build = new AssetBundleBuild(); build.assetBundleName = "asset_" + ext + i; build.assetNames = assetChunkList.ToArray(); //Debug.Log("Chunk " + i + " has " + assetChunkList.Count + " asset(s)"); assetBundleBuilds.Add(build); } } Debug.Log("[OVRBundleManager] - Created chucked scene bundles in: " + (DateTime.Now - labelingStart).TotalSeconds); // Build asset bundles BuildPipeline.BuildAssetBundles(sceneBundleDirectory, assetBundleBuilds.ToArray(), BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.Android); double bundleBuildTime = (DateTime.Now - totalStart).TotalSeconds; Debug.Log("[OVRBundleManager] - Total Time: " + bundleBuildTime); OVRPlugin.SendEvent("oculus_bundle_tool", "bundle_build_time", bundleBuildTime.ToString()); } private static void ProcessAssets(string[] assetPaths, string assetParent, ref Dictionary<string, string> uniqueAssetInSceneBundle, ref Dictionary<string, List<string>> extToAssetList) { foreach (string asset in assetPaths) { string ext = Path.GetExtension(asset); if (!string.IsNullOrEmpty(ext)) { ext = ext.Substring(1); if (!ext.Equals("cs") && !ext.Equals("unity")) { // Only process each asset once across all resource and scene bundles // Each asset is keyed by full path as a unique identifier if (!uniqueAssetInSceneBundle.ContainsKey(asset)) { var assetObject = (UnityEngine.Object)AssetDatabase.LoadAssetAtPath(asset, typeof(UnityEngine.Object)); if (assetObject == null || (assetObject.hideFlags & HideFlags.DontSaveInBuild) == 0) { uniqueAssetInSceneBundle[asset] = assetParent; if (assetParent != "resources") { if (!extToAssetList.ContainsKey(ext)) { extToAssetList[ext] = new List<string>(); } extToAssetList[ext].Add(asset); } } } } } } } private static bool DeploySceneBundles(List<OVRBundleTool.EditorSceneInfo> sceneList) { // Create Temp directory on local machine if it does not exist string tempDirectory = Path.Combine(BUNDLE_MANAGER_OUTPUT_PATH, "Temp"); if (!Directory.Exists(tempDirectory)) { Directory.CreateDirectory(tempDirectory); } string absoluteTempPath = Path.Combine(Path.Combine(Application.dataPath, ".."), tempDirectory); OVRBundleTool.PrintLog("Deploying scene bundles to device . . . "); OVRADBTool adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath()); if (adbTool.isReady) { DateTime transferStart = DateTime.Now; OVRBundleTool.UpdateSceneBuildStatus(OVRBundleTool.SceneBundleStatus.TRANSFERRING); // Transfer all scene bundles that are relavent if (!TransferSceneBundles(adbTool, absoluteTempPath, externalSceneCache)) { return false; } OVRBundleTool.UpdateSceneBuildStatus(OVRBundleTool.SceneBundleStatus.DEPLOYED); // Create file to tell transition scene APK which scene to load and push it to the device string sceneLoadDataPath = Path.Combine(tempDirectory, OVRSceneLoader.sceneLoadDataName); if (File.Exists(sceneLoadDataPath)) { File.Delete(sceneLoadDataPath); } StreamWriter writer = new StreamWriter(sceneLoadDataPath, true); // Write version and scene names long unixTime = (int)(DateTimeOffset.UtcNow.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds; writer.WriteLine(unixTime.ToString()); for (int i = 0; i < sceneList.Count; i++) { writer.WriteLine(Path.GetFileNameWithoutExtension(sceneList[i].scenePath)); } writer.Close(); string absoluteSceneLoadDataPath = Path.Combine(absoluteTempPath, OVRSceneLoader.sceneLoadDataName); string[] pushCommand = { "-d push", "\"" + absoluteSceneLoadDataPath + "\"", "\"" + externalSceneCache + "\"" }; string output, error; if (adbTool.RunCommand(pushCommand, null, out output, out error) == 0) { Debug.Log("[OVRBundleManager] Scene Load Data Pushed to Device."); OVRPlugin.SendEvent("oculus_bundle_tool", "transfer_bundle_time", (DateTime.Now - transferStart).TotalSeconds.ToString()); return true; } OVRBundleTool.PrintError(string.IsNullOrEmpty(error) ? output : error); } else { OVRBundleTool.PrintError(ADB_TOOL_INITIALIZE_ERROR); } return false; } private static bool TransferSceneBundles(OVRADBTool adbTool, string absoluteTempPath, string externalSceneCache) { List<string> bundlesToTransfer = new List<string>(); List<string> bundlesToDelete = new List<string>(); string manifestFilePath = externalSceneCache + "/" + BUNDLE_MANAGER_MASTER_BUNDLE; string[] pullManifestCommand = { "-d pull", "\"" + manifestFilePath + "\"", "\"" + absoluteTempPath + "\"" }; string output, error; if (adbTool.RunCommand(pullManifestCommand, null, out output, out error) == 0) { // An existing manifest file was found on device. Load hashes and upload bundles that have changed hashes. Debug.Log("[OVRBundleManager] - Scene bundle manifest file found. Decoding changes . . ."); // Load hashes from remote manifest AssetBundle remoteBundle = AssetBundle.LoadFromFile(Path.Combine(absoluteTempPath, BUNDLE_MANAGER_MASTER_BUNDLE)); if (remoteBundle == null) { OVRBundleTool.PrintError("Failed to load remote asset bundle manifest file."); return false; } AssetBundleManifest remoteManifest = remoteBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest"); Dictionary<string, Hash128> remoteBundleToHash = new Dictionary<string, Hash128>(); if (remoteManifest != null) { string[] assetBundles = remoteManifest.GetAllAssetBundles(); foreach (string bundleName in assetBundles) { remoteBundleToHash[bundleName] = remoteManifest.GetAssetBundleHash(bundleName); } } remoteBundle.Unload(true); // Load hashes from local manifest AssetBundle localBundle = AssetBundle.LoadFromFile(BUNDLE_MANAGER_OUTPUT_PATH + "\\" + BUNDLE_MANAGER_MASTER_BUNDLE + "\\" + BUNDLE_MANAGER_MASTER_BUNDLE); if (localBundle == null) { OVRBundleTool.PrintError("<color=red>Failed to load local asset bundle manifest file.\n</color>"); return false; } AssetBundleManifest localManifest = localBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest"); if (localManifest != null) { Hash128 zeroHash = new Hash128(0, 0, 0, 0); // Build a list of dirty bundles that will have to be transfered string relativeSceneBundlesPath = Path.Combine(BUNDLE_MANAGER_OUTPUT_PATH, BUNDLE_MANAGER_MASTER_BUNDLE); bundlesToTransfer.Add(Path.Combine(relativeSceneBundlesPath, BUNDLE_MANAGER_MASTER_BUNDLE)); string[] assetBundles = localManifest.GetAllAssetBundles(); foreach (string bundleName in assetBundles) { if (!remoteBundleToHash.ContainsKey(bundleName)) { bundlesToTransfer.Add(Path.Combine(relativeSceneBundlesPath, bundleName)); } else { if (remoteBundleToHash[bundleName] != localManifest.GetAssetBundleHash(bundleName)) { bundlesToTransfer.Add(Path.Combine(relativeSceneBundlesPath, bundleName)); } remoteBundleToHash[bundleName] = zeroHash; } } OVRBundleTool.PrintLog(bundlesToTransfer.Count + " dirty bundle(s) will be transfered.\n"); } } else { if (output.Contains("does not exist")) { // Fresh install of asset bundles, transfer all asset bundles OVRBundleTool.PrintLog("Manifest file not found. Transfering all bundles . . . "); string[] mkdirCommand = { "-d shell", "mkdir -p", "\"" + externalSceneCache + "\"" }; if (adbTool.RunCommand(mkdirCommand, null, out output, out error) == 0) { string absoluteSceneBundlePath = Path.Combine(Path.Combine(Application.dataPath, ".."), Path.Combine(BUNDLE_MANAGER_OUTPUT_PATH, BUNDLE_MANAGER_MASTER_BUNDLE)); string[] assetBundlePaths = Directory.GetFiles(absoluteSceneBundlePath); if (assetBundlePaths.Length != 0) { foreach (string path in assetBundlePaths) { if (!path.Contains(".manifest")) { bundlesToTransfer.Add(path); } } } else { OVRBundleTool.PrintError("Failed to locate scene bundles to transfer."); return false; } } } } // If any adb error occured during manifest calculation, print it and return false if (!string.IsNullOrEmpty(error) || output.Contains("error")) { OVRBundleTool.PrintError(string.IsNullOrEmpty(error) ? output : error); return false; } // Transfer bundles to device DateTime transferStart = DateTime.Now; foreach (string bundle in bundlesToTransfer) { string absoluteBundlePath = Path.Combine(Path.Combine(Application.dataPath, ".."), bundle); string[] pushBundleCommand = { "-d push", "\"" + absoluteBundlePath + "\"", "\"" + externalSceneCache + "\"" }; adbTool.RunCommandAsync(pushBundleCommand, null); } Debug.Log("[OVRBundleManager] - Transfer took " + (DateTime.Now - transferStart).TotalSeconds + " seconds."); // Delete stale bundles on device if (bundlesToDelete.Count > 0) { foreach (string bundle in bundlesToDelete) { string bundlePath = externalSceneCache + "/" + bundle; string[] deleteBundleCommand = { "-d shell", "rm", "\"" + bundlePath + "\"" }; adbTool.RunCommandAsync(deleteBundleCommand, null); } OVRBundleTool.PrintLog("Deleted " + bundlesToDelete.Count + " bundle(s) that were stale"); } return true; } public static bool LaunchApplication() { OVRBundleTool.PrintLog("Launching Application . . . "); OVRADBTool adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath()); if (adbTool.isReady) { string output, error; string appPackagename = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android) + GetTransitionApkOptionalIdentifier(); string playerActivityName = "\"" + appPackagename + "/com.unity3d.player.UnityPlayerActivity\""; string[] appStartCommand = { "-d shell", "am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -S -f 0x10200000 -n", playerActivityName }; if (adbTool.RunCommand(appStartCommand, null, out output, out error) == 0) { OVRBundleTool.PrintSuccess(); OVRBundleTool.PrintLog("App package " + appPackagename + " is launched."); return true; } string completeError = "Failed to launch application. Try launching it manually through the device.\n" + (string.IsNullOrEmpty(error) ? output : error); OVRBundleTool.PrintError(completeError); } else { OVRBundleTool.PrintError(ADB_TOOL_INITIALIZE_ERROR); } return false; } public static bool UninstallAPK() { OVRBundleTool.PrintLog("Uninstalling Application . . ."); OVRADBTool adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath()); if (adbTool.isReady) { string output, error; string appPackagename = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android) + GetTransitionApkOptionalIdentifier(); string[] appStartCommand = { "-d shell", "pm uninstall", appPackagename }; if (adbTool.RunCommand(appStartCommand, null, out output, out error) == 0) { OVRBundleTool.PrintSuccess(); OVRBundleTool.PrintLog("App package " + appPackagename + " is uninstalled."); return true; } OVRBundleTool.PrintError("Failed to uninstall APK."); } else { OVRBundleTool.PrintError(ADB_TOOL_INITIALIZE_ERROR); } return false; } public static void DeleteRemoteAssetBundles() { OVRADBTool adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath()); if (adbTool.isReady) { bool failure = false; string fileExistsError = "No such file or directory"; OVRBundleTool.PrintLog("Deleting device bundles . . . "); string output, error; string[] deleteBundleCommand = { "-d shell", "rm -r", externalSceneCache }; if (adbTool.RunCommand(deleteBundleCommand, null, out output, out error) != 0) { if (!(output.Contains(fileExistsError) || error.Contains(fileExistsError))) { failure = true; } } if (failure) { OVRBundleTool.PrintError(string.IsNullOrEmpty(error) ? output : error); OVRBundleTool.PrintError("Failed to delete scene bundle cache directory."); } else { OVRBundleTool.PrintSuccess(); } } else { OVRBundleTool.PrintError(ADB_TOOL_INITIALIZE_ERROR); } } public static void DeleteLocalAssetBundles() { try { if (Directory.Exists(BUNDLE_MANAGER_OUTPUT_PATH)) { OVRBundleTool.PrintLog("Deleting local bundles . . . "); Directory.Delete(BUNDLE_MANAGER_OUTPUT_PATH, true); } } catch (Exception e) { OVRBundleTool.PrintError(e.Message); } OVRBundleTool.PrintSuccess(); } private static bool CheckForResources() { string[] resourceDirectories = Directory.GetDirectories("Assets", "Resources", SearchOption.AllDirectories); return resourceDirectories.Length > 0; } private static string GetTransitionApkOptionalIdentifier() { string transitionApkOptionalIdentifier; // Check option value from editor UI if (OVRBundleTool.GetUseOptionalTransitionApkPackage()) { // Append .transition to default app package name to optionally allow both // full build apk and transition apk to be installed on device transitionApkOptionalIdentifier = ".transition"; } else { transitionApkOptionalIdentifier = ""; } return transitionApkOptionalIdentifier; } } #endif
using UnityEngine; using System.Collections.Generic; using Pathfinding.Util; namespace Pathfinding { [AddComponentMenu("Pathfinding/Modifiers/Funnel")] [System.Serializable] /** Simplifies paths on navmesh graphs using the funnel algorithm. * The funnel algorithm is an algorithm which can, given a path corridor with nodes in the path where the nodes have an area, like triangles, it can find the shortest path inside it. * This makes paths on navmeshes look much cleaner and smoother. * \image html images/funnelModifier_on.png * \ingroup modifiers */ [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_funnel_modifier.php")] public class FunnelModifier : MonoModifier { #if UNITY_EDITOR [UnityEditor.MenuItem("CONTEXT/Seeker/Add Funnel Modifier")] public static void AddComp (UnityEditor.MenuCommand command) { (command.context as Component).gameObject.AddComponent(typeof(FunnelModifier)); } #endif public override int Order { get { return 10; } } public override void Apply (Path p) { List<GraphNode> path = p.path; List<Vector3> vectorPath = p.vectorPath; if (path == null || path.Count == 0 || vectorPath == null || vectorPath.Count != path.Count) { return; } List<Vector3> funnelPath = ListPool<Vector3>.Claim(); // Claim temporary lists and try to find lists with a high capacity List<Vector3> left = ListPool<Vector3>.Claim(path.Count+1); List<Vector3> right = ListPool<Vector3>.Claim(path.Count+1); AstarProfiler.StartProfile("Construct Funnel"); // Add start point left.Add(vectorPath[0]); right.Add(vectorPath[0]); // Loop through all nodes in the path (except the last one) for (int i = 0; i < path.Count-1; i++) { // Get the portal between path[i] and path[i+1] and add it to the left and right lists bool portalWasAdded = path[i].GetPortal(path[i+1], left, right, false); if (!portalWasAdded) { // Fallback, just use the positions of the nodes left.Add((Vector3)path[i].position); right.Add((Vector3)path[i].position); left.Add((Vector3)path[i+1].position); right.Add((Vector3)path[i+1].position); } } // Add end point left.Add(vectorPath[vectorPath.Count-1]); right.Add(vectorPath[vectorPath.Count-1]); if (!RunFunnel(left, right, funnelPath)) { // If funnel algorithm failed, degrade to simple line funnelPath.Add(vectorPath[0]); funnelPath.Add(vectorPath[vectorPath.Count-1]); } // Release lists back to the pool ListPool<Vector3>.Release(p.vectorPath); p.vectorPath = funnelPath; ListPool<Vector3>.Release(left); ListPool<Vector3>.Release(right); } /** Calculate a funnel path from the \a left and \a right portal lists. * The result will be appended to \a funnelPath */ public static bool RunFunnel (List<Vector3> left, List<Vector3> right, List<Vector3> funnelPath) { if (left == null) throw new System.ArgumentNullException("left"); if (right == null) throw new System.ArgumentNullException("right"); if (funnelPath == null) throw new System.ArgumentNullException("funnelPath"); if (left.Count != right.Count) throw new System.ArgumentException("left and right lists must have equal length"); if (left.Count <= 3) { return false; } //Remove identical vertices while (left[1] == left[2] && right[1] == right[2]) { //System.Console.WriteLine ("Removing identical left and right"); left.RemoveAt(1); right.RemoveAt(1); if (left.Count <= 3) { return false; } } Vector3 swPoint = left[2]; if (swPoint == left[1]) { swPoint = right[2]; } //Test while (VectorMath.IsColinearXZ(left[0], left[1], right[1]) || VectorMath.RightOrColinearXZ(left[1], right[1], swPoint) == VectorMath.RightOrColinearXZ(left[1], right[1], left[0])) { #if ASTARDEBUG Debug.DrawLine(left[1], right[1], new Color(0, 0, 0, 0.5F)); Debug.DrawLine(left[0], swPoint, new Color(0, 0, 0, 0.5F)); #endif left.RemoveAt(1); right.RemoveAt(1); if (left.Count <= 3) { return false; } swPoint = left[2]; if (swPoint == left[1]) { swPoint = right[2]; } } //Switch left and right to really be on the "left" and "right" sides /** \todo The colinear check should not be needed */ if (!VectorMath.IsClockwiseXZ(left[0], left[1], right[1]) && !VectorMath.IsColinearXZ(left[0], left[1], right[1])) { //System.Console.WriteLine ("Wrong Side 2"); List<Vector3> tmp = left; left = right; right = tmp; } #if ASTARDEBUG for (int i = 0; i < left.Count-1; i++) { Debug.DrawLine(left[i], left[i+1], Color.red); Debug.DrawLine(right[i], right[i+1], Color.magenta); Debug.DrawRay(right[i], Vector3.up, Color.magenta); } for (int i = 0; i < left.Count; i++) { //Debug.DrawLine (right[i],left[i], Color.cyan); } #endif funnelPath.Add(left[0]); Vector3 portalApex = left[0]; Vector3 portalLeft = left[1]; Vector3 portalRight = right[1]; int apexIndex = 0; int rightIndex = 1; int leftIndex = 1; for (int i = 2; i < left.Count; i++) { if (funnelPath.Count > 2000) { Debug.LogWarning("Avoiding infinite loop. Remove this check if you have this long paths."); break; } Vector3 pLeft = left[i]; Vector3 pRight = right[i]; /*Debug.DrawLine (portalApex,portalLeft,Color.red); * Debug.DrawLine (portalApex,portalRight,Color.yellow); * Debug.DrawLine (portalApex,left,Color.cyan); * Debug.DrawLine (portalApex,right,Color.cyan);*/ if (VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalRight, pRight) >= 0) { if (portalApex == portalRight || VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalLeft, pRight) <= 0) { portalRight = pRight; rightIndex = i; } else { funnelPath.Add(portalLeft); portalApex = portalLeft; apexIndex = leftIndex; portalLeft = portalApex; portalRight = portalApex; leftIndex = apexIndex; rightIndex = apexIndex; i = apexIndex; continue; } } if (VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalLeft, pLeft) <= 0) { if (portalApex == portalLeft || VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalRight, pLeft) >= 0) { portalLeft = pLeft; leftIndex = i; } else { funnelPath.Add(portalRight); portalApex = portalRight; apexIndex = rightIndex; portalLeft = portalApex; portalRight = portalApex; leftIndex = apexIndex; rightIndex = apexIndex; i = apexIndex; continue; } } } funnelPath.Add(left[left.Count-1]); return true; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System; using System.Globalization; using System.Numerics; using System.Reflection; using Scriban.Helpers; using Scriban.Parsing; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban.Functions { /// <summary> /// Math functions available through the object 'math' in scriban. /// </summary> #if SCRIBAN_PUBLIC public #else internal #endif partial class MathFunctions : ScriptObject { private const string RandomTagKey = "random"; /// <summary> /// Returns the absolute value of a specified number. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="value">The input value</param> /// <returns>The absolute value of the input value</returns> /// <remarks> /// ```scriban-html /// {{ -15.5| math.abs }} /// {{ -5| math.abs }} /// ``` /// ```html /// 15.5 /// 5 /// ``` /// </remarks> public static object Abs(TemplateContext context, SourceSpan span, object value) { if (value == null) { return null; } if (value is int) { return Math.Abs((int) value); } if (value is float) { return Math.Abs((float)value); } if (value is double) { return Math.Abs((double)value); } if (value is sbyte) { return Math.Abs((sbyte)value); } if (value is short) { return Math.Abs((short)value); } if (value is long) { return Math.Abs((long)value); } if (value is decimal) { return Math.Abs((decimal)value); } // If it is a primitive it is already unsigned if (value.GetType().IsPrimitive) { return value; } // otherwise we don't have a number, throw an exception just in case throw new ScriptRuntimeException(span, $"The value `{value}` is not a number"); } /// <summary> /// Returns the smallest integer greater than or equal to the specified number. /// </summary> /// <param name="value">The input value</param> /// <returns>The smallest integer greater than or equal to the specified number.</returns> /// <remarks> /// ```scriban-html /// {{ 4.6 | math.ceil }} /// {{ 4.3 | math.ceil }} /// ``` /// ```html /// 5 /// 5 /// ``` /// </remarks> public static double Ceil(double value) { return Math.Ceiling(value); } /// <summary> /// Divides the specified value by another value. If the divisor is an integer, the result will /// be floor to and converted back to an integer. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="value">The input value</param> /// <param name="divisor">The divisor value</param> /// <returns>The division of `value` by `divisor`.</returns> /// <remarks> /// ```scriban-html /// {{ 8.4 | math.divided_by 2.0 | math.round 1 }} /// {{ 8.4 | math.divided_by 2 }} /// ``` /// ```html /// 4.2 /// 4 /// ``` /// </remarks> public static object DividedBy(TemplateContext context, SourceSpan span, double value, object divisor) { var result = ScriptBinaryExpression.Evaluate(context, span, ScriptBinaryOperator.Divide, value, divisor); // If the divisor is an integer, return a an integer if (divisor is int) { if (result is double) { return (int) Math.Floor((double) result); } if (result is float) { return (int) Math.Floor((float) result); } } return result; } /// <summary> /// Returns the largest integer less than or equal to the specified number. /// </summary> /// <param name="value">The input value</param> /// <returns>The largest integer less than or equal to the specified number.</returns> /// <remarks> /// ```scriban-html /// {{ 4.6 | math.floor }} /// {{ 4.3 | math.floor }} /// ``` /// ```html /// 4 /// 4 /// ``` /// </remarks> public static double Floor(double value) { return Math.Floor(value); } /// <summary> /// Formats a number value with specified [.NET standard numeric format strings](https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="value">The input value</param> /// <param name="format">The format string.</param> /// <param name="culture">The culture as a string (e.g `en-US`). By default the culture from <see cref="TemplateContext.CurrentCulture"/> is used</param> /// <returns>The largest integer less than or equal to the specified number.</returns> /// <remarks> /// ```scriban-html /// {{ 255 | math.format "X4" }} /// ``` /// ```html /// 00FF /// ``` /// </remarks> public static string Format(TemplateContext context, SourceSpan span, object value, string format, string culture = null) { if (value == null) { return string.Empty; } format = format ?? string.Empty; var formattable = value as IFormattable; if (!IsNumber(value) || formattable == null) { throw new ScriptRuntimeException(span, $"Unexpected `{value}`. Must be a formattable number"); } return formattable.ToString(format, culture != null ? new CultureInfo(culture) : context.CurrentCulture); } /// <summary> /// Returns a boolean indicating if the input value is a number /// </summary> /// <param name="value">The input value</param> /// <returns>**true** if the input value is a number; otherwise false.</returns> /// <remarks> /// ```scriban-html /// {{ 255 | math.is_number }} /// {{ "yo" | math.is_number }} /// ``` /// ```html /// true /// false /// ``` /// </remarks> public static bool IsNumber(object value) { return value is sbyte || value is byte || value is short || value is ushort || value is int || value is uint || value is long || value is ulong || value is float || value is double || value is decimal || value is BigInteger; } /// <summary> /// Substracts from the input value the `with` value /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="value">The input value</param> /// <param name="with">The with value to substract from `value`</param> /// <returns>The results of the substraction: `value` - `with`</returns> /// <remarks> /// ```scriban-html /// {{ 255 | math.minus 5}} /// ``` /// ```html /// 250 /// ``` /// </remarks> public static object Minus(TemplateContext context, SourceSpan span, object value, object with) { return ScriptBinaryExpression.Evaluate(context, span, ScriptBinaryOperator.Substract, value, with); } /// <summary> /// Performs the modulo of the input value with the `with` value /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="value">The input value</param> /// <param name="with">The with value to module `value`</param> /// <returns>The results of the modulo: `value` % `with`</returns> /// <remarks> /// ```scriban-html /// {{ 11 | math.modulo 10}} /// ``` /// ```html /// 1 /// ``` /// </remarks> public static object Modulo(TemplateContext context, SourceSpan span, object value, object with) { return ScriptBinaryExpression.Evaluate(context, span, ScriptBinaryOperator.Modulus, value, with); } /// <summary> /// Performs the addition of the input value with the `with` value /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="value">The input value</param> /// <param name="with">The with value to add to`value`</param> /// <returns>The results of the addition: `value` + `with`</returns> /// <remarks> /// ```scriban-html /// {{ 1 | math.plus 2}} /// ``` /// ```html /// 3 /// ``` /// </remarks> public static object Plus(TemplateContext context, SourceSpan span, object value, object with) { return ScriptBinaryExpression.Evaluate(context, span, ScriptBinaryOperator.Add, value, with); } /// <summary> /// Rounds a value to the nearest integer or to the specified number of fractional digits. /// </summary> /// <param name="value">The input value</param> /// <param name="precision">The number of fractional digits in the return value. Default is 0.</param> /// <returns>A value rounded to the nearest integer or to the specified number of fractional digits.</returns> /// <remarks> /// ```scriban-html /// {{ 4.6 | math.round }} /// {{ 4.3 | math.round }} /// {{ 4.5612 | math.round 2 }} /// ``` /// ```html /// 5 /// 4 /// 4.56 /// ``` /// </remarks> public static double Round(double value, int precision = 0) { return Math.Round(value, precision); } /// <summary> /// Performs the multiplication of the input value with the `with` value /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="value">The input value</param> /// <param name="with">The with value to multiply to`value`</param> /// <returns>The results of the multiplication: `value` * `with`</returns> /// <remarks> /// ```scriban-html /// {{ 2 | math.times 3}} /// ``` /// ```html /// 6 /// ``` /// </remarks> public static object Times(TemplateContext context, SourceSpan span, object value, object with) { return ScriptBinaryExpression.Evaluate(context, span, ScriptBinaryOperator.Multiply, value, with); } /// <summary> /// Creates a new UUID /// </summary> /// <returns>The created UUID, ex. 2dc55d50-3f6c-446a-87d0-a5a4eed23269</returns> /// <remarks> /// ```scriban-html /// {{ math.uuid }} /// ``` /// ```html /// 1c0a4aa8-680e-4bd6-95e9-cdbec45ef057 /// ``` /// </remarks> public static string Uuid() { return Guid.NewGuid().ToString(); } /// <summary> /// Creates a random number /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="minValue">The inclusive lower bound of the random number returned</param> /// <param name="maxValue">The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.</param> /// <returns>A random number greater or equal to minValue and less than maxValue</returns> /// <remarks> /// ```scriban-html /// {{ math.random 1 10 }} /// ``` /// ```html /// 7 /// ``` /// </remarks> public static object Random(TemplateContext context, SourceSpan span, int minValue, int maxValue) { if (minValue > maxValue) { throw new ScriptRuntimeException(span, "minValue must be greater than maxValue"); } var currentTags = context.Tags; if (!currentTags.TryGetValue(RandomTagKey, out var randomObject)) { randomObject = new Random(); currentTags.Add(RandomTagKey, randomObject); } var random = (Random)randomObject; return random.Next(minValue, maxValue); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- if ($platform $= "windows") $platformFontType = "lucida console"; else if ($platform $= "Android") $platformFontType = "Droid"; else $platformFontType = "monaco"; if ($platform $= "ios") $platformFontSize = 18; else if ($platform $= "Android") $platformFontSize = 14; else $platformFontSize = 12; //----------------------------------------------------------------------------- new GuiCursor(DefaultCursor) { hotSpot = "4 4"; renderOffset = "0 0"; bitmapName = "^Sandbox/gui/images/defaultCursor"; }; //--------------------------------------------------------------------------------------------- // GuiDefaultProfile is a special profile that all other profiles inherit defaults from. It // must exist. //--------------------------------------------------------------------------------------------- if(!isObject(GuiDefaultProfile)) new GuiControlProfile (GuiDefaultProfile) { tab = false; canKeyFocus = false; hasBitmapArray = false; mouseOverSelected = false; // fill color opaque = false; fillColor = "211 211 211"; fillColorHL = "244 244 244"; fillColorNA = "244 244 244"; // border color border = 0; borderColor = "100 100 100 255"; borderColorHL = "128 128 128"; borderColorNA = "64 64 64"; // font fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "0 0 0"; fontColorHL = "32 100 100"; fontColorNA = "0 0 0"; fontColorSEL= "10 10 10"; // bitmap information bitmap = "^Sandbox/gui/images/window.png"; bitmapBase = ""; textOffset = "0 0"; // used by guiTextControl modal = true; justify = "left"; autoSizeWidth = false; autoSizeHeight = false; returnTab = false; numbersOnly = false; cursorColor = "0 0 0 255"; // sounds soundButtonDown = $ButtonSound.fileName; soundButtonOver = ""; }; // ---------------------------------------------------------------------------- if (!isObject(GuiTransparentProfile)) new GuiControlProfile (GuiTransparentProfile : GuiDefaultProfile) { opaque = false; border = false; }; // ---------------------------------------------------------------------------- if(!isObject(GuiSolidProfile)) new GuiControlProfile (GuiSolidProfile) { opaque = true; border = true; }; // ---------------------------------------------------------------------------- if (!isObject(GuiToolTipProfile)) new GuiControlProfile (GuiToolTipProfile : GuiDefaultProfile) { fillColor = "246 220 165 255"; fontType = $platformFontType; fontSize = $platformFontSize; }; // ---------------------------------------------------------------------------- if (!isObject(GuiPopupMenuItemBorder)) new GuiControlProfile (GuiPopupMenuItemBorder : GuiDefaultProfile) { bitmap = "^Sandbox/gui/images/scroll"; hasBitmapArray = true; }; // ---------------------------------------------------------------------------- if (!isObject(GuiPopUpMenuDefault)) new GuiControlProfile (GuiPopUpMenuDefault) { tab = false; canKeyFocus = false; hasBitmapArray = false; mouseOverSelected = false; // fill color opaque = false; fillColor = "255 255 255 192"; fillColorHL = "255 0 0 192"; fillColorNA = "0 0 255 255"; // border color border = 1; borderColor = "100 100 100 255"; borderColorHL = "0 128 0 255"; borderColorNA = "0 226 226 52"; // font fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "27 59 95 255"; fontColorHL = "232 240 248 255"; fontColorNA = "0 0 0 255"; fontColorSEL= "255 255 255 255"; // bitmap information bitmap = "^Sandbox/gui/images/scroll"; hasBitmapArray = true; bitmapBase = ""; textOffset = "0 0"; // used by guiTextControl modal = true; justify = "left"; autoSizeWidth = false; autoSizeHeight = false; returnTab = false; numbersOnly = false; cursorColor = "0 0 0 255"; profileForChildren = GuiPopupMenuItemBorder; // sounds soundButtonDown = ""; soundButtonOver = ""; }; // ---------------------------------------------------------------------------- if (!isObject(GuiPopUpMenuProfile)) new GuiControlProfile (GuiPopUpMenuProfile : GuiPopUpMenuDefault) { textOffset = "6 3"; justify = "center"; bitmap = "^Sandbox/gui/images/dropDown"; hasBitmapArray = true; border = -3; profileForChildren = GuiPopUpMenuDefault; opaque = true; }; //----------------------------------------------------------------------------- if (!isObject(GuiTextProfile)) new GuiControlProfile (GuiTextProfile) { border=false; // font fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "white"; modal = true; justify = "left"; autoSizeWidth = false; autoSizeHeight = false; returnTab = false; numbersOnly = false; cursorColor = "0 0 0 255"; }; //----------------------------------------------------------------------------- if (!isObject(GuiCheckBoxProfile)) new GuiControlProfile (GuiCheckBoxProfile) { opaque = false; fontColor = "white"; fillColor = "232 232 232 255"; fontColorHL = "white"; border = false; borderColor = "0 0 0 255"; fontType = $platformFontType; fontSize = $platformFontSize; fixedExtent = true; justify = "left"; bitmap = "^Sandbox/gui/images/checkBox"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if(!isObject(GuiConsoleProfile)) new GuiControlProfile (GuiConsoleProfile) { fontType = $platformFontType; fontSize = $platformFontSize * 1.1; fontColor = White; fontColorHL = LightSlateGray; fontColorNA = Red; fontColors[6] = "100 100 100"; fontColors[7] = "100 100 0"; fontColors[8] = "0 0 100"; fontColors[9] = "0 100 0"; }; //----------------------------------------------------------------------------- if (!isObject(GuiTextEditProfile)) new GuiControlProfile (GuiTextEditProfile) { fontSize = $platformFontSize; opaque = false; fillColor = "232 240 248 255"; fillColorHL = "251 170 0 255"; fillColorNA = "127 127 127 52"; border = -2; bitmap = "^Sandbox/gui/images/textEdit.png"; borderColor = "40 40 40 10"; fontColor = "27 59 95 255"; fontColorHL = "232 240 248 255"; fontColorNA = "0 0 0 52"; fontColorSEL = "0 0 0 255"; textOffset = "5 2"; autoSizeWidth = false; autoSizeHeight = false; tab = false; canKeyFocus = true; returnTab = true; }; //----------------------------------------------------------------------------- if(!isObject(GuiNumberEditProfile)) new GuiControlProfile (GuiNumberEditProfile: GuiTextEditProfile) { numbersOnly = true; }; //----------------------------------------------------------------------------- if(!isObject(GuiConsoleTextEditProfile)) new GuiControlProfile (GuiConsoleTextEditProfile : GuiTextEditProfile) { fontType = $platformFontType; fontSize = $platformFontSize * 1.1; }; //----------------------------------------------------------------------------- if(!isObject(GuiScrollProfile)) new GuiControlProfile (GuiScrollProfile) { opaque = true; fillColor = "255 255 255"; border = 1; borderThickness = 2; bitmap = "^Sandbox/gui/images/scrollBar.png"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if(!isObject(GuiTransparentScrollProfile)) new GuiControlProfile (GuiTransparentScrollProfile) { opaque = false; fillColor = "255 255 255"; border = false; borderThickness = 2; borderColor = "0 0 0"; bitmap = "^Sandbox/gui/images/scrollBar.png"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if(!isObject(ConsoleScrollProfile)) new GuiControlProfile( ConsoleScrollProfile : GuiScrollProfile ) { opaque = true; fillColor = "0 0 0 120"; border = 3; borderThickness = 0; borderColor = "0 0 0"; }; //----------------------------------------------------------------------------- if(!isObject(GuiToolboxProfile)) new GuiControlProfile( GuiToolboxProfile : GuiScrollProfile ) { opaque = true; fillColor = "255 255 255 220"; border = 3; borderThickness = 0; borderColor = "0 0 0"; }; //----------------------------------------------------------------------------- if(!isObject(SandboxWindowProfile)) new GuiControlProfile (SandboxWindowProfile : GuiDefaultProfile) { // fill color opaque = false; fillColor = "0 0 0 92"; // font fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "255 255 255 255"; }; //----------------------------------------------------------------------------- if (!isObject(GuiButtonProfile)) new GuiControlProfile (GuiButtonProfile) { opaque = true; border = -1; fontColor = "white"; fontColorHL = "229 229 229 255"; fixedExtent = true; justify = "center"; canKeyFocus = false; fontType = $platformFontType; bitmap = "^Sandbox/gui/images/smallButtonContainer"; }; //----------------------------------------------------------------------------- if (!isObject(BlueButtonProfile)) new GuiControlProfile (BlueButtonProfile : GuiButtonProfile) { fontSize = $platformFontSize; fontColor = "255 255 255 255"; fontColorHL = "255 255 255 255"; bitmap = "^Sandbox/gui/images/blueButton.png"; }; //----------------------------------------------------------------------------- if (!isObject(RedButtonProfile)) new GuiControlProfile (RedButtonProfile : GuiButtonProfile) { fontSize = $platformFontSize; fontColor = "255 255 255 255"; fontColorHL = "255 255 255 255"; bitmap = "^Sandbox/gui/images/redButton.png"; }; //----------------------------------------------------------------------------- if (!isObject(GreenButtonProfile)) new GuiControlProfile (GreenButtonProfile : GuiButtonProfile) { fontSize = $platformFontSize; fontColor = "255 255 255 255"; fontColorHL = "255 255 255 255"; bitmap = "^Sandbox/gui/images/greenButton.png"; }; //----------------------------------------------------------------------------- if (!isObject(GuiRadioProfile)) new GuiControlProfile (GuiRadioProfile : GuiDefaultProfile) { fillColor = "232 232 232 255"; fixedExtent = true; bitmap = "^Sandbox/gui/images/radioButton.png"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if (!isObject(GuiSliderProfile)) new GuiControlProfile (GuiSliderProfile) { bitmap = "^Sandbox/gui/images/slider.png"; fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "white"; }; //----------------------------------------------------------------------------- if (!isObject(GuiSliderNoTextProfile)) new GuiControlProfile (GuiSliderNoTextProfile) { bitmap = "^Sandbox/gui/images/slider.png"; fontColor = "white"; fontSize = 1; }; //----------------------------------------------------------------------------- if (!isObject(GuiSpinnerProfile)) new GuiControlProfile (GuiSpinnerProfile) { fontType = $platformFontType; fontSize = $platformFontSize; opaque = false; justify = "center"; fillColor = "232 240 248 255"; fillColorHL = "251 170 0 255"; fillColorNA = "127 127 127 52"; numbersOnly = true; border = -2; bitmap = "^Sandbox/gui/images/textEdit_noSides"; borderColor = "40 40 40 10"; fontColor = "27 59 95 255"; fontColorHL = "232 240 248 255"; fontColorNA = "0 0 0 52"; fontColorSEL = "0 0 0 255"; textOffset = "4 2"; autoSizeWidth = false; autoSizeHeight = false; tab = false; canKeyFocus = true; returnTab = true; }; //----------------------------------------------------------------------------- if (!isObject(GuiLightScrollProfile)) new GuiControlProfile (GuiLightScrollProfile : GuiScrollProfile) { opaque = false; fillColor = "212 216 220"; border = 0; bitmap = "^Sandbox/gui/images/scrollBar"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if (!isObject(GuiSunkenContainerProfile)) new GuiControlProfile (GuiSunkenContainerProfile) { opaque = false; fillColor = "232 240 248 255"; fillColorHL = "251 170 0 255"; fillColorNA = "127 127 127 52"; border = -2; bitmap = "^Sandbox/gui/images/sunkenContainer"; borderColor = "40 40 40 10"; };
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.IO; /// <summary> /// Represents a ClientExtension object. /// </summary> public sealed class ClientExtension : ComplexProperty { /// <summary> /// Initializes a new instance of the <see cref="ClientExtension"/> class. /// </summary> internal ClientExtension() : base() { this.Namespace = XmlNamespace.Types; } /// <summary> /// Initializes a new instance of the <see cref="ClientExtension"/> class. /// </summary> /// <param name="type">Extension type</param> /// <param name="scope">Extension install scope</param> /// <param name="manifestStream">Manifest stream, can be null</param> /// <param name="marketplaceAssetID">The asset ID for Office Marketplace</param> /// <param name="marketplaceContentMarket">The content market for Office Marketplace</param> /// <param name="isAvailable">Whether extension is available</param> /// <param name="isMandatory">Whether extension is mandatory</param> /// <param name="isEnabledByDefault">Whether extension is enabled by default</param> /// <param name="providedTo">Who the extension is provided for (e.g. "entire org" or "specific users")</param> /// <param name="specificUsers">List of users extension is provided for, can be null</param> /// <param name="appStatus">App status</param> /// <param name="etoken">Etoken</param> public ClientExtension( ExtensionType type, ExtensionInstallScope scope, Stream manifestStream, string marketplaceAssetID, string marketplaceContentMarket, bool isAvailable, bool isMandatory, bool isEnabledByDefault, ClientExtensionProvidedTo providedTo, StringList specificUsers, string appStatus, string etoken) : this() { this.Type = type; this.Scope = scope; this.ManifestStream = manifestStream; this.MarketplaceAssetID = marketplaceAssetID; this.MarketplaceContentMarket = marketplaceContentMarket; this.IsAvailable = isAvailable; this.IsMandatory = isMandatory; this.IsEnabledByDefault = isEnabledByDefault; this.ProvidedTo = providedTo; this.SpecificUsers = specificUsers; this.AppStatus = appStatus; this.Etoken = etoken; } /// <summary> /// Gets or sets the extension type. /// </summary> public ExtensionType Type { get; set; } /// <summary> /// Gets or sets the extension scope. /// </summary> public ExtensionInstallScope Scope { get; set; } /// <summary> /// Gets or sets the extension manifest stream. /// </summary> public Stream ManifestStream { get; set; } /// <summary> /// Gets or sets the asset ID for Office Marketplace. /// </summary> public string MarketplaceAssetID { get; set; } /// <summary> /// Gets or sets the content market for Office Marketplace. /// </summary> public string MarketplaceContentMarket { get; set; } /// <summary> /// Gets or sets the app status /// </summary> public string AppStatus { get; set; } /// <summary> /// Gets or sets the etoken /// </summary> public string Etoken { get; set; } /// <summary> /// Gets or sets the value indicating whether extension is available. /// </summary> public bool IsAvailable { get; set; } /// <summary> /// Gets or sets the value indicating whether extension is available. /// </summary> public bool IsMandatory { get; set; } /// <summary> /// Gets or sets the value indicating whether extension is enabled by default. /// </summary> public bool IsEnabledByDefault { get; set; } /// <summary> /// Gets or sets the extension ProvidedTo value. /// </summary> public ClientExtensionProvidedTo ProvidedTo { get; set; } /// <summary> /// Gets or sets the user list this extension is provided to. /// </summary> public StringList SpecificUsers { get; set; } /// <summary> /// Reads attributes from XML. /// </summary> /// <param name="reader">The reader.</param> internal override void ReadAttributesFromXml(EwsServiceXmlReader reader) { string value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionType); if (!string.IsNullOrEmpty(value)) { this.Type = reader.ReadAttributeValue<ExtensionType>(XmlAttributeNames.ClientExtensionType); } value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionScope); if (!string.IsNullOrEmpty(value)) { this.Scope = reader.ReadAttributeValue<ExtensionInstallScope>(XmlAttributeNames.ClientExtensionScope); } value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionMarketplaceAssetID); if (!string.IsNullOrEmpty(value)) { this.MarketplaceAssetID = reader.ReadAttributeValue<string>(XmlAttributeNames.ClientExtensionMarketplaceAssetID); } value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionMarketplaceContentMarket); if (!string.IsNullOrEmpty(value)) { this.MarketplaceContentMarket = reader.ReadAttributeValue<string>(XmlAttributeNames.ClientExtensionMarketplaceContentMarket); } value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionAppStatus); if (!string.IsNullOrEmpty(value)) { this.AppStatus = reader.ReadAttributeValue<string>(XmlAttributeNames.ClientExtensionAppStatus); } value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionEtoken); if (!string.IsNullOrEmpty(value)) { this.Etoken = reader.ReadAttributeValue<string>(XmlAttributeNames.ClientExtensionEtoken); } value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionIsAvailable); if (!string.IsNullOrEmpty(value)) { this.IsAvailable = reader.ReadAttributeValue<bool>(XmlAttributeNames.ClientExtensionIsAvailable); } value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionIsMandatory); if (!string.IsNullOrEmpty(value)) { this.IsMandatory = reader.ReadAttributeValue<bool>(XmlAttributeNames.ClientExtensionIsMandatory); } value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionIsEnabledByDefault); if (!string.IsNullOrEmpty(value)) { this.IsEnabledByDefault = reader.ReadAttributeValue<bool>(XmlAttributeNames.ClientExtensionIsEnabledByDefault); } value = reader.ReadAttributeValue(XmlAttributeNames.ClientExtensionProvidedTo); if (!string.IsNullOrEmpty(value)) { this.ProvidedTo = reader.ReadAttributeValue<ClientExtensionProvidedTo>(XmlAttributeNames.ClientExtensionProvidedTo); } } /// <summary> /// Writes attributes to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteAttributesToXml(EwsServiceXmlWriter writer) { writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionType, this.Type); writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionScope, this.Scope); writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionMarketplaceAssetID, this.MarketplaceAssetID); writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionMarketplaceContentMarket, this.MarketplaceContentMarket); writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionAppStatus, this.AppStatus); writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionEtoken, this.Etoken); writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionIsAvailable, this.IsAvailable); writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionIsMandatory, this.IsMandatory); writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionIsEnabledByDefault, this.IsEnabledByDefault); writer.WriteAttributeValue(XmlAttributeNames.ClientExtensionProvidedTo, this.ProvidedTo); } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.Manifest: this.ManifestStream = new MemoryStream(); reader.ReadBase64ElementValue(this.ManifestStream); this.ManifestStream.Position = 0; return true; case XmlElementNames.ClientExtensionSpecificUsers: this.SpecificUsers = new StringList(); this.SpecificUsers.LoadFromXml(reader, XmlNamespace.Types, XmlElementNames.ClientExtensionSpecificUsers); return true; default: return base.TryReadElementFromXml(reader); } } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { if (null != this.SpecificUsers) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ClientExtensionSpecificUsers); this.SpecificUsers.WriteElementsToXml(writer); writer.WriteEndElement(); } if (null != this.ManifestStream) { if (this.ManifestStream.CanSeek) { this.ManifestStream.Position = 0; } writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Manifest); writer.WriteBase64ElementValue(this.ManifestStream); writer.WriteEndElement(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Streams; using Orleans.Runtime.Scheduler; using Orleans.Runtime.Versions; using Orleans.Versions; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; namespace Orleans.Runtime { internal class TypeManager : SystemTarget, IClusterTypeManager, ISiloTypeManager, ISiloStatusListener, IDisposable { private readonly ILogger logger; private readonly GrainTypeManager grainTypeManager; private readonly ISiloStatusOracle statusOracle; private readonly ImplicitStreamSubscriberTable implicitStreamSubscriberTable; private readonly IInternalGrainFactory grainFactory; private readonly CachedVersionSelectorManager versionSelectorManager; private readonly OrleansTaskScheduler scheduler; private readonly TimeSpan refreshClusterMapInterval; private bool hasToRefreshClusterGrainInterfaceMap; private IDisposable refreshClusterGrainInterfaceMapTimer; private IVersionStore versionStore; internal TypeManager( SiloAddress myAddr, GrainTypeManager grainTypeManager, ISiloStatusOracle oracle, OrleansTaskScheduler scheduler, TimeSpan refreshClusterMapInterval, ImplicitStreamSubscriberTable implicitStreamSubscriberTable, IInternalGrainFactory grainFactory, CachedVersionSelectorManager versionSelectorManager, ILoggerFactory loggerFactory) : base(Constants.TypeManagerId, myAddr, loggerFactory) { if (grainTypeManager == null) throw new ArgumentNullException(nameof(grainTypeManager)); if (oracle == null) throw new ArgumentNullException(nameof(oracle)); if (scheduler == null) throw new ArgumentNullException(nameof(scheduler)); if (implicitStreamSubscriberTable == null) throw new ArgumentNullException(nameof(implicitStreamSubscriberTable)); this.logger = loggerFactory.CreateLogger<TypeManager>(); this.grainTypeManager = grainTypeManager; this.statusOracle = oracle; this.implicitStreamSubscriberTable = implicitStreamSubscriberTable; this.grainFactory = grainFactory; this.versionSelectorManager = versionSelectorManager; this.scheduler = scheduler; this.refreshClusterMapInterval = refreshClusterMapInterval; // We need this so we can place needed local activations this.grainTypeManager.SetInterfaceMapsBySilo(new Dictionary<SiloAddress, GrainInterfaceMap> { {this.Silo, grainTypeManager.GetTypeCodeMap()} }); } internal async Task Initialize(IVersionStore store) { this.versionStore = store; this.hasToRefreshClusterGrainInterfaceMap = true; await this.OnRefreshClusterMapTimer(null); this.refreshClusterGrainInterfaceMapTimer = this.RegisterTimer( OnRefreshClusterMapTimer, null, this.refreshClusterMapInterval, this.refreshClusterMapInterval); } public Task<IGrainTypeResolver> GetClusterGrainTypeResolver() { return Task.FromResult<IGrainTypeResolver>(grainTypeManager.GrainTypeResolver); } public Task<GrainInterfaceMap> GetSiloTypeCodeMap() { return Task.FromResult(grainTypeManager.GetTypeCodeMap()); } public Task<ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(SiloAddress silo) { return Task.FromResult(implicitStreamSubscriberTable); } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { hasToRefreshClusterGrainInterfaceMap = true; if (status == SiloStatus.Active && !updatedSilo.Equals(this.Silo)) { if (this.logger.IsEnabled(LogLevel.Information)) { this.logger.LogInformation("Expediting cluster type map refresh due to new silo, {SiloAddress}", updatedSilo); } this.scheduler.QueueTask(() => this.OnRefreshClusterMapTimer(null), SchedulingContext); } } private async Task OnRefreshClusterMapTimer(object _) { // Check if we have to refresh if (!hasToRefreshClusterGrainInterfaceMap) { if (this.logger.IsEnabled(LogLevel.Trace)) logger.Trace("OnRefreshClusterMapTimer: no refresh required"); return; } while (hasToRefreshClusterGrainInterfaceMap) { hasToRefreshClusterGrainInterfaceMap = false; if (this.logger.IsEnabled(LogLevel.Debug)) logger.Debug("OnRefreshClusterMapTimer: refresh start"); var activeSilos = statusOracle.GetApproximateSiloStatuses(onlyActive: true); var knownSilosClusterGrainInterfaceMap = grainTypeManager.GrainInterfaceMapsBySilo; // Build the new map. Always start by himself var newSilosClusterGrainInterfaceMap = new Dictionary<SiloAddress, GrainInterfaceMap> { {this.Silo, grainTypeManager.GetTypeCodeMap()} }; var getGrainInterfaceMapTasks = new List<Task<KeyValuePair<SiloAddress, GrainInterfaceMap>>>(); foreach (var siloAddress in activeSilos.Keys) { if (siloAddress.IsSameLogicalSilo(this.Silo)) continue; GrainInterfaceMap value; if (knownSilosClusterGrainInterfaceMap.TryGetValue(siloAddress, out value)) { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace("OnRefreshClusterMapTimer: value already found locally for {SiloAddress}", siloAddress); newSilosClusterGrainInterfaceMap[siloAddress] = value; } else { // Value not found, let's get it if (this.logger.IsEnabled(LogLevel.Debug)) this.logger.Debug("OnRefreshClusterMapTimer: value not found locally for {SiloAddress}", siloAddress); getGrainInterfaceMapTasks.Add(GetTargetSiloGrainInterfaceMap(siloAddress)); } } if (getGrainInterfaceMapTasks.Any()) { foreach (var keyValuePair in await Task.WhenAll(getGrainInterfaceMapTasks)) { if (keyValuePair.Value != null) newSilosClusterGrainInterfaceMap.Add(keyValuePair.Key, keyValuePair.Value); } } grainTypeManager.SetInterfaceMapsBySilo(newSilosClusterGrainInterfaceMap); if (this.versionStore.IsEnabled) { await this.GetAndSetDefaultCompatibilityStrategy(); foreach (var kvp in await GetStoredCompatibilityStrategies()) { this.versionSelectorManager.CompatibilityDirectorManager.SetStrategy(kvp.Key, kvp.Value); } await this.GetAndSetDefaultSelectorStrategy(); foreach (var kvp in await GetSelectorStrategies()) { this.versionSelectorManager.VersionSelectorManager.SetSelector(kvp.Key, kvp.Value); } } versionSelectorManager.ResetCache(); // Either a new silo joined or a refresh failed, so continue until no refresh is required. if (hasToRefreshClusterGrainInterfaceMap) { if (this.logger.IsEnabled(LogLevel.Debug)) { this.logger.LogDebug("OnRefreshClusterMapTimer: cluster type map still requires a refresh and will be refreshed again after a short delay"); } await Task.Delay(TimeSpan.FromSeconds(1)); } } } private async Task GetAndSetDefaultSelectorStrategy() { try { var strategy = await this.versionStore.GetSelectorStrategy(); this.versionSelectorManager.VersionSelectorManager.SetSelector(strategy); } catch (Exception) { hasToRefreshClusterGrainInterfaceMap = true; } } private async Task GetAndSetDefaultCompatibilityStrategy() { try { var strategy = await this.versionStore.GetCompatibilityStrategy(); this.versionSelectorManager.CompatibilityDirectorManager.SetStrategy(strategy); } catch (Exception) { hasToRefreshClusterGrainInterfaceMap = true; } } private async Task<Dictionary<int, CompatibilityStrategy>> GetStoredCompatibilityStrategies() { try { return await this.versionStore.GetCompatibilityStrategies(); } catch (Exception) { hasToRefreshClusterGrainInterfaceMap = true; return new Dictionary<int, CompatibilityStrategy>(); } } private async Task<Dictionary<int, VersionSelectorStrategy>> GetSelectorStrategies() { try { return await this.versionStore.GetSelectorStrategies(); } catch (Exception) { hasToRefreshClusterGrainInterfaceMap = true; return new Dictionary<int, VersionSelectorStrategy>(); } } private async Task<KeyValuePair<SiloAddress, GrainInterfaceMap>> GetTargetSiloGrainInterfaceMap(SiloAddress siloAddress) { try { var remoteTypeManager = this.grainFactory.GetSystemTarget<ISiloTypeManager>(Constants.TypeManagerId, siloAddress); var siloTypeCodeMap = await scheduler.QueueTask(() => remoteTypeManager.GetSiloTypeCodeMap(), SchedulingContext); return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, siloTypeCodeMap); } catch (Exception ex) { // Will be retried on the next timer hit logger.Error(ErrorCode.TypeManager_GetSiloGrainInterfaceMapError, $"Exception when trying to get GrainInterfaceMap for silos {siloAddress}", ex); hasToRefreshClusterGrainInterfaceMap = true; return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, null); } } public void Dispose() { if (this.refreshClusterGrainInterfaceMapTimer != null) { this.refreshClusterGrainInterfaceMapTimer.Dispose(); } } } }
//----------------------------------------------------------------------- // <copyright file="DateAndTime.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright> //----------------------------------------------------------------------- namespace MSBuild.ExtensionPack.Framework { using System; using System.Globalization; using Microsoft.Build.Framework; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>AddDays</i> (<b>Required: </b>Format, Value <b>Optional: </b>Start <b>Output: </b> Result)</para> /// <para><i>AddHours</i> (<b>Required: </b>Format, Value <b>Optional: </b>Start <b>Output: </b> Result)</para> /// <para><i>AddMilliseconds</i> (<b>Required: </b>Format, Value <b>Optional: </b>Start <b>Output: </b> Result)</para> /// <para><i>AddMinutes</i> (<b>Required: </b>Format, Value <b>Optional: </b>Start <b>Output: </b> Result)</para> /// <para><i>AddMonths</i> (<b>Required: </b>Format, Value <b>Optional: </b>Start <b>Output: </b> Result)</para> /// <para><i>AddSeconds</i> (<b>Required: </b>Format, Value <b>Optional: </b>Start <b>Output: </b> Result)</para> /// <para><i>AddTicks</i> (<b>Required: </b>Format, Value <b>Optional: </b>Start <b>Output: </b> Result)</para> /// <para><i>AddYears</i> (<b>Required: </b>Format, Value <b>Optional: </b>Start <b>Output: </b> Result)</para> /// <para><i>CheckBetween</i> (<b>Required: </b>Start, End <b>Optional:</b> UseUtc <b>Output: </b> BoolResult)</para> /// <para><i>CheckLater</i> (<b>Required: </b>Start <b>Optional:</b> UseUtc <b>Output: </b> BoolResult)</para> /// <para><i>Get</i> (<b>Required: </b>Format <b>Optional:</b> UseUtc <b>Output: </b> Result)</para> /// <para><i>GetElapsed</i> (<b>Required: </b>Format, Start <b>Optional: </b>End, UseUtc <b>Output: </b> Result)</para> /// <para><b>Remote Execution Support:</b> NA</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="3.5" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <PropertyGroup> /// <Start>1 Jan 2009</Start> /// </PropertyGroup> /// <Target Name="Default"> /// <!-- Let's Time how long it takes to perform a certain group of tasks --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="Get" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="MyStartTime"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="I'm sleeping..."/> /// <MSBuild.ExtensionPack.Framework.Thread TaskAction="Sleep" Timeout="2000"/> /// <Message Text="Sleep Over!"/> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(MyStartTime)" Format="Seconds"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Slept For: $(DTResult)"/> /// <!-- Get the elapsed days since the start date --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(Start)" Format="Days"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Days Since $(Start): $(DTResult)"/> /// <!-- Get the elapsed minutes since the start date --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(Start)" Format="Minutes"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Minutes Since $(Start): $(DTResult)"/> /// <!-- Get the elapsed hours since the start date --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(Start)" Format="Hours"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Hours Since $(Start): $(DTResult)"/> /// <!-- Get the total elapsed time since the start date --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(Start)" Format="Total"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Total Elapsed Time Since $(Start): $(DTResult)"/> /// <!-- Get the time in the specified format --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="Get" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Date / Time: $(DTResult)"/> /// <!-- Get the UTC time in the specified format --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="Get" Format="dd MMM yy HH:mm:ss" UseUtc="true"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="UTC Date / Time: $(DTResult)"/> /// <!-- Check if its later than a given time --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="CheckLater" Start="14:10"> /// <Output TaskParameter="BoolResult" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Later: $(DTResult)"/> /// <!-- Check if the current time is between two times --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="CheckBetween" Start="14:10" End="14:25"> /// <Output TaskParameter="BoolResult" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Between: $(DTResult)"/> /// <!-- Test Add time targets based on start time provided in AddTimeStart. --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="Get" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="AddTimeStart"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Add Time To: $(AddTimeStart)"/> /// <!-- Add days --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddDays" Start="$(Start)" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Add 30 days: $(DTResult)"/> /// <!-- Verify add days --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(Start)" End="$(DTResult)" Format="Days"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Days Since $(Start): $(DTResult)"/> /// <!-- Add hours --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddHours" Start="$(Start)" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 hours from time: $(DTResult)"/> /// <!-- Verify add hours --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(Start)" End="$(DTResult)" Format="Hours"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Hours Since $(Start): $(DTResult)"/> /// <!-- Add milliseconds --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddMilliseconds" Start="$(Start)" Value="3000" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="3000 Millisecond from time: $(DTResult)"/> /// <!-- Verify add milliseconds --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(Start)" End="$(DTResult)" Format="MilliSeconds"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Milliseconds Since $(Start): $(DTResult)"/> /// <!-- Add minutes --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddMinutes" Start="$(Start)" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 minutes from time: $(DTResult)"/> /// <!-- Verify add minutes --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(Start)" End="$(DTResult)" Format="Minutes"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Minutes Since $(Start): $(DTResult)"/> /// <!-- Add months --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddMonths" Start="$(Start)" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 months from time: $(DTResult)"/> /// <!-- Add seconds --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddSeconds" Start="$(Start)" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 Seconds from time: $(DTResult)"/> /// <!-- Verify add seconds --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="GetElapsed" Start="$(Start)" End="$(DTResult)" Format="Seconds"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="Seconds Since $(Start): $(DTResult)"/> /// <!-- Add ticks --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddTicks" Start="$(Start)" Value="3000" Format="dd MMM yy HH:mm:ss:fff"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="3000 ticks from time: $(DTResult)"/> /// <!-- Add years --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddYears" Start="$(Start)" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 Years from time: $(DTResult)"/> /// <!-- Test Add time targets based current time. --> /// <!-- Add days --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddDays" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 days from time: $(DTResult)"/> /// <!-- Add hours --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddHours" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 hours from time: $(DTResult)"/> /// <!-- Add milliseconds --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddMilliseconds" Value="3000" Format="dd MMM yy HH:mm:ss:fff"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="3000 Millisecond from time: $(DTResult)"/> /// <!-- Add minutes --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddMinutes" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 minutes from time: $(DTResult)"/> /// <!-- Add months --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddMonths" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 months from time: $(DTResult)"/> /// <!-- Add seconds --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddSeconds" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 Seconds from time: $(DTResult)"/> /// <!-- Add ticks --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddTicks" Value="3000" Format="dd MMM yy HH:mm:ss:fff"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="3000 ticks from time: $(DTResult)"/> /// <!-- Add years --> /// <MSBuild.ExtensionPack.Framework.DateAndTime TaskAction="AddYears" Value="30" Format="dd MMM yy HH:mm:ss"> /// <Output TaskParameter="Result" PropertyName="DTResult"/> /// </MSBuild.ExtensionPack.Framework.DateAndTime> /// <Message Text="30 Years from time: $(DTResult)"/> /// </Target> /// </Project> /// ]]></code> /// </example> [HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/1c668832-24f2-d646-1f66-7ea1f3e76415.htm")] public class DateAndTime : BaseTask { private const string GetTaskAction = "Get"; private const string GetElapsedTaskAction = "GetElapsed"; private const string CheckLaterTaskAction = "CheckLater"; private const string CheckBetweenTaskAction = "CheckBetween"; private const string AddDaysTaskAction = "AddDays"; private const string AddHoursTaskAction = "AddHours"; private const string AddMillisecondsTaskAction = "AddMilliseconds"; private const string AddMinutesTaskAction = "AddMinutes"; private const string AddMonthsTaskAction = "AddMonths"; private const string AddSecondsTaskAction = "AddSeconds"; private const string AddTicksTaskAction = "AddTicks"; private const string AddYearsTaskAction = "AddYears"; [DropdownValue(CheckBetweenTaskAction)] [DropdownValue(CheckLaterTaskAction)] [DropdownValue(GetTaskAction)] [DropdownValue(GetElapsedTaskAction)] [DropdownValue(AddDaysTaskAction)] [DropdownValue(AddHoursTaskAction)] [DropdownValue(AddMillisecondsTaskAction)] [DropdownValue(AddMinutesTaskAction)] [DropdownValue(AddMonthsTaskAction)] [DropdownValue(AddSecondsTaskAction)] [DropdownValue(AddTicksTaskAction)] [DropdownValue(AddYearsTaskAction)] public override string TaskAction { get { return base.TaskAction; } set { base.TaskAction = value; } } /// <summary> /// The start time to use /// </summary> [TaskAction(CheckBetweenTaskAction, true)] [TaskAction(CheckLaterTaskAction, true)] [TaskAction(GetElapsedTaskAction, true)] [TaskAction(AddDaysTaskAction, false)] [TaskAction(AddHoursTaskAction, false)] [TaskAction(AddMillisecondsTaskAction, false)] [TaskAction(AddMinutesTaskAction, false)] [TaskAction(AddMonthsTaskAction, false)] [TaskAction(AddSecondsTaskAction, false)] [TaskAction(AddTicksTaskAction, false)] [TaskAction(AddYearsTaskAction, false)] public DateTime Start { get; set; } /// <summary> /// The end time to use for GetElapsed. Default is DateTime.Now /// </summary> [TaskAction(GetElapsedTaskAction, false)] [TaskAction(CheckBetweenTaskAction, true)] public DateTime End { get; set; } /// <summary> /// Format to apply to the Result. For GetTime, Format can be any valid DateTime format. For GetElapsed, Format can be Milliseconds, Seconds, Minutes, Hours, Days or Total. Total returns dd:hh:mm:ss /// </summary> [TaskAction(GetTaskAction, true)] [TaskAction(GetElapsedTaskAction, true)] public string Format { get; set; } [TaskAction(AddDaysTaskAction, true)] [TaskAction(AddHoursTaskAction, true)] [TaskAction(AddMillisecondsTaskAction, true)] [TaskAction(AddMinutesTaskAction, true)] [TaskAction(AddMonthsTaskAction, true)] [TaskAction(AddSecondsTaskAction, true)] [TaskAction(AddTicksTaskAction, true)] [TaskAction(AddYearsTaskAction, true)] public double Value { get; set; } /// <summary> /// The output Result /// </summary> [Output] [TaskAction(GetTaskAction, false)] [TaskAction(GetElapsedTaskAction, false)] [TaskAction(AddDaysTaskAction, false)] [TaskAction(AddHoursTaskAction, false)] [TaskAction(AddMillisecondsTaskAction, false)] [TaskAction(AddMinutesTaskAction, false)] [TaskAction(AddMonthsTaskAction, false)] [TaskAction(AddSecondsTaskAction, false)] [TaskAction(AddTicksTaskAction, false)] [TaskAction(AddYearsTaskAction, false)] public string Result { get; set; } /// <summary> /// The output boolean result. /// </summary> [Output] [TaskAction(CheckBetweenTaskAction, false)] [TaskAction(CheckLaterTaskAction, false)] public bool BoolResult { get; set; } /// <summary> /// Set to true to use UTC Date / Time for the TaskAction. Default is false. /// </summary> [TaskAction(GetTaskAction, false)] [TaskAction(CheckBetweenTaskAction, false)] [TaskAction(CheckLaterTaskAction, false)] [TaskAction(GetElapsedTaskAction, false)] public bool UseUtc { get; set; } protected override void InternalExecute() { if (!this.TargetingLocalMachine()) { return; } switch (this.TaskAction) { case GetTaskAction: this.GetDate(); break; case GetElapsedTaskAction: this.GetElapsed(); break; case CheckLaterTaskAction: this.CheckLater(); break; case CheckBetweenTaskAction: this.CheckBetween(); break; case AddDaysTaskAction: this.AddDays(); break; case AddHoursTaskAction: this.AddHours(); break; case AddMillisecondsTaskAction: this.AddMilliseconds(); break; case AddMinutesTaskAction: this.AddMinutes(); break; case AddMonthsTaskAction: this.AddMonths(); break; case AddSecondsTaskAction: this.AddSeconds(); break; case AddTicksTaskAction: this.AddTicks(); break; case AddYearsTaskAction: this.AddYears(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } private static DateTime GetDefaultOrUserStartTime(DateTime startTime) { // Default to current time if caller did not specify a time. if (startTime == Convert.ToDateTime("01/01/0001 00:00:00", CultureInfo.CurrentCulture)) { return DateTime.Now; } return startTime; } private void CheckLater() { if (this.Start == Convert.ToDateTime("01/01/0001 00:00:00", CultureInfo.CurrentCulture)) { Log.LogError("Start must be specified"); return; } if (this.UseUtc) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking if: {0} is later than: {1}", DateTime.UtcNow.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture), this.Start.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture))); this.BoolResult = DateTime.UtcNow > this.Start; } else { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking if: {0} is later than: {1}", DateTime.Now.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture), this.Start.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture))); this.BoolResult = DateTime.Now > this.Start; } } private void CheckBetween() { if (this.Start == Convert.ToDateTime("01/01/0001 00:00:00", CultureInfo.CurrentCulture)) { Log.LogError("Start must be specified"); return; } if (this.End == Convert.ToDateTime("01/01/0001 00:00:00", CultureInfo.CurrentCulture)) { Log.LogError("End must be specified"); return; } if (this.UseUtc) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking if: {0} is between: {1} and: {2}", DateTime.UtcNow.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture), this.Start.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture), this.End.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture))); this.BoolResult = DateTime.UtcNow > this.Start && DateTime.UtcNow < this.End; } else { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking if: {0} is between: {1} and: {2}", DateTime.Now.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture), this.Start.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture), this.End.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.CurrentCulture))); this.BoolResult = DateTime.Now > this.Start && DateTime.Now < this.End; } } private void GetElapsed() { if (this.Start == Convert.ToDateTime("01/01/0001 00:00:00", CultureInfo.CurrentCulture)) { Log.LogError("Start must be specified"); return; } if (this.End == Convert.ToDateTime("01/01/0001 00:00:00", CultureInfo.CurrentCulture)) { this.End = this.UseUtc ? DateTime.UtcNow : DateTime.Now; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Getting Elapsed: {0}", this.Format)); TimeSpan t = this.End - this.Start; switch (this.Format) { case "MilliSeconds": this.Result = t.TotalMilliseconds.ToString(CultureInfo.CurrentCulture); break; case "Seconds": this.Result = t.TotalSeconds.ToString(CultureInfo.CurrentCulture); break; case "Minutes": this.Result = t.TotalMinutes.ToString(CultureInfo.CurrentCulture); break; case "Hours": this.Result = t.TotalHours.ToString(CultureInfo.CurrentCulture); break; case "Days": this.Result = t.TotalDays.ToString(CultureInfo.CurrentCulture); break; case "Total": this.Result = string.Format(CultureInfo.CurrentCulture, "{0}:{1}:{2}:{3}", t.Days.ToString("00", CultureInfo.CurrentCulture), t.Hours.ToString("00", CultureInfo.CurrentCulture), t.Minutes.ToString("00", CultureInfo.CurrentCulture), t.Seconds.ToString("00", CultureInfo.CurrentCulture)); break; default: Log.LogError("Format must be specified"); return; } } private void GetDate() { this.LogTaskMessage("Getting Date / Time"); this.Result = this.UseUtc ? DateTime.UtcNow.ToString(this.Format, CultureInfo.CurrentCulture) : DateTime.Now.ToString(this.Format, CultureInfo.CurrentCulture); } private void AddDays() { this.LogTaskMessage("Add Days"); this.Result = GetDefaultOrUserStartTime(this.Start).AddDays(this.Value).ToString(this.Format, CultureInfo.CurrentCulture); } private void AddHours() { this.LogTaskMessage("Add Hours"); this.Result = GetDefaultOrUserStartTime(this.Start).AddHours(this.Value).ToString(this.Format, CultureInfo.CurrentCulture); } private void AddMilliseconds() { this.LogTaskMessage("Add Milliseconds"); this.Result = GetDefaultOrUserStartTime(this.Start).AddMilliseconds(this.Value).ToString(this.Format, CultureInfo.CurrentCulture); } private void AddMinutes() { this.LogTaskMessage("Add Minutes"); this.Result = GetDefaultOrUserStartTime(this.Start).AddMinutes(this.Value).ToString(this.Format, CultureInfo.CurrentCulture); } private void AddMonths() { this.LogTaskMessage("Add Months"); this.Result = GetDefaultOrUserStartTime(this.Start).AddMonths((int)this.Value).ToString(this.Format, CultureInfo.CurrentCulture); } private void AddSeconds() { this.LogTaskMessage("Add Seconds"); this.Result = GetDefaultOrUserStartTime(this.Start).AddSeconds(this.Value).ToString(this.Format, CultureInfo.CurrentCulture); } private void AddTicks() { this.LogTaskMessage("Add Ticks"); this.Result = GetDefaultOrUserStartTime(this.Start).AddTicks((long)this.Value).ToString(this.Format, CultureInfo.CurrentCulture); } private void AddYears() { this.LogTaskMessage("Add Years"); this.Result = GetDefaultOrUserStartTime(this.Start).AddYears((int)this.Value).ToString(this.Format, CultureInfo.CurrentCulture); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace EncompassRest.Loans { /// <summary> /// DocumentLog /// </summary> public sealed partial class DocumentLog : DirtyExtensibleObject, IIdentifiable { private DirtyValue<string?>? _accessedBy; private DirtyValue<DateTime?>? _accessedDateUtc; private DirtyValue<string?>? _addedBy; private DirtyList<LogAlert>? _alerts; private DirtyValue<string?>? _alertsXml; private DirtyValue<string?>? _allowedRoleDelimitedList; private DirtyList<EntityReference>? _allowedRoles; private DirtyValue<string?>? _allowedRolesXml; private DirtyValue<DateTime?>? _archiveDateUtc; private DirtyValue<string?>? _archivedBy; private DirtyValue<bool?>? _closingDocumentIndicator; private DirtyList<LogComment>? _commentList; private DirtyValue<string?>? _commentListXml; private DirtyValue<string?>? _comments; private DirtyValue<string?>? _company; private DirtyList<EntityReference>? _conditions; private DirtyValue<string?>? _conditionsXml; private DirtyValue<DateTime?>? _dateAddedUtc; private DirtyValue<DateTime?>? _dateExpected; private DirtyValue<DateTime?>? _dateExpires; private DirtyValue<DateTime?>? _dateReceived; private DirtyValue<DateTime?>? _dateRequested; private DirtyValue<DateTime?>? _dateRerequested; private DirtyValue<DateTime?>? _dateUtc; private DirtyValue<int?>? _daysDue; private DirtyValue<int?>? _daysTillExpire; private DirtyValue<string?>? _description; private DirtyValue<string?>? _documentDateTimeType; private DirtyValue<string?>? _docVerificationsXml; private DirtyValue<bool?>? _eDisclosureIndicator; private DirtyValue<string?>? _ePassSignature; private DirtyValue<bool?>? _expected; private DirtyValue<bool?>? _expires; private DirtyList<FileAttachmentReference>? _fileAttachmentReferences; private DirtyValue<bool?>? _fileAttachmentsMigrated; private DirtyValue<string?>? _fileAttachmentsXml; private DirtyValue<string?>? _groupName; private DirtyValue<string?>? _guid; private DirtyValue<string?>? _id; private DirtyValue<bool?>? _isAssetVerification; private DirtyValue<bool?>? _isEmploymentVerification; private DirtyValue<bool?>? _isEPassIndicator; private DirtyValue<bool?>? _isExpired; private DirtyValue<bool?>? _isExternalIndicator; private DirtyValue<bool?>? _isIncomeVerification; private DirtyValue<bool?>? _isObligationVerification; private DirtyValue<bool?>? _isPastDue; private DirtyValue<bool?>? _isSystemSpecificIndicator; private DirtyValue<bool?>? _isThirdPartyDocIndicator; private DirtyValue<bool?>? _isTPOWebcenterPortalIndicator; private DirtyValue<bool?>? _isWebCenterIndicator; private DirtyValue<DateTime?>? _lastAttachmentDateUtc; private DirtyValue<int?>? _logRecordIndex; private DirtyValue<DateTime?>? _orderDateUtc; private DirtyValue<string?>? _pairId; private DirtyValue<bool?>? _preClosingDocumentIndicator; private DirtyValue<bool?>? _received; private DirtyValue<DateTime?>? _receiveDateUtc; private DirtyValue<string?>? _receivedBy; private DirtyValue<DateTime?>? _reorderDateUtc; private DirtyValue<bool?>? _requested; private DirtyValue<string?>? _requestedBy; private DirtyValue<string?>? _requestedFrom; private DirtyValue<bool?>? _rerequested; private DirtyValue<string?>? _rerequestedBy; private DirtyValue<bool?>? _reviewed; private DirtyValue<string?>? _reviewedBy; private DirtyValue<DateTime?>? _reviewedDateUtc; private DirtyValue<bool?>? _shippingReady; private DirtyValue<string?>? _shippingReadyBy; private DirtyValue<DateTime?>? _shippingReadyDateUtc; private DirtyValue<string?>? _stage; private DirtyValue<string?>? _status; private DirtyValue<string?>? _systemId; private DirtyValue<string?>? _title; private DirtyValue<bool?>? _underwritingReady; private DirtyValue<string?>? _underwritingReadyBy; private DirtyValue<DateTime?>? _underwritingReadyDateUtc; private DirtyValue<DateTime?>? _updatedDateUtc; /// <summary> /// DocumentLog AccessedBy /// </summary> public string? AccessedBy { get => _accessedBy; set => SetField(ref _accessedBy, value); } /// <summary> /// DocumentLog AccessedDateUtc /// </summary> public DateTime? AccessedDateUtc { get => _accessedDateUtc; set => SetField(ref _accessedDateUtc, value); } /// <summary> /// DocumentLog AddedBy /// </summary> public string? AddedBy { get => _addedBy; set => SetField(ref _addedBy, value); } /// <summary> /// DocumentLog Alerts /// </summary> [AllowNull] public IList<LogAlert> Alerts { get => GetField(ref _alerts); set => SetField(ref _alerts, value); } /// <summary> /// DocumentLog AlertsXml /// </summary> public string? AlertsXml { get => _alertsXml; set => SetField(ref _alertsXml, value); } /// <summary> /// DocumentLog AllowedRoleDelimitedList /// </summary> public string? AllowedRoleDelimitedList { get => _allowedRoleDelimitedList; set => SetField(ref _allowedRoleDelimitedList, value); } /// <summary> /// DocumentLog AllowedRoles /// </summary> [AllowNull] public IList<EntityReference> AllowedRoles { get => GetField(ref _allowedRoles); set => SetField(ref _allowedRoles, value); } /// <summary> /// DocumentLog AllowedRolesXml /// </summary> public string? AllowedRolesXml { get => _allowedRolesXml; set => SetField(ref _allowedRolesXml, value); } /// <summary> /// DocumentLog ArchiveDateUtc /// </summary> public DateTime? ArchiveDateUtc { get => _archiveDateUtc; set => SetField(ref _archiveDateUtc, value); } /// <summary> /// DocumentLog ArchivedBy /// </summary> public string? ArchivedBy { get => _archivedBy; set => SetField(ref _archivedBy, value); } /// <summary> /// DocumentLog ClosingDocumentIndicator /// </summary> public bool? ClosingDocumentIndicator { get => _closingDocumentIndicator; set => SetField(ref _closingDocumentIndicator, value); } /// <summary> /// DocumentLog CommentList /// </summary> [AllowNull] public IList<LogComment> CommentList { get => GetField(ref _commentList); set => SetField(ref _commentList, value); } /// <summary> /// DocumentLog CommentListXml /// </summary> public string? CommentListXml { get => _commentListXml; set => SetField(ref _commentListXml, value); } /// <summary> /// DocumentLog Comments /// </summary> public string? Comments { get => _comments; set => SetField(ref _comments, value); } /// <summary> /// DocumentLog Company /// </summary> public string? Company { get => _company; set => SetField(ref _company, value); } /// <summary> /// DocumentLog Conditions /// </summary> [AllowNull] public IList<EntityReference> Conditions { get => GetField(ref _conditions); set => SetField(ref _conditions, value); } /// <summary> /// DocumentLog ConditionsXml /// </summary> public string? ConditionsXml { get => _conditionsXml; set => SetField(ref _conditionsXml, value); } /// <summary> /// DocumentLog DateAddedUtc /// </summary> public DateTime? DateAddedUtc { get => _dateAddedUtc; set => SetField(ref _dateAddedUtc, value); } /// <summary> /// DocumentLog DateExpected /// </summary> public DateTime? DateExpected { get => _dateExpected; set => SetField(ref _dateExpected, value); } /// <summary> /// DocumentLog DateExpires /// </summary> public DateTime? DateExpires { get => _dateExpires; set => SetField(ref _dateExpires, value); } /// <summary> /// DocumentLog DateReceived /// </summary> public DateTime? DateReceived { get => _dateReceived; set => SetField(ref _dateReceived, value); } /// <summary> /// DocumentLog DateRequested /// </summary> public DateTime? DateRequested { get => _dateRequested; set => SetField(ref _dateRequested, value); } /// <summary> /// DocumentLog DateRerequested /// </summary> public DateTime? DateRerequested { get => _dateRerequested; set => SetField(ref _dateRerequested, value); } /// <summary> /// DocumentLog DateUtc /// </summary> public DateTime? DateUtc { get => _dateUtc; set => SetField(ref _dateUtc, value); } /// <summary> /// DocumentLog DaysDue /// </summary> public int? DaysDue { get => _daysDue; set => SetField(ref _daysDue, value); } /// <summary> /// DocumentLog DaysTillExpire /// </summary> public int? DaysTillExpire { get => _daysTillExpire; set => SetField(ref _daysTillExpire, value); } /// <summary> /// DocumentLog Description /// </summary> public string? Description { get => _description; set => SetField(ref _description, value); } /// <summary> /// DocumentLog DocumentDateTimeType /// </summary> public string? DocumentDateTimeType { get => _documentDateTimeType; set => SetField(ref _documentDateTimeType, value); } /// <summary> /// DocumentLog DocVerificationsXml /// </summary> public string? DocVerificationsXml { get => _docVerificationsXml; set => SetField(ref _docVerificationsXml, value); } /// <summary> /// DocumentLog EDisclosureIndicator /// </summary> public bool? EDisclosureIndicator { get => _eDisclosureIndicator; set => SetField(ref _eDisclosureIndicator, value); } /// <summary> /// DocumentLog EPassSignature /// </summary> public string? EPassSignature { get => _ePassSignature; set => SetField(ref _ePassSignature, value); } /// <summary> /// DocumentLog Expected /// </summary> public bool? Expected { get => _expected; set => SetField(ref _expected, value); } /// <summary> /// DocumentLog Expires /// </summary> public bool? Expires { get => _expires; set => SetField(ref _expires, value); } /// <summary> /// DocumentLog FileAttachmentReferences /// </summary> [AllowNull] public IList<FileAttachmentReference> FileAttachmentReferences { get => GetField(ref _fileAttachmentReferences); set => SetField(ref _fileAttachmentReferences, value); } /// <summary> /// DocumentLog FileAttachmentsMigrated /// </summary> public bool? FileAttachmentsMigrated { get => _fileAttachmentsMigrated; set => SetField(ref _fileAttachmentsMigrated, value); } /// <summary> /// DocumentLog FileAttachmentsXml /// </summary> public string? FileAttachmentsXml { get => _fileAttachmentsXml; set => SetField(ref _fileAttachmentsXml, value); } /// <summary> /// DocumentLog GroupName /// </summary> public string? GroupName { get => _groupName; set => SetField(ref _groupName, value); } /// <summary> /// DocumentLog Guid /// </summary> public string? Guid { get => _guid; set => SetField(ref _guid, value); } /// <summary> /// DocumentLog Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// DocumentLog IsAssetVerification /// </summary> public bool? IsAssetVerification { get => _isAssetVerification; set => SetField(ref _isAssetVerification, value); } /// <summary> /// DocumentLog IsEmploymentVerification /// </summary> public bool? IsEmploymentVerification { get => _isEmploymentVerification; set => SetField(ref _isEmploymentVerification, value); } /// <summary> /// DocumentLog IsEPassIndicator /// </summary> public bool? IsEPassIndicator { get => _isEPassIndicator; set => SetField(ref _isEPassIndicator, value); } /// <summary> /// DocumentLog IsExpired /// </summary> public bool? IsExpired { get => _isExpired; set => SetField(ref _isExpired, value); } /// <summary> /// DocumentLog IsExternalIndicator /// </summary> public bool? IsExternalIndicator { get => _isExternalIndicator; set => SetField(ref _isExternalIndicator, value); } /// <summary> /// DocumentLog IsIncomeVerification /// </summary> public bool? IsIncomeVerification { get => _isIncomeVerification; set => SetField(ref _isIncomeVerification, value); } /// <summary> /// DocumentLog IsObligationVerification /// </summary> public bool? IsObligationVerification { get => _isObligationVerification; set => SetField(ref _isObligationVerification, value); } /// <summary> /// DocumentLog IsPastDue /// </summary> public bool? IsPastDue { get => _isPastDue; set => SetField(ref _isPastDue, value); } /// <summary> /// DocumentLog IsSystemSpecificIndicator /// </summary> public bool? IsSystemSpecificIndicator { get => _isSystemSpecificIndicator; set => SetField(ref _isSystemSpecificIndicator, value); } /// <summary> /// DocumentLog IsThirdPartyDocIndicator /// </summary> public bool? IsThirdPartyDocIndicator { get => _isThirdPartyDocIndicator; set => SetField(ref _isThirdPartyDocIndicator, value); } /// <summary> /// DocumentLog IsTPOWebcenterPortalIndicator /// </summary> public bool? IsTPOWebcenterPortalIndicator { get => _isTPOWebcenterPortalIndicator; set => SetField(ref _isTPOWebcenterPortalIndicator, value); } /// <summary> /// DocumentLog IsWebCenterIndicator /// </summary> public bool? IsWebCenterIndicator { get => _isWebCenterIndicator; set => SetField(ref _isWebCenterIndicator, value); } /// <summary> /// DocumentLog LastAttachmentDateUtc /// </summary> public DateTime? LastAttachmentDateUtc { get => _lastAttachmentDateUtc; set => SetField(ref _lastAttachmentDateUtc, value); } /// <summary> /// DocumentLog LogRecordIndex /// </summary> public int? LogRecordIndex { get => _logRecordIndex; set => SetField(ref _logRecordIndex, value); } /// <summary> /// DocumentLog OrderDateUtc /// </summary> public DateTime? OrderDateUtc { get => _orderDateUtc; set => SetField(ref _orderDateUtc, value); } /// <summary> /// DocumentLog PairId /// </summary> public string? PairId { get => _pairId; set => SetField(ref _pairId, value); } /// <summary> /// DocumentLog PreClosingDocumentIndicator /// </summary> public bool? PreClosingDocumentIndicator { get => _preClosingDocumentIndicator; set => SetField(ref _preClosingDocumentIndicator, value); } /// <summary> /// DocumentLog Received /// </summary> public bool? Received { get => _received; set => SetField(ref _received, value); } /// <summary> /// DocumentLog ReceiveDateUtc /// </summary> public DateTime? ReceiveDateUtc { get => _receiveDateUtc; set => SetField(ref _receiveDateUtc, value); } /// <summary> /// DocumentLog ReceivedBy /// </summary> public string? ReceivedBy { get => _receivedBy; set => SetField(ref _receivedBy, value); } /// <summary> /// DocumentLog ReorderDateUtc /// </summary> public DateTime? ReorderDateUtc { get => _reorderDateUtc; set => SetField(ref _reorderDateUtc, value); } /// <summary> /// DocumentLog Requested /// </summary> public bool? Requested { get => _requested; set => SetField(ref _requested, value); } /// <summary> /// DocumentLog RequestedBy /// </summary> public string? RequestedBy { get => _requestedBy; set => SetField(ref _requestedBy, value); } /// <summary> /// DocumentLog RequestedFrom /// </summary> public string? RequestedFrom { get => _requestedFrom; set => SetField(ref _requestedFrom, value); } /// <summary> /// DocumentLog Rerequested /// </summary> public bool? Rerequested { get => _rerequested; set => SetField(ref _rerequested, value); } /// <summary> /// DocumentLog RerequestedBy /// </summary> public string? RerequestedBy { get => _rerequestedBy; set => SetField(ref _rerequestedBy, value); } /// <summary> /// DocumentLog Reviewed /// </summary> public bool? Reviewed { get => _reviewed; set => SetField(ref _reviewed, value); } /// <summary> /// DocumentLog ReviewedBy /// </summary> public string? ReviewedBy { get => _reviewedBy; set => SetField(ref _reviewedBy, value); } /// <summary> /// DocumentLog ReviewedDateUtc /// </summary> public DateTime? ReviewedDateUtc { get => _reviewedDateUtc; set => SetField(ref _reviewedDateUtc, value); } /// <summary> /// DocumentLog ShippingReady /// </summary> public bool? ShippingReady { get => _shippingReady; set => SetField(ref _shippingReady, value); } /// <summary> /// DocumentLog ShippingReadyBy /// </summary> public string? ShippingReadyBy { get => _shippingReadyBy; set => SetField(ref _shippingReadyBy, value); } /// <summary> /// DocumentLog ShippingReadyDateUtc /// </summary> public DateTime? ShippingReadyDateUtc { get => _shippingReadyDateUtc; set => SetField(ref _shippingReadyDateUtc, value); } /// <summary> /// DocumentLog Stage /// </summary> public string? Stage { get => _stage; set => SetField(ref _stage, value); } /// <summary> /// DocumentLog Status /// </summary> public string? Status { get => _status; set => SetField(ref _status, value); } /// <summary> /// DocumentLog SystemId /// </summary> public string? SystemId { get => _systemId; set => SetField(ref _systemId, value); } /// <summary> /// DocumentLog Title /// </summary> public string? Title { get => _title; set => SetField(ref _title, value); } /// <summary> /// DocumentLog UnderwritingReady /// </summary> public bool? UnderwritingReady { get => _underwritingReady; set => SetField(ref _underwritingReady, value); } /// <summary> /// DocumentLog UnderwritingReadyBy /// </summary> public string? UnderwritingReadyBy { get => _underwritingReadyBy; set => SetField(ref _underwritingReadyBy, value); } /// <summary> /// DocumentLog UnderwritingReadyDateUtc /// </summary> public DateTime? UnderwritingReadyDateUtc { get => _underwritingReadyDateUtc; set => SetField(ref _underwritingReadyDateUtc, value); } /// <summary> /// DocumentLog UpdatedDateUtc /// </summary> public DateTime? UpdatedDateUtc { get => _updatedDateUtc; set => SetField(ref _updatedDateUtc, value); } } }
using System; using System.IO; using System.Collections; using System.Collections.Generic; namespace ClickHouse.Ado.Impl.ATG.Insert { internal class Token { public int kind; // token kind public int pos; // token position in bytes in the source text (starting at 0) public int charPos; // token position in characters in the source text (starting at 0) public int col; // token column (starting at 1) public int line; // token line (starting at 1) public string val; // token value public Token next; // ML 2005-03-11 Tokens are kept in linked list } //----------------------------------------------------------------------------------- // Buffer //----------------------------------------------------------------------------------- internal class Buffer { // This Buffer supports the following cases: // 1) seekable stream (file) // a) whole stream in buffer // b) part of stream in buffer // 2) non seekable stream (network, console) public const int EOF = char.MaxValue + 1; const int MIN_BUFFER_LENGTH = 1024; // 1KB const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB byte[] buf; // input buffer int bufStart; // position of first byte in buffer relative to input stream int bufLen; // length of buffer int fileLen; // length of input stream (may change if the stream is no file) int bufPos; // current position in buffer Stream stream; // input stream (seekable) bool isUserStream; // was the stream opened by the user? public Buffer (Stream s, bool isUserStream) { stream = s; this.isUserStream = isUserStream; if (stream.CanSeek) { fileLen = (int) stream.Length; bufLen = Math.Min(fileLen, MAX_BUFFER_LENGTH); bufStart = Int32.MaxValue; // nothing in the buffer so far } else { fileLen = bufLen = bufStart = 0; } buf = new byte[(bufLen>0) ? bufLen : MIN_BUFFER_LENGTH]; if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start) else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid if (bufLen == fileLen && stream.CanSeek) Close(); } protected Buffer(Buffer b) { // called in UTF8Buffer constructor buf = b.buf; bufStart = b.bufStart; bufLen = b.bufLen; fileLen = b.fileLen; bufPos = b.bufPos; stream = b.stream; // keep destructor from closing the stream b.stream = null; isUserStream = b.isUserStream; } ~Buffer() { Close(); } protected void Close() { if (!isUserStream && stream != null) { #if !CLASSIC_FRAMEWORK stream.Dispose(); #else stream.Close(); #endif stream = null; } } public virtual int Read () { if (bufPos < bufLen) { return buf[bufPos++]; } else if (Pos < fileLen) { Pos = Pos; // shift buffer start to Pos return buf[bufPos++]; } else if (stream != null && !stream.CanSeek && ReadNextStreamChunk() > 0) { return buf[bufPos++]; } else { return EOF; } } public int Peek () { int curPos = Pos; int ch = Read(); Pos = curPos; return ch; } // beg .. begin, zero-based, inclusive, in byte // end .. end, zero-based, exclusive, in byte public string GetString (int beg, int end) { int len = 0; char[] buf = new char[end - beg]; int oldPos = Pos; Pos = beg; while (Pos < end) buf[len++] = (char) Read(); Pos = oldPos; return new String(buf, 0, len); } public int Pos { get { return bufPos + bufStart; } set { if (value >= fileLen && stream != null && !stream.CanSeek) { // Wanted position is after buffer and the stream // is not seek-able e.g. network or console, // thus we have to read the stream manually till // the wanted position is in sight. while (value >= fileLen && ReadNextStreamChunk() > 0); } if (value < 0 || value > fileLen) { throw new FatalError("buffer out of bounds access, position: " + value); } if (value >= bufStart && value < bufStart + bufLen) { // already in buffer bufPos = value - bufStart; } else if (stream != null) { // must be swapped in stream.Seek(value, SeekOrigin.Begin); bufLen = stream.Read(buf, 0, buf.Length); bufStart = value; bufPos = 0; } else { // set the position to the end of the file, Pos will return fileLen. bufPos = fileLen - bufStart; } } } // Read the next chunk of bytes from the stream, increases the buffer // if needed and updates the fields fileLen and bufLen. // Returns the number of bytes read. private int ReadNextStreamChunk() { int free = buf.Length - bufLen; if (free == 0) { // in the case of a growing input stream // we can neither seek in the stream, nor can we // foresee the maximum length, thus we must adapt // the buffer size on demand. byte[] newBuf = new byte[bufLen * 2]; Array.Copy(buf, newBuf, bufLen); buf = newBuf; free = bufLen; } int read = stream.Read(buf, bufLen, free); if (read > 0) { fileLen = bufLen = (bufLen + read); return read; } // end of stream reached return 0; } } //----------------------------------------------------------------------------------- // UTF8Buffer //----------------------------------------------------------------------------------- internal class UTF8Buffer: Buffer { public UTF8Buffer(Buffer b): base(b) {} public override int Read() { int ch; do { ch = base.Read(); // until we find a utf8 start (0xxxxxxx or 11xxxxxx) } while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EOF)); if (ch < 128 || ch == EOF) { // nothing to do, first 127 chars are the same in ascii and utf8 // 0xxxxxxx or end of file character } else if ((ch & 0xF0) == 0xF0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx int c1 = ch & 0x07; ch = base.Read(); int c2 = ch & 0x3F; ch = base.Read(); int c3 = ch & 0x3F; ch = base.Read(); int c4 = ch & 0x3F; ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4; } else if ((ch & 0xE0) == 0xE0) { // 1110xxxx 10xxxxxx 10xxxxxx int c1 = ch & 0x0F; ch = base.Read(); int c2 = ch & 0x3F; ch = base.Read(); int c3 = ch & 0x3F; ch = (((c1 << 6) | c2) << 6) | c3; } else if ((ch & 0xC0) == 0xC0) { // 110xxxxx 10xxxxxx int c1 = ch & 0x1F; ch = base.Read(); int c2 = ch & 0x3F; ch = (c1 << 6) | c2; } return ch; } } //----------------------------------------------------------------------------------- // Scanner //----------------------------------------------------------------------------------- internal class Scanner { const char EOL = '\n'; const int eofSym = 0; /* pdt */ const int maxT = 18; const int noSym = 18; char valCh; // current input character (for token.val) public Buffer buffer; // scanner buffer Token t; // current token int ch; // current input character int pos; // byte position of current character int charPos; // position by unicode characters starting with 0 int col; // column number of current character int line; // line number of current character int oldEols; // EOLs that appeared in a comment; static readonly Dictionary<int,int> start; // maps first token character to start state Token tokens; // list of tokens already peeked (first token is a dummy) Token pt; // current peek token char[] tval = new char[128]; // text of current token int tlen; // length of current token static Scanner() { start = new Dictionary<int,int>(128); for (int i = 95; i <= 95; ++i) start[i] = 14; for (int i = 97; i <= 122; ++i) start[i] = 14; for (int i = 48; i <= 57; ++i) start[i] = 10; start[96] = 3; start[34] = 5; start[39] = 7; start[46] = 26; for (int i = 43; i <= 43; ++i) start[i] = 9; for (int i = 45; i <= 45; ++i) start[i] = 9; start[44] = 18; start[64] = 19; start[58] = 20; start[91] = 21; start[93] = 22; start[40] = 23; start[41] = 24; start[59] = 25; start[Buffer.EOF] = -1; } public Scanner (string fileName) { try { Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); buffer = new Buffer(stream, false); Init(); } catch (IOException) { throw new FatalError("Cannot open file " + fileName); } } public Scanner (Stream s) { buffer = new UTF8Buffer(new Buffer(s, true)); Init(); } void Init() { pos = -1; line = 1; col = 0; charPos = -1; oldEols = 0; NextCh(); if (ch == 0xEF) { // check optional byte order mark for UTF-8 NextCh(); int ch1 = ch; NextCh(); int ch2 = ch; if (ch1 != 0xBB || ch2 != 0xBF) { throw new FatalError(String.Format("illegal byte order mark: EF {0,2:X} {1,2:X}", ch1, ch2)); } buffer = new UTF8Buffer(buffer); col = 0; charPos = -1; NextCh(); } pt = tokens = new Token(); // first token is a dummy } void NextCh() { if (oldEols > 0) { ch = EOL; oldEols--; } else { pos = buffer.Pos; // buffer reads unicode chars, if UTF8 has been detected ch = buffer.Read(); col++; charPos++; // replace isolated '\r' by '\n' in order to make // eol handling uniform across Windows, Unix and Mac if (ch == '\r' && buffer.Peek() != '\n') ch = EOL; if (ch == EOL) { line++; col = 0; } } if (ch != Buffer.EOF) { valCh = (char) ch; ch = char.ToLower((char) ch); } } void AddCh() { if (tlen >= tval.Length) { char[] newBuf = new char[2 * tval.Length]; Array.Copy(tval, 0, newBuf, 0, tval.Length); tval = newBuf; } if (ch != Buffer.EOF) { tval[tlen++] = valCh; NextCh(); } } void CheckLiteral() { switch (t.val.ToLower()) { case "insert": t.kind = 6; break; case "values": t.kind = 7; break; case "into": t.kind = 8; break; default: break; } } Token NextToken() { while (ch == ' ' || ch >= 9 && ch <= 10 || ch == 13 ) NextCh(); int recKind = noSym; int recEnd = pos; t = new Token(); t.pos = pos; t.col = col; t.line = line; t.charPos = charPos; int state; if (start.ContainsKey(ch)) { state = (int) start[ch]; } else { state = 0; } tlen = 0; AddCh(); switch (state) { case -1: { t.kind = eofSym; break; } // NextCh already done case 0: { if (recKind != noSym) { tlen = recEnd - t.pos; SetScannerBehindT(); } t.kind = recKind; break; } // NextCh already done case 1: if (ch == '_' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 2;} else {goto case 0;} case 2: recEnd = pos; recKind = 1; if (ch >= '0' && ch <= '9' || ch == '_' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 2;} else {t.kind = 1; t.val = new String(tval, 0, tlen); CheckLiteral(); return t;} case 3: if (ch <= '!' || ch >= '#' && ch <= '&' || ch >= '(' && ch <= '[' || ch >= ']' && ch <= '_' || ch >= 'a' && ch <= 65535) {AddCh(); goto case 3;} else if (ch == '`') {AddCh(); goto case 4;} else if (ch == 92) {AddCh(); goto case 15;} else {goto case 0;} case 4: {t.kind = 2; break;} case 5: if (ch <= '!' || ch >= '#' && ch <= '&' || ch >= '(' && ch <= '[' || ch >= ']' && ch <= '_' || ch >= 'a' && ch <= 65535) {AddCh(); goto case 5;} else if (ch == '"') {AddCh(); goto case 6;} else if (ch == 92) {AddCh(); goto case 16;} else {goto case 0;} case 6: {t.kind = 3; break;} case 7: if (ch <= '!' || ch >= '#' && ch <= '&' || ch >= '(' && ch <= '[' || ch >= ']' && ch <= '_' || ch >= 'a' && ch <= 65535) {AddCh(); goto case 7;} else if (ch == 39) {AddCh(); goto case 8;} else if (ch == 92) {AddCh(); goto case 17;} else {goto case 0;} case 8: {t.kind = 4; break;} case 9: if (ch >= '0' && ch <= '9') {AddCh(); goto case 10;} else if (ch == '.') {AddCh(); goto case 12;} else {goto case 0;} case 10: recEnd = pos; recKind = 5; if (ch >= '0' && ch <= '9') {AddCh(); goto case 10;} else if (ch == '.') {AddCh(); goto case 11;} else {t.kind = 5; break;} case 11: recEnd = pos; recKind = 5; if (ch >= '0' && ch <= '9') {AddCh(); goto case 11;} else {t.kind = 5; break;} case 12: if (ch >= '0' && ch <= '9') {AddCh(); goto case 13;} else {goto case 0;} case 13: recEnd = pos; recKind = 5; if (ch >= '0' && ch <= '9') {AddCh(); goto case 13;} else {t.kind = 5; break;} case 14: recEnd = pos; recKind = 1; if (ch >= '0' && ch <= '9' || ch == '_' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 14;} else if (ch == '.') {AddCh(); goto case 1;} else {t.kind = 1; t.val = new String(tval, 0, tlen); CheckLiteral(); return t;} case 15: if (ch == 39 || ch == 92 || ch == '`') {AddCh(); goto case 3;} else {goto case 0;} case 16: if (ch == 39 || ch == 92) {AddCh(); goto case 5;} else {goto case 0;} case 17: if (ch == '"' || ch == 39 || ch == 92 || ch == '`') {AddCh(); goto case 7;} else {goto case 0;} case 18: {t.kind = 10; break;} case 19: {t.kind = 11; break;} case 20: {t.kind = 12; break;} case 21: {t.kind = 13; break;} case 22: {t.kind = 14; break;} case 23: {t.kind = 15; break;} case 24: {t.kind = 16; break;} case 25: {t.kind = 17; break;} case 26: recEnd = pos; recKind = 9; if (ch >= '0' && ch <= '9') {AddCh(); goto case 13;} else {t.kind = 9; break;} } t.val = new String(tval, 0, tlen); return t; } private void SetScannerBehindT() { buffer.Pos = t.pos; NextCh(); line = t.line; col = t.col; charPos = t.charPos; for (int i = 0; i < tlen; i++) NextCh(); } // get the next token (possibly a token already seen during peeking) public Token Scan () { if (tokens.next == null) { return NextToken(); } else { pt = tokens = tokens.next; return tokens; } } // peek for the next token, ignore pragmas public Token Peek () { do { if (pt.next == null) { pt.next = NextToken(); } pt = pt.next; } while (pt.kind > maxT); // skip pragmas return pt; } // make sure that peeking starts at the current scan position public void ResetPeek () { pt = tokens; } } // end Scanner }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Concurrent; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Testing; namespace Microsoft.AspNetCore.Analyzers; public abstract class StartupAnalyzerTest { public StartupAnalyzerTest() { StartupAnalyzer = new StartupAnalyzer(); Analyses = new ConcurrentBag<object>(); ConfigureServicesMethods = new ConcurrentBag<IMethodSymbol>(); ConfigureMethods = new ConcurrentBag<IMethodSymbol>(); StartupAnalyzer.ServicesAnalysisCompleted += (sender, analysis) => Analyses.Add(analysis); StartupAnalyzer.OptionsAnalysisCompleted += (sender, analysis) => Analyses.Add(analysis); StartupAnalyzer.MiddlewareAnalysisCompleted += (sender, analysis) => Analyses.Add(analysis); StartupAnalyzer.ConfigureServicesMethodFound += (sender, method) => ConfigureServicesMethods.Add(method); StartupAnalyzer.ConfigureMethodFound += (sender, method) => ConfigureMethods.Add(method); } internal StartupAnalyzer StartupAnalyzer { get; } internal ConcurrentBag<object> Analyses { get; } internal ConcurrentBag<IMethodSymbol> ConfigureServicesMethods { get; } internal ConcurrentBag<IMethodSymbol> ConfigureMethods { get; } [Fact] public async Task StartupAnalyzer_FindsStartupMethods_StartupSignatures_Standard() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class StartupSignatures_Standard { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app) { } } } "; // Act await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults); // Assert Assert.Collection(ConfigureServicesMethods, m => Assert.Equal("ConfigureServices", m.Name)); Assert.Collection(ConfigureMethods, m => Assert.Equal("Configure", m.Name)); } [Fact] public async Task StartupAnalyzer_FindsStartupMethods_StartupSignatures_MoreVariety() { // Arrange var source = @" using System.Text; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class StartupSignatures_MoreVariety { public void ConfigureServices(IServiceCollection services) { } public void ConfigureServices(IServiceCollection services, StringBuilder s) // Ignored { } public void Configure(StringBuilder s) // Ignored, { } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { } public void ConfigureProduction(IWebHostEnvironment env, IApplicationBuilder app) { } private void Configure(IApplicationBuilder app) // Ignored { } } } "; // Act await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults); // Assert Assert.Collection( ConfigureServicesMethods.OrderBy(m => m.Name), m => Assert.Equal("ConfigureServices", m.Name)); Assert.Collection( ConfigureMethods.OrderBy(m => m.Name), m => Assert.Equal("Configure", m.Name), m => Assert.Equal("ConfigureProduction", m.Name)); } [Fact] public async Task StartupAnalyzer_MvcOptionsAnalysis_UseMvc_FindsEndpointRoutingDisabled() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class MvcOptions_UseMvcWithDefaultRouteAndEndpointRoutingDisabled { public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => options.EnableEndpointRouting = false); } public void Configure(IApplicationBuilder app) { app.UseMvcWithDefaultRoute(); } } }"; // Act await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults); // Assert var optionsAnalysis = Assert.Single(Analyses.OfType<OptionsAnalysis>()); Assert.True(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis)); var middlewareAnalysis = Assert.Single(Analyses.OfType<MiddlewareAnalysis>()); var middleware = Assert.Single(middlewareAnalysis.Middleware); Assert.Equal("UseMvcWithDefaultRoute", middleware.UseMethod.Name); } [Fact] public async Task StartupAnalyzer_MvcOptionsAnalysis_AddMvcOptions_FindsEndpointRoutingDisabled() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class MvcOptions_UseMvcWithDefaultRouteAndAddMvcOptionsEndpointRoutingDisabled { public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddMvcOptions(options => options.EnableEndpointRouting = false); } public void Configure(IApplicationBuilder app) { app.UseMvcWithDefaultRoute(); } } } "; // Act await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults); // Assert var optionsAnalysis = Assert.Single(Analyses.OfType<OptionsAnalysis>()); Assert.True(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis)); var middlewareAnalysis = Assert.Single(Analyses.OfType<MiddlewareAnalysis>()); var middleware = Assert.Single(middlewareAnalysis.Middleware); Assert.Equal("UseMvcWithDefaultRoute", middleware.UseMethod.Name); } [Fact] public Task StartupAnalyzer_MvcOptionsAnalysis_UseMvc_FindsEndpointRoutingEnabled() { var source = @" using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class MvcOptions_UseMvc { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app) { {|#0:app.UseMvc()|}; } } }"; var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting) .WithArguments("UseMvc", "ConfigureServices") .WithLocation(0); return VerifyMvcOptionsAnalysis(source, "UseMvc", diagnosticResult); } [Fact] public Task StartupAnalyzer_MvcOptionsAnalysis_UseMvcAndConfiguredRoutes_FindsEndpointRoutingEnabled() { var source = @" using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class MvcOptions_UseMvcAndConfiguredRoutes { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app) { {|#0:app.UseMvc(routes => { routes.MapRoute(""Name"", ""Template""); })|}; } } } "; var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting) .WithArguments("UseMvc", "ConfigureServices") .WithLocation(0); return VerifyMvcOptionsAnalysis(source, "UseMvc", diagnosticResult); } [Fact] public Task StartupAnalyzer_MvcOptionsAnalysis_MvcOptions_UseMvcWithDefaultRoute_FindsEndpointRoutingEnabled() { var source = @" using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class MvcOptions_UseMvcWithDefaultRoute { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app) { {|#0:app.UseMvcWithDefaultRoute()|}; } } } "; var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting) .WithArguments("UseMvcWithDefaultRoute", "ConfigureServices") .WithLocation(0); return VerifyMvcOptionsAnalysis(source, "UseMvcWithDefaultRoute", diagnosticResult); } private async Task VerifyMvcOptionsAnalysis(string source, string mvcMiddlewareName, params DiagnosticResult[] diagnosticResults) { // Arrange await VerifyAnalyzerAsync(source, diagnosticResults); // Assert var optionsAnalysis = Analyses.OfType<OptionsAnalysis>().First(); Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis)); var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First(); var middleware = Assert.Single(middlewareAnalysis.Middleware); Assert.Equal(mvcMiddlewareName, middleware.UseMethod.Name); } [Fact] public async Task StartupAnalyzer_MvcOptionsAnalysis_MultipleMiddleware() { // Arrange var source = @" using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class MvcOptions_UseMvcWithOtherMiddleware { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); app.UseMiddleware<AuthorizationMiddleware>(); {|#0:app.UseMvc()|}; app.UseRouting(); app.UseEndpoints(endpoints => { }); } } }"; var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting) .WithLocation(0) .WithArguments("UseMvc", "ConfigureServices"); // Act await VerifyAnalyzerAsync(source, diagnosticResult); // Assert var optionsAnalysis = Analyses.OfType<OptionsAnalysis>().First(); Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis)); var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First(); Assert.Collection( middlewareAnalysis.Middleware, item => Assert.Equal("UseStaticFiles", item.UseMethod.Name), item => Assert.Equal("UseMiddleware", item.UseMethod.Name), item => Assert.Equal("UseMvc", item.UseMethod.Name), item => Assert.Equal("UseRouting", item.UseMethod.Name), item => Assert.Equal("UseEndpoints", item.UseMethod.Name)); } [Fact] public async Task StartupAnalyzer_MvcOptionsAnalysis_MultipleUseMvc() { // Arrange var source = @" using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class MvcOptions_UseMvcMultiple { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app) { {|#0:app.UseMvcWithDefaultRoute()|}; app.UseStaticFiles(); app.UseMiddleware<AuthorizationMiddleware>(); {|#1:app.UseMvc()|}; app.UseRouting(); app.UseEndpoints(endpoints => { }); {|#2:app.UseMvc()|}; } } }"; var diagnosticResults = new[] { new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting) .WithLocation(0) .WithArguments("UseMvcWithDefaultRoute", "ConfigureServices"), new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting) .WithLocation(1) .WithArguments("UseMvc", "ConfigureServices"), new DiagnosticResult(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting) .WithLocation(2) .WithArguments("UseMvc", "ConfigureServices"), }; // Act await VerifyAnalyzerAsync(source, diagnosticResults); // Assert var optionsAnalysis = Analyses.OfType<OptionsAnalysis>().First(); Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis)); } [Fact] public async Task StartupAnalyzer_ServicesAnalysis_CallBuildServiceProvider() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class ConfigureServices_BuildServiceProvider { public void ConfigureServices(IServiceCollection services) { {|#0:services.BuildServiceProvider()|}; } public void Configure(IApplicationBuilder app) { } } }"; var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.BuildServiceProviderShouldNotCalledInConfigureServicesMethod) .WithLocation(0); // Act await VerifyAnalyzerAsync(source, diagnosticResult); // Assert var servicesAnalysis = Analyses.OfType<ServicesAnalysis>().First(); Assert.NotEmpty(servicesAnalysis.Services); } [Fact] public async Task StartupAnalyzer_UseAuthorizationConfiguredCorrectly_ReportsNoDiagnostics() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class UseAuthConfiguredCorrectly { public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(r => { }); } } }"; // Act await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults); // Assert var middlewareAnalysis = Assert.Single(Analyses.OfType<MiddlewareAnalysis>()); Assert.NotEmpty(middlewareAnalysis.Middleware); } [Fact] public async Task StartupAnalyzer_UseAuthorizationConfiguredAsAChain_ReportsNoDiagnostics() { // Regression test for https://github.com/dotnet/aspnetcore/issues/15203 // Arrange var source = @" using Microsoft.AspNetCore.Builder; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class UseAuthConfiguredCorrectlyChained { public void Configure(IApplicationBuilder app) { app.UseRouting() .UseAuthorization() .UseEndpoints(r => { }); } } }"; // Act await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults); // Assert var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First(); Assert.NotEmpty(middlewareAnalysis.Middleware); } [Fact] public async Task StartupAnalyzer_UseAuthorizationInvokedMultipleTimesInEndpointRoutingBlock_ReportsNoDiagnostics() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class UseAuthMultipleTimes { public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseAuthorization(); app.UseAuthorization(); app.UseEndpoints(r => { }); } } }"; // Act await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults); // Assert var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First(); Assert.NotEmpty(middlewareAnalysis.Middleware); } [Fact] public async Task StartupAnalyzer_UseAuthorizationConfiguredBeforeUseRouting_ReportsDiagnostics() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class UseAuthBeforeUseRouting { public void Configure(IApplicationBuilder app) { app.UseFileServer(); {|#0:app.UseAuthorization()|}; app.UseRouting(); app.UseEndpoints(r => { }); } } }"; var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.IncorrectlyConfiguredAuthorizationMiddleware) .WithLocation(0); // Act await VerifyAnalyzerAsync(source, diagnosticResult); } [Fact] public async Task StartupAnalyzer_UseAuthorizationConfiguredBeforeUseRoutingChained_ReportsDiagnostics() { // This one asserts a false negative for https://github.com/dotnet/aspnetcore/issues/15203. // We don't correctly identify chained calls, this test verifies the behavior. // Arrange var source = @" using Microsoft.AspNetCore.Builder; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class UseAuthBeforeUseRoutingChained { public void Configure(IApplicationBuilder app) { app.UseFileServer() .UseAuthorization() .UseRouting() .UseEndpoints(r => { }); } } }"; // Act await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults); // Assert var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First(); Assert.NotEmpty(middlewareAnalysis.Middleware); } [Fact] public async Task StartupAnalyzer_UseAuthorizationConfiguredAfterUseEndpoints_ReportsDiagnostics() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class UseAuthAfterUseEndpoints { public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseEndpoints(r => { }); {|#0:app.UseAuthorization()|}; } } } "; var diagnosticResult = new DiagnosticResult(StartupAnalyzer.Diagnostics.IncorrectlyConfiguredAuthorizationMiddleware) .WithLocation(0); // Act await VerifyAnalyzerAsync(source, diagnosticResult); // Assert var middlewareAnalysis = Analyses.OfType<MiddlewareAnalysis>().First(); Assert.NotEmpty(middlewareAnalysis.Middleware); } [Fact] public async Task StartupAnalyzer_MultipleUseAuthorization_ReportsNoDiagnostics() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; namespace Microsoft.AspNetCore.Analyzers.TestFiles.StartupAnalyzerTest { public class UseAuthFallbackPolicy { public void Configure(IApplicationBuilder app) { // This sort of setup would be useful if the user wants to use Auth for non-endpoint content to be handled using the Fallback policy, while // using the second instance for regular endpoint routing based auth. We do not want to produce a warning in this case. app.UseAuthorization(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(r => { }); } } }"; // Act await VerifyAnalyzerAsync(source, DiagnosticResult.EmptyDiagnosticResults); // Assert var middlewareAnalysis = Assert.Single(Analyses.OfType<MiddlewareAnalysis>()); Assert.NotEmpty(middlewareAnalysis.Middleware); } private Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected) { var test = new StartupCSharpAnalyzerTest(StartupAnalyzer, TestReferences.MetadataReferences) { TestCode = source, ReferenceAssemblies = TestReferences.EmptyReferenceAssemblies, }; test.ExpectedDiagnostics.AddRange(expected); return test.RunAsync(); } }
// // System.Web.UI/KeyedList.cs // // Author: Todd Berman <tberman@gentoo.org> // // (C) 2003 Todd Berman // // 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. // #if NET_2_0 using System.Collections; using System.Collections.Specialized; namespace System.Web.UI { public class KeyedList : IOrderedDictionary, IStateManager { private Hashtable objectTable = new Hashtable (); private ArrayList objectList = new ArrayList (); public void Add (object key, object value) { objectTable.Add (key, value); objectList.Add (new DictionaryEntry (key, value)); } public void Clear () { objectTable.Clear (); objectList.Clear (); } public bool Contains (object key) { return objectTable.Contains (key); } public void CopyTo (Array array, int idx) { objectTable.CopyTo (array, idx); } public void Insert (int idx, object key, object value) { if (idx > Count) throw new ArgumentOutOfRangeException ("index"); objectTable.Add (key, value); objectList.Insert (idx, new DictionaryEntry (key, value)); } public void Remove (object key) { objectTable.Remove (key); objectList.RemoveAt (IndexOf (key)); } public void RemoveAt (int idx) { if (idx >= Count) throw new ArgumentOutOfRangeException ("index"); objectTable.Remove ( ((DictionaryEntry)objectList[idx]).Key ); objectList.RemoveAt (idx); } IDictionaryEnumerator IDictionary.GetEnumerator () { return new KeyedListEnumerator (objectList); } IEnumerator IEnumerable.GetEnumerator () { return new KeyedListEnumerator (objectList); } void IStateManager.LoadViewState (object state) { if (state != null) { object[] states = (object[]) state; if (states[0] != null) { objectList = (ArrayList) states[0]; for (int i = 0; i < objectList.Count; i++) { DictionaryEntry pair = (DictionaryEntry) objectList[i]; objectTable.Add (pair.Key, pair.Value); } } } } object IStateManager.SaveViewState () { object[] ret = new object[] { objectList }; if (ret[0] == null) return null; return ret; } void IStateManager.TrackViewState () { trackViewState = true; } public int Count { get { return objectList.Count; } } public bool IsFixedSize { get { return false; } } public bool IsReadOnly { get { return false; } } public bool IsSynchronized { get { return false; } } public object this[int idx] { get { return ((DictionaryEntry) objectList[idx]).Value; } set { if (idx < 0 || idx >= Count) throw new ArgumentOutOfRangeException ("index"); object key = ((DictionaryEntry) objectList[idx]).Key; objectList[idx] = new DictionaryEntry (key, value); objectTable[key] = value; } } public object this[object key] { get { return objectTable[key]; } set { if (objectTable.Contains (key)) { objectTable[key] = value; objectTable[IndexOf (key)] = new DictionaryEntry (key, value); return; } Add (key, value); } } public ICollection Keys { get { ArrayList retList = new ArrayList (); for (int i = 0; i < objectList.Count; i++) { retList.Add ( ((DictionaryEntry)objectList[i]).Key ); } return retList; } } public ICollection Values { get { ArrayList retList = new ArrayList (); for (int i = 0; i < objectList.Count; i++) { retList.Add ( ((DictionaryEntry)objectList[i]).Value ); } return retList; } } public object SyncRoot { get { return this; } } private bool trackViewState; bool IStateManager.IsTrackingViewState { get { return trackViewState; } } private int IndexOf (object key) { for (int i = 0; i < objectList.Count; i++) { if (((DictionaryEntry) objectList[i]).Key.Equals (key)) { return i; } } return -1; } } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Orleans.Runtime; using Orleans.Serialization.TypeSystem; namespace Orleans.CodeGeneration { internal static class GrainInterfaceUtils { public static bool IsGrainInterface(Type t) { if (t.IsClass) return false; if (t == typeof(IGrainObserver) || t == typeof(IAddressable) || t == typeof(IGrainExtension)) return false; if (t == typeof(IGrain) || t == typeof(IGrainWithGuidKey) || t == typeof(IGrainWithIntegerKey) || t == typeof(IGrainWithGuidCompoundKey) || t == typeof(IGrainWithIntegerCompoundKey)) return false; if (t == typeof (ISystemTarget)) return false; return typeof (IAddressable).IsAssignableFrom(t); } public static MethodInfo[] GetMethods(Type grainType, bool bAllMethods = true) { var methodInfos = new List<MethodInfo>(); GetMethodsImpl(grainType, grainType, methodInfos); var flags = BindingFlags.Public | BindingFlags.Instance; if (!bAllMethods) flags |= BindingFlags.DeclaredOnly; MethodInfo[] infos = grainType.GetMethods(flags); foreach (var methodInfo in infos) { if (!methodInfos.Contains(methodInfo, MethodInfoComparer.Default)) { methodInfos.Add(methodInfo); } } return methodInfos.ToArray(); static void GetMethodsImpl(Type grainType, Type serviceType, List<MethodInfo> methodInfos) { foreach (var iType in GetGrainInterfaces(serviceType)) { if (grainType.IsClass) { var mapping = grainType.GetInterfaceMap(iType); foreach (var methodInfo in iType.GetMethods(BindingFlags.Instance | BindingFlags.Public)) { foreach (var info in mapping.TargetMethods) { if (info.DeclaringType == grainType && MethodInfoComparer.Default.Equals(methodInfo, info)) { if (!methodInfos.Contains(methodInfo, MethodInfoComparer.Default)) methodInfos.Add(methodInfo); break; } } } } else if (grainType.IsInterface) { foreach (var methodInfo in iType.GetMethods(BindingFlags.Instance | BindingFlags.Public)) { if (!methodInfos.Contains(methodInfo, MethodInfoComparer.Default)) methodInfos.Add(methodInfo); } } } } static List<Type> GetGrainInterfaces(Type type) { var res = new List<Type>(); if (IsGrainInterface(type)) { res.Add(type); } foreach (var interfaceType in type.GetInterfaces()) { res.Add(interfaceType); } return res; } } public static int GetGrainClassTypeCode(Type grainClass) { var fullName = RuntimeTypeNameFormatter.Format(grainClass); return Utils.CalculateIdHash(fullName); } private sealed class MethodInfoComparer : IEqualityComparer<MethodInfo>, IComparer<MethodInfo> { public static MethodInfoComparer Default { get; } = new(); private MethodInfoComparer() { } public bool Equals(MethodInfo x, MethodInfo y) { if (!string.Equals(x.Name, y.Name, StringComparison.Ordinal)) { return false; } var xArgs = x.GetGenericArguments(); var yArgs = y.GetGenericArguments(); if (xArgs.Length != yArgs.Length) { return false; } for (var i = 0; i < x.GetGenericArguments().Length; i++) { if (xArgs[i] != yArgs[i]) { return false; } } var xParams = x.GetParameters(); var yParams = y.GetParameters(); if (xParams.Length != yParams.Length) { return false; } for (var i = 0; i < xParams.Length; i++) { if (xParams[i].ParameterType != yParams[i].ParameterType) { return false; } } return true; } public int GetHashCode(MethodInfo obj) { int hashCode = -499943048; hashCode = hashCode * -1521134295 + StringComparer.Ordinal.GetHashCode(obj.Name); foreach (var arg in obj.GetGenericArguments()) { hashCode = hashCode * -1521134295 + arg.GetHashCode(); } foreach (var parameter in obj.GetParameters()) { hashCode = hashCode * -1521134295 + parameter.ParameterType.GetHashCode(); } return hashCode; } public int Compare(MethodInfo x, MethodInfo y) { var result = StringComparer.Ordinal.Compare(x.Name, y.Name); if (result != 0) { return result; } var xArgs = x.GetGenericArguments(); var yArgs = y.GetGenericArguments(); result = xArgs.Length.CompareTo(yArgs.Length); if (result != 0) { return result; } for (var i = 0; i < xArgs.Length; i++) { var xh = xArgs[i].GetHashCode(); var yh = yArgs[i].GetHashCode(); result = xh.CompareTo(yh); if (result != 0) { return result; } } var xParams = x.GetParameters(); var yParams = y.GetParameters(); result = xParams.Length.CompareTo(yParams.Length); if (result != 0) { return result; } for (var i = 0; i < xParams.Length; i++) { var xh = xParams[i].ParameterType.GetHashCode(); var yh = yParams[i].ParameterType.GetHashCode(); result = xh.CompareTo(yh); if (result != 0) { return result; } } return 0; } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Net; using System.Text; using System.Xml; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Calls the specified web service on each log message. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/WebService-target">Documentation on NLog Wiki</seealso> /// <remarks> /// The web service must implement a method that accepts a number of string parameters. /// </remarks> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/WebService/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/Example.cs" /> /// <p>The example web service that works with this example is shown below</p> /// <code lang="C#" source="examples/targets/Configuration API/WebService/Simple/WebService1/Service1.asmx.cs" /> /// </example> [Target("WebService")] public sealed class WebServiceTarget : MethodCallTargetBase { private const string SoapEnvelopeNamespaceUri = "http://schemas.xmlsoap.org/soap/envelope/"; private const string Soap12EnvelopeNamespaceUri = "http://www.w3.org/2003/05/soap-envelope"; /// <summary> /// dictionary that maps a concrete <see cref="HttpPostFormatterBase"/> implementation /// to a specific <see cref="WebServiceProtocol"/>-value. /// </summary> private static Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>> _postFormatterFactories = new Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>>() { { WebServiceProtocol.Soap11, t => new HttpPostSoap11Formatter(t)}, { WebServiceProtocol.Soap12, t => new HttpPostSoap12Formatter(t)}, { WebServiceProtocol.HttpPost, t => new HttpPostFormEncodedFormatter(t)}, { WebServiceProtocol.JsonPost, t => new HttpPostJsonFormatter(t)}, { WebServiceProtocol.XmlPost, t => new HttpPostXmlDocumentFormatter(t)}, }; /// <summary> /// Initializes a new instance of the <see cref="WebServiceTarget" /> class. /// </summary> public WebServiceTarget() { Protocol = WebServiceProtocol.Soap11; //default NO utf-8 bom const bool writeBOM = false; Encoding = new UTF8Encoding(writeBOM); IncludeBOM = writeBOM; OptimizeBufferReuse = true; Headers = new List<MethodCallParameter>(); #if NETSTANDARD // WebRequest.GetSystemWebProxy throws PlatformNotSupportedException on NetCore, when Proxy is not configured ProxyType = WebServiceProxyType.NoProxy; #endif } /// <summary> /// Initializes a new instance of the <see cref="WebServiceTarget" /> class. /// </summary> /// <param name="name">Name of the target</param> public WebServiceTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the web service URL. /// </summary> /// <docgen category='Web Service Options' order='10' /> public Uri Url { get; set; } /// <summary> /// Gets or sets the Web service method name. Only used with Soap. /// </summary> /// <docgen category='Web Service Options' order='10' /> public string MethodName { get; set; } /// <summary> /// Gets or sets the Web service namespace. Only used with Soap. /// </summary> /// <docgen category='Web Service Options' order='10' /> public string Namespace { get; set; } /// <summary> /// Gets or sets the protocol to be used when calling web service. /// </summary> /// <docgen category='Web Service Options' order='10' /> [DefaultValue("Soap11")] public WebServiceProtocol Protocol { get => _activeProtocol.Key; set => _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(value, null); } private KeyValuePair<WebServiceProtocol, HttpPostFormatterBase> _activeProtocol; #if !SILVERLIGHT /// <summary> /// Gets or sets the proxy configuration when calling web service /// </summary> /// <docgen category='Web Service Options' order='10' /> [DefaultValue("DefaultWebProxy")] public WebServiceProxyType ProxyType { get => _activeProxy.Key; set => _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(value, null); } private KeyValuePair<WebServiceProxyType, IWebProxy> _activeProxy; #endif /// <summary> /// Gets or sets the custom proxy address, include port separated by a colon /// </summary> /// <docgen category='Web Service Options' order='10' /> public string ProxyAddress { get; set; } /// <summary> /// Should we include the BOM (Byte-order-mark) for UTF? Influences the <see cref="Encoding"/> property. /// /// This will only work for UTF-8. /// </summary> /// <docgen category='Web Service Options' order='10' /> public bool? IncludeBOM { get; set; } /// <summary> /// Gets or sets the encoding. /// </summary> /// <docgen category='Web Service Options' order='10' /> public Encoding Encoding { get; set; } /// <summary> /// Gets or sets a value whether escaping be done according to Rfc3986 (Supports Internationalized Resource Identifiers - IRIs) /// </summary> /// <value>A value of <c>true</c> if Rfc3986; otherwise, <c>false</c> for legacy Rfc2396.</value> /// <docgen category='Web Service Options' order='100' /> public bool EscapeDataRfc3986 { get; set; } /// <summary> /// Gets or sets a value whether escaping be done according to the old NLog style (Very non-standard) /// </summary> /// <value>A value of <c>true</c> if legacy encoding; otherwise, <c>false</c> for standard UTF8 encoding.</value> /// <docgen category='Web Service Options' order='100' /> public bool EscapeDataNLogLegacy { get; set; } /// <summary> /// Gets or sets the name of the root XML element, /// if POST of XML document chosen. /// If so, this property must not be <c>null</c>. /// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>). /// </summary> /// <docgen category='Web Service Options' order='100' /> public string XmlRoot { get; set; } /// <summary> /// Gets or sets the (optional) root namespace of the XML document, /// if POST of XML document chosen. /// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>). /// </summary> /// <docgen category='Web Service Options' order='100' /> public string XmlRootNamespace { get; set; } /// <summary> /// Gets the array of parameters to be passed. /// </summary> /// <docgen category='Web Service Options' order='10' /> [ArrayParameter(typeof(MethodCallParameter), "header")] public IList<MethodCallParameter> Headers { get; private set; } #if !SILVERLIGHT /// <summary> /// Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in <see cref="Headers"/> parameters) /// </summary> /// <docgen category='Web Service Options' order='100' /> public bool PreAuthenticate { get; set; } #endif private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter(); /// <summary> /// Calls the target method. Must be implemented in concrete classes. /// </summary> /// <param name="parameters">Method call parameters.</param> protected override void DoInvoke(object[] parameters) { // method is not used, instead asynchronous overload will be used throw new NotImplementedException(); } /// <summary> /// Calls the target DoInvoke method, and handles AsyncContinuation callback /// </summary> /// <param name="parameters">Method call parameters.</param> /// <param name="continuation">The continuation.</param> protected override void DoInvoke(object[] parameters, AsyncContinuation continuation) { var webRequest = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters)); DoInvoke(parameters, webRequest, continuation); } /// <summary> /// Invokes the web service method. /// </summary> /// <param name="parameters">Parameters to be passed.</param> /// <param name="logEvent">The logging event.</param> protected override void DoInvoke(object[] parameters, AsyncLogEventInfo logEvent) { var webRequest = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters)); if (Headers != null && Headers.Count > 0) { for (int i = 0; i < Headers.Count; i++) { string headerValue = RenderLogEvent(Headers[i].Layout, logEvent.LogEvent); if (headerValue == null) continue; webRequest.Headers[Headers[i].Name] = headerValue; } } DoInvoke(parameters, webRequest, logEvent.Continuation); } void DoInvoke(object[] parameters, HttpWebRequest webRequest, AsyncContinuation continuation) { Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest = (request, result) => request.BeginGetRequestStream(result, null); Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream = (request, result) => request.EndGetRequestStream(result); #if !SILVERLIGHT switch (ProxyType) { case WebServiceProxyType.DefaultWebProxy: break; #if !NETSTANDARD1_0 case WebServiceProxyType.AutoProxy: if (_activeProxy.Value == null) { IWebProxy proxy = WebRequest.GetSystemWebProxy(); proxy.Credentials = CredentialCache.DefaultCredentials; _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy); } webRequest.Proxy = _activeProxy.Value; break; case WebServiceProxyType.ProxyAddress: if (!string.IsNullOrEmpty(ProxyAddress)) { if (_activeProxy.Value == null) { IWebProxy proxy = new WebProxy(ProxyAddress, true); _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy); } webRequest.Proxy = _activeProxy.Value; } break; #endif default: webRequest.Proxy = null; break; } #endif #if !SILVERLIGHT && !NETSTANDARD1_0 if (PreAuthenticate || ProxyType == WebServiceProxyType.AutoProxy) { webRequest.PreAuthenticate = true; } #endif DoInvoke(parameters, continuation, webRequest, beginGetRequest, getRequestStream); } internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest webRequest, Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest, Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream) { Stream postPayload = null; if (Protocol == WebServiceProtocol.HttpGet) { PrepareGetRequest(webRequest); } else { if (_activeProtocol.Value == null) _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(Protocol, _postFormatterFactories[Protocol](this)); postPayload = _activeProtocol.Value.PrepareRequest(webRequest, parameters); } var sendContinuation = CreateSendContinuation(continuation, webRequest); PostPayload(continuation, webRequest, beginGetRequest, getRequestStream, postPayload, sendContinuation); } private AsyncContinuation CreateSendContinuation(AsyncContinuation continuation, HttpWebRequest webRequest) { AsyncContinuation sendContinuation = ex => { if (ex != null) { DoInvokeCompleted(continuation, ex); return; } try { webRequest.BeginGetResponse( r => { try { using (var response = webRequest.EndGetResponse(r)) { // Request successfully initialized } DoInvokeCompleted(continuation, null); } catch (Exception ex2) { InternalLogger.Error(ex2, "WebServiceTarget(Name={0}): Error sending request", Name); if (ex2.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } DoInvokeCompleted(continuation, ex2); } }, null); } catch (Exception ex2) { InternalLogger.Error(ex2, "WebServiceTarget(Name={0}): Error starting request", Name); if (ExceptionMustBeRethrown(ex2)) { throw; } DoInvokeCompleted(continuation, ex2); } }; return sendContinuation; } private void PostPayload(AsyncContinuation continuation, HttpWebRequest webRequest, Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest, Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream, Stream postPayload, AsyncContinuation sendContinuation) { if (postPayload != null && postPayload.Length > 0) { postPayload.Position = 0; try { _pendingManualFlushList.BeginOperation(); beginGetRequest(webRequest, result => { try { using (Stream stream = getRequestStream(webRequest, result)) { WriteStreamAndFixPreamble(postPayload, stream, IncludeBOM, Encoding); postPayload.Dispose(); } sendContinuation(null); } catch (Exception ex) { InternalLogger.Error(ex, "WebServiceTarget(Name={0}): Error sending post data", Name); if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } postPayload.Dispose(); DoInvokeCompleted(continuation, ex); } }); } catch (Exception ex) { InternalLogger.Error(ex, "WebServiceTarget(Name={0}): Error starting post data", Name); if (ExceptionMustBeRethrown(ex)) { throw; } DoInvokeCompleted(continuation, ex); } } else { _pendingManualFlushList.BeginOperation(); sendContinuation(null); } } private void DoInvokeCompleted(AsyncContinuation continuation, Exception ex) { _pendingManualFlushList.CompleteOperation(ex); continuation(ex); } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { _pendingManualFlushList.RegisterCompletionNotification(asyncContinuation).Invoke(null); } /// <summary> /// Closes the target. /// </summary> protected override void CloseTarget() { _pendingManualFlushList.Clear(); // Maybe consider to wait a short while if pending requests? base.CloseTarget(); } /// <summary> /// Builds the URL to use when calling the web service for a message, depending on the WebServiceProtocol. /// </summary> /// <param name="parameterValues"></param> /// <returns></returns> private Uri BuildWebServiceUrl(object[] parameterValues) { if (Protocol != WebServiceProtocol.HttpGet) { return Url; } //if the protocol is HttpGet, we need to add the parameters to the query string of the url string queryParameters; using (var targetBuilder = OptimizeBufferReuse ? ReusableLayoutBuilder.Allocate() : ReusableLayoutBuilder.None) { StringBuilder sb = targetBuilder.Result ?? new StringBuilder(); UrlHelper.EscapeEncodingOptions encodingOptions = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, false, EscapeDataRfc3986); BuildWebServiceQueryParameters(parameterValues, sb, encodingOptions); queryParameters = sb.ToString(); } var builder = new UriBuilder(Url); //append our query string to the URL following //the recommendations at https://msdn.microsoft.com/en-us/library/system.uribuilder.query.aspx if (builder.Query != null && builder.Query.Length > 1) { builder.Query = string.Concat(builder.Query.Substring(1), "&", queryParameters); } else { builder.Query = queryParameters; } return builder.Uri; } private void BuildWebServiceQueryParameters(object[] parameterValues, StringBuilder sb, UrlHelper.EscapeEncodingOptions encodingOptions) { string separator = string.Empty; for (int i = 0; i < Parameters.Count; i++) { sb.Append(separator); sb.Append(Parameters[i].Name); sb.Append("="); string parameterValue = XmlHelper.XmlConvertToString(parameterValues[i]); if (!string.IsNullOrEmpty(parameterValue)) { UrlHelper.EscapeDataEncode(parameterValue, sb, encodingOptions); } separator = "&"; } } private void PrepareGetRequest(HttpWebRequest webRequest) { webRequest.Method = "GET"; } /// <summary> /// Write from input to output. Fix the UTF-8 bom /// </summary> /// <param name="input"></param> /// <param name="output"></param> /// <param name="writeUtf8BOM"></param> /// <param name="encoding"></param> private static void WriteStreamAndFixPreamble(Stream input, Stream output, bool? writeUtf8BOM, Encoding encoding) { //only when utf-8 encoding is used, the Encoding preamble is optional var nothingToDo = writeUtf8BOM == null || !(encoding is UTF8Encoding); const int preambleSize = 3; if (!nothingToDo) { //it's UTF-8 var hasBomInEncoding = encoding.GetPreamble().Length == preambleSize; //BOM already in Encoding. nothingToDo = writeUtf8BOM.Value && hasBomInEncoding; //Bom already not in Encoding nothingToDo = nothingToDo || !writeUtf8BOM.Value && !hasBomInEncoding; } var offset = nothingToDo ? 0 : preambleSize; input.CopyWithOffset(output, offset); } /// <summary> /// base class for POST formatters, that /// implement former <c>PrepareRequest()</c> method, /// that creates the content for /// the requested kind of HTTP request /// </summary> private abstract class HttpPostFormatterBase { protected HttpPostFormatterBase(WebServiceTarget target) { Target = target; } protected string ContentType => _contentType ?? (_contentType = GetContentType(Target)); private string _contentType; protected WebServiceTarget Target { get; private set; } protected virtual string GetContentType(WebServiceTarget target) { return string.Concat("charset=", target.Encoding.WebName); } public MemoryStream PrepareRequest(HttpWebRequest request, object[] parameterValues) { InitRequest(request); var ms = new MemoryStream(); WriteContent(ms, parameterValues); return ms; } protected virtual void InitRequest(HttpWebRequest request) { request.Method = "POST"; request.ContentType = ContentType; } protected abstract void WriteContent(MemoryStream ms, object[] parameterValues); } private class HttpPostFormEncodedFormatter : HttpPostTextFormatterBase { readonly UrlHelper.EscapeEncodingOptions _encodingOptions; public HttpPostFormEncodedFormatter(WebServiceTarget target) : base(target) { _encodingOptions = UrlHelper.GetUriStringEncodingFlags(target.EscapeDataNLogLegacy, true, target.EscapeDataRfc3986); } protected override string GetContentType(WebServiceTarget target) { return string.Concat("application/x-www-form-urlencoded", "; ", base.GetContentType(target)); } protected override void WriteStringContent(StringBuilder builder, object[] parameterValues) { Target.BuildWebServiceQueryParameters(parameterValues, builder, _encodingOptions); } } private class HttpPostJsonFormatter : HttpPostTextFormatterBase { private IJsonConverter JsonConverter => _jsonConverter ?? (_jsonConverter = ConfigurationItemFactory.Default.JsonConverter); private IJsonConverter _jsonConverter; public HttpPostJsonFormatter(WebServiceTarget target) : base(target) { } protected override string GetContentType(WebServiceTarget target) { return string.Concat("application/json", "; ", base.GetContentType(target)); } protected override void WriteStringContent(StringBuilder builder, object[] parameterValues) { if (Target.Parameters.Count == 1 && string.IsNullOrEmpty(Target.Parameters[0].Name) && parameterValues[0] is string s) { // JsonPost with single nameless parameter means complex JsonLayout builder.Append(s); } else { builder.Append("{"); string separator = string.Empty; for (int i = 0; i < Target.Parameters.Count; ++i) { var parameter = Target.Parameters[i]; builder.Append(separator); builder.Append('"'); builder.Append(parameter.Name); builder.Append("\":"); JsonConverter.SerializeObject(parameterValues[i], builder); separator = ","; } builder.Append('}'); } } } private class HttpPostSoap11Formatter : HttpPostSoapFormatterBase { private readonly string _defaultSoapAction; public HttpPostSoap11Formatter(WebServiceTarget target) : base(target) { _defaultSoapAction = GetDefaultSoapAction(target); } protected override string SoapEnvelopeNamespace => SoapEnvelopeNamespaceUri; protected override string SoapName => "soap"; protected override string GetContentType(WebServiceTarget target) { return string.Concat("text/xml", "; ", base.GetContentType(target)); } protected override void InitRequest(HttpWebRequest request) { base.InitRequest(request); if (Target.Headers?.Count == 0 || string.IsNullOrEmpty(request.Headers["SOAPAction"])) request.Headers["SOAPAction"] = _defaultSoapAction; } } private class HttpPostSoap12Formatter : HttpPostSoapFormatterBase { public HttpPostSoap12Formatter(WebServiceTarget target) : base(target) { } protected override string SoapEnvelopeNamespace => Soap12EnvelopeNamespaceUri; protected override string SoapName => "soap12"; protected override string GetContentType(WebServiceTarget target) { return GetContentTypeSoap12(target, GetDefaultSoapAction(target)); } protected override void InitRequest(HttpWebRequest request) { base.InitRequest(request); string nonDefaultSoapAction = Target.Headers?.Count > 0 ? request.Headers["SOAPAction"] : string.Empty; if (!string.IsNullOrEmpty(nonDefaultSoapAction)) request.ContentType = GetContentTypeSoap12(Target, nonDefaultSoapAction); } private string GetContentTypeSoap12(WebServiceTarget target, string soapAction) { return string.Concat("application/soap+xml", "; ", base.GetContentType(target), "; action=\"", soapAction, "\""); } } private abstract class HttpPostSoapFormatterBase : HttpPostXmlFormatterBase { private readonly XmlWriterSettings _xmlWriterSettings; protected HttpPostSoapFormatterBase(WebServiceTarget target) : base(target) { _xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding }; } protected abstract string SoapEnvelopeNamespace { get; } protected abstract string SoapName { get; } protected override void WriteContent(MemoryStream ms, object[] parameterValues) { XmlWriter xtw = XmlWriter.Create(ms, _xmlWriterSettings); xtw.WriteStartElement(SoapName, "Envelope", SoapEnvelopeNamespace); xtw.WriteStartElement("Body", SoapEnvelopeNamespace); xtw.WriteStartElement(Target.MethodName, Target.Namespace); WriteAllParametersToCurrenElement(xtw, parameterValues); xtw.WriteEndElement(); // method name xtw.WriteEndElement(); // Body xtw.WriteEndElement(); // soap:Envelope xtw.Flush(); } protected static string GetDefaultSoapAction(WebServiceTarget target) { return target.Namespace.EndsWith("/", StringComparison.Ordinal) ? string.Concat(target.Namespace, target.MethodName) : string.Concat(target.Namespace, "/", target.MethodName); } } private abstract class HttpPostTextFormatterBase : HttpPostFormatterBase { readonly ReusableBuilderCreator _reusableStringBuilder = new ReusableBuilderCreator(); readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(1024); readonly byte[] _encodingPreamble; protected HttpPostTextFormatterBase(WebServiceTarget target) : base(target) { _encodingPreamble = target.Encoding.GetPreamble(); } protected override void WriteContent(MemoryStream ms, object[] parameterValues) { lock (_reusableStringBuilder) { using (var targetBuilder = _reusableStringBuilder.Allocate()) { WriteStringContent(targetBuilder.Result, parameterValues); using (var transformBuffer = _reusableEncodingBuffer.Allocate()) { if (_encodingPreamble.Length > 0) ms.Write(_encodingPreamble, 0, _encodingPreamble.Length); targetBuilder.Result.CopyToStream(ms, Target.Encoding, transformBuffer.Result); } } } } protected abstract void WriteStringContent(StringBuilder builder, object[] parameterValues); } private class HttpPostXmlDocumentFormatter : HttpPostXmlFormatterBase { private readonly XmlWriterSettings _xmlWriterSettings; public HttpPostXmlDocumentFormatter(WebServiceTarget target) : base(target) { if (string.IsNullOrEmpty(target.XmlRoot)) throw new InvalidOperationException("WebServiceProtocol.Xml requires WebServiceTarget.XmlRoot to be set."); _xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding, OmitXmlDeclaration = true, Indent = false }; } protected override string GetContentType(WebServiceTarget target) { return string.Concat("application/xml", "; ", base.GetContentType(target)); } protected override void WriteContent(MemoryStream ms, object[] parameterValues) { XmlWriter xtw = XmlWriter.Create(ms, _xmlWriterSettings); xtw.WriteStartElement(Target.XmlRoot, Target.XmlRootNamespace); WriteAllParametersToCurrenElement(xtw, parameterValues); xtw.WriteEndElement(); xtw.Flush(); } } private abstract class HttpPostXmlFormatterBase : HttpPostFormatterBase { protected HttpPostXmlFormatterBase(WebServiceTarget target) : base(target) { } protected void WriteAllParametersToCurrenElement(XmlWriter currentXmlWriter, object[] parameterValues) { for (int i = 0; i < Target.Parameters.Count; i++) { string parameterValue = XmlHelper.XmlConvertToStringSafe(parameterValues[i]); currentXmlWriter.WriteElementString(Target.Parameters[i].Name, parameterValue); } } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands { /// <summary> /// Implements the start-transcript cmdlet. /// </summary> [Cmdlet(VerbsLifecycle.Start, "Transcript", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096485")] [OutputType(typeof(string))] public sealed class StartTranscriptCommand : PSCmdlet { /// <summary> /// The name of the file in which to write the transcript. If not provided, the file indicated by the variable /// $TRANSCRIPT is used. If neither the filename is supplied or $TRANSCRIPT is not set, the filename shall be $HOME/My /// Documents/PowerShell_transcript.YYYYMMDDmmss.txt. /// </summary> /// <value></value> [Parameter(Position = 0, ParameterSetName = "ByPath")] [ValidateNotNullOrEmpty] public string Path { get { return _outFilename; } set { _isFilenameSet = true; _outFilename = value; } } /// <summary> /// The literal name of the file in which to write the transcript. /// </summary> [Parameter(Position = 0, ParameterSetName = "ByLiteralPath")] [Alias("PSPath", "LP")] [ValidateNotNullOrEmpty] public string LiteralPath { get { return _outFilename; } set { _isFilenameSet = true; _outFilename = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// The literal name of the file in which to write the transcript. /// </summary> [Parameter(Position = 0, ParameterSetName = "ByOutputDirectory")] [ValidateNotNullOrEmpty] public string OutputDirectory { get; set; } /// <summary> /// Describes the current state of the activity. /// </summary> /// <value></value> [Parameter] public SwitchParameter Append { get { return _shouldAppend; } set { _shouldAppend = value; } } /// <summary> /// Property that sets force parameter. This will reset the read-only /// attribute on an existing file. /// </summary> /// <remarks> /// The read-only attribute will not be replaced when the transcript is done. /// </remarks> [Parameter()] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Property that prevents file overwrite. /// </summary> [Parameter()] [Alias("NoOverwrite")] public SwitchParameter NoClobber { get { return _noclobber; } set { _noclobber = value; } } private bool _noclobber; /// <summary> /// Whether to include command invocation time headers between commands. /// </summary> [Parameter()] public SwitchParameter IncludeInvocationHeader { get; set; } /// <summary> /// Gets or sets whether to use minimal transcript header. /// </summary> [Parameter] public SwitchParameter UseMinimalHeader { get; set; } /// <summary> /// Starts the transcription. /// </summary> protected override void BeginProcessing() { // If they haven't specified a path, figure out the correct output path. if (!_isFilenameSet) { // read the filename from $TRANSCRIPT object value = this.GetVariableValue("global:TRANSCRIPT", null); // $TRANSCRIPT is not set, so create a file name (the default: $HOME/My Documents/PowerShell_transcript.YYYYMMDDmmss.txt) if (value == null) { // If they've specified an output directory, use it. Otherwise, use "My Documents" if (OutputDirectory != null) { _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(OutputDirectory, false); _isLiteralPath = true; } else { _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(); } } else { _outFilename = (string)value; } } // Normalize outFilename here in case it is a relative path try { string effectiveFilePath = ResolveFilePath(Path, _isLiteralPath); if (!ShouldProcess(effectiveFilePath)) return; if (System.IO.File.Exists(effectiveFilePath)) { if (NoClobber && !Append) { string message = StringUtil.Format(TranscriptStrings.TranscriptFileExistsNoClobber, effectiveFilePath, "NoClobber"); // prevents localization Exception uae = new UnauthorizedAccessException(message); ErrorRecord errorRecord = new ErrorRecord( uae, "NoClobber", ErrorCategory.ResourceExists, effectiveFilePath); // NOTE: this call will throw ThrowTerminatingError(errorRecord); } System.IO.FileInfo fInfo = new System.IO.FileInfo(effectiveFilePath); if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // Save some disk write time by checking whether file is readonly.. if (Force) { // Make sure the file is not read only // Note that we will not clear the ReadOnly flag later fInfo.Attributes &= ~(FileAttributes.ReadOnly); } else { string errorMessage = string.Format( System.Globalization.CultureInfo.CurrentCulture, TranscriptStrings.TranscriptFileReadOnly, effectiveFilePath); Exception innerException = new ArgumentException(errorMessage); ThrowTerminatingError(new ErrorRecord(innerException, "FileReadOnly", ErrorCategory.InvalidArgument, effectiveFilePath)); } } // If they didn't specify -Append, empty the file if (!_shouldAppend) { System.IO.File.WriteAllText(effectiveFilePath, string.Empty); } } System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = this.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool(), UseMinimalHeader.IsPresent); // ch.StartTranscribing(effectiveFilePath, Append); // NTRAID#Windows Out Of Band Releases-931008-2006/03/21 // Previous behavior was to write this even if ShouldProcess // returned false. Why would we want that? PSObject outputObject = new PSObject( StringUtil.Format(TranscriptStrings.TranscriptionStarted, Path)); outputObject.Properties.Add(new PSNoteProperty("Path", Path)); WriteObject(outputObject); } catch (Exception e) { try { Host.UI.StopTranscribing(); } catch { } string errorMessage = string.Format( System.Globalization.CultureInfo.CurrentCulture, TranscriptStrings.CannotStartTranscription, e.Message); ErrorRecord er = new ErrorRecord( PSTraceSource.NewInvalidOperationException(e, errorMessage), "CannotStartTranscription", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } } /// resolve a user provided file name or path (including globbing characters) /// to a fully qualified file path, using the file system provider private string ResolveFilePath(string filePath, bool isLiteralPath) { string path = null; try { if (isLiteralPath) { path = SessionState.Path.GetUnresolvedProviderPathFromPSPath(filePath); } else { ProviderInfo provider = null; Collection<string> filePaths = SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider); if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { ReportWrongProviderType(provider.FullName); } if (filePaths.Count > 1) { ReportMultipleFilesNotSupported(); } path = filePaths[0]; } } catch (ItemNotFoundException) { path = null; } if (string.IsNullOrEmpty(path)) { CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(this); ProviderInfo provider = null; PSDriveInfo drive = null; path = SessionState.Path.GetUnresolvedProviderPathFromPSPath( filePath, cmdletProviderContext, out provider, out drive); cmdletProviderContext.ThrowFirstErrorOrDoNothing(); if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { ReportWrongProviderType(provider.FullName); } } return path; } private void ReportWrongProviderType(string providerId) { ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewInvalidOperationException(TranscriptStrings.ReadWriteFileNotFileSystemProvider, providerId), "ReadWriteFileNotFileSystemProvider", ErrorCategory.InvalidArgument, null); ThrowTerminatingError(errorRecord); } private void ReportMultipleFilesNotSupported() { ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewInvalidOperationException(TranscriptStrings.MultipleFilesNotSupported), "MultipleFilesNotSupported", ErrorCategory.InvalidArgument, null); ThrowTerminatingError(errorRecord); } private bool _shouldAppend; private string _outFilename; private bool _isFilenameSet; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents an operation between an expression and a type. /// </summary> [DebuggerTypeProxy(typeof(Expression.TypeBinaryExpressionProxy))] public sealed class TypeBinaryExpression : Expression { private readonly Expression _expression; private readonly Type _typeOperand; private readonly ExpressionType _nodeKind; internal TypeBinaryExpression(Expression expression, Type typeOperand, ExpressionType nodeKind) { _expression = expression; _typeOperand = typeOperand; _nodeKind = nodeKind; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return typeof(bool); } } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get { return _nodeKind; } } /// <summary> /// Gets the expression operand of a type test operation. /// </summary> public Expression Expression { get { return _expression; } } /// <summary> /// Gets the type operand of a type test operation. /// </summary> public Type TypeOperand { get { return _typeOperand; } } #region Reduce TypeEqual internal Expression ReduceTypeEqual() { Type cType = Expression.Type; if (cType.GetTypeInfo().IsValueType) { if (cType.IsNullableType()) { // If the expression type is a a nullable type, it will match if // the value is not null and the type operand // either matches or is its type argument (T to its T?). if (cType.GetNonNullableType() != _typeOperand.GetNonNullableType()) { return Expression.Block(Expression, Expression.Constant(false)); } else { return Expression.NotEqual(Expression, Expression.Constant(null, Expression.Type)); } } else { // For other value types (including Void), we can // determine the result now return Expression.Block(Expression, Expression.Constant(cType == _typeOperand.GetNonNullableType())); } } Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(object), Expression.Type), "Expecting reference types only after this point."); // Can check the value right now for constants. if (Expression.NodeType == ExpressionType.Constant) { return ReduceConstantTypeEqual(); } // expression is a ByVal parameter. Can safely reevaluate. var parameter = Expression as ParameterExpression; if (parameter != null && !parameter.IsByRef) { return ByValParameterTypeEqual(parameter); } // Create a temp so we only evaluate the left side once parameter = Expression.Parameter(typeof(object)); return Expression.Block( new[] { parameter }, Expression.Assign(parameter, Expression), ByValParameterTypeEqual(parameter) ); } // Helper that is used when re-eval of LHS is safe. private Expression ByValParameterTypeEqual(ParameterExpression value) { Expression getType = Expression.Call(value, typeof(object).GetMethod("GetType")); // In remoting scenarios, obj.GetType() can return an interface. // But JIT32's optimized "obj.GetType() == typeof(ISomething)" codegen, // causing it to always return false. // We workaround this optimization by generating different, less optimal IL // if TypeOperand is an interface. if (_typeOperand.GetTypeInfo().IsInterface) { var temp = Expression.Parameter(typeof(Type)); getType = Expression.Block(new[] { temp }, Expression.Assign(temp, getType), temp); } // We use reference equality when comparing to null for correctness // (don't invoke a user defined operator), and reference equality // on types for performance (so the JIT can optimize the IL). return Expression.AndAlso( Expression.ReferenceNotEqual(value, Expression.Constant(null)), Expression.ReferenceEqual( getType, Expression.Constant(_typeOperand.GetNonNullableType(), typeof(Type)) ) ); } private Expression ReduceConstantTypeEqual() { ConstantExpression ce = Expression as ConstantExpression; //TypeEqual(null, T) always returns false. if (ce.Value == null) { return Expression.Constant(false); } else { return Expression.Constant(_typeOperand.GetNonNullableType() == ce.Value.GetType()); } } #endregion /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitTypeBinary(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expression">The <see cref="Expression" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public TypeBinaryExpression Update(Expression expression) { if (expression == Expression) { return this; } if (NodeType == ExpressionType.TypeIs) { return Expression.TypeIs(expression, TypeOperand); } return Expression.TypeEqual(expression, TypeOperand); } } public partial class Expression { /// <summary> /// Creates a <see cref="TypeBinaryExpression"/>. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeIs"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeIs(Expression expression, Type type) { RequiresCanRead(expression, nameof(expression)); ContractUtils.RequiresNotNull(type, nameof(type)); if (type.IsByRef) throw Error.TypeMustNotBeByRef(nameof(type)); return new TypeBinaryExpression(expression, type, ExpressionType.TypeIs); } /// <summary> /// Creates a <see cref="TypeBinaryExpression"/> that compares run-time type identity. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeEqual"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeEqual(Expression expression, Type type) { RequiresCanRead(expression, nameof(expression)); ContractUtils.RequiresNotNull(type, nameof(type)); if (type.IsByRef) throw Error.TypeMustNotBeByRef(nameof(type)); return new TypeBinaryExpression(expression, type, ExpressionType.TypeEqual); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Collections.Generic; using Windows.Foundation.Metadata; using Windows.Graphics.Printing; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Printing; namespace PrintSample { /// <summary> /// This class customizes the standard PrintHelper in order to disable print preview. /// </summary> /// <remarks> /// The PrintTaskRequestedMethod sets printTask.IsPreviewEnabled to false in order /// to disable print preview. /// Since print preview is disabled, the Paginate event will not be raised. /// Instead, the pages to be printed are generated in response to the AddPages event. /// </remarks> class DisablePreviewPrintHelper : PrintHelper { /// <summary> /// A list of UIElements used to store the print pages. This gives easy access /// to any desired print page. /// </summary> internal List<UIElement> printPages; public DisablePreviewPrintHelper(Page scenarioPage) : base(scenarioPage) { printPages = new List<UIElement>(); } /// <summary> /// This is the event handler for PrintManager.PrintTaskRequested. /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified by PrintTaskRequestedEventArgs.Request.Deadline. /// Therefore, we use this handler to only create the print task. /// The print settings customization can be done when the print document source is requested. /// </summary> /// <param name="sender">PrintManager</param> /// <param name="e">PrintTaskRequestedEventArgs</param> protected override void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e) { PrintTask printTask = null; printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", sourceRequestedArgs => { // Print Task event handler is invoked when the print job is completed. printTask.Completed += async (s, args) => { // Notify the user when the print operation fails. if (args.Completion == PrintTaskCompletion.Failed) { await scenarioPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { MainPage.Current.NotifyUser("Failed to print.", NotifyType.ErrorMessage); }); } }; sourceRequestedArgs.SetSource(printDocumentSource); }); // Choose not to show the preview by setting the property on PrintTask printTask.IsPreviewEnabled = false; } /// <summary> /// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of /// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements /// into a pages that the Windows print system can deal with. /// </summary> /// <param name="sender">PrintDocument</param> /// <param name="e">Add page event arguments containing a print task options reference</param> protected override void AddPrintPages(object sender, AddPagesEventArgs e) { // Clear the cache of print pages printPages.Clear(); // Clear the print canvas of print pages PrintCanvas.Children.Clear(); // This variable keeps track of the last RichTextBlockOverflow element that was added to a page which will be printed RichTextBlockOverflow lastRTBOOnPage; // Get the PrintTaskOptions PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions); // Get the page description to deterimine how big the page is PrintPageDescription pageDescription = printingOptions.GetPageDescription(0); // We know there is at least one page to be printed. passing null as the first parameter to // AddOnePrintPage tells the function to add the first page. lastRTBOOnPage = AddOnePrintPage(null, pageDescription); // We know there are more pages to be added as long as the last RichTextBoxOverflow added to a print // page has extra content while (lastRTBOOnPage.HasOverflowContent && (lastRTBOOnPage.Visibility == Windows.UI.Xaml.Visibility.Visible)) { lastRTBOOnPage = AddOnePrintPage(lastRTBOOnPage, pageDescription); } // Loop over all of the pages and add each one to add each page to be printed for (int i = 0; i < printPages.Count; i++) { // We should have all pages ready at this point... printDocument.AddPage(printPages[i]); } PrintDocument printDoc = (PrintDocument)sender; // Indicate that all of the print pages have been provided printDoc.AddPagesComplete(); } /// <summary> /// This function creates and adds one print page to the internal cache of print pages /// pages stored in printPages. /// </summary> /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param> /// <param name="printPageDescription">Printer's page description</param> protected RichTextBlockOverflow AddOnePrintPage(RichTextBlockOverflow lastRTBOAdded, PrintPageDescription printPageDescription) { // XAML element that is used to represent to "printing page" FrameworkElement page; // The link container for text overflowing in this page RichTextBlockOverflow textLink; // Check if this is the first page ( no previous RichTextBlockOverflow) if (lastRTBOAdded == null) { // If this is the first page add the specific scenario content page = firstPage; // Hide footer since we don't know yet if it will be displayed (this might not be the last page) - wait for layout StackPanel footer = (StackPanel)page.FindName("Footer"); footer.Visibility = Visibility.Collapsed; } else { // Flow content (text) from previous pages page = new ContinuationPage(lastRTBOAdded); } // Set "paper" width page.Width = printPageDescription.PageSize.Width; page.Height = printPageDescription.PageSize.Height; Grid printableArea = (Grid)page.FindName("PrintableArea"); // Get the margins size // If the ImageableRect is smaller than the app provided margins use the ImageableRect double marginWidth = Math.Max(printPageDescription.PageSize.Width - printPageDescription.ImageableRect.Width, printPageDescription.PageSize.Width * ApplicationContentMarginLeft * 2); double marginHeight = Math.Max(printPageDescription.PageSize.Height - printPageDescription.ImageableRect.Height, printPageDescription.PageSize.Height * ApplicationContentMarginTop * 2); // Set-up "printable area" on the "paper" printableArea.Width = firstPage.Width - marginWidth; printableArea.Height = firstPage.Height - marginHeight; // Add the (newly created) page to the print canvas which is part of the visual tree and force it to go // through layout so that the linked containers correctly distribute the content inside them. PrintCanvas.Children.Add(page); PrintCanvas.InvalidateMeasure(); PrintCanvas.UpdateLayout(); // Find the last text container and see if the content is overflowing textLink = (RichTextBlockOverflow)page.FindName("ContinuationPageLinkedContainer"); // Check if this is the last page if ((!textLink.HasOverflowContent) && (textLink.Visibility == Windows.UI.Xaml.Visibility.Visible)) { StackPanel footer = (StackPanel)page.FindName("Footer"); footer.Visibility = Visibility.Visible; PrintCanvas.UpdateLayout(); } // Add the page to the print page collection printPages.Add(page); return textLink; } } /// <summary> /// Scenario that demos how to disable the print preview in the Modern Print Dialog window. /// </summary> public sealed partial class Scenario6DisablePreview : Page { private DisablePreviewPrintHelper printHelper; public Scenario6DisablePreview() { this.InitializeComponent(); } /// <summary> /// This is the click handler for the 'Print' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void OnPrintButtonClick(object sender, RoutedEventArgs e) { await printHelper.ShowPrintUIAsync(); } protected override void OnNavigatedTo(NavigationEventArgs e) { if (PrintManager.IsSupported()) { // Tell the user how to print MainPage.Current.NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType.StatusMessage); } else { // Remove the print button InvokePrintingButton.Visibility = Visibility.Collapsed; // Inform user that Printing is not supported MainPage.Current.NotifyUser("Printing is not supported.", NotifyType.ErrorMessage); // Printing-related event handlers will never be called if printing // is not supported, but it's okay to register for them anyway. } // Initalize common helper class and register for printing printHelper = new DisablePreviewPrintHelper(this); printHelper.RegisterForPrinting(); // Initialize print content for this scenario printHelper.PreparePrintContent(new PageToPrint()); } protected override void OnNavigatedFrom(NavigationEventArgs e) { if (printHelper != null) { printHelper.UnregisterForPrinting(); } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the SysProvincium class. /// </summary> [Serializable] public partial class SysProvinciumCollection : ActiveList<SysProvincium, SysProvinciumCollection> { public SysProvinciumCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysProvinciumCollection</returns> public SysProvinciumCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysProvincium o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_Provincia table. /// </summary> [Serializable] public partial class SysProvincium : ActiveRecord<SysProvincium>, IActiveRecord { #region .ctors and Default Settings public SysProvincium() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysProvincium(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysProvincium(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysProvincium(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_Provincia", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdProvincia = new TableSchema.TableColumn(schema); colvarIdProvincia.ColumnName = "idProvincia"; colvarIdProvincia.DataType = DbType.Int32; colvarIdProvincia.MaxLength = 0; colvarIdProvincia.AutoIncrement = true; colvarIdProvincia.IsNullable = false; colvarIdProvincia.IsPrimaryKey = true; colvarIdProvincia.IsForeignKey = false; colvarIdProvincia.IsReadOnly = false; colvarIdProvincia.DefaultSetting = @""; colvarIdProvincia.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdProvincia); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 100; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarIdPais = new TableSchema.TableColumn(schema); colvarIdPais.ColumnName = "idPais"; colvarIdPais.DataType = DbType.Int32; colvarIdPais.MaxLength = 0; colvarIdPais.AutoIncrement = false; colvarIdPais.IsNullable = false; colvarIdPais.IsPrimaryKey = false; colvarIdPais.IsForeignKey = false; colvarIdPais.IsReadOnly = false; colvarIdPais.DefaultSetting = @""; colvarIdPais.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPais); TableSchema.TableColumn colvarCodigoINDEC = new TableSchema.TableColumn(schema); colvarCodigoINDEC.ColumnName = "codigoINDEC"; colvarCodigoINDEC.DataType = DbType.String; colvarCodigoINDEC.MaxLength = 100; colvarCodigoINDEC.AutoIncrement = false; colvarCodigoINDEC.IsNullable = true; colvarCodigoINDEC.IsPrimaryKey = false; colvarCodigoINDEC.IsForeignKey = false; colvarCodigoINDEC.IsReadOnly = false; colvarCodigoINDEC.DefaultSetting = @""; colvarCodigoINDEC.ForeignKeyTableName = ""; schema.Columns.Add(colvarCodigoINDEC); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_Provincia",schema); } } #endregion #region Props [XmlAttribute("IdProvincia")] [Bindable(true)] public int IdProvincia { get { return GetColumnValue<int>(Columns.IdProvincia); } set { SetColumnValue(Columns.IdProvincia, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("IdPais")] [Bindable(true)] public int IdPais { get { return GetColumnValue<int>(Columns.IdPais); } set { SetColumnValue(Columns.IdPais, value); } } [XmlAttribute("CodigoINDEC")] [Bindable(true)] public string CodigoINDEC { get { return GetColumnValue<string>(Columns.CodigoINDEC); } set { SetColumnValue(Columns.CodigoINDEC, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.SysParentescoCollection colSysParentescoRecords; public DalSic.SysParentescoCollection SysParentescoRecords { get { if(colSysParentescoRecords == null) { colSysParentescoRecords = new DalSic.SysParentescoCollection().Where(SysParentesco.Columns.IdProvincia, IdProvincia).Load(); colSysParentescoRecords.ListChanged += new ListChangedEventHandler(colSysParentescoRecords_ListChanged); } return colSysParentescoRecords; } set { colSysParentescoRecords = value; colSysParentescoRecords.ListChanged += new ListChangedEventHandler(colSysParentescoRecords_ListChanged); } } void colSysParentescoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysParentescoRecords[e.NewIndex].IdProvincia = IdProvincia; } } private DalSic.SysPacienteCollection colSysPacienteRecords; public DalSic.SysPacienteCollection SysPacienteRecords { get { if(colSysPacienteRecords == null) { colSysPacienteRecords = new DalSic.SysPacienteCollection().Where(SysPaciente.Columns.IdProvincia, IdProvincia).Load(); colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged); } return colSysPacienteRecords; } set { colSysPacienteRecords = value; colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged); } } void colSysPacienteRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysPacienteRecords[e.NewIndex].IdProvincia = IdProvincia; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre,int varIdPais,string varCodigoINDEC) { SysProvincium item = new SysProvincium(); item.Nombre = varNombre; item.IdPais = varIdPais; item.CodigoINDEC = varCodigoINDEC; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdProvincia,string varNombre,int varIdPais,string varCodigoINDEC) { SysProvincium item = new SysProvincium(); item.IdProvincia = varIdProvincia; item.Nombre = varNombre; item.IdPais = varIdPais; item.CodigoINDEC = varCodigoINDEC; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdProvinciaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdPaisColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn CodigoINDECColumn { get { return Schema.Columns[3]; } } #endregion #region Columns Struct public struct Columns { public static string IdProvincia = @"idProvincia"; public static string Nombre = @"nombre"; public static string IdPais = @"idPais"; public static string CodigoINDEC = @"codigoINDEC"; } #endregion #region Update PK Collections public void SetPKValues() { if (colSysParentescoRecords != null) { foreach (DalSic.SysParentesco item in colSysParentescoRecords) { if (item.IdProvincia != IdProvincia) { item.IdProvincia = IdProvincia; } } } if (colSysPacienteRecords != null) { foreach (DalSic.SysPaciente item in colSysPacienteRecords) { if (item.IdProvincia != IdProvincia) { item.IdProvincia = IdProvincia; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colSysParentescoRecords != null) { colSysParentescoRecords.SaveAll(); } if (colSysPacienteRecords != null) { colSysPacienteRecords.SaveAll(); } } #endregion } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using Gallio.Icarus.Models; using Gallio.Icarus.Models.TestTreeNodes; using Gallio.Icarus.Projects; using Gallio.Icarus.Utilities; using Gallio.Model; using Gallio.UI.Common.Synchronization; using SortOrder = Gallio.Icarus.Models.SortOrder; namespace Gallio.Icarus.TestExplorer { internal partial class TestExplorerView : UserControl { private readonly ITestExplorerController testExplorerController; private readonly ITestExplorerModel testExplorerModel; private bool updateFlag; public TestExplorerView(ITestExplorerController testExplorerController, ITestExplorerModel testExplorerModel) { this.testExplorerController = testExplorerController; this.testExplorerModel = testExplorerModel; InitializeComponent(); } protected override void OnLoad(EventArgs eventArgs) { SetupColors(); SetupTreeViewCategories(); testTree.Model = testExplorerModel.TreeModel; EventHandler testExplorerControllerOnRestoreState = (s, e) => RestoreState(); testExplorerController.RestoreState += testExplorerControllerOnRestoreState; Disposed += (s, e) => { testExplorerController.RestoreState -= testExplorerControllerOnRestoreState; }; PropertyChangedEventHandler canEditTreeOnPropertyChanged = (s, e) => testTree.SetEditEnabled(testExplorerModel.CanEditTree); testExplorerModel.CanEditTree.PropertyChanged += canEditTreeOnPropertyChanged; Disposed += (s, e) => { testExplorerModel.CanEditTree.PropertyChanged -= canEditTreeOnPropertyChanged; }; SetupFilters(); SetupSorting(); EventHandler testExplorerControllerOnSaveState = (s, e) => SaveState(); testExplorerController.SaveState += testExplorerControllerOnSaveState; Disposed += (s, e) => { testExplorerController.SaveState -= testExplorerControllerOnSaveState; }; base.OnLoad(eventArgs); } private void SetupColors() { testTree.SetPassedColor(testExplorerModel.PassedColor); testTree.SetFailedColor(testExplorerModel.FailedColor); testTree.SetInconclusiveColor(testExplorerModel.InconclusiveColor); testTree.SetSkippedColor(testExplorerModel.SkippedColor); PropertyChangedEventHandler passedColorOnPropertyChanged = (s, e) => testTree.SetPassedColor(testExplorerModel.PassedColor); PropertyChangedEventHandler failedColorOnPropertyChanged = (s, e) => testTree.SetFailedColor(testExplorerModel.FailedColor); PropertyChangedEventHandler inconclusiveColorOnPropertyChanged = (s, e) => testTree.SetInconclusiveColor(testExplorerModel.InconclusiveColor); PropertyChangedEventHandler skippedColorOnPropertyChanged = (s, e) => testTree.SetSkippedColor(testExplorerModel.SkippedColor); testExplorerModel.PassedColor.PropertyChanged += passedColorOnPropertyChanged; testExplorerModel.FailedColor.PropertyChanged += failedColorOnPropertyChanged; testExplorerModel.InconclusiveColor.PropertyChanged += inconclusiveColorOnPropertyChanged; testExplorerModel.SkippedColor.PropertyChanged += skippedColorOnPropertyChanged; Disposed += (s, e) => { testExplorerModel.PassedColor.PropertyChanged -= passedColorOnPropertyChanged; testExplorerModel.FailedColor.PropertyChanged -= failedColorOnPropertyChanged; testExplorerModel.InconclusiveColor.PropertyChanged -= inconclusiveColorOnPropertyChanged; testExplorerModel.SkippedColor.PropertyChanged -= skippedColorOnPropertyChanged; }; } private void SetupTreeViewCategories() { updateFlag = true; treeViewComboBox.ComboBox.DataSource = testExplorerModel.TreeViewCategories.Value; updateFlag = false; PropertyChangedEventHandler currentTreeViewCategoryOnPropertyChanged = (s, e) => treeViewComboBox.ComboBox.SelectedItem = testExplorerModel.CurrentTreeViewCategory.Value; testExplorerModel.CurrentTreeViewCategory.PropertyChanged += currentTreeViewCategoryOnPropertyChanged; treeViewComboBox.ComboBox.SelectedItem = testExplorerModel.CurrentTreeViewCategory.Value ?? UserOptions.DefaultTreeViewCategory; PropertyChangedEventHandler treeViewCategoriesOnPropertyChanged = (s, e) => { updateFlag = true; treeViewComboBox.ComboBox.DataSource = testExplorerModel.TreeViewCategories.Value; updateFlag = false; }; testExplorerModel.TreeViewCategories.PropertyChanged += treeViewCategoriesOnPropertyChanged; Disposed += (s, e) => { testExplorerModel.CurrentTreeViewCategory.PropertyChanged -= currentTreeViewCategoryOnPropertyChanged; testExplorerModel.TreeViewCategories.PropertyChanged -= treeViewCategoriesOnPropertyChanged; }; } private void SetupSorting() { EventHandler sortAscToolStripButtonOnClick = (s, e) => SortTree(SortOrder.Ascending); EventHandler sortDescToolStripButtonOnClick = (s, e) => SortTree(SortOrder.Descending); sortAscToolStripButton.Click += sortAscToolStripButtonOnClick; sortDescToolStripButton.Click += sortDescToolStripButtonOnClick; Disposed += (s, e) => { sortAscToolStripButton.Click -= sortAscToolStripButtonOnClick; sortDescToolStripButton.Click -= sortDescToolStripButtonOnClick; }; } private void SetupFilters() { SetupPassedFilters(); SetupFailedFilters(); SetupInconclusiveFilters(); } private void SetupPassedFilters() { EventHandler filterPassedTestsToolStripMenuItemOnClick = (s, e) => FilterStatus(TestStatus.Passed); filterPassedTestsToolStripMenuItem.Click += filterPassedTestsToolStripMenuItemOnClick; filterPassedTestsToolStripButton.Click += filterPassedTestsToolStripMenuItemOnClick; PropertyChangedEventHandler filterPassedOnPropertyChanged = (s, e) => { filterPassedTestsToolStripMenuItem.Checked = filterPassedTestsToolStripButton.Checked = testExplorerModel.FilterPassed.Value; }; testExplorerModel.FilterPassed.PropertyChanged += filterPassedOnPropertyChanged; Disposed += (s, e) => { filterPassedTestsToolStripMenuItem.Click -= filterPassedTestsToolStripMenuItemOnClick; filterPassedTestsToolStripButton.Click -= filterPassedTestsToolStripMenuItemOnClick; testExplorerModel.FilterPassed.PropertyChanged -= filterPassedOnPropertyChanged; }; } private void SetupFailedFilters() { EventHandler filterFailedTestsToolStripMenuItemOnClick = (s, e) => FilterStatus(TestStatus.Failed); filterFailedTestsToolStripMenuItem.Click += filterFailedTestsToolStripMenuItemOnClick; filterFailedTestsToolStripButton.Click += filterFailedTestsToolStripMenuItemOnClick; PropertyChangedEventHandler filterFailedOnPropertyChanged = (s, e) => { filterFailedTestsToolStripMenuItem.Checked = filterFailedTestsToolStripButton.Checked = testExplorerModel.FilterFailed.Value; }; testExplorerModel.FilterFailed.PropertyChanged += filterFailedOnPropertyChanged; Disposed += (s, e) => { filterFailedTestsToolStripMenuItem.Click -= filterFailedTestsToolStripMenuItemOnClick; filterFailedTestsToolStripButton.Click -= filterFailedTestsToolStripMenuItemOnClick; testExplorerModel.FilterFailed.PropertyChanged -= filterFailedOnPropertyChanged; }; } private void SetupInconclusiveFilters() { EventHandler filterInconclusiveTestsToolStripMenuItemOnClick = (s, e) => FilterStatus(TestStatus.Inconclusive); filterInconclusiveTestsToolStripMenuItem.Click += filterInconclusiveTestsToolStripMenuItemOnClick; filterInconclusiveTestsToolStripButton.Click += filterInconclusiveTestsToolStripMenuItemOnClick; PropertyChangedEventHandler filterInconclusiveOnPropertyChanged = (s, e) => { filterInconclusiveTestsToolStripMenuItem.Checked = filterInconclusiveTestsToolStripButton.Checked = testExplorerModel.FilterInconclusive.Value; }; testExplorerModel.FilterInconclusive.PropertyChanged += filterInconclusiveOnPropertyChanged; Disposed += (s, e) => { filterInconclusiveTestsToolStripMenuItem.Click -= filterInconclusiveTestsToolStripMenuItemOnClick; filterInconclusiveTestsToolStripButton.Click -= filterInconclusiveTestsToolStripMenuItemOnClick; testExplorerModel.FilterInconclusive.PropertyChanged -= filterInconclusiveOnPropertyChanged; }; } private void FilterStatus(TestStatus testStatus) { testExplorerController.FilterStatus(testStatus); } private void SortTree(SortOrder sortOrder) { sortAscToolStripButton.Checked = (sortOrder == SortOrder.Ascending); sortDescToolStripButton.Checked = (sortOrder == SortOrder.Descending); testExplorerController.SortTree(sortOrder); } private void removeFileToolStripMenuItem_Click(object sender, EventArgs e) { if (testTree.SelectedNode == null || !(testTree.SelectedNode.Tag is TestDataNode)) return; var node = (TestDataNode)testTree.SelectedNode.Tag; if (node.FileName != null) { testExplorerController.RemoveFile(node.FileName); } } private void treeViewComboBox_SelectedIndexChanged(object sender, EventArgs e) { var newValue = (string)treeViewComboBox.SelectedItem; if (testExplorerModel.CurrentTreeViewCategory == newValue) return; // if updateFlag is set, then the index has changed because // we are populating the list, so no need to refresh! if (updateFlag) return; SaveState(); testExplorerController.ChangeTreeCategory(newValue, pm => RestoreState()); } private void resetTestsMenuItem_Click(object sender, EventArgs e) { testExplorerController.ResetTests(); } private void expandAllMenuItem_Click(object sender, EventArgs e) { testTree.ExpandAll(); } private void collapseAllMenuItem_Click(object sender, EventArgs e) { testTree.CollapseAll(); } private void viewSourceCodeToolStripMenuItem_Click(object sender, EventArgs e) { ViewSourceCode(); } private void ViewSourceCode() { if (testTree.SelectedNode == null || !(testTree.SelectedNode.Tag is TestTreeNode)) return; var node = (TestTreeNode)testTree.SelectedNode.Tag; testExplorerController.ShowSourceCode(node.Id); } private void expandPassedTestsToolStripMenuItem_Click(object sender, EventArgs e) { testTree.Expand(TestStatus.Passed); } private void expandFailedTestsToolStripMenuItem_Click(object sender, EventArgs e) { testTree.Expand(TestStatus.Failed); } private void expandInconclusiveTestsToolStripMenuItem_Click(object sender, EventArgs e) { testTree.Expand(TestStatus.Inconclusive); } private void addFilesToolStripMenuItem_Click(object sender, EventArgs e) { using (var openFileDialog = Dialogs.CreateAddFilesDialog()) { if (openFileDialog.ShowDialog(this) != DialogResult.OK) return; testExplorerController.AddFiles(openFileDialog.FileNames); } } private void removeAllFilesToolStripMenuItem_Click(object sender, EventArgs e) { testExplorerController.RemoveAllFiles(); } private void testTree_SelectionChanged(object sender, EventArgs e) { SyncContext.Post(cb => TreeSelectionChanged(), null); } private void TreeSelectionChanged() { var nodes = new List<TestTreeNode>(); if (testTree.SelectedNode != null && testTree.SelectedNode.Tag is TestDataNode) { var testTreeNode = (TestDataNode)testTree.SelectedNode.Tag; removeFileToolStripMenuItem.Enabled = testTreeNode.FileName != null; viewSourceCodeToolStripMenuItem.Enabled = testTreeNode.SourceCodeAvailable; nodes.AddRange(GetSelectedNodes(testTreeNode)); } else { removeFileToolStripMenuItem.Enabled = false; viewSourceCodeToolStripMenuItem.Enabled = false; } testExplorerController.SetTreeSelection(nodes); } private static IEnumerable<TestTreeNode> GetSelectedNodes(TestTreeNode testTreeNode) { var nodes = new List<TestTreeNode>(); if (testTreeNode is NamespaceNode) { nodes.AddRange(((NamespaceNode)testTreeNode).GetChildren()); } else { nodes.Add(testTreeNode); } return nodes; } private void SaveState() { var collapsedNodes = testTree.GetCollapsedNodes(); testExplorerController.SetCollapsedNodes(collapsedNodes); } private void RestoreState() { testTree.CollapseNodes(testExplorerModel.CollapsedNodes.Value); } private void testTree_DoubleClick(object sender, EventArgs e) { ViewSourceCode(); } private void selectFailedToolStripMenuItem_Click(object sender, EventArgs e) { testTree.Select(TestStatus.Failed); } private void selectPassedToolStripMenuItem_Click(object sender, EventArgs e) { testTree.Select(TestStatus.Passed); } private void selectInconclusiveToolStripMenuItem_Click(object sender, EventArgs e) { testTree.Select(TestStatus.Inconclusive); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Collections.Generic; namespace OLEDB.Test.ModuleCore { public class CTestModule : CTestBase { //Data private string _clsid; private CTestCase _curtestcase; private int _pass = 0; private int _fail = 0; private int _skip = 0; public int PassCount { get { return _pass; } set { _pass = value; } } public int FailCount { get { return _fail; } set { _fail = value; } } public int SkipCount { get { return _skip; } set { _skip = value; } } //Constructors public CTestModule() : this(null, "Microsoft", 1) { } public CTestModule(string desc) : this(desc, "Microsoft", 1) { //Delegate } public CTestModule(string desc, string owner, int version) : base(desc) { _clsid = GetType().ToString(); //The attribute should take precedence if (this.Owner == null) this.Owner = owner; if (this.Version <= 0) this.Version = version; //Population DetermineIncludes(); DetermineChildren(); DetermineFilters(); } static CTestModule() { } //Accessors public new virtual TestModule Attribute { get { return (TestModule)base.Attribute; } set { base.Attribute = value; } } public string Owner { get { return Attribute.Owner; } set { Attribute.Owner = value; } } public string[] Owners { get { return Attribute.Owners; } set { Attribute.Owners = value; } } public int Version { get { return Attribute.Version; } set { Attribute.Version = value; } } public string Created { get { return Attribute.Created; } set { Attribute.Created = value; } } public string Modified { get { return Attribute.Modified; } set { Attribute.Modified = value; } } public override int Init(object o) { //Delegate int result = base.Init(o); return result; } public override int Terminate(object o) { //Delegate return base.Terminate(o); } //Helpers public void AddTestCase(CTestCase testcase) { //Delegate this.AddChild(testcase); } public virtual string GetCLSID() { return _clsid; } public virtual string GetOwnerName() { return Attribute.Owner; } public virtual int GetVersion() { return Attribute.Version; } public void SetErrorInterface(IError rIError) { //Delegate to our global object CError.Error = rIError; CError.WriteLine(); } public IError GetErrorInterface() { //Delegate to our global object return CError.Error; } public int GetCaseCount() { return Children.Count; } public ITestCases GetCase(int index) { return (ITestCases)Children[index]; } protected override CAttrBase CreateAttribute() { return new TestModule(); } protected override void DetermineChildren() { try { DetermineTestCases(); } catch (Exception e) { //Make this easier to debug Console.WriteLine(e); Common.Assert(false, e.ToString()); throw e; } } public virtual void DetermineTestCases() { //Default - no sort //int idPrev = Int32.MinValue; bool bSort = false; //Normally the reflection Type.GetMethods() api returns the methods in order //of how they appear in the code. But it will change that order depending //upon if there are virtual functions, which are returned first before other //non-virtual functions. Then there are also many times were people want multiple //source files, so its totally up the compiler on how it pulls in the files (*.cs). //So we have added the support of specifying an id=x, as an attribute so you can have //then sorted and displayed however your see fit. if (bSort) Children.Sort(/*Default sort is based upon IComparable of each item*/); } protected virtual void DetermineIncludes() { } protected virtual void DetermineFilters() { } protected virtual string FilterScope(string xpath) { //Basically we want to allow either simply filtering at the variation node (i.e.: no scope), //in which case we'll just add the 'assumed' scope, or allow filtering at any level. //We also want to be consistent with the XmlDriver in which all filters are predicates only. string varfilter = "//Variation[{0}]"; if (xpath != null) { xpath = xpath.Trim(); if (xpath.Length > 0) { //Add the Variation Scope, if no scope was specified if (xpath[0] != '/') xpath = string.Format(varfilter, xpath); } } return xpath; } public CTestCase CurTestCase { //Return the current test case: //Note: We do this so that within global functions (i.e.: at the module level) the user can //have know which test case/variation were in, without having to pass this state from //execute around get { return _curtestcase; } set { _curtestcase = value; } } public override tagVARIATION_STATUS Execute() { List<object> children = Children; if (children != null && children.Count > 0) { // this is not a leaf node, just invoke all the children's execute foreach (object child in children) { CTestCase tc = child as CTestCase; if (tc != null) { if (CModInfo.IsTestCaseSelected(tc.Name)) { Console.WriteLine("TestCase:{0} - {1}", tc.Attribute.Name, tc.Attribute.Desc); tc.Init(); tc.Execute(); } } } } Console.WriteLine("Pass:{0}, Fail:{1}, Skip:{2}", PassCount, FailCount, SkipCount); return tagVARIATION_STATUS.eVariationStatusPassed; } public override IEnumerable<XunitTestCase> TestCases() { List<object> children = Children; if (children != null && children.Count > 0) { foreach (object child in children) { CTestCase tc = child as CTestCase; if (tc != null) { if (CModInfo.IsTestCaseSelected(tc.Name)) { tc.Init(); foreach (XunitTestCase testCase in tc.TestCases()) { yield return testCase; } } } } } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G06_Country (editable child object).<br/> /// This is a generated base class of <see cref="G06_Country"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="G07_RegionObjects"/> of type <see cref="G07_RegionColl"/> (1:M relation to <see cref="G08_Region"/>)<br/> /// This class is an item of <see cref="G05_CountryColl"/> collection. /// </remarks> [Serializable] public partial class G06_Country : BusinessBase<G06_Country> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] private byte[] _rowVersion = new byte[] {}; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Countries ID"); /// <summary> /// Gets the Countries ID. /// </summary> /// <value>The Countries ID.</value> public int Country_ID { get { return GetProperty(Country_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Country_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Countries Name"); /// <summary> /// Gets or sets the Countries Name. /// </summary> /// <value>The Countries Name.</value> public string Country_Name { get { return GetProperty(Country_NameProperty); } set { SetProperty(Country_NameProperty, value); } } /// <summary> /// Maintains metadata about <see cref="ParentSubContinentID"/> property. /// </summary> public static readonly PropertyInfo<int> ParentSubContinentIDProperty = RegisterProperty<int>(p => p.ParentSubContinentID, "ParentSubContinentID"); /// <summary> /// Gets or sets the ParentSubContinentID. /// </summary> /// <value>The ParentSubContinentID.</value> public int ParentSubContinentID { get { return GetProperty(ParentSubContinentIDProperty); } set { SetProperty(ParentSubContinentIDProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G07_Country_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<G07_Country_Child> G07_Country_SingleObjectProperty = RegisterProperty<G07_Country_Child>(p => p.G07_Country_SingleObject, "G07 Country Single Object", RelationshipTypes.Child); /// <summary> /// Gets the G07 Country Single Object ("self load" child property). /// </summary> /// <value>The G07 Country Single Object.</value> public G07_Country_Child G07_Country_SingleObject { get { return GetProperty(G07_Country_SingleObjectProperty); } private set { LoadProperty(G07_Country_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G07_Country_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<G07_Country_ReChild> G07_Country_ASingleObjectProperty = RegisterProperty<G07_Country_ReChild>(p => p.G07_Country_ASingleObject, "G07 Country ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the G07 Country ASingle Object ("self load" child property). /// </summary> /// <value>The G07 Country ASingle Object.</value> public G07_Country_ReChild G07_Country_ASingleObject { get { return GetProperty(G07_Country_ASingleObjectProperty); } private set { LoadProperty(G07_Country_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G07_RegionObjects"/> property. /// </summary> public static readonly PropertyInfo<G07_RegionColl> G07_RegionObjectsProperty = RegisterProperty<G07_RegionColl>(p => p.G07_RegionObjects, "G07 Region Objects", RelationshipTypes.Child); /// <summary> /// Gets the G07 Region Objects ("self load" child property). /// </summary> /// <value>The G07 Region Objects.</value> public G07_RegionColl G07_RegionObjects { get { return GetProperty(G07_RegionObjectsProperty); } private set { LoadProperty(G07_RegionObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G06_Country"/> object. /// </summary> /// <returns>A reference to the created <see cref="G06_Country"/> object.</returns> internal static G06_Country NewG06_Country() { return DataPortal.CreateChild<G06_Country>(); } /// <summary> /// Factory method. Loads a <see cref="G06_Country"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="G06_Country"/> object.</returns> internal static G06_Country GetG06_Country(SafeDataReader dr) { G06_Country obj = new G06_Country(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G06_Country"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G06_Country() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G06_Country"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(G07_Country_SingleObjectProperty, DataPortal.CreateChild<G07_Country_Child>()); LoadProperty(G07_Country_ASingleObjectProperty, DataPortal.CreateChild<G07_Country_ReChild>()); LoadProperty(G07_RegionObjectsProperty, DataPortal.CreateChild<G07_RegionColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G06_Country"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Country_IDProperty, dr.GetInt32("Country_ID")); LoadProperty(Country_NameProperty, dr.GetString("Country_Name")); LoadProperty(ParentSubContinentIDProperty, dr.GetInt32("Parent_SubContinent_ID")); _rowVersion = dr.GetValue("RowVersion") as byte[]; var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(G07_Country_SingleObjectProperty, G07_Country_Child.GetG07_Country_Child(Country_ID)); LoadProperty(G07_Country_ASingleObjectProperty, G07_Country_ReChild.GetG07_Country_ReChild(Country_ID)); LoadProperty(G07_RegionObjectsProperty, G07_RegionColl.GetG07_RegionColl(Country_ID)); } /// <summary> /// Inserts a new <see cref="G06_Country"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G04_SubContinent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG06_Country", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", parent.SubContinent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(Country_IDProperty, (int) cmd.Parameters["@Country_ID"].Value); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="G06_Country"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG06_Country", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", ReadProperty(ParentSubContinentIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="G06_Country"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteG06_Country", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(G07_Country_SingleObjectProperty, DataPortal.CreateChild<G07_Country_Child>()); LoadProperty(G07_Country_ASingleObjectProperty, DataPortal.CreateChild<G07_Country_ReChild>()); LoadProperty(G07_RegionObjectsProperty, DataPortal.CreateChild<G07_RegionColl>()); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using GuruComponents.Netrix; using GuruComponents.Netrix.ComInterop; using GuruComponents.Netrix.Events; using GuruComponents.Netrix.WebEditing.Elements; using GuruComponents.Netrix.PlugIns; using System.Collections.Generic; namespace GuruComponents.Netrix.Designer { /// <summary> /// Provides methods to manage the global designer verbs and menu commands available in design mode, and to show some types of shortcut menus. /// </summary> /// <remarks> /// Provides support for commands and verbs. Verbs are opposite to properties and does not have any value one can set but instead provide method invoking. Though, the methods being invoked cannot have parameters. An good example of usage is the TableDesigner plugin. It exposes some commands like "AddRow", "DeleteColumn", or "RemoveCell". These commands are related to the current object and context and does not need any parameters. /// The way commands appear to the user depends on the host's user interface. The PropertyGrid will show them as links the ould click on. Implementers often add the commands to the context menu or extend parts of the main menu dynamically. This way the menu can show only valuable commands available for the current selection. /// The interface calls also the ContextMenu (and <see cref="GuruComponents.Netrix.HtmlEditor.ContextMenuStrip">ContextMenuStrip</see>) event. It does not provide any information about the menu itself. The latter is part of the user interface and not of NetRix. However, it provides the element which causes the menu being shown and from the element's Site property we have access to the services and the IMenuCommandService allows us to get the appropriate verbs. /// Adding verbs is done on several ways: /// <list type="bullet"> /// <item>Using default verbs, implemented by NetRix. These verbs are available for all elements.</item> /// <item>Add verbs globally by calling the interface's AddCommand method. These verbs are available for al elements.</item> /// <item>Add verbs from plugin. The plugin can decide to add verbs based on current element or globally.</item> /// <item>Add verbs using a designer. The element's designer (if one exists) can provide individual verbs for each object instance.</item> /// </list> /// As you can see, adding verbs can be very flexible. Commands can appear permanently and globally, per element type, or per element instance. /// Verbs have specific properties to manage the appearance. The appearance itself depends on the hosts capabilities. The PropertyGrid for instance does not support the Checked property, whereas a context menu could support this and show a check sign accordingly. The NetRix implementation tries to apply these properties: /// <list type="bullet"> /// <item><c>Checked</c> *</item> /// <item><c>Enabled</c></item> /// <item><c>Visible</c></item> /// <item><c>Supported</c> *</item> /// </list> /// * = Not supported by PropertyGrid /// <para> /// The properties does control the UI only, setting a the Enabled property to false does not prevent an object from calling the Invoke method and invoking the command. It's up to the host to prevent unwanted access to commands. /// </para> /// </remarks> /// <seealso cref="Verbs">Verbs (property)</seealso> /// <seealso cref="DesignerHost">DesignerHost (class)</seealso> public class CommandService : System.ComponentModel.Design.IMenuCommandService { private ArrayList commands; private HtmlEditor editor; private DesignerVerbCollection verbs = null; /// <summary> /// Creates an instance of the MenuCommandService. /// </summary> /// <param name="editor">Reference to the editor this service belongs to.</param> public CommandService(IHtmlEditor editor) { this.editor = (HtmlEditor) editor; this.commands = new ArrayList(); } #region IMenuCommandService Member /// <summary> /// Adds the specified standard menu command to the menu. /// </summary> /// <param name="command">The System.ComponentModel.Design.MenuCommand to add.</param> public void AddCommand(System.ComponentModel.Design.MenuCommand command) { commands.Add(command); } /// <summary> /// Removes the specified designer verb from the collection of global designer verbs. /// </summary> /// <param name="verb">The System.ComponentModel.Design.DesignerVerb to remove.</param> public void RemoveVerb(System.ComponentModel.Design.DesignerVerb verb) { Verbs.Remove(verb); } /// <summary> /// Removes the specified standard menu command from the menu. /// </summary> /// <param name="command">The System.ComponentModel.Design.MenuCommand to remove.</param> public void RemoveCommand(System.ComponentModel.Design.MenuCommand command) { commands.Remove(command); } /// <summary> /// Searches for the specified command ID and returns the menu command associated /// with it. /// </summary> /// <param name="commandID">The System.ComponentModel.Design.CommandID to search for.</param> /// <returns>The System.ComponentModel.Design.MenuCommand associated with the command /// ID, or <c>null</c> if no command is found.</returns> public System.ComponentModel.Design.MenuCommand FindCommand(System.ComponentModel.Design.CommandID commandID) { foreach (MenuCommand command in commands) { if (command.CommandID == commandID) { return command; } } return null; } /// <summary> /// Invokes a menu or designer verb command matching the specified command ID. /// </summary> /// <remarks> /// This is widely used by plug-ins to add commands to the base control. /// </remarks> /// <seealso cref="System.ComponentModel.Design.CommandID"/> /// <param name="commandID">The System.ComponentModel.Design.CommandID of the command to search for and execute.</param> /// <returns><c>True</c> if the command was found and invoked successfully; otherwise, <c>false</c>.</returns> public bool GlobalInvoke(System.ComponentModel.Design.CommandID commandID) { foreach (MenuCommand command in commands) { if (command.CommandID.Equals(commandID)) { command.Invoke(); return true; } } return false; } /// <summary> /// Shows the specified shortcut menu at the specified location. /// </summary> /// <remarks> /// Calling this method invokes the <see cref="OnShowContextMenu"/> event. /// </remarks> /// <seealso cref="System.ComponentModel.Design.CommandID"/> /// <param name="menuID">The System.ComponentModel.Design.CommandID for the shortcut menu to show.</param> /// <param name="x">The x-coordinate at which to display the menu, in screen coordinates.</param> /// <param name="y">The y-coordinate at which to display the menu, in screen coordinates.</param> public void ShowContextMenu(System.ComponentModel.Design.CommandID menuID, int x, int y) { if (OnShowContextMenu != null) { System.Web.UI.Control element = null; element = this.editor.GenericElementFactory.CreateElement(GetPrimaryElement()); OnShowContextMenu(this, new ShowContextMenuEventArgs(new System.Drawing.Point(x, y), false, 0, element)); } } /// <summary> /// Adds the specified designer verb to the set of global designer verbs. /// </summary> /// <param name="verb">The System.ComponentModel.Design.DesignerVerb to add.</param> public void AddVerb(System.ComponentModel.Design.DesignerVerb verb) { if (verbs == null) verbs = new DesignerVerbCollection(); verbs.Add(verb); } /// <summary> /// Default designer verb collection. /// </summary> /// <remarks> /// By default only one verb is added to invoke the element delete command. /// </remarks> public System.ComponentModel.Design.DesignerVerbCollection Verbs { get { //if (verbs == null || verbs.Count == 0) IComponent component = this.GetPrimaryComponent(); IDesignerHost host = (IDesignerHost)editor.ServiceProvider.GetService(typeof(IDesignerHost)); DesignerVerbCollection localverbs = new DesignerVerbCollection(); if (host != null && component != null) { IDesigner d = host.GetDesigner(component); // designer verbs if (d != null && d.Verbs.Count > 0) { localverbs.AddRange(d.Verbs); } if (component is IElement) { // default //if (editor.Selection.IsSelectableElement(component as IElement)) //{ // localverbs.Add(new DesignerVerb("Delete " + (component as IElement).UniqueName, Delete_Element)); //} if (((HtmlEditor)editor).RegisteredPlugIns != null) { //add verbs provided by plugins foreach (IPlugIn plugin in ((HtmlEditor)editor).RegisteredPlugIns) { List<CommandExtender> ceList = plugin.GetElementExtenders(component as IElement); if (ceList == null) continue; foreach (CommandExtender ce in ceList) { if (FindCommand(ce.CommandID) == null) { throw new NotSupportedException("The command + " + ce.CommandID + " is not supported"); } DesignerVerb v = new DesignerVerb(ce.Text, new EventHandler(InvokePlugInVerb), ce.CommandID); v.Checked = ce.Checked; v.Visible = ce.Visible; v.Enabled = ce.Enabled; v.Supported = ce.Supported; localverbs.Add(v); } } } } } // global verbs if (verbs != null && verbs.Count > 0) { localverbs.AddRange(verbs); } return localverbs; } } private void InvokePlugInVerb(object sender, EventArgs e) { GlobalInvoke(((MenuCommand) sender).CommandID); } private void Delete_Element(object sender, EventArgs e) { if (sender is IElement) { ((IElement) sender).ElementDom.RemoveElement(true); } } #endregion /// <summary> /// Fired when the command service recognizes a right click and is up to show the context menu. /// </summary> public event GuruComponents.Netrix.Events.ShowContextMenuEventHandler OnShowContextMenu; private Interop.IHTMLElement GetPrimaryElement() { IComponent component = GetPrimaryComponent(); if (component is IElement) { return ((IElement)component).GetBaseElement() as Interop.IHTMLElement; } else { return null; } } private IComponent GetPrimaryComponent() { ISelectionService s = (ISelectionService) editor.ServiceProvider.GetService(typeof(ISelectionService)); IComponent component = (IComponent) s.PrimarySelection; return component; } } }
using UnityEngine; using System.Collections; public class OTScale9Sprite : OTSprite { public enum SideFillType { Scale, Repeat }; public OTScale9Margins _margins = new OTScale9Margins(); // public SideFillType _fillSide = SideFillType.Scale; //----------------------------------------------------------------------------- // public attributes (get/set) //----------------------------------------------------------------------------- /* public SideFillType fillSide { get { return _fillSide; } set { if (value!=_fillSide) { _fillSide = value; meshDirty = true; } } } */ public OTScale9Margins margins { get { return _margins; } set { _margins = value; meshDirty = true; } } private OTScale9Margins _margins_; // private SideFillType _fillSide_ = SideFillType.Scale; Vector3[] verts = new Vector3[]{}; Vector2[] _uv = new Vector2[]{}; int[] tris = new int[]{}; int Scale9Verts(int idx, float yp, float uvp) { int ix = 100; if (image!=null) ix = image.width; float maLeft = (_meshsize_.x * ((margins.left>=1)?(margins.left/ix):margins.left)) * (ix/_size.x) * OT.view.sizeFactor; float maRight = (_meshsize_.x * ((margins.right>=1)?(margins.right/ix):margins.right)) * (ix/_size.x) * OT.view.sizeFactor; float uvLeft = ((margins.left>=1)?(margins.left/ix):margins.left); float uvRight = ((margins.right>=1)?(margins.right/ix):margins.right); _uv[idx] = new Vector2(0, uvp); verts[idx++] = new Vector3(mLeft, yp, 0); _uv[idx] = new Vector2(uvLeft, uvp); verts[idx++] = new Vector3(mLeft + maLeft , yp, 0); _uv[idx] = new Vector2(1-uvRight, uvp); verts[idx++] = new Vector3(mRight - maRight, yp, 0); _uv[idx] = new Vector2(1, uvp); verts[idx++] = new Vector3(mRight, yp, 0); return idx; } int Scale9Face(int idx, int start, int vcount) { tris[idx++] = start; tris[idx++] = start+1; tris[idx++] = start+vcount; tris[idx++] = start+1; tris[idx++] = start+vcount+1; tris[idx++] = start+vcount; return idx; } protected override Mesh GetMesh() { Mesh mesh =InitMesh(); int iy = 100; if (image!=null) iy = image.height; float maTop = (_meshsize_.y * ((margins.top>=1)?(margins.top/iy):margins.top)) * (iy/_size.y)* OT.view.sizeFactor; float maBottom = (_meshsize_.y * ((margins.bottom>=1)?(margins.bottom/iy):margins.bottom)) * (iy/_size.y) * OT.view.sizeFactor; float uvTop = ((margins.top>=1)?(margins.top/iy):margins.top); float uvBottom = ((margins.bottom>=1)?(margins.bottom/iy):margins.bottom); verts = new Vector3[16]; _uv = new Vector2[16]; tris = new int[ 9 * 6 ]; int idx = 0; idx = Scale9Verts(idx, mTop, 1); idx = Scale9Verts(idx, mTop - maTop, 1-uvTop); idx = Scale9Verts(idx, mBottom + maBottom, uvBottom); idx = Scale9Verts(idx, mBottom, 0); idx = 0; idx = Scale9Face(idx,0,4); idx = Scale9Face(idx,1,4); idx = Scale9Face(idx,2,4); idx = Scale9Face(idx,4,4); idx = Scale9Face(idx,5,4); idx = Scale9Face(idx,6,4); idx = Scale9Face(idx,8,4); idx = Scale9Face(idx,9,4); idx = Scale9Face(idx,10,4); mesh.vertices = verts; mesh.uv = _uv; mesh.triangles = tris; mesh.RecalculateBounds(); mesh.RecalculateNormals(); return mesh; } //----------------------------------------------------------------------------- // overridden subclass methods //----------------------------------------------------------------------------- protected override void CheckSettings() { Vector2 loc = transform.localScale; if (!_size.Equals(_size_) || !_size.Equals(loc)) meshDirty = true; base.CheckSettings(); if (MarginsChanged() /* || _fillSide != _fillSide_ */ ) { meshDirty = true; _margins_ = _margins; // _fillSide_ = _fillSide; } } protected override string GetTypeName() { return "Scale9"; } protected override void HandleUV() { if (spriteContainer != null && spriteContainer.isReady) { OTContainer.Frame frame = spriteContainer.GetFrame(frameIndex); // adjust this sprites UV coords if (frame.uv != null && mesh != null) { // splice UV that we got from the container. mesh.uv = frame.uv; } } } protected override void Clean() { base.Clean(); } //----------------------------------------------------------------------------- // class methods //----------------------------------------------------------------------------- bool MarginsChanged() { return (!margins.Equals(_margins_)); } protected override void Awake() { base.Awake(); _margins_ = _margins; // _fillSide_ = _fillSide; } public void Rebuild() { meshDirty = true; } new void Start() { base.Start(); } // Update is called once per frame new void Update() { base.Update(); } } [System.Serializable] public class OTScale9Margins { public float top = 25; public float bottom = 25; public float left = 25; public float right = 25; public bool Equals(OTScale9Margins other) { return (top==other.top && bottom == other.bottom && left == other.left && right == other.right); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestZSByte() { var test = new BooleanBinaryOpTest__TestZSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestZSByte { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(SByte); private const int Op2ElementCount = VectorSize / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private BooleanBinaryOpTest__DataTable<SByte, SByte> _dataTable; static BooleanBinaryOpTest__TestZSByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); } public BooleanBinaryOpTest__TestZSByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } _dataTable = new BooleanBinaryOpTest__DataTable<SByte, SByte>(_data1, _data2, VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.TestZ( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Sse41.TestZ( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Sse41.TestZ( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Sse41.TestZ( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Sse41.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse41.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse41.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanBinaryOpTest__TestZSByte(); var result = Sse41.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Sse41.TestZ(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<SByte> left, Vector128<SByte> right, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(SByte[] left, SByte[] right, bool result, [CallerMemberName] string method = "") { var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((left[i] & right[i]) == 0); } if (expectedResult != result) { Succeeded = false; Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestZ)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using GraphX.Measure; using GraphX.Common.Interfaces; using QuikGraph; namespace GraphX.Logic.Algorithms.LayoutAlgorithms { /*public abstract class ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TVertexInfo, TEdgeInfo, TParam> : ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam> where TVertex : class where TEdge : IEdge<TVertex> where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge> where TParam : class, ILayoutParameters { protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph ) : base( visitedGraph, null, null ) { } protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph, IDictionary<TVertex, Point> vertexPositions, TParam oldParameters ) : base( visitedGraph, vertexPositions, oldParameters ) { } }*/ /// <summary> /// Use this class as a base class for your layout algorithm /// if it's parameter class has a default contstructor. /// </summary> /// <typeparam name="TVertex">The type of the vertices.</typeparam> /// <typeparam name="TEdge">The type of the edges.</typeparam> /// <typeparam name="TGraph">The type of the graph.</typeparam> /// <typeparam name="TParam">The type of the parameters. Must be based on the LayoutParametersBase.</typeparam> public abstract class DefaultParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam> : ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam> where TVertex : class where TEdge : IEdge<TVertex> where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge> where TParam : class, ILayoutParameters, new() { protected DefaultParameterizedLayoutAlgorithmBase(TGraph visitedGraph) : base(visitedGraph) { } protected DefaultParameterizedLayoutAlgorithmBase(TGraph visitedGraph, IDictionary<TVertex, Point> vertexPositions, TParam oldParameters) : base(visitedGraph, vertexPositions, oldParameters) { } protected override TParam DefaultParameters => new TParam(); } /// <typeparam name="TVertex">Type of the vertices.</typeparam> /// <typeparam name="TEdge">Type of the edges.</typeparam> /// <typeparam name="TGraph">Type of the graph.</typeparam> /// <typeparam name="TParam">Type of the parameters. Must be based on the LayoutParametersBase.</typeparam> public abstract class ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam> : LayoutAlgorithmBase<TVertex, TEdge, TGraph>, IParameterizedLayoutAlgorithm<TParam> where TVertex : class where TEdge : IEdge<TVertex> where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge> where TParam : class, ILayoutParameters { #region Properties /// <summary> /// Parameters of the algorithm. For more information see <see cref="LayoutParametersBase"/>. /// </summary> public TParam Parameters { get; protected set; } public ILayoutParameters GetParameters() { return Parameters; } #endregion #region Constructors protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph ) : this( visitedGraph, null, null ) { } protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph, IDictionary<TVertex, Point> vertexPositions, TParam oldParameters ) : base( visitedGraph, vertexPositions ) { InitParameters( oldParameters ); //TraceSource = new TraceSource( "LayoutAlgorithm", SourceLevels.All ); } #endregion #region Initializers protected abstract TParam DefaultParameters { get; } /// <summary> /// Ensures that all positions generated by InitializeWithRandomPositions() method will be unique. /// Can lead to excessive CPU usage for large amount of vertices. Default value is False. True for LinLog. /// </summary> protected bool EnsureUniqueRandomInitialPositions { get; set; } /// <summary> /// Initializes the parameters (cloning or creating new parameter object with default values). /// </summary> /// <param name="oldParameters">Parameters from a prevorious layout. If it is null, /// the parameters will be set to the default ones.</param> protected void InitParameters( TParam oldParameters ) { if (oldParameters == null) Parameters = DefaultParameters; else { Parameters = (TParam)oldParameters.Clone(); } } /// <summary> /// Initializes the positions of the vertices. Assign a random position inside the 'bounding box' to the vertices without positions. /// It does NOT modify the position of the other vertices. /// /// It generates an <code>IterationEnded</code> event. /// /// Bounding box: /// x coordinates: double.Epsilon - <code>width</code> /// y coordinates: double.Epsilon - <code>height</code> /// </summary> /// <param name="width">Width of the bounding box.</param> /// <param name="height">Height of the bounding box.</param> protected virtual void InitializeWithRandomPositions( double width, double height ) { InitializeWithRandomPositions( width, height, 0, 0 ); } /// <summary> /// Initializes the positions of the vertices. Assign a random position inside the 'bounding box' to the vertices without positions. /// It does NOT modify the position of the other vertices. /// /// It generates an <code>IterationEnded</code> event. /// /// Bounding box: /// x coordinates: double.Epsilon - <code>width</code> /// y coordinates: double.Epsilon - <code>height</code> /// </summary> /// <param name="width">Width of the bounding box.</param> /// <param name="height">Height of the bounding box.</param> /// <param name="translate_x">Translates the generated x coordinate.</param> /// <param name="translate_y">Translates the generated y coordinate.</param> protected virtual void InitializeWithRandomPositions( double width, double height, double translate_x, double translate_y ) { var rnd = new Random(Parameters.Seed); //initialize with random position foreach ( TVertex v in VisitedGraph.Vertices ) { //for vertices without assigned position if ( !VertexPositions.ContainsKey( v ) ) { if (EnsureUniqueRandomInitialPositions) { Point newPoint; do { newPoint = new Point( Math.Max(double.Epsilon, rnd.NextDouble()*width + translate_x), Math.Max(double.Epsilon, rnd.NextDouble()*height + translate_y)); } while (VertexPositions.Values.Contains(newPoint)); VertexPositions[v] = newPoint; } else { VertexPositions[v] = new Point( Math.Max(double.Epsilon, rnd.NextDouble()*width + translate_x), Math.Max(double.Epsilon, rnd.NextDouble()*height + translate_y)); } } } } protected virtual void NormalizePositions() { NormalizePositions( VertexPositions ); } protected static void NormalizePositions( IDictionary<TVertex, Point> vertexPositions ) { if ( vertexPositions == null || vertexPositions.Count == 0 ) return; //get the topLeft position var topLeft = new Point( float.PositiveInfinity, float.PositiveInfinity ); foreach ( var pos in vertexPositions.Values.ToArray() ) { topLeft.X = Math.Min( topLeft.X, pos.X ); topLeft.Y = Math.Min( topLeft.Y, pos.Y ); } //translate with the topLeft position foreach ( var v in vertexPositions.ToArray()) { var pos = v.Value; pos.X -= topLeft.X; pos.Y -= topLeft.Y; vertexPositions[v.Key] = pos; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { public class MemoryMappedFileTests_CreateOrOpen : MemoryMappedFilesTestBase { /// <summary> /// Tests invalid arguments to the CreateOrOpen mapName parameter. /// </summary> [Fact] public void InvalidArguments_MapName() { // null is an invalid map name with CreateOrOpen (it's valid with CreateNew and CreateFromFile) Assert.Throws<ArgumentNullException>("mapName", () => MemoryMappedFile.CreateOrOpen(null, 4096)); Assert.Throws<ArgumentNullException>("mapName", () => MemoryMappedFile.CreateOrOpen(null, 4096, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<ArgumentNullException>("mapName", () => MemoryMappedFile.CreateOrOpen(null, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); // Empty string is always an invalid map name Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateOrOpen(string.Empty, 4096)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateOrOpen(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateOrOpen(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Test to verify that map names are left unsupported on Unix. /// </summary> [PlatformSpecific(PlatformID.AnyUnix)] [Theory] [MemberData("CreateValidMapNames")] public void MapNamesNotSupported_Unix(string mapName) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateOrOpen(mapName, 4096)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateOrOpen(mapName, 4096, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateOrOpen(mapName, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateOrOpen capacity parameter. /// </summary> [Theory] [InlineData(0)] // can't create a new map with a default capacity [InlineData(-1)] // negative capacities don't make sense public void InvalidArguments_Capacity(long capacity) { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), capacity)); Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), capacity, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateOrOpen capacity parameter. /// </summary> [Fact] public void InvalidArguments_Capacity_TooLarge() { // On 32-bit, values larger than uint.MaxValue aren't allowed if (IntPtr.Size == 4) { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 1 + (long)uint.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } } /// <summary> /// Tests invalid arguments to the CreateOrOpen access parameter. /// </summary> [Theory] [InlineData((MemoryMappedFileAccess)(-1))] [InlineData((MemoryMappedFileAccess)(42))] public void InvalidArgument_Access(MemoryMappedFileAccess access) { Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, access)); Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, access, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateOrOpen options parameter. /// </summary> [Theory] [InlineData((MemoryMappedFileOptions)(-1))] [InlineData((MemoryMappedFileOptions)(42))] public void InvalidArgument_Options(MemoryMappedFileOptions options) { Assert.Throws<ArgumentOutOfRangeException>("options", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, options, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateOrOpen inheritability parameter. /// </summary> [Theory] [InlineData((HandleInheritability)(-1))] [InlineData((HandleInheritability)(42))] public void InvalidArgument_Inheritability(HandleInheritability inheritability) { Assert.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, inheritability)); } /// <summary> /// Test various combinations of arguments to CreateOrOpen, validating the created maps each time they're created, /// focusing on on accesses that don't involve execute permissions. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Theory] [MemberData("MemberData_ValidArgumentCombinations", new string[] { "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite }, new MemoryMappedFileOptions[] { MemoryMappedFileOptions.None, MemoryMappedFileOptions.DelayAllocatePages }, new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable })] public void ValidArgumentCombinations_NonExecute( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { // Map doesn't exist using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } // Map does exist (CreateNew) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { ValidateMemoryMappedFile(mmf2, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf2, capacity, access, inheritability); } // Map does exist (CreateFromFile) using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { ValidateMemoryMappedFile(mmf2, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } } /// <summary> /// Test various combinations of arguments to CreateOrOpen, validating the created maps each time they're created, /// focusing on on accesses that involve execute permissions. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Theory] [MemberData("MemberData_ValidArgumentCombinations", new string[] { "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute }, new MemoryMappedFileOptions[] { MemoryMappedFileOptions.None, MemoryMappedFileOptions.DelayAllocatePages }, new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable })] public void ValidArgumentCombinations_Execute( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { // Map doesn't exist using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } // Map does exist (CreateNew) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf2, capacity, access, inheritability); } // (Avoid testing with CreateFromFile when using execute permissions.) } /// <summary> /// Provides input data to the ValidArgumentCombinations tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses">The accesses to yield</param> /// <param name="options">The options to yield.</param> /// <param name="inheritabilities">The inheritabilities to yield.</param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinations( string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, MemoryMappedFileOptions[] options, HandleInheritability[] inheritabilities) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { foreach (MemoryMappedFileOptions option in options) { foreach (HandleInheritability inheritability in inheritabilities) { yield return new object[] { mapName, capacity, access, option, inheritability }; } } } } } } /// <summary> /// Test to validate behavior with MemoryMappedFileAccess.Write. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Fact] public void OpenWrite() { // Write-only access fails when the map doesn't exist Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write)); Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, MemoryMappedFileOptions.None, HandleInheritability.None)); // Write-only access works when the map does exist const int Capacity = 4096; string name = CreateUniqueMapName(); using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(name, Capacity)) using (MemoryMappedFile opened = MemoryMappedFile.CreateOrOpen(name, Capacity, MemoryMappedFileAccess.Write)) { ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Write); } } /// <summary> /// Test the exceptional behavior when attempting to create a map so large it's not supported. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Fact] public void TooLargeCapacity() { if (IntPtr.Size == 4) { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 1 + (long)uint.MaxValue)); } else { Assert.Throws<IOException>(() => MemoryMappedFile.CreateNew(CreateUniqueMapName(), long.MaxValue)); } } /// <summary> /// Test that the capacity of a view matches the original capacity, not that specified when opening the new map, /// and that the original capacity doesn't change from opening another map with a different capacity. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Fact] public void OpenedCapacityMatchesOriginal() { string name = CreateUniqueMapName(); using (MemoryMappedFile original = MemoryMappedFile.CreateNew(name, 10000)) { // Get the capacity of a view before we open any copies long capacity; using (MemoryMappedViewAccessor originalAcc = original.CreateViewAccessor()) { capacity = originalAcc.Capacity; } // Open additional maps using (MemoryMappedFile opened1 = MemoryMappedFile.CreateOrOpen(name, 1)) // smaller capacity using (MemoryMappedFile opened2 = MemoryMappedFile.CreateOrOpen(name, 20000)) // larger capacity { // Verify that the original's capacity hasn't changed using (MemoryMappedViewAccessor originalAcc = original.CreateViewAccessor()) { Assert.Equal(capacity, originalAcc.Capacity); } // Verify that each map's capacity is the same as the original even though // different values were provided foreach (MemoryMappedFile opened in new[] { opened1, opened2 }) { using (MemoryMappedViewAccessor acc = opened.CreateViewAccessor()) { Assert.Equal(capacity, acc.Capacity); } } } } } [PlatformSpecific(PlatformID.Windows)] [Fact] public void OpenedAccessibilityLimitedToOriginal() { const int Capacity = 4096; string name = CreateUniqueMapName(); // Open the original as Read but the copy as ReadWrite using (MemoryMappedFile original = MemoryMappedFile.CreateNew(name, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedFile opened = MemoryMappedFile.CreateOrOpen(name, Capacity, MemoryMappedFileAccess.ReadWrite)) { // Even though we passed ReadWrite to CreateOrOpen, trying to open a view accessor with ReadWrite should fail Assert.Throws<IOException>(() => opened.CreateViewAccessor()); Assert.Throws<IOException>(() => opened.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.ReadWrite)); // But Read should succeed opened.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read).Dispose(); } } [PlatformSpecific(PlatformID.Windows)] [Fact] public void OpenedAccessibilityLimitedBeyondOriginal() { const int Capacity = 4096; string name = CreateUniqueMapName(); // Open the original as ReadWrite but the copy as Read using (MemoryMappedFile original = MemoryMappedFile.CreateNew(name, Capacity, MemoryMappedFileAccess.ReadWrite)) using (MemoryMappedFile opened = MemoryMappedFile.CreateOrOpen(name, Capacity, MemoryMappedFileAccess.Read)) { // Even though we passed ReadWrite to CreateNew, trying to open a view accessor with ReadWrite should fail Assert.Throws<UnauthorizedAccessException>(() => opened.CreateViewAccessor()); Assert.Throws<UnauthorizedAccessException>(() => opened.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.ReadWrite)); // But Read should succeed opened.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read).Dispose(); } } } }
// <developer>niklas@protocol7.com</developer> // <completed>100</completed> using System; using System.Xml; using SharpVectors.Dom.Events; namespace SharpVectors.Dom.Svg { /// <summary> /// The SVGRectElement interface corresponds to the 'rect' element. /// </summary> public sealed class SvgRectElement : SvgTransformableElement, ISvgRectElement { #region Private Fields private ISvgAnimatedLength x; private ISvgAnimatedLength y; private ISvgAnimatedLength rx; private ISvgAnimatedLength ry; private ISvgAnimatedLength width; private ISvgAnimatedLength height; private SvgTests svgTests; private SvgExternalResourcesRequired svgExternalResourcesRequired; #endregion #region Constructors and Destructor public SvgRectElement(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { svgExternalResourcesRequired = new SvgExternalResourcesRequired(this); svgTests = new SvgTests(this); } #endregion #region Public Methods public void Invalidate() { } public override void HandleAttributeChange(XmlAttribute attribute) { if (attribute.NamespaceURI.Length == 0) { switch (attribute.LocalName) { case "x": x = null; Invalidate(); return; case "y": y = null; Invalidate(); return; case "width": width = null; Invalidate(); return; case "height": height = null; Invalidate(); return; case "rx": rx = null; Invalidate(); return; case "ry": ry = null; Invalidate(); return; // Color.attrib, Paint.attrib case "color": case "fill": case "fill-rule": case "stroke": case "stroke-dasharray": case "stroke-dashoffset": case "stroke-linecap": case "stroke-linejoin": case "stroke-miterlimit": case "stroke-width": // Opacity.attrib case "opacity": case "stroke-opacity": case "fill-opacity": // Graphics.attrib case "display": case "image-rendering": case "shape-rendering": case "text-rendering": case "visibility": Invalidate(); break; case "transform": Invalidate(); break; case "onclick": break; } base.HandleAttributeChange(attribute); } } #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.Shape"/> /// </value> public override SvgRenderingHint RenderingHint { get { return SvgRenderingHint.Shape; } } #endregion #region ISvgExternalResourcesRequired Members public ISvgAnimatedBoolean ExternalResourcesRequired { get { return svgExternalResourcesRequired.ExternalResourcesRequired; } } #endregion #region ISvgRectElement Members public ISvgAnimatedLength Width { get { if (width == null) { width = new SvgAnimatedLength(this, "width", SvgLengthDirection.Horizontal, "100"); } return width; } } public ISvgAnimatedLength Height { get { if (height == null) { height = new SvgAnimatedLength(this, "height", SvgLengthDirection.Vertical, "100"); } return height; } } public ISvgAnimatedLength X { get { if (x == null) { x = new SvgAnimatedLength(this, "x", SvgLengthDirection.Horizontal, "0"); } return x; } } public ISvgAnimatedLength Y { get { if (y == null) { y = new SvgAnimatedLength(this, "y", SvgLengthDirection.Vertical, "0"); } return y; } } public ISvgAnimatedLength Rx { get { if (rx == null) { rx = new SvgAnimatedLength(this, "rx", SvgLengthDirection.Horizontal, "0"); } return rx; } } public ISvgAnimatedLength Ry { get { if (ry == null) { ry = new SvgAnimatedLength(this, "ry", SvgLengthDirection.Vertical, "0"); } return ry; } } #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 License // Copyright (c) 2007 James Newton-King // // 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; using System.Collections.Generic; using System.ComponentModel; #if !(NET35 || NET20 || PORTABLE40) using System.Dynamic; #endif using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Serialization { internal class JsonSerializerInternalWriter : JsonSerializerInternalBase { private JsonContract _rootContract; private readonly List<object> _serializeStack = new List<object>(); private JsonSerializerProxy _internalSerializer; public JsonSerializerInternalWriter(JsonSerializer serializer) : base(serializer) { } public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { if (jsonWriter == null) throw new ArgumentNullException("jsonWriter"); if (objectType != null) _rootContract = Serializer._contractResolver.ResolveContract(objectType); SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null); } private JsonSerializerProxy GetInternalSerializer() { if (_internalSerializer == null) _internalSerializer = new JsonSerializerProxy(this); return _internalSerializer; } private JsonContract GetContractSafe(object value) { if (value == null) return null; return Serializer._contractResolver.ResolveContract(value.GetType()); } private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (contract.TypeCode == PrimitiveTypeCode.Bytes) { // if type name handling is enabled then wrap the base64 byte string in an object with the type name bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty); if (includeTypeDetails) { writer.WriteStartObject(); WriteTypeProperty(writer, contract.CreatedType); writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false); JsonWriter.WriteValue(writer, contract.TypeCode, value); writer.WriteEndObject(); return; } } JsonWriter.WriteValue(writer, contract.TypeCode, value); } private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null) { writer.WriteNull(); return; } JsonConverter converter; if ((((converter = (member != null) ? member.Converter : null) != null) || ((converter = (containerProperty != null) ? containerProperty.ItemConverter : null) != null) || ((converter = (containerContract != null) ? containerContract.ItemConverter : null) != null) || ((converter = valueContract.Converter) != null) || ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null) || ((converter = valueContract.InternalConverter) != null)) && converter.CanWrite) { SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty); return; } switch (valueContract.ContractType) { case JsonContractType.Object: SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty); break; case JsonContractType.Array: JsonArrayContract arrayContract = (JsonArrayContract)valueContract; if (!arrayContract.IsMultidimensionalArray) SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty); else SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty); break; case JsonContractType.Primitive: SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty); break; case JsonContractType.String: SerializeString(writer, value, (JsonStringContract)valueContract); break; case JsonContractType.Dictionary: JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract; SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty); break; #if !(NET35 || NET20 || PORTABLE40) case JsonContractType.Dynamic: SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty); break; #endif #if !(NETFX_CORE || PORTABLE40 || PORTABLE) case JsonContractType.Serializable: SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty); break; #endif case JsonContractType.Linq: ((JToken)value).WriteTo(writer, Serializer.Converters.ToArray()); break; } } private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty) { bool? isReference = null; // value could be coming from a dictionary or array and not have a property if (property != null) isReference = property.IsReference; if (isReference == null && containerProperty != null) isReference = containerProperty.ItemIsReference; if (isReference == null && collectionContract != null) isReference = collectionContract.ItemIsReference; if (isReference == null) isReference = contract.IsReference; return isReference; } private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (value == null) return false; if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String) return false; bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty); if (isReference == null) { if (valueContract.ContractType == JsonContractType.Array) isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); else isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); } if (!isReference.Value) return false; return Serializer.GetReferenceResolver().IsReferenced(this, value); } private bool ShouldWriteProperty(object memberValue, JsonProperty property) { if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && memberValue == null) return false; if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) && MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue())) return false; return true; } private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) return true; ReferenceLoopHandling? referenceLoopHandling = null; if (property != null) referenceLoopHandling = property.ReferenceLoopHandling; if (referenceLoopHandling == null && containerProperty != null) referenceLoopHandling = containerProperty.ItemReferenceLoopHandling; if (referenceLoopHandling == null && containerContract != null) referenceLoopHandling = containerContract.ItemReferenceLoopHandling; if (_serializeStack.IndexOf(value) != -1) { string message = "Self referencing loop detected"; if (property != null) message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName); message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()); switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling)) { case ReferenceLoopHandling.Error: throw JsonSerializationException.Create(null, writer.ContainerPath, message, null); case ReferenceLoopHandling.Ignore: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null); return false; case ReferenceLoopHandling.Serialize: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null); return true; } } return true; } private void WriteReference(JsonWriter writer, object value) { string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null); writer.WriteStartObject(); writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false); writer.WriteValue(reference); writer.WriteEndObject(); } private string GetReference(JsonWriter writer, object value) { try { string reference = Serializer.GetReferenceResolver().GetReference(this, value); return reference; } catch (Exception ex) { throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex); } } internal static bool TryConvertToString(object value, Type type, out string s) { #if !(NETFX_CORE || PORTABLE40 || PORTABLE) TypeConverter converter = ConvertUtils.GetConverter(type); // use the objectType's TypeConverter if it has one and can convert to a string if (converter != null && !(converter is ComponentConverter) && converter.GetType() != typeof(TypeConverter)) { if (converter.CanConvertTo(typeof(string))) { s = converter.ConvertToInvariantString(value); return true; } } #endif #if NETFX_CORE || PORTABLE if (value is Guid || value is Uri || value is TimeSpan) { s = value.ToString(); return true; } #endif if (value is Type) { s = ((Type)value).AssemblyQualifiedName; return true; } s = null; return false; } private void SerializeString(JsonWriter writer, object value, JsonStringContract contract) { OnSerializing(writer, contract, value); string s; TryConvertToString(value, contract.UnderlyingType, out s); writer.WriteValue(s); OnSerialized(writer, contract, value); } private void OnSerializing(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); contract.InvokeOnSerializing(value, Serializer._context); } private void OnSerialized(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); contract.InvokeOnSerialized(value, Serializer._context); } private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); int initialDepth = writer.Top; for (int index = 0; index < contract.Properties.Count; index++) { JsonProperty property = contract.Properties[index]; try { object memberValue; JsonContract memberContract; if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) continue; property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); } catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } if (contract.ExtensionDataGetter != null) { IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value); if (extensionData != null) { foreach (KeyValuePair<object, object> e in extensionData) { JsonContract keyContract = GetContractSafe(e.Key); JsonContract valueContract = GetContractSafe(e.Value); bool escape; string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape); if (ShouldWriteReference(e.Value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName); WriteReference(writer, e.Value); } else { if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member)) continue; writer.WritePropertyName(propertyName); SerializeValue(writer, e.Value, valueContract, null, contract, member); } } } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue) { if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value)) { if (property.PropertyContract == null) property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); memberValue = property.ValueProvider.GetValue(value); memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue); if (ShouldWriteProperty(memberValue, property)) { if (ShouldWriteReference(memberValue, property, memberContract, contract, member)) { property.WritePropertyName(writer); WriteReference(writer, memberValue); return false; } if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member)) return false; if (memberValue == null) { JsonObjectContract objectContract = contract as JsonObjectContract; Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default; if (resolvedRequired == Required.Always) throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null); } return true; } } memberContract = null; memberValue = null; return false; } private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { writer.WriteStartObject(); bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); if (isReference) { WriteReferenceIdProperty(writer, contract.UnderlyingType, value); } if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty)) { WriteTypeProperty(writer, contract.UnderlyingType); } } private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value) { string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null); writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false); writer.WriteValue(reference); } private void WriteTypeProperty(JsonWriter writer, Type type) { string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null); writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false); writer.WriteValue(typeName); } private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) { return ((value & flag) == flag); } private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag) { return ((value & flag) == flag); } private bool HasFlag(TypeNameHandling value, TypeNameHandling flag) { return ((value & flag) == flag); } private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) { WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty)) return; _serializeStack.Add(value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); converter.WriteJson(writer, value, GetInternalSerializer()); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); _serializeStack.RemoveAt(_serializeStack.Count - 1); } } private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { IWrappedCollection wrappedCollection = values as IWrappedCollection; object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values; OnSerializing(writer, contract, underlyingList); _serializeStack.Add(underlyingList); bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty); writer.WriteStartArray(); int initialDepth = writer.Top; int index = 0; // note that an error in the IEnumerable won't be caught foreach (object value in values) { try { JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { WriteReference(writer, value); } else { if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) { SerializeValue(writer, value, valueContract, null, contract, member); } } } catch (Exception ex) { if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } finally { index++; } } writer.WriteEndArray(); if (hasWrittenMetadataObject) writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingList); } private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, values); _serializeStack.Add(values); bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty); SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]); if (hasWrittenMetadataObject) writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, values); } private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices) { int dimension = indices.Length; int[] newIndices = new int[dimension + 1]; for (int i = 0; i < dimension; i++) { newIndices[i] = indices[i]; } writer.WriteStartArray(); for (int i = 0; i < values.GetLength(dimension); i++) { newIndices[dimension] = i; bool isTopLevel = (newIndices.Length == values.Rank); if (isTopLevel) { object value = values.GetValue(newIndices); try { JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { WriteReference(writer, value); } else { if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) { SerializeValue(writer, value, valueContract, null, contract, member); } } } catch (Exception ex) { if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth + 1); else throw; } } else { SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices); } } writer.WriteEndArray(); } private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty); bool writeMetadataObject = isReference || includeTypeDetails; if (writeMetadataObject) { writer.WriteStartObject(); if (isReference) { WriteReferenceIdProperty(writer, contract.UnderlyingType, values); } if (includeTypeDetails) { WriteTypeProperty(writer, values.GetType()); } writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false); } if (contract.ItemContract == null) contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object)); return writeMetadataObject; } #if !(NETFX_CORE || PORTABLE40 || PORTABLE) #if !(NET20 || NET35) [SecuritySafeCritical] #endif private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (!JsonTypeReflector.FullyTrusted) { throw JsonSerializationException.Create(null, writer.ContainerPath, @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data. To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null); } OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter()); value.GetObjectData(serializationInfo, Serializer._context); foreach (SerializationEntry serializationEntry in serializationInfo) { JsonContract valueContract = GetContractSafe(serializationEntry.Value); if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member)) { writer.WritePropertyName(serializationEntry.Name); SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member); } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } #endif #if !(NET35 || NET20 || PORTABLE40) private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); int initialDepth = writer.Top; for (int index = 0; index < contract.Properties.Count; index++) { JsonProperty property = contract.Properties[index]; // only write non-dynamic properties that have an explicit attribute if (property.HasMemberAttribute) { try { object memberValue; JsonContract memberContract; if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) continue; property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); } catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } } foreach (string memberName in value.GetDynamicMemberNames()) { object memberValue; if (contract.TryGetMember(value, memberName, out memberValue)) { try { JsonContract valueContract = GetContractSafe(memberValue); if (!ShouldWriteDynamicProperty(memberValue)) continue; if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member)) { string resolvedPropertyName = (contract.PropertyNameResolver != null) ? contract.PropertyNameResolver(memberName) : memberName; writer.WritePropertyName(resolvedPropertyName); SerializeValue(writer, memberValue, valueContract, null, contract, member); } } catch (Exception ex) { if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } #endif private bool ShouldWriteDynamicProperty(object memberValue) { if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) return false; if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) && (memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType())))) return false; return true; } private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { TypeNameHandling resolvedTypeNameHandling = ((member != null) ? member.TypeNameHandling : null) ?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null) ?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null) ?? Serializer._typeNameHandling; if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag)) return true; // instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default) if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto)) { if (member != null) { if (contract.UnderlyingType != member.PropertyContract.CreatedType) return true; } else if (containerContract != null) { if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType) return true; } else if (_rootContract != null && _serializeStack.Count == 1) { if (contract.UnderlyingType != _rootContract.CreatedType) return true; } } return false; } private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { IWrappedDictionary wrappedDictionary = values as IWrappedDictionary; object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values; OnSerializing(writer, contract, underlyingDictionary); _serializeStack.Add(underlyingDictionary); WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty); if (contract.ItemContract == null) contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object)); if (contract.KeyContract == null) contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object)); int initialDepth = writer.Top; foreach (DictionaryEntry entry in values) { bool escape; string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape); propertyName = (contract.PropertyNameResolver != null) ? contract.PropertyNameResolver(propertyName) : propertyName; try { object value = entry.Value; JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName, escape); WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, valueContract, contract, member)) continue; writer.WritePropertyName(propertyName, escape); SerializeValue(writer, value, valueContract, null, contract, member); } } catch (Exception ex) { if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingDictionary); } private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) { string propertyName; if (contract.ContractType == JsonContractType.Primitive) { JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable) { escape = false; StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); DateTimeUtils.WriteDateTimeString(sw, (DateTime)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); return sw.ToString(); } #if !NET20 else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable) { escape = false; StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); return sw.ToString(); } #endif else { escape = true; return Convert.ToString(name, CultureInfo.InvariantCulture); } } else if (TryConvertToString(name, name.GetType(), out propertyName)) { escape = true; return propertyName; } else { escape = true; return name.ToString(); } } private void HandleError(JsonWriter writer, int initialDepth) { ClearErrorContext(); if (writer.WriteState == WriteState.Property) writer.WriteNull(); while (writer.Top > initialDepth) { writer.WriteEnd(); } } private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target) { if (property.ShouldSerialize == null) return true; bool shouldSerialize = property.ShouldSerialize(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null); return shouldSerialize; } private bool IsSpecified(JsonWriter writer, JsonProperty property, object target) { if (property.GetIsSpecified == null) return true; bool isSpecified = property.GetIsSpecified(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null); return isSpecified; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery.Models { /// <summary> /// The definition of a Fabric properties. /// </summary> public partial class ReplicationProtectedItemProperties { private string _activeLocation; /// <summary> /// Optional. Gets or sets the Current active location of the PE. /// </summary> public string ActiveLocation { get { return this._activeLocation; } set { this._activeLocation = value; } } private IList<string> _allowedOperations; /// <summary> /// Optional. Gets or sets the allowed operations on the Replication /// protected item. /// </summary> public IList<string> AllowedOperations { get { return this._allowedOperations; } set { this._allowedOperations = value; } } private CurrentScenarioDetails _currentScenario; /// <summary> /// Optional. Gets or sets the current scenario. /// </summary> public CurrentScenarioDetails CurrentScenario { get { return this._currentScenario; } set { this._currentScenario = value; } } private string _failoverRecoveryPointId; /// <summary> /// Optional. Gets or sets the recovery point Id used by failover /// operation. /// </summary> public string FailoverRecoveryPointId { get { return this._failoverRecoveryPointId; } set { this._failoverRecoveryPointId = value; } } private string _friendlyName; /// <summary> /// Optional. Gets or sets the name. /// </summary> public string FriendlyName { get { return this._friendlyName; } set { this._friendlyName = value; } } private System.DateTime? _lastSuccessfulFailoverTime; /// <summary> /// Optional. Gets or sets the Last successful failover time. /// </summary> public System.DateTime? LastSuccessfulFailoverTime { get { return this._lastSuccessfulFailoverTime; } set { this._lastSuccessfulFailoverTime = value; } } private System.DateTime? _lastSuccessfulTestFailoverTime; /// <summary> /// Optional. Gets or sets the Last successful test failover time. /// </summary> public System.DateTime? LastSuccessfulTestFailoverTime { get { return this._lastSuccessfulTestFailoverTime; } set { this._lastSuccessfulTestFailoverTime = value; } } private string _policyFriendlyName; /// <summary> /// Optional. Gets or sets the name of Policy governing this PE. /// </summary> public string PolicyFriendlyName { get { return this._policyFriendlyName; } set { this._policyFriendlyName = value; } } private string _policyID; /// <summary> /// Optional. Gets or sets the ID of Policy governing this PE. /// </summary> public string PolicyID { get { return this._policyID; } set { this._policyID = value; } } private string _primaryFabricFriendlyName; /// <summary> /// Optional. Gets or sets the friendly name of the primary fabric. /// </summary> public string PrimaryFabricFriendlyName { get { return this._primaryFabricFriendlyName; } set { this._primaryFabricFriendlyName = value; } } private string _primaryProtectionContainerFriendlyName; /// <summary> /// Optional. Gets or sets the name of primary protection container /// friendly name. /// </summary> public string PrimaryProtectionContainerFriendlyName { get { return this._primaryProtectionContainerFriendlyName; } set { this._primaryProtectionContainerFriendlyName = value; } } private string _protectableItemId; /// <summary> /// Optional. Gets or sets the protected item Id. /// </summary> public string ProtectableItemId { get { return this._protectableItemId; } set { this._protectableItemId = value; } } private string _protectedItemType; /// <summary> /// Optional. Gets or sets the type of protected item type. /// </summary> public string ProtectedItemType { get { return this._protectedItemType; } set { this._protectedItemType = value; } } private string _protectionState; /// <summary> /// Optional. Gets or sets the protection status. /// </summary> public string ProtectionState { get { return this._protectionState; } set { this._protectionState = value; } } private string _protectionStateDescription; /// <summary> /// Optional. Gets or sets the protection state description. /// </summary> public string ProtectionStateDescription { get { return this._protectionStateDescription; } set { this._protectionStateDescription = value; } } private ReplicationProviderSpecificSettings _providerSpecificDetails; /// <summary> /// Optional. Gets or sets the Replication provider custom settings. /// </summary> public ReplicationProviderSpecificSettings ProviderSpecificDetails { get { return this._providerSpecificDetails; } set { this._providerSpecificDetails = value; } } private string _recoveryFabricFriendlyName; /// <summary> /// Optional. Gets or sets the friendly name of recovery fabric. /// </summary> public string RecoveryFabricFriendlyName { get { return this._recoveryFabricFriendlyName; } set { this._recoveryFabricFriendlyName = value; } } private string _recoveryFabricId; /// <summary> /// Optional. Gets or sets the Arm Id of recovery fabric. /// </summary> public string RecoveryFabricId { get { return this._recoveryFabricId; } set { this._recoveryFabricId = value; } } private string _recoveryProtectionContainerFriendlyName; /// <summary> /// Optional. Gets or sets the name of recovery container friendly name. /// </summary> public string RecoveryProtectionContainerFriendlyName { get { return this._recoveryProtectionContainerFriendlyName; } set { this._recoveryProtectionContainerFriendlyName = value; } } private string _recoveryServicesProviderId; /// <summary> /// Optional. Gets or sets the recovery provider name. /// </summary> public string RecoveryServicesProviderId { get { return this._recoveryServicesProviderId; } set { this._recoveryServicesProviderId = value; } } private string _replicationHealth; /// <summary> /// Optional. Gets or sets the consolidated protection health /// </summary> public string ReplicationHealth { get { return this._replicationHealth; } set { this._replicationHealth = value; } } private IList<HealthError> _replicationHealthErrors; /// <summary> /// Optional. Gets or sets list of replication health errors. /// </summary> public IList<HealthError> ReplicationHealthErrors { get { return this._replicationHealthErrors; } set { this._replicationHealthErrors = value; } } private string _testFailoverState; /// <summary> /// Optional. Gets or sets the Test failover state. /// </summary> public string TestFailoverState { get { return this._testFailoverState; } set { this._testFailoverState = value; } } private string _testFailoverStateDescription; /// <summary> /// Optional. Gets or sets the Test failover state description. /// </summary> public string TestFailoverStateDescription { get { return this._testFailoverStateDescription; } set { this._testFailoverStateDescription = value; } } /// <summary> /// Initializes a new instance of the /// ReplicationProtectedItemProperties class. /// </summary> public ReplicationProtectedItemProperties() { this.AllowedOperations = new LazyList<string>(); this.ReplicationHealthErrors = new LazyList<HealthError>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; namespace System.Runtime.Serialization { #if uapaot public class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext #else internal class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext #endif { private bool _preserveObjectReferences; private SerializationMode _mode; private ISerializationSurrogateProvider _serializationSurrogateProvider; internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { _mode = SerializationMode.SharedContract; _preserveObjectReferences = serializer.PreserveObjectReferences; _serializationSurrogateProvider = serializer.SerializationSurrogateProvider; } internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal override SerializationMode Mode { get { return _mode; } } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns) { if (_mode == SerializationMode.SharedContract) { if (_serializationSurrogateProvider == null) return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns); else return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null /*surrogateDataContract*/, name, ns); } else { return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns); } } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { if (_mode == SerializationMode.SharedContract) { if (_serializationSurrogateProvider == null) return base.InternalDeserialize(xmlReader, declaredType, name, ns); else return InternalDeserializeWithSurrogate(xmlReader, declaredType, null /*surrogateDataContract*/, name, ns); } else { return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns); } } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (_mode == SerializationMode.SharedContract) { if (_serializationSurrogateProvider == null) return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns); else return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns); } else { return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns); } } private object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns) { object retObj = null; if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj)) return retObj; DataContract dataContract; string assemblyName = attributes.ClrAssembly; string typeName = attributes.ClrType; if (assemblyName != null && typeName != null) { Assembly assembly; Type type; dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type); if (dataContract == null) { if (assembly == null) throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.AssemblyNotFound, assemblyName)); if (type == null) throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ClrTypeNotFound, assembly.FullName, typeName)); } //Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array if (declaredType != null && declaredType.IsArray) dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle); } else { if (assemblyName != null) throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))); else if (typeName != null) throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))); else if (declaredType == null) throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))); dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle); } return ReadDataContractValue(dataContract, xmlReader); } private object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns) { DataContract dataContract = surrogateDataContract ?? GetDataContract(DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, declaredType)); if (this.IsGetOnlyCollection && dataContract.UnderlyingType != declaredType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(declaredType)))); } ReadAttributes(xmlReader); string objectId = GetObjectId(); object oldObj = InternalDeserialize(xmlReader, name, ns, ref dataContract); object obj = DataContractSurrogateCaller.GetDeserializedObject(_serializationSurrogateProvider, oldObj, dataContract.UnderlyingType, declaredType); ReplaceDeserializedObject(objectId, oldObj, obj); return obj; } private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly) { throw new PlatformNotSupportedException(); } private DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type) { type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly); if (type != null) { return GetDataContract(type); } return null; } protected override DataContract ResolveDataContractFromTypeName() { if (_mode == SerializationMode.SharedContract) { return base.ResolveDataContractFromTypeName(); } else { if (attributes.ClrAssembly != null && attributes.ClrType != null) { Assembly assembly; Type type; return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type); } } return null; } internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { if (_serializationSurrogateProvider != null) { while (memberType.IsArray) memberType = memberType.GetElementType(); memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType); if (!DataContract.IsTypeSerializable(memberType)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType))); return; } base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable); } internal override Type GetSurrogatedType(Type type) { if (_serializationSurrogateProvider == null) { return base.GetSurrogatedType(type); } else { type = DataContract.UnwrapNullableType(type); Type surrogateType = DataContractSerializer.GetSurrogatedType(_serializationSurrogateProvider, type); if (this.IsGetOnlyCollection && surrogateType != type) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(type)))); } else { return surrogateType; } } } #if USE_REFEMIT public override int GetArraySize() #else internal override int GetArraySize() #endif { return _preserveObjectReferences ? attributes.ArraySZSize : -1; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Mapping { using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Resources; using System.Linq; using Xunit; public class AssociationSetMappingTests { [Fact] public void Can_add_get_remove_column_conditions() { var entitySet1 = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet1); Assert.Empty(associationSetMapping.Conditions); var conditionPropertyMapping = new ConditionPropertyMapping(null, new EdmProperty("C", TypeUsage.Create(new PrimitiveType() { DataSpace = DataSpace.SSpace })), 42, null); associationSetMapping.AddCondition(conditionPropertyMapping); Assert.Same(conditionPropertyMapping, associationSetMapping.Conditions.Single()); associationSetMapping.RemoveCondition(conditionPropertyMapping); Assert.Empty(associationSetMapping.Conditions); } [Fact] public void Can_initialize_with_entity_set() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var conditionPropertyMapping = new ConditionPropertyMapping(null, new EdmProperty("C", TypeUsage.Create(new PrimitiveType() { DataSpace = DataSpace.SSpace })), 42, null); associationSetMapping.SetReadOnly(); var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var associationTypeMapping = associationSetMapping.TypeMappings.Single(); Assert.NotNull(associationTypeMapping); Assert.Same(associationSet.ElementType, associationTypeMapping.Types.Single()); Assert.Same(associationSetMapping, associationTypeMapping.SetMapping); var mappingFragment = associationTypeMapping.MappingFragments.Single(); Assert.Same(entitySet, mappingFragment.TableSet); } [Fact] public void Can_get_association_set() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); Assert.Same(associationSet, associationSetMapping.AssociationSet); } [Fact] public void Can_get_and_set_store_entity_set() { var entitySet1 = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet1); Assert.Same(entitySet1, associationSetMapping.StoreEntitySet); var entitySet2 = new EntitySet(); associationSetMapping.StoreEntitySet = entitySet2; Assert.Same(entitySet2, associationSetMapping.StoreEntitySet); } [Fact] public void Can_get_table() { var entityType = new EntityType("E", "N", DataSpace.CSpace); var entitySet = new EntitySet("ES", null, null, null, entityType); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); Assert.Same(entityType, associationSetMapping.Table); } [Fact] public void Can_get_and_set_source_and_target_end_mappings() { var entitySet1 = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet1); Assert.Null(associationSetMapping.SourceEndMapping); Assert.Null(associationSetMapping.TargetEndMapping); var sourceEndMapping = new EndPropertyMapping(); associationSetMapping.SourceEndMapping = sourceEndMapping; Assert.Same(sourceEndMapping, associationSetMapping.SourceEndMapping); var targetEndMapping = new EndPropertyMapping(); associationSetMapping.TargetEndMapping = targetEndMapping; Assert.Same(targetEndMapping, associationSetMapping.TargetEndMapping); } [Fact] public void Cannot_set_source_end_mapping_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var sourceEndMapping = new EndPropertyMapping(); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => (associationSetMapping.SourceEndMapping = sourceEndMapping)).Message); } [Fact] public void Cannot_set_target_end_mapping_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var targetEndMapping = new EndPropertyMapping(); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => (associationSetMapping.TargetEndMapping = targetEndMapping)).Message); } [Fact] public void Cannot_set__modification_function_mapping_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var modificationFunctionMapping = new AssociationSetModificationFunctionMapping(associationSet, null, null); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => (associationSetMapping.ModificationFunctionMapping = modificationFunctionMapping)).Message); } [Fact] public void Cannot_add_condition_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var conditionPropertyMapping = new ConditionPropertyMapping(null, new EdmProperty("C", TypeUsage.Create(new PrimitiveType() { DataSpace = DataSpace.SSpace })), 42, null); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => associationSetMapping.AddCondition(conditionPropertyMapping)).Message); } [Fact] public void Cannot_remove_condition_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var conditionPropertyMapping = new ConditionPropertyMapping(null, new EdmProperty("C", TypeUsage.Create(new PrimitiveType() { DataSpace = DataSpace.SSpace })), 42, null); associationSetMapping.AddCondition(conditionPropertyMapping); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => associationSetMapping.RemoveCondition(conditionPropertyMapping)).Message); } [Fact] public void SetReadOnly_is_called_on_child_mapping_items() { var entityType = new EntityType("ET", "N", DataSpace.SSpace); var entitySet = new EntitySet("ES", "S", "T", "Q", entityType); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet, null); var modificationFunctionMapping = new AssociationSetModificationFunctionMapping(associationSet, null, null); associationSetMapping.ModificationFunctionMapping = modificationFunctionMapping; Assert.False(associationSetMapping.AssociationTypeMapping.IsReadOnly); Assert.False(modificationFunctionMapping.IsReadOnly); associationSetMapping.SetReadOnly(); Assert.True(associationSetMapping.AssociationTypeMapping.IsReadOnly); Assert.True(modificationFunctionMapping.IsReadOnly); } } }
// ZipNameTransform.cs // // Copyright 2005 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using System.Text; using GitHub.ICSharpCode.SharpZipLib.Core; namespace GitHub.ICSharpCode.SharpZipLib.Zip { /// <summary> /// ZipNameTransform transforms names as per the Zip file naming convention. /// </summary> /// <remarks>The use of absolute names is supported although its use is not valid /// according to Zip naming conventions, and should not be used if maximum compatability is desired.</remarks> public class ZipNameTransform : INameTransform { #region Constructors /// <summary> /// Initialize a new instance of <see cref="ZipNameTransform"></see> /// </summary> public ZipNameTransform() { } /// <summary> /// Initialize a new instance of <see cref="ZipNameTransform"></see> /// </summary> /// <param name="trimPrefix">The string to trim from the front of paths if found.</param> public ZipNameTransform(string trimPrefix) { TrimPrefix = trimPrefix; } #endregion /// <summary> /// Static constructor. /// </summary> static ZipNameTransform() { char[] invalidPathChars; #if NET_1_0 || NET_1_1 || NETCF_1_0 invalidPathChars = Path.InvalidPathChars; #else invalidPathChars = Path.GetInvalidPathChars(); #endif int howMany = invalidPathChars.Length + 2; InvalidEntryCharsRelaxed = new char[howMany]; Array.Copy(invalidPathChars, 0, InvalidEntryCharsRelaxed, 0, invalidPathChars.Length); InvalidEntryCharsRelaxed[howMany - 1] = '*'; InvalidEntryCharsRelaxed[howMany - 2] = '?'; howMany = invalidPathChars.Length + 4; InvalidEntryChars = new char[howMany]; Array.Copy(invalidPathChars, 0, InvalidEntryChars, 0, invalidPathChars.Length); InvalidEntryChars[howMany - 1] = ':'; InvalidEntryChars[howMany - 2] = '\\'; InvalidEntryChars[howMany - 3] = '*'; InvalidEntryChars[howMany - 4] = '?'; } /// <summary> /// Transform a windows directory name according to the Zip file naming conventions. /// </summary> /// <param name="name">The directory name to transform.</param> /// <returns>The transformed name.</returns> public string TransformDirectory(string name) { name = TransformFile(name); if (name.Length > 0) { if ( !name.EndsWith("/") ) { name += "/"; } } else { throw new ZipException("Cannot have an empty directory name"); } return name; } /// <summary> /// Transform a windows file name according to the Zip file naming conventions. /// </summary> /// <param name="name">The file name to transform.</param> /// <returns>The transformed name.</returns> public string TransformFile(string name) { if (name != null) { string lowerName = name.ToLower(); if ( (trimPrefix_ != null) && (lowerName.IndexOf(trimPrefix_) == 0) ) { name = name.Substring(trimPrefix_.Length); } name = name.Replace(@"\", "/"); name = WindowsPathUtils.DropPathRoot(name); // Drop any leading slashes. while ((name.Length > 0) && (name[0] == '/')) { name = name.Remove(0, 1); } // Drop any trailing slashes. while ((name.Length > 0) && (name[name.Length - 1] == '/')) { name = name.Remove(name.Length - 1, 1); } // Convert consecutive // characters to / int index = name.IndexOf("//"); while (index >= 0) { name = name.Remove(index, 1); index = name.IndexOf("//"); } name = MakeValidName(name, '_'); } else { name = string.Empty; } return name; } /// <summary> /// Get/set the path prefix to be trimmed from paths if present. /// </summary> /// <remarks>The prefix is trimmed before any conversion from /// a windows path is done.</remarks> public string TrimPrefix { get { return trimPrefix_; } set { trimPrefix_ = value; if (trimPrefix_ != null) { trimPrefix_ = trimPrefix_.ToLower(); } } } /// <summary> /// Force a name to be valid by replacing invalid characters with a fixed value /// </summary> /// <param name="name">The name to force valid</param> /// <param name="replacement">The replacement character to use.</param> /// <returns>Returns a valid name</returns> static string MakeValidName(string name, char replacement) { int index = name.IndexOfAny(InvalidEntryChars); if (index >= 0) { StringBuilder builder = new StringBuilder(name); while (index >= 0 ) { builder[index] = replacement; if (index >= name.Length) { index = -1; } else { index = name.IndexOfAny(InvalidEntryChars, index + 1); } } name = builder.ToString(); } if (name.Length > 0xffff) { throw new PathTooLongException(); } return name; } /// <summary> /// Test a name to see if it is a valid name for a zip entry. /// </summary> /// <param name="name">The name to test.</param> /// <param name="relaxed">If true checking is relaxed about windows file names and absolute paths.</param> /// <returns>Returns true if the name is a valid zip name; false otherwise.</returns> /// <remarks>Zip path names are actually in Unix format, and should only contain relative paths. /// This means that any path stored should not contain a drive or /// device letter, or a leading slash. All slashes should forward slashes '/'. /// An empty name is valid for a file where the input comes from standard input. /// A null name is not considered valid. /// </remarks> public static bool IsValidName(string name, bool relaxed) { bool result = (name != null); if ( result ) { if ( relaxed ) { result = name.IndexOfAny(InvalidEntryCharsRelaxed) < 0; } else { result = (name.IndexOfAny(InvalidEntryChars) < 0) && (name.IndexOf('/') != 0); } } return result; } /// <summary> /// Test a name to see if it is a valid name for a zip entry. /// </summary> /// <param name="name">The name to test.</param> /// <returns>Returns true if the name is a valid zip name; false otherwise.</returns> /// <remarks>Zip path names are actually in unix format, /// and should only contain relative paths if a path is present. /// This means that the path stored should not contain a drive or /// device letter, or a leading slash. All slashes should forward slashes '/'. /// An empty name is valid where the input comes from standard input. /// A null name is not considered valid. /// </remarks> public static bool IsValidName(string name) { bool result = (name != null) && (name.IndexOfAny(InvalidEntryChars) < 0) && (name.IndexOf('/') != 0) ; return result; } #region Instance Fields string trimPrefix_; #endregion #region Class Fields static readonly char[] InvalidEntryChars; static readonly char[] InvalidEntryCharsRelaxed; #endregion } }
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; using Frapid.WebApi; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Smtp Configs. /// </summary> [RoutePrefix("api/v1.0/config/smtp-config")] public class SmtpConfigController : FrapidApiController { /// <summary> /// The SmtpConfig repository. /// </summary> private ISmtpConfigRepository SmtpConfigRepository; public SmtpConfigController() { } public SmtpConfigController(ISmtpConfigRepository repository) { this.SmtpConfigRepository = repository; } protected override void Initialize(HttpControllerContext context) { base.Initialize(context); if (this.SmtpConfigRepository == null) { this.SmtpConfigRepository = new Frapid.Config.DataAccess.SmtpConfig { _Catalog = this.MetaUser.Catalog, _LoginId = this.MetaUser.LoginId, _UserId = this.MetaUser.UserId }; } } /// <summary> /// Creates meta information of "smtp config" entity. /// </summary> /// <returns>Returns the "smtp config" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/config/smtp-config/meta")] [RestAuthorize] public EntityView GetEntityView() { return new EntityView { PrimaryKey = "smtp_id", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "smtp_id", PropertyName = "SmtpId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "configuration_name", PropertyName = "ConfigurationName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "enabled", PropertyName = "Enabled", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "is_default", PropertyName = "IsDefault", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "from_display_name", PropertyName = "FromDisplayName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "from_email_address", PropertyName = "FromEmailAddress", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "smtp_host", PropertyName = "SmtpHost", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "smtp_enable_ssl", PropertyName = "SmtpEnableSsl", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "smtp_username", PropertyName = "SmtpUsername", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "smtp_password", PropertyName = "SmtpPassword", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "smtp_port", PropertyName = "SmtpPort", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "audit_user_id", PropertyName = "AuditUserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "audit_ts", PropertyName = "AuditTs", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } /// <summary> /// Counts the number of smtp configs. /// </summary> /// <returns>Returns the count of the smtp configs.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/smtp-config/count")] [RestAuthorize] public long Count() { try { return this.SmtpConfigRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns all collection of smtp config. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/config/smtp-config/all")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetAll() { try { return this.SmtpConfigRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of smtp config for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/config/smtp-config/export")] [RestAuthorize] public IEnumerable<dynamic> Export() { try { return this.SmtpConfigRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns an instance of smtp config. /// </summary> /// <param name="smtpId">Enter SmtpId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{smtpId}")] [Route("~/api/config/smtp-config/{smtpId}")] [RestAuthorize] public Frapid.Config.Entities.SmtpConfig Get(int smtpId) { try { return this.SmtpConfigRepository.Get(smtpId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/config/smtp-config/get")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.SmtpConfig> Get([FromUri] int[] smtpIds) { try { return this.SmtpConfigRepository.Get(smtpIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the first instance of smtp config. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/config/smtp-config/first")] [RestAuthorize] public Frapid.Config.Entities.SmtpConfig GetFirst() { try { return this.SmtpConfigRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the previous instance of smtp config. /// </summary> /// <param name="smtpId">Enter SmtpId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{smtpId}")] [Route("~/api/config/smtp-config/previous/{smtpId}")] [RestAuthorize] public Frapid.Config.Entities.SmtpConfig GetPrevious(int smtpId) { try { return this.SmtpConfigRepository.GetPrevious(smtpId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the next instance of smtp config. /// </summary> /// <param name="smtpId">Enter SmtpId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{smtpId}")] [Route("~/api/config/smtp-config/next/{smtpId}")] [RestAuthorize] public Frapid.Config.Entities.SmtpConfig GetNext(int smtpId) { try { return this.SmtpConfigRepository.GetNext(smtpId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the last instance of smtp config. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/config/smtp-config/last")] [RestAuthorize] public Frapid.Config.Entities.SmtpConfig GetLast() { try { return this.SmtpConfigRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 smtp configs on each page, sorted by the property SmtpId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/smtp-config")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetPaginatedResult() { try { return this.SmtpConfigRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 smtp configs on each page, sorted by the property SmtpId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/smtp-config/page/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetPaginatedResult(long pageNumber) { try { return this.SmtpConfigRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of smtp configs using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered smtp configs.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/smtp-config/count-where")] [RestAuthorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.SmtpConfigRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 smtp configs on each page, sorted by the property SmtpId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/smtp-config/get-where/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.SmtpConfigRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of smtp configs using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered smtp configs.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/smtp-config/count-filtered/{filterName}")] [RestAuthorize] public long CountFiltered(string filterName) { try { return this.SmtpConfigRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 smtp configs on each page, sorted by the property SmtpId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/smtp-config/get-filtered/{pageNumber}/{filterName}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.SmtpConfig> GetFiltered(long pageNumber, string filterName) { try { return this.SmtpConfigRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of smtp configs. /// </summary> /// <returns>Returns an enumerable key/value collection of smtp configs.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/config/smtp-config/display-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { try { return this.SmtpConfigRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for smtp configs. /// </summary> /// <returns>Returns an enumerable custom field collection of smtp configs.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/config/smtp-config/custom-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields() { try { return this.SmtpConfigRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for smtp configs. /// </summary> /// <returns>Returns an enumerable custom field collection of smtp configs.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/config/smtp-config/custom-fields/{resourceId}")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { try { return this.SmtpConfigRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds or edits your instance of SmtpConfig class. /// </summary> /// <param name="smtpConfig">Your instance of smtp configs class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/config/smtp-config/add-or-edit")] [RestAuthorize] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic smtpConfig = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer()); if (smtpConfig == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { return this.SmtpConfigRepository.AddOrEdit(smtpConfig, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds your instance of SmtpConfig class. /// </summary> /// <param name="smtpConfig">Your instance of smtp configs class to add.</param> [AcceptVerbs("POST")] [Route("add/{smtpConfig}")] [Route("~/api/config/smtp-config/add/{smtpConfig}")] [RestAuthorize] public void Add(Frapid.Config.Entities.SmtpConfig smtpConfig) { if (smtpConfig == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.SmtpConfigRepository.Add(smtpConfig); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Edits existing record with your instance of SmtpConfig class. /// </summary> /// <param name="smtpConfig">Your instance of SmtpConfig class to edit.</param> /// <param name="smtpId">Enter the value for SmtpId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{smtpId}")] [Route("~/api/config/smtp-config/edit/{smtpId}")] [RestAuthorize] public void Edit(int smtpId, [FromBody] Frapid.Config.Entities.SmtpConfig smtpConfig) { if (smtpConfig == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.SmtpConfigRepository.Update(smtpConfig, smtpId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of SmtpConfig class. /// </summary> /// <param name="collection">Your collection of SmtpConfig class to bulk import.</param> /// <returns>Returns list of imported smtpIds.</returns> /// <exception cref="DataAccessException">Thrown when your any SmtpConfig class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/config/smtp-config/bulk-import")] [RestAuthorize] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> smtpConfigCollection = this.ParseCollection(collection); if (smtpConfigCollection == null || smtpConfigCollection.Count.Equals(0)) { return null; } try { return this.SmtpConfigRepository.BulkImport(smtpConfigCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Deletes an existing instance of SmtpConfig class via SmtpId. /// </summary> /// <param name="smtpId">Enter the value for SmtpId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{smtpId}")] [Route("~/api/config/smtp-config/delete/{smtpId}")] [RestAuthorize] public void Delete(int smtpId) { try { this.SmtpConfigRepository.Delete(smtpId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
// <copyright file="PlayGamesLocalUser.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> namespace GooglePlayGames { using System; using GooglePlayGames.BasicApi; using UnityEngine.SocialPlatforms; /// <summary> /// Represents the Google Play Games local user. /// </summary> public class PlayGamesLocalUser : PlayGamesUserProfile, ILocalUser { internal PlayGamesPlatform mPlatform; private string emailAddress; private PlayerStats mStats; internal PlayGamesLocalUser(PlayGamesPlatform plaf) : base("localUser", string.Empty, string.Empty) { mPlatform = plaf; emailAddress = null; mStats = null; } /// <summary> /// Authenticates the local user. Equivalent to calling /// <see cref="PlayGamesPlatform.Authenticate" />. /// </summary> public void Authenticate(Action<bool> callback) { mPlatform.Authenticate(callback); } /// <summary> /// Authenticates the local user. Equivalent to calling /// <see cref="PlayGamesPlatform.Authenticate" />. /// </summary> public void Authenticate(Action<bool> callback, bool silent) { mPlatform.Authenticate(callback, silent); } /// <summary> /// Loads all friends of the authenticated user. /// </summary> public void LoadFriends(Action<bool> callback) { mPlatform.LoadFriends(this, callback); } /// <summary> /// Synchronous version of friends, returns null until loaded. /// </summary> public IUserProfile[] friends { get { return mPlatform.GetFriends(); } } /// <summary> /// Gets an id token for the user. /// NOTE: This property can only be accessed using the main Unity thread. /// </summary> /// <param name="idTokenCallback"> A callback to be invoked after token is retrieved. Will be passed null value /// on failure. </param> [Obsolete("Use PlayGamesPlatform.GetServerAuthCode()")] public void GetIdToken(Action<string> idTokenCallback) { if(authenticated) mPlatform.GetIdToken(idTokenCallback); else idTokenCallback(null); } /// <summary> /// Returns whether or not the local user is authenticated to Google Play Games. /// </summary> /// <returns> /// <c>true</c> if authenticated; otherwise, <c>false</c>. /// </returns> public bool authenticated { get { return mPlatform.IsAuthenticated(); } } /// <summary> /// Not implemented. As safety placeholder, returns true. /// </summary> public bool underage { get { return true; } } /// <summary> /// Gets the display name of the user. /// </summary> /// <returns> /// The display name of the user. /// </returns> public new string userName { get { string retval = string.Empty; if (authenticated) { retval = mPlatform.GetUserDisplayName(); if (!base.userName.Equals(retval)) { ResetIdentity(retval, mPlatform.GetUserId(), mPlatform.GetUserImageUrl()); } } return retval; } } /// <summary> /// Gets the user's Google id. /// </summary> /// <returns> /// The user's Google id. /// </returns> public new string id { get { string retval = string.Empty; if (authenticated) { retval = mPlatform.GetUserId(); if (!base.id.Equals(retval)) { ResetIdentity(mPlatform.GetUserDisplayName(), retval, mPlatform.GetUserImageUrl()); } } return retval; } } /// <summary> /// Gets an access token for the user. /// NOTE: This property can only be accessed using the main Unity thread. /// </summary> /// <returns> /// An id token for the user. /// </returns> [Obsolete("Use PlayGamesPlatform.GetServerAuthCode()")] public string accessToken { get { return authenticated ? mPlatform.GetAccessToken() : string.Empty; } } /// <summary> /// Returns true (since this is the local user). /// </summary> public new bool isFriend { get { return true; } } /// <summary> /// Gets the local user's state. This is always <c>UserState.Online</c> for /// the local user. /// </summary> public new UserState state { get { return UserState.Online; } } public new string AvatarURL { get { string retval = string.Empty; if (authenticated) { retval = mPlatform.GetUserImageUrl(); if (!base.id.Equals(retval)) { ResetIdentity(mPlatform.GetUserDisplayName(), mPlatform.GetUserId(), retval); } } return retval; } } /// <summary>Gets the email of the signed in player.</summary> /// <remarks>If your game requires a persistent, unique id for the /// player, the use of PlayerId is recommendend since it does not /// require extra permission consent from the user. /// This is only available if the Requires Google Plus option /// is added to the setup (which enables additional /// permissions for the application). /// NOTE: This property can only be accessed using the main Unity thread. /// </remarks> /// <value>The email.</value> public string Email { get { // treat null as unitialized, empty as no email. This can // happen when the web client is not initialized. if (authenticated && string.IsNullOrEmpty(emailAddress)) { emailAddress = mPlatform.GetUserEmail(); emailAddress = emailAddress ?? string.Empty; } return authenticated ? emailAddress : string.Empty; } } /// <summary> /// Gets the player's stats. /// </summary> /// <param name="callback">Callback when they are available.</param> public void GetStats(Action<CommonStatusCodes, PlayerStats> callback) { if (mStats == null || !mStats.Valid) { mPlatform.GetPlayerStats((rc, stats) => { mStats = stats; callback(rc, stats); }); } else { // 0 = success callback(CommonStatusCodes.Success, mStats); } } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData.Query { #region Namespaces using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Spatial; using System.Text; using System.Xml; using Microsoft.Data.Edm; using Microsoft.Data.OData.Json; using Microsoft.Data.OData.Metadata; using o = Microsoft.Data.OData; #endregion /// <summary> /// Utility functions for writing values for use in a URL. /// </summary> internal static class ODataUriConversionUtils { /// <summary> /// Converts a primitive to a string for use in a Url. /// </summary> /// <param name="value">Value to convert.</param> /// <param name="version">OData version to be compliant with.</param> /// <returns>A string representation of <paramref name="value"/> to be added to a Url.</returns> internal static string ConvertToUriPrimitiveLiteral(object value, ODataVersion version) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(value, "value"); /* This should have the same behavior of Astoria with these differences: (iawillia, 10/7/11) * TODO BUG 292670: Differences betwen Astoria and ODL's Uri literals * 1) Cannot handle the System.Data.Linq.Binary type * 2) Cannot handle the System.Data.Linq.XElement type * 3) Astoria does not put a 'd' or 'D' on double values */ StringBuilder builder = new StringBuilder(); Type valueType = value.GetType(); valueType = Nullable.GetUnderlyingType(valueType) ?? valueType; TypeCode code = o.PlatformHelper.GetTypeCode(valueType); switch (code) { case TypeCode.Boolean: builder.Append(XmlConvert.ToString((bool)value)); return builder.ToString(); case TypeCode.Byte: builder.Append(XmlConvert.ToString((byte)value)); return builder.ToString(); case TypeCode.DateTime: builder.Append(ExpressionConstants.LiteralPrefixDateTime); builder.Append(ExpressionConstants.LiteralSingleQuote); builder.Append(o.PlatformHelper.ConvertDateTimeToString((DateTime)value)); builder.Append(ExpressionConstants.LiteralSingleQuote); return builder.ToString(); case TypeCode.Decimal: builder.Append(XmlConvert.ToString((Decimal)value)); builder.Append(ExpressionConstants.LiteralSuffixDecimal); return builder.ToString(); case TypeCode.Double: builder.Append(AppendDecimalMarkerToDouble(XmlConvert.ToString((Double)value))); builder.Append(ExpressionConstants.LiteralSuffixDouble); return builder.ToString(); case TypeCode.Int16: builder.Append(XmlConvert.ToString((Int16)value)); return builder.ToString(); case TypeCode.Int32: builder.Append(XmlConvert.ToString((Int32)value)); return builder.ToString(); case TypeCode.Int64: builder.Append(XmlConvert.ToString((Int64)value)); builder.Append(ExpressionConstants.LiteralSuffixInt64); return builder.ToString(); case TypeCode.Object: if (valueType == typeof(byte[])) { builder.Append(ConvertByteArrayToKeyString((byte[])value)); } else if (valueType == typeof(Guid)) { builder.Append(ExpressionConstants.LiteralPrefixGuid); builder.Append(ExpressionConstants.LiteralSingleQuote); builder.Append(value.ToString()); builder.Append(ExpressionConstants.LiteralSingleQuote); } else if (valueType == typeof(DateTimeOffset)) { builder.Append(ExpressionConstants.LiteralPrefixDateTimeOffset); builder.Append(ExpressionConstants.LiteralSingleQuote); builder.Append(XmlConvert.ToString((DateTimeOffset)value)); builder.Append(ExpressionConstants.LiteralSingleQuote); } else if (valueType == typeof(TimeSpan)) { builder.Append(ExpressionConstants.LiteralPrefixTime); builder.Append(ExpressionConstants.LiteralSingleQuote); builder.Append(XmlConvert.ToString((TimeSpan)value)); builder.Append(ExpressionConstants.LiteralSingleQuote); } else if (typeof(Geography).IsAssignableFrom(valueType)) { ODataVersionChecker.CheckSpatialValue(version); builder.Append(ExpressionConstants.LiteralPrefixGeography); builder.Append(ExpressionConstants.LiteralSingleQuote); builder.Append(WellKnownTextSqlFormatter.Create(true).Write((Geography)value)); builder.Append(ExpressionConstants.LiteralSingleQuote); } else if (typeof(Geometry).IsAssignableFrom(valueType)) { ODataVersionChecker.CheckSpatialValue(version); builder.Append(ExpressionConstants.LiteralPrefixGeometry); builder.Append(ExpressionConstants.LiteralSingleQuote); builder.Append(WellKnownTextSqlFormatter.Create(true).Write((Geometry)value)); builder.Append(ExpressionConstants.LiteralSingleQuote); } else { throw new ODataException(o.Strings.ODataUriUtils_ConvertToUriLiteralUnsupportedType(valueType.ToString())); } return builder.ToString(); case TypeCode.SByte: builder.Append(XmlConvert.ToString((SByte)value)); return builder.ToString(); case TypeCode.Single: builder.Append(XmlConvert.ToString((Single)value)); builder.Append(ExpressionConstants.LiteralSuffixSingle); return builder.ToString(); case TypeCode.String: builder.Append(ExpressionConstants.LiteralSingleQuote); builder.Append(((String)value).Replace("'", "''")); builder.Append(ExpressionConstants.LiteralSingleQuote); return builder.ToString(); default: throw new ODataException(o.Strings.ODataUriUtils_ConvertToUriLiteralUnsupportedType(valueType.ToString())); } } /// <summary> /// Converts the given string <paramref name="value"/> to an ODataComplexValue or ODataCollectionValue and returns it. /// </summary> /// <remarks>Does not handle primitive values.</remarks> /// <param name="value">Value to be deserialized.</param> /// <param name="version">ODataVersion to be compliant with.</param> /// <param name="model">Model to use for verification.</param> /// <param name="typeReference">Expected type reference from deserialization. If null, verification will be skipped.</param> /// <returns>An ODataComplexValue or ODataCollectionValue that results from the deserialization of <paramref name="value"/>.</returns> internal static object ConvertFromComplexOrCollectionValue(string value, ODataVersion version, IEdmModel model, IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); ODataMessageReaderSettings settings = new ODataMessageReaderSettings(); using (StringReader reader = new StringReader(value)) { using (ODataJsonInputContext context = new ODataJsonInputContext( ODataFormat.VerboseJson, reader, settings, version, false /*readingResponse*/, true /*synchronous*/, model, null /*urlResolver*/)) { ODataJsonPropertyAndValueDeserializer deserializer = new ODataJsonPropertyAndValueDeserializer(context); deserializer.ReadPayloadStart(false); object rawResult = deserializer.ReadNonEntityValue(typeReference, null /*DuplicatePropertyNameChecker*/, null /*CollectionWithoutExpectedTypeValidator*/, true /*validateNullValue*/); deserializer.ReadPayloadEnd(false); Debug.Assert(rawResult is ODataComplexValue || rawResult is ODataCollectionValue, "rawResult is ODataComplexValue || rawResult is ODataCollectionValue"); return rawResult; } } } /// <summary> /// Verifies that the given <paramref name="primitiveValue"/> is or can be coerced to <paramref name="expectedTypeReference"/>, and coerces it if necessary. /// </summary> /// <param name="primitiveValue">An EDM primitive value to verify.</param> /// <param name="model">Model to verify against.</param> /// <param name="expectedTypeReference">Expected type reference.</param> /// <param name="version">The version to use for reading.</param> /// <returns>Coerced version of the <paramref name="primitiveValue"/>.</returns> internal static object VerifyAndCoerceUriPrimitiveLiteral(object primitiveValue, IEdmModel model, IEdmTypeReference expectedTypeReference, ODataVersion version) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(primitiveValue, "primitiveValue"); ExceptionUtils.CheckArgumentNotNull(model, "model"); ExceptionUtils.CheckArgumentNotNull(expectedTypeReference, "expectedTypeReference"); // First deal with null literal ODataUriNullValue nullValue = primitiveValue as ODataUriNullValue; if (nullValue != null) { if (!expectedTypeReference.IsNullable) { throw new ODataException(o.Strings.ODataUriUtils_ConvertFromUriLiteralNullOnNonNullableType(expectedTypeReference.ODataFullName())); } IEdmType actualResolvedType = ValidationUtils.ValidateValueTypeName(model, nullValue.TypeName, expectedTypeReference.Definition.TypeKind); Debug.Assert(actualResolvedType != null, "This is a primitive-only codepath so actualResolvedType != null."); if (actualResolvedType.IsSpatial()) { ODataVersionChecker.CheckSpatialValue(version); } if (TypePromotionUtils.CanConvertTo(actualResolvedType.ToTypeReference(), expectedTypeReference)) { nullValue.TypeName = expectedTypeReference.ODataFullName(); return nullValue; } throw new ODataException(o.Strings.ODataUriUtils_ConvertFromUriLiteralNullTypeVerificationFailure(expectedTypeReference.ODataFullName(), nullValue.TypeName)); } // Only other positive case is a numeric primitive that needs to be coerced IEdmPrimitiveTypeReference expectedPrimitiveTypeReference = expectedTypeReference.AsPrimitiveOrNull(); if (expectedPrimitiveTypeReference == null) { throw new ODataException(o.Strings.ODataUriUtils_ConvertFromUriLiteralTypeVerificationFailure(expectedTypeReference.ODataFullName(), primitiveValue)); } object coercedResult = CoerceNumericType(primitiveValue, expectedPrimitiveTypeReference.PrimitiveDefinition()); if (coercedResult != null) { return coercedResult; } Type actualType = primitiveValue.GetType(); Type targetType = TypeUtils.GetNonNullableType(EdmLibraryExtensions.GetPrimitiveClrType(expectedPrimitiveTypeReference)); // If target type is assignable from actual type, we're OK if (targetType.IsAssignableFrom(actualType)) { return primitiveValue; } throw new ODataException(o.Strings.ODataUriUtils_ConvertFromUriLiteralTypeVerificationFailure(expectedPrimitiveTypeReference.ODataFullName(), primitiveValue)); } /// <summary> /// Converts a <see cref="ODataComplexValue"/> to a string for use in a Url. /// </summary> /// <param name="complexValue">Instance to convert.</param> /// <param name="model">Model to be used for validation. User model is optional. The EdmLib core model is expected as a minimum.</param> /// <param name="version">Version to be compliant with.</param> /// <returns>A string representation of <paramref name="complexValue"/> to be added to a Url.</returns> internal static string ConvertToUriComplexLiteral(ODataComplexValue complexValue, IEdmModel model, ODataVersion version) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(complexValue, "complexValue"); ExceptionUtils.CheckArgumentNotNull(model, "model"); StringBuilder builder = new StringBuilder(); using (TextWriter textWriter = new StringWriter(builder, CultureInfo.InvariantCulture)) { JsonWriter jsonWriter = new JsonWriter(textWriter, false); bool writingResponse = false; ODataMessageWriterSettings messageWriterSettings = new ODataMessageWriterSettings() { Version = version }; // Calling dispose since it's the right thing to do, but when created from JsonWriter // the output context Dispose will not actually dispose anything, it will just cleanup itself. using (ODataJsonOutputContext jsonOutputContext = ODataJsonOutputContext.Create( ODataFormat.VerboseJson, jsonWriter, messageWriterSettings, writingResponse, model, null /*urlResolver*/)) { ODataJsonPropertyAndValueSerializer jsonPropertyAndValueSerializer = new ODataJsonPropertyAndValueSerializer(jsonOutputContext); jsonPropertyAndValueSerializer.WriteComplexValue( complexValue, null, /*propertyTypeReference - this call will fill this in and verify if possible*/ true, /*isOpenPropertyType - this determines if the TypeName will be written*/ jsonPropertyAndValueSerializer.CreateDuplicatePropertyNamesChecker(), null /*collectionValidator*/); jsonPropertyAndValueSerializer.AssertRecursionDepthIsZero(); } } return builder.ToString(); } /// <summary> /// Converts an <see cref="ODataUriNullValue"/> to a string for use in a Url. /// </summary> /// <param name="nullValue">Instance to convert.</param> /// <param name="model">Model to verify against. If not a user model, <paramref name="nullValue"/> will only be checked against empty/whitespace.</param> /// <returns>A string representation of <paramref name="nullValue"/> to be added to a Url.</returns> internal static string ConvertToUriNullValue(ODataUriNullValue nullValue, IEdmModel model) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(nullValue, "nullValue"); if (nullValue.TypeName != null) { ValidationUtils.ValidateTypeName(model, nullValue.TypeName); StringBuilder builder = new StringBuilder(); builder.Append(ExpressionConstants.KeywordNull); builder.Append(ExpressionConstants.LiteralSingleQuote); builder.Append(nullValue.TypeName); builder.Append(ExpressionConstants.LiteralSingleQuote); return builder.ToString(); } return ExpressionConstants.KeywordNull; } /// <summary> /// Converts a <see cref="ODataCollectionValue"/> to a string for use in a Url. /// </summary> /// <param name="collectionValue">Instance to convert.</param> /// <param name="model">Model to be used for validation. User model is optional. The EdmLib core model is expected as a minimum.</param> /// <param name="version">Version to be compliant with. Collection requires >= V3.</param> /// <returns>A string representation of <paramref name="collectionValue"/> to be added to a Url.</returns> internal static string ConvertToUriCollectionLiteral(ODataCollectionValue collectionValue, IEdmModel model, ODataVersion version) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(collectionValue, "collectionValue"); ExceptionUtils.CheckArgumentNotNull(model, "model"); ODataVersionChecker.CheckCollectionValue(version); StringBuilder builder = new StringBuilder(); using (TextWriter textWriter = new StringWriter(builder, CultureInfo.InvariantCulture)) { JsonWriter jsonWriter = new JsonWriter(textWriter, false); ODataMessageWriterSettings messageWriterSettings = new ODataMessageWriterSettings() { Version = version }; // Calling dispose since it's the right thing to do, but when created from JsonWriter // the output context Dispose will not actually dispose anything, it will just cleanup itself. using (ODataJsonOutputContext jsonOutputContext = ODataJsonOutputContext.Create( ODataFormat.VerboseJson, jsonWriter, messageWriterSettings, false /*writingResponse*/, model, null /*urlResolver*/)) { ODataJsonPropertyAndValueSerializer jsonPropertyAndValueSerializer = new ODataJsonPropertyAndValueSerializer(jsonOutputContext); jsonPropertyAndValueSerializer.WriteCollectionValue( collectionValue, null, /*propertyTypeRefereence*/ false /*openPropertyType - this determines if the TypeName will be written*/); jsonPropertyAndValueSerializer.AssertRecursionDepthIsZero(); } } return builder.ToString(); } /// <summary>Appends the decimal marker to string form of double value if necessary.</summary> /// <param name="input">Input string.</param> /// <returns>String with decimal marker optionally added.</returns> private static string AppendDecimalMarkerToDouble(string input) { if (input.Contains(".") || input.Contains("INF") || input.Contains("NaN")) { return input; } return input + ".0"; } /// <summary> /// Coerces the given <paramref name="primitiveValue"/> to the appropriate CLR type based on <paramref name="targetEdmType"/>. /// </summary> /// <param name="primitiveValue">Primitive value to coerce.</param> /// <param name="targetEdmType">Edm primitive type to check against.</param> /// <returns><paramref name="primitiveValue"/> as the corresponding CLR type indicated by <paramref name="targetEdmType"/>, or null if unable to coerce.</returns> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Centralized method for coercing numeric types in easiest to understand.")] private static object CoerceNumericType(object primitiveValue, IEdmPrimitiveType targetEdmType) { // This is implemented to match TypePromotionUtils and MetadataUtilsCommon.CanConvertPrimitiveTypeTo() DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(primitiveValue, "primitiveValue"); ExceptionUtils.CheckArgumentNotNull(targetEdmType, "targetEdmType"); Type fromType = primitiveValue.GetType(); TypeCode fromTypeCode = o.PlatformHelper.GetTypeCode(fromType); EdmPrimitiveTypeKind targetPrimitiveKind = targetEdmType.PrimitiveKind; switch (fromTypeCode) { case TypeCode.SByte: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.SByte: return primitiveValue; case EdmPrimitiveTypeKind.Int16: return Convert.ToInt16((SByte)primitiveValue); case EdmPrimitiveTypeKind.Int32: return Convert.ToInt32((SByte)primitiveValue); case EdmPrimitiveTypeKind.Int64: return Convert.ToInt64((SByte)primitiveValue); case EdmPrimitiveTypeKind.Single: return Convert.ToSingle((SByte)primitiveValue); case EdmPrimitiveTypeKind.Double: return Convert.ToDouble((SByte)primitiveValue); case EdmPrimitiveTypeKind.Decimal: return Convert.ToDecimal((SByte)primitiveValue); } break; case TypeCode.Byte: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Byte: return primitiveValue; case EdmPrimitiveTypeKind.Int16: return Convert.ToInt16((Byte)primitiveValue); case EdmPrimitiveTypeKind.Int32: return Convert.ToInt32((Byte)primitiveValue); case EdmPrimitiveTypeKind.Int64: return Convert.ToInt64((Byte)primitiveValue); case EdmPrimitiveTypeKind.Single: return Convert.ToSingle((Byte)primitiveValue); case EdmPrimitiveTypeKind.Double: return Convert.ToDouble((Byte)primitiveValue); case EdmPrimitiveTypeKind.Decimal: return Convert.ToDecimal((Byte)primitiveValue); } break; case TypeCode.Int16: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Int16: return primitiveValue; case EdmPrimitiveTypeKind.Int32: return Convert.ToInt32((Int16)primitiveValue); case EdmPrimitiveTypeKind.Int64: return Convert.ToInt64((Int16)primitiveValue); case EdmPrimitiveTypeKind.Single: return Convert.ToSingle((Int16)primitiveValue); case EdmPrimitiveTypeKind.Double: return Convert.ToDouble((Int16)primitiveValue); case EdmPrimitiveTypeKind.Decimal: return Convert.ToDecimal((Int16)primitiveValue); } break; case TypeCode.Int32: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Int32: return primitiveValue; case EdmPrimitiveTypeKind.Int64: return Convert.ToInt64((Int32)primitiveValue); case EdmPrimitiveTypeKind.Single: return Convert.ToSingle((Int32)primitiveValue); case EdmPrimitiveTypeKind.Double: return Convert.ToDouble((Int32)primitiveValue); case EdmPrimitiveTypeKind.Decimal: return Convert.ToDecimal((Int32)primitiveValue); } break; case TypeCode.Int64: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Int64: return primitiveValue; case EdmPrimitiveTypeKind.Single: return Convert.ToSingle((Int64)primitiveValue); case EdmPrimitiveTypeKind.Double: return Convert.ToDouble((Int64)primitiveValue); case EdmPrimitiveTypeKind.Decimal: return Convert.ToDecimal((Int64)primitiveValue); } break; case TypeCode.Single: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Single: return primitiveValue; case EdmPrimitiveTypeKind.Double: return Convert.ToDouble((Single)primitiveValue); } break; case TypeCode.Double: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Double: return primitiveValue; } break; case TypeCode.Decimal: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Decimal: return primitiveValue; } break; default: break; } return null; } /// <summary>Converts the given byte[] into string.</summary> /// <param name="byteArray">byte[] that needs to be converted.</param> /// <returns>String containing hex values representing the byte[].</returns> private static string ConvertByteArrayToKeyString(byte[] byteArray) { StringBuilder hexBuilder = new StringBuilder(3 + byteArray.Length * 2); hexBuilder.Append(ExpressionConstants.LiteralPrefixShortBinary); hexBuilder.Append(ExpressionConstants.LiteralSingleQuote); for (int i = 0; i < byteArray.Length; i++) { hexBuilder.Append(byteArray[i].ToString("X2", CultureInfo.InvariantCulture)); } hexBuilder.Append(ExpressionConstants.LiteralSingleQuote); return hexBuilder.ToString(); } } }
using UnityEngine; using System; using System.Text; using System.Collections; namespace TeamUtility.IO { #region [Enumerations] public enum InputDPADButton { Left, Right, Up, Down, Left_Up, Right_Up, Left_Down, Right_Down, Any } public enum InputTriggerButton { Left, Right, Any } public enum InputTriggerAxis { Left, Right } public enum InputDPADAxis { Horizontal, Vertical } public enum InputDevice { KeyboardAndMouse, Joystick } #endregion public sealed class InputAdapter : MonoBehaviour { public event Action<InputDevice> InputDeviceChanged; [SerializeField] private bool dontDestroyOnLoad = false; [SerializeField] private bool allowRealtimeInputDeviceSwitch = true; [SerializeField] [Range(0.1f, 1.0f)] private float updateInputDeviceInterval = 1.0f; [SerializeField] [Range(1.0f, 5.0f)] private float updateJoystickCountInterval = 1.0f; [SerializeField] private string keyboardConfiguration = "KeyboardAndMouse"; [SerializeField] private string windowsJoystickConfiguration = "Windows_Gamepad"; [SerializeField] private string osxJoystickConfiguration = "OSX_Gamepad"; [SerializeField] private string linuxJoystickConfiguration = "Linux_Gamepad"; [SerializeField] private string leftTriggerAxis = "LeftTrigger"; [SerializeField] private string rightTriggerAxis = "RightTrigger"; [SerializeField] private string dpadHorizontalAxis = "DPADHorizontal"; [SerializeField] private string dpadVerticalAxis = "DPADVertical"; private Vector2 _lastDpadValues = Vector2.zero; private Vector2 _currentDpadValues = Vector2.zero; private Vector2 _lastTriggerValues = Vector2.zero; private Vector2 _currentTriggerValues = Vector2.zero; private InputDevice _inputDevice; private int _joystickCount = 0; private int _firstJoystickKey = 330; private bool _canUpdateInputDevice = false; private string _joystickConfiguration; private string _keyboardConfiguration; private static InputAdapter _instance; #region [Static Accessors] public static InputAdapter Instance { get { return _instance; } } public static InputDevice inputDevice { get { return _instance._inputDevice; } set { if(value != _instance._inputDevice) { if(value == InputDevice.Joystick && _instance._joystickCount > 0) { _instance.SetInputDevice(InputDevice.Joystick); } else { _instance.SetInputDevice(InputDevice.KeyboardAndMouse); } } } } public static string KeyboardConfiguration { get { return _instance._keyboardConfiguration; } } public static string JoystickConfiguration { get { return _instance._joystickConfiguration; } } public static Vector3 mousePosition { get { return InputManager.mousePosition; } } public static float GetAxis(string axisName) { return InputManager.GetAxis(axisName); } public static float GetTriggerAxis(InputTriggerAxis axis) { if(_instance._inputDevice == InputDevice.KeyboardAndMouse) return 0.0f; if(axis == InputTriggerAxis.Left) { return InputManager.GetAxis(_instance.leftTriggerAxis); } else { return InputManager.GetAxis(_instance.rightTriggerAxis); } } public static float GetDPADAxis(InputDPADAxis axis) { if(_instance._inputDevice == InputDevice.KeyboardAndMouse) return 0.0f; if(axis == InputDPADAxis.Horizontal) { return InputManager.GetAxis(_instance.dpadHorizontalAxis); } else { return InputManager.GetAxis(_instance.dpadVerticalAxis); } } public static bool GetButton(string buttonName) { return InputManager.GetButton(buttonName); } public static bool GetButtonDown(string buttonName) { return InputManager.GetButtonDown(buttonName); } public static bool GetButtonUp(string buttonName) { return InputManager.GetButtonUp(buttonName); } public static bool GetMouseButton(int button) { return InputManager.GetMouseButton(button); } public static bool GetMouseButtonDown(int button) { return InputManager.GetMouseButtonDown(button); } public static bool GetMouseButtonUp(int button) { return InputManager.GetMouseButtonUp(button); } public static bool GetDPADButton(InputDPADButton button) { if(_instance._inputDevice == InputDevice.KeyboardAndMouse) return false; if(button == InputDPADButton.Any) { return (!Mathf.Approximately(_instance._currentDpadValues.x, 0.0f) || !Mathf.Approximately(_instance._currentDpadValues.y, 0.0f)); } bool state = false; switch(button) { case InputDPADButton.Left_Up: state = (_instance._currentDpadValues.x <= -1.0f && _instance._currentDpadValues.y >= 1.0f); break; case InputDPADButton.Right_Up: state = (_instance._currentDpadValues.x >= 1.0f && _instance._currentDpadValues.y >= 1.0f); break; case InputDPADButton.Left_Down: state = (_instance._currentDpadValues.x <= -1.0f && _instance._currentDpadValues.y <= -1.0f); break; case InputDPADButton.Right_Down: state = (_instance._currentDpadValues.x >= 1.0f && _instance._currentDpadValues.y <= -1.0f); break; case InputDPADButton.Left: state = (_instance._currentDpadValues.x <= -1.0f); break; case InputDPADButton.Right: state = (_instance._currentDpadValues.x >= 1.0f); break; case InputDPADButton.Up: state = (_instance._currentDpadValues.y >= 1.0f); break; case InputDPADButton.Down: state = (_instance._currentDpadValues.y <= -1.0f); break; default: break; } return state; } public static bool GetDPADButtonDown(InputDPADButton button) { if(_instance._inputDevice == InputDevice.KeyboardAndMouse) return false; if(button == InputDPADButton.Any) { return ((!Mathf.Approximately(_instance._currentDpadValues.x, 0.0f) && Mathf.Approximately(_instance._lastDpadValues.x, 0.0f)) || (!Mathf.Approximately(_instance._currentDpadValues.y, 0.0f) && Mathf.Approximately(_instance._lastDpadValues.y, 0.0f))); } bool state = false; switch(button) { case InputDPADButton.Left_Up: state = (_instance._currentDpadValues.x <= -1.0f && _instance._lastDpadValues.x > -1.0f && _instance._currentDpadValues.y >= 1.0f && _instance._lastDpadValues.y < 1.0f); break; case InputDPADButton.Right_Up: state = (_instance._currentDpadValues.x >= 1.0f && _instance._lastDpadValues.x < 1.0f && _instance._currentDpadValues.y >= 1.0f && _instance._lastDpadValues.y < 1.0f); break; case InputDPADButton.Left_Down: state = (_instance._currentDpadValues.x <= -1.0f && _instance._lastDpadValues.x > -1.0f && _instance._currentDpadValues.y <= -1.0f && _instance._lastDpadValues.y > -1.0f); break; case InputDPADButton.Right_Down: state = (_instance._currentDpadValues.x >= 1.0f && _instance._lastDpadValues.x < 1.0f && _instance._currentDpadValues.y <= -1.0f && _instance._lastDpadValues.y > -1.0f); break; case InputDPADButton.Left: state = (_instance._currentDpadValues.x <= -1.0f && _instance._lastDpadValues.x > -1.0f); break; case InputDPADButton.Right: state = (_instance._currentDpadValues.x >= 1.0f && _instance._lastDpadValues.x < 1.0f); break; case InputDPADButton.Up: state = (_instance._currentDpadValues.y >= 1.0f && _instance._lastDpadValues.y < 1.0f); break; case InputDPADButton.Down: state = (_instance._currentDpadValues.y <= -1.0f && _instance._lastDpadValues.y > -1.0f); break; default: break; } return state; } public static bool GetDPADButtonUp(InputDPADButton button) { if(_instance._inputDevice == InputDevice.KeyboardAndMouse) return false; if(button == InputDPADButton.Any) { return ((Mathf.Approximately(_instance._currentDpadValues.x, 0.0f) && !Mathf.Approximately(_instance._lastDpadValues.x, 0.0f)) || (Mathf.Approximately(_instance._currentDpadValues.y, 0.0f) && !Mathf.Approximately(_instance._lastDpadValues.y, 0.0f))); } bool state = false; switch(button) { case InputDPADButton.Left_Up: state = (_instance._currentDpadValues.x > -1.0f && _instance._lastDpadValues.x <= -1.0f && _instance._currentDpadValues.y < 1.0f && _instance._lastDpadValues.y >= 1.0f); break; case InputDPADButton.Right_Up: state = (_instance._currentDpadValues.x < 1.0f && _instance._lastDpadValues.x >= 1.0f && _instance._currentDpadValues.y < 1.0f && _instance._lastDpadValues.y >= 1.0f); break; case InputDPADButton.Left_Down: state = (_instance._currentDpadValues.x > -1.0f && _instance._lastDpadValues.x <= -1.0f && _instance._currentDpadValues.y > -1.0f && _instance._lastDpadValues.y <= -1.0f); break; case InputDPADButton.Right_Down: state = (_instance._currentDpadValues.x < 1.0f && _instance._lastDpadValues.x >= 1.0f && _instance._currentDpadValues.y > -1.0f && _instance._lastDpadValues.y <= -1.0f); break; case InputDPADButton.Left: state = (_instance._currentDpadValues.x > -1.0f && _instance._lastDpadValues.x <= -1.0f); break; case InputDPADButton.Right: state = (_instance._currentDpadValues.x < 1.0f && _instance._lastDpadValues.x >= 1.0f); break; case InputDPADButton.Up: state = (_instance._currentDpadValues.y < 1.0f && _instance._lastDpadValues.y >= 1.0f); break; case InputDPADButton.Down: state = (_instance._currentDpadValues.y > -1.0f && _instance._lastDpadValues.y <= -1.0f); break; default: break; } return state; } public static bool GetTriggerButton(InputTriggerButton button) { if(_instance._inputDevice == InputDevice.KeyboardAndMouse) return false; if(button == InputTriggerButton.Left) { return (_instance._currentTriggerValues.x >= 1.0f); } else if(button == InputTriggerButton.Right) { return (_instance._currentTriggerValues.y >= 1.0f); } else { return (_instance._currentTriggerValues.x >= 1.0f || _instance._currentTriggerValues.y >= 1.0f); } } public static bool GetTriggerButtonDown(InputTriggerButton button) { if(_instance._inputDevice == InputDevice.KeyboardAndMouse) return false; if(button == InputTriggerButton.Left) { return (_instance._currentTriggerValues.x >= 1.0f && _instance._lastTriggerValues.x < 1.0f); } else if(button == InputTriggerButton.Right) { return (_instance._currentTriggerValues.y >= 1.0f && _instance._lastTriggerValues.y < 1.0f); } else { return (_instance._currentTriggerValues.x >= 1.0f && _instance._lastTriggerValues.x < 1.0f) || (_instance._currentTriggerValues.y >= 1.0f && _instance._lastTriggerValues.y < 1.0f); } } public static bool GetTriggerButtonUp(InputTriggerButton button) { if(_instance._inputDevice == InputDevice.KeyboardAndMouse) return false; if(button == InputTriggerButton.Left) { return (_instance._currentTriggerValues.x < 1.0f && _instance._lastTriggerValues.x >= 1.0f); } else if(button == InputTriggerButton.Right) { return (_instance._currentTriggerValues.y < 1.0f && _instance._lastTriggerValues.y >= 1.0f); } else { return (_instance._currentTriggerValues.x < 1.0f && _instance._lastTriggerValues.x >= 1.0f) || (_instance._currentTriggerValues.y < 1.0f && _instance._lastTriggerValues.y >= 1.0f); } } public static void ResetInputAxes() { InputManager.ResetInputAxes(); } public static string[] GetJoystickNames() { return InputManager.GetJoystickNames(); } public static bool IsUsingJoystick() { return (inputDevice == InputDevice.Joystick); } public static bool IsUsingKeyboardAndMouse() { return (inputDevice == InputDevice.KeyboardAndMouse); } #endregion private void Awake() { if(_instance != null) { Destroy(this); } else { SetInputManagerConfigurations(); SetInputDevice(InputDevice.KeyboardAndMouse); _instance = this; _joystickCount = InputManager.GetJoystickNames().Length; if(dontDestroyOnLoad) { DontDestroyOnLoad(gameObject); } } } private void Start() { StartCoroutine(UpdateJoystickCount()); if(allowRealtimeInputDeviceSwitch) { StartCoroutine(SetCanUpdateInputDevice()); } } private void Update() { if(_canUpdateInputDevice) { UpdateInputDevice(); _canUpdateInputDevice = false; } UpdateTriggerAndDPAD(); } private void UpdateTriggerAndDPAD() { if(_inputDevice == InputDevice.Joystick) { _lastDpadValues = _currentDpadValues; _currentDpadValues.x = InputManager.GetAxis(_instance.dpadHorizontalAxis); _currentDpadValues.y = InputManager.GetAxis(_instance.dpadVerticalAxis); _lastTriggerValues = _currentTriggerValues; _currentTriggerValues.x = InputManager.GetAxis(_instance.leftTriggerAxis); _currentTriggerValues.y = InputManager.GetAxis(_instance.rightTriggerAxis); } else { _lastDpadValues = Vector2.zero; _currentDpadValues = Vector2.zero; _lastTriggerValues = Vector2.zero; _lastTriggerValues = Vector2.zero; } } private IEnumerator UpdateJoystickCount() { while(true) { _joystickCount = InputManager.GetJoystickNames().Length; if(_inputDevice == InputDevice.Joystick && _joystickCount == 0) { Debug.LogWarning("Lost connection with joystick. Switching to keyboard and mouse input."); SetInputDevice(InputDevice.KeyboardAndMouse); } yield return new WaitForSeconds(updateJoystickCountInterval); } } private IEnumerator SetCanUpdateInputDevice() { while(true) { _canUpdateInputDevice = true; yield return new WaitForSeconds(updateInputDeviceInterval); } } private void UpdateInputDevice() { bool anyJoystickKey = false; if(_inputDevice == InputDevice.Joystick) { if(InputManager.anyKey) { for(int i = 0; i <= 19; i++) { if(InputManager.GetKey((KeyCode)(_firstJoystickKey + i))) { anyJoystickKey = true; break; } } if(!anyJoystickKey) { SetInputDevice(InputDevice.KeyboardAndMouse); } } else { if(InputManager.AnyInput(_keyboardConfiguration)) { SetInputDevice(InputDevice.KeyboardAndMouse); } } } else { if(InputManager.anyKey) { for(int i = 0; i <= 19; i++) { if(InputManager.GetKey((KeyCode)(_firstJoystickKey + i))) { anyJoystickKey = true; break; } } if(anyJoystickKey) { SetInputDevice(InputDevice.Joystick); } } else { if(InputManager.AnyInput(_joystickConfiguration)) { SetInputDevice(InputDevice.Joystick); } } } } private void SetInputDevice(InputDevice inpuDevice) { _inputDevice = inpuDevice; if(inpuDevice == InputDevice.Joystick) { #if UNITY_5 Cursor.visible = false; #else Screen.showCursor = false; #endif InputManager.SetInputConfiguration(_joystickConfiguration); Debug.Log("Current Input Device: Joystick"); } else { #if UNITY_5 Cursor.visible = true; #else Screen.showCursor = true; #endif InputManager.SetInputConfiguration(_keyboardConfiguration); Debug.Log("Current Input Device: KeyboardAndMouse"); } InputManager.ResetInputAxes(); RaiseInputDeviceChangedEvent(); } private void SetInputManagerConfigurations() { _keyboardConfiguration = keyboardConfiguration; switch(Application.platform) { case RuntimePlatform.WindowsPlayer: case RuntimePlatform.WindowsEditor: case RuntimePlatform.WindowsWebPlayer: _joystickConfiguration = windowsJoystickConfiguration; break; case RuntimePlatform.OSXPlayer: case RuntimePlatform.OSXEditor: case RuntimePlatform.OSXWebPlayer: _joystickConfiguration = osxJoystickConfiguration; break; case RuntimePlatform.LinuxPlayer: _joystickConfiguration = linuxJoystickConfiguration; break; default: Debug.LogWarning("Unsupported XBOX 360 Controller driver. The default Windows driver configuration has been chosen."); _joystickConfiguration = windowsJoystickConfiguration; break; } } private void RaiseInputDeviceChangedEvent() { if(InputDeviceChanged != null) { InputDeviceChanged(_inputDevice); } } private void OnDestroy() { #if UNITY_5 Cursor.visible = true; #else Screen.showCursor = true; #endif StopAllCoroutines(); } #if UNITY_EDITOR [UnityEditor.MenuItem("Team Utility/Input Manager/Create Input Adapter", false, 3)] private static void Create() { GameObject gameObject = new GameObject("Input Adapter"); gameObject.AddComponent<InputAdapter>(); UnityEditor.Selection.activeGameObject = gameObject; } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The decoder (implemented as visitors for the IL) using System; using Generics = System.Collections.Generic; using Microsoft.Research.DataStructures; using System.Diagnostics; using System.Diagnostics.Contracts; namespace Microsoft.Research.CodeAnalysis { /// <summary> /// The wrapper for the analysis, so to share some code (in particular the decoder) /// </summary> public static class ExternalExpressionDecoder { public static IFullExpressionDecoder<Type, Variable, Expression> Create<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>( IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> context ) where Expression : IEquatable<Expression> where Variable : IEquatable<Variable> where Type : IEquatable<Type> { Contract.Requires(context != null); return new TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>.Decoder(context, mdDecoder); } // This class is just to provide bindings to type parameters public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable> where Variable : IEquatable<Variable> where Expression : IEquatable<Expression> where Type : IEquatable<Type> { #region Expression decoder, implementation and helper visitors /// <summary> /// The decoder for the expressions /// </summary> public class Decoder : IFullExpressionDecoder<Type, Variable, Expression> { #region Private environment protected IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> context; protected IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> decoderForMetaData; private VisitorForIsBinaryExpression visitorForIsBinaryExpression; private VisitorForIsUnaryExpression visitorForIsUnaryExpression; private VisitorForVariablesIn visitorForVariablesIn; private VisitorForValueOf visitorForValueOf; private VisitorForIsNull visitorForIsNull; private VisitorForSizeOf visitorForSizeOf; private VisitorForIsInst visitorForIsInst; private VisitorForVariable visitorForVariable; private VisitorForUnderlyingVariable visitorForUnderlyingVariable; private VisitorForDispatch visitorForDispatch; #endregion #region Getters public IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> Context { get { Contract.Ensures(Contract.Result<IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable>>() != null); return this.context; } } #endregion public Decoder(IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> context, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> decoderForMetaData) { Contract.Requires(context != null); this.context = context; this.decoderForMetaData = decoderForMetaData; visitorForIsUnaryExpression = new VisitorForIsUnaryExpression(); visitorForIsBinaryExpression = new VisitorForIsBinaryExpression(); visitorForVariablesIn = new VisitorForVariablesIn(context); visitorForValueOf = new VisitorForValueOf(); visitorForSizeOf = new VisitorForSizeOf(); visitorForIsNull = new VisitorForIsNull(); visitorForVariable = new VisitorForVariable(); visitorForIsInst = new VisitorForIsInst(); visitorForUnderlyingVariable = new VisitorForUnderlyingVariable(); visitorForDispatch = new VisitorForDispatch(this); } #region IFullExpressionDecoder<Type,Field,Expression> Members public bool IsVariable(Expression exp, out object variable) { Variable var; bool result = VisitorForVariable.IsVariable(exp, out var, this); variable = var; return result; } public Variable UnderlyingVariable(Expression exp) { return VisitorForUnderlyingVariable.UnderlyingVariable(exp, this); } public bool IsConstant(Expression exp, out object value, out Type type) { return VisitorForValueOf.IsConstant(exp, out value, out type, this); } public bool IsSizeOf(Expression exp, out Type type) { return VisitorForSizeOf.IsSizeOf(exp, out type, this); } public bool IsInst(Expression exp, out Expression arg, out Type type) { return VisitorForIsInst.IsIsInst(exp, out type, out arg, this); } public bool IsUnaryOperator(Expression exp, out UnaryOperator op, out Expression arg) { return VisitorForIsUnaryExpression.IsUnary(exp, out op, out arg, this); } public bool IsBinaryOperator(Expression exp, out BinaryOperator op, out Expression left, out Expression right) { return VisitorForIsBinaryExpression.IsBinary(exp, out op, out left, out right, this); } public FList<PathElement> GetVariableAccessPath(Expression exp) { return this.context.ValueContext.AccessPathList(this.context.ExpressionContext.GetPC(exp), this.context.ExpressionContext.Unrefine(exp), true, false); } public void AddFreeVariables(Expression exp, Microsoft.Research.DataStructures.IMutableSet<Expression> set) { VisitorForVariablesIn.AddFreeVariables(exp, set, this); } public bool TryGetType(Expression exp, out object type) { var liftedType = this.context.ExpressionContext.GetType(exp); if (liftedType.IsNormal) { type = liftedType.Value; return true; } type = default(object); return false; } #endregion #region The visitors protected abstract class QueryVisitor : IVisitValueExprIL<Expression, Type, Expression, Variable, Unit, bool> { protected static bool Decode<Visitor>(Expression exp, Visitor v, Decoder decoder) where Visitor : QueryVisitor { Contract.Requires(decoder != null); return decoder.Context.ExpressionContext.Decode<Unit, bool, Visitor>(exp, v, Unit.Value); } #region IVisitValueExprIL<Expression,Type,ExternalExpression,Variable,Unit,bool> Members public virtual bool SymbolicConstant(Expression pc, Variable symbol, Unit data) { return false; } #endregion #region IVisitExprIL<Expression,Type,ExternalExpression,Variable,Unit,bool> Members public virtual bool Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, Unit data) { return false; } public virtual bool Isinst(Expression pc, Type type, Variable dest, Expression obj, Unit data) { return false; } public virtual bool Ldconst(Expression pc, object constant, Type type, Variable dest, Unit data) { return false; } public virtual bool Ldnull(Expression pc, Variable dest, Unit data) { return false; } public virtual bool Sizeof(Expression pc, Type type, Variable dest, Unit data) { return false; } public virtual bool Unary(Expression pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Expression source, Unit data) { return false; } public virtual bool Box(Expression pc, Type type, Variable dest, Expression source, Unit data) { return false; } #endregion } private class VisitorForVariable : QueryVisitor { private Variable Variable; public static bool IsVariable(Expression exp, out Variable var, Decoder decoder) { VisitorForVariable visitor = decoder.visitorForVariable; bool result = Decode(exp, visitor, decoder); var = visitor.Variable; return result; } public override bool SymbolicConstant(Expression pc, Variable symbol, Unit data) { Variable = symbol; return true; } } private class VisitorForUnderlyingVariable : QueryVisitor { private Variable Variable; public static Variable UnderlyingVariable(Expression exp, Decoder decoder) { var visitor = decoder.visitorForUnderlyingVariable; var dummy = Decode(exp, visitor, decoder); return visitor.Variable; } public override bool Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, Unit data) { Variable = dest; return true; } public override bool Isinst(Expression pc, Type type, Variable dest, Expression obj, Unit data) { Variable = dest; return true; } public override bool Ldconst(Expression pc, object constant, Type type, Variable dest, Unit data) { Variable = dest; return true; } public override bool Ldnull(Expression pc, Variable dest, Unit data) { Variable = dest; return true; } public override bool Sizeof(Expression pc, Type type, Variable dest, Unit data) { Variable = dest; return true; } public override bool SymbolicConstant(Expression pc, Variable symbol, Unit data) { Variable = symbol; return true; } public override bool Unary(Expression pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Expression source, Unit data) { Variable = dest; return true; } } private class VisitorForIsUnaryExpression : QueryVisitor { private UnaryOperator Operator; private Expression Argument; public static bool IsUnary(Expression exp, out UnaryOperator op, out Expression arg, Decoder decoder) { VisitorForIsUnaryExpression visitor = decoder.visitorForIsUnaryExpression; bool result = Decode(exp, visitor, decoder); op = visitor.Operator; arg = visitor.Argument; return result; } public override bool Unary(Expression pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Expression source, Unit data) { Argument = source; Operator = op; return true; } } private class VisitorForIsBinaryExpression : QueryVisitor { private BinaryOperator Operator; private Expression Left; private Expression Right; public static bool IsBinary(Expression exp, out BinaryOperator op, out Expression left, out Expression right, Decoder decoder) { VisitorForIsBinaryExpression visitor = decoder.visitorForIsBinaryExpression; bool result = Decode(exp, visitor, decoder); op = visitor.Operator; left = visitor.Left; right = visitor.Right; return result; } public override bool Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, Unit data) { Operator = op; Left = s1; Right = s2; return true; } } private class VisitorForVariablesIn : IVisitValueExprIL<Expression, Type, Expression, Variable, Microsoft.Research.DataStructures.IMutableSet<Expression>, Unit> { #region Private state private IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> context; #endregion public VisitorForVariablesIn(IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable>/*!*/ context) { this.context = context; } public static void AddFreeVariables(Expression exp, Microsoft.Research.DataStructures.IMutableSet<Expression> set, Decoder decoder) { decoder.visitorForVariablesIn.Recurse(exp, set); } private void Recurse(Expression exp, Microsoft.Research.DataStructures.IMutableSet<Expression> set) { context.ExpressionContext.Decode<Microsoft.Research.DataStructures.IMutableSet<Expression>, Unit, VisitorForVariablesIn>(exp, this, set); } #region IVisitValueExprIL<Expression,Type,Expression,Variable,Generics.Set<Variable>,Generics.Set<Variable>> Members public Unit SymbolicConstant(Expression pc, Variable symbol, Microsoft.Research.DataStructures.IMutableSet<Expression> data) { data.Add(pc); return Unit.Value; } #endregion #region IVisitExprIL<Expression,Type,Expression,Variable,Generics.Set<Expression>,Microsoft.Research.DataStructures.ISet<Expression>> Members public Unit Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, Microsoft.Research.DataStructures.IMutableSet<Expression> data) { Recurse(s1, data); Recurse(s2, data); return Unit.Value; } public Unit Isinst(Expression pc, Type type, Variable dest, Expression obj, Microsoft.Research.DataStructures.IMutableSet<Expression> data) { data.Add(pc); // TODO: figure out who depends on this! This should not be treated as a free variable! return Unit.Value; } public Unit Ldconst(Expression pc, object constant, Type type, Variable dest, Microsoft.Research.DataStructures.IMutableSet<Expression> data) { return Unit.Value; } public Unit Ldnull(Expression pc, Variable dest, Microsoft.Research.DataStructures.IMutableSet<Expression> data) { return Unit.Value; } public Unit Sizeof(Expression pc, Type type, Variable dest, Microsoft.Research.DataStructures.IMutableSet<Expression> data) { // Why is this used here? TODO: figure out what depends on this! data.Add(pc); return Unit.Value; } public Unit Unary(Expression pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Expression source, Microsoft.Research.DataStructures.IMutableSet<Expression> data) { Recurse(source, data); return Unit.Value; } public Unit Box(Expression pc, Type type, Variable dest, Expression source, IMutableSet<Expression> data) { Recurse(source, data); return Unit.Value; } #endregion } private class VisitorForValueOf : QueryVisitor { #region Private state private Type Type; private object Value; #endregion public static bool IsConstant(Expression exp, out object value, out Type type, Decoder decoder) { VisitorForValueOf visitor = decoder.visitorForValueOf; bool result = Decode(exp, visitor, decoder); value = visitor.Value; type = visitor.Type; return result; } public override bool Ldconst(Expression pc, object constant, Type type, Variable dest, Unit data) { Type = type; Value = constant; return true; } public override bool Ldnull(Expression pc, Variable dest, Unit data) { Type = default(Type); Value = null; return true; } } private class VisitorForSizeOf : QueryVisitor { #region Constructor #endregion private Type Type; public static bool IsSizeOf(Expression exp, out Type type, Decoder decoder) { VisitorForSizeOf visitor = decoder.visitorForSizeOf; bool result = Decode(exp, visitor, decoder); type = visitor.Type; return result; } public override bool Sizeof(Expression pc, Type type, Variable dest, Unit data) { Type = type; return true; } } private class VisitorForIsInst : QueryVisitor { #region Constructor #endregion private Type Type; private Expression Argument; public static bool IsIsInst(Expression exp, out Type type, out Expression arg, Decoder decoder) { VisitorForIsInst visitor = decoder.visitorForIsInst; bool result = Decode(exp, visitor, decoder); type = visitor.Type; arg = visitor.Argument; return result; } public override bool Isinst(Expression pc, Type type, Variable dest, Expression obj, Unit data) { Type = type; Argument = obj; return true; } } #if false private class VisitorForNameOf : IVisitValueExprIL<Expression, Type, Expression, Variable, Unit, string> { #region Private state private IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> context; #endregion #region Constructor public VisitorForNameOf(IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> context) { this.context = context; } #endregion #region IVisitValueExprIL<Expression,Type,Expression,Variable,Unit,string> Members public string SymbolicConstant(Expression aPC, Variable symbol, Unit data) { return symbol.ToString(); } #endregion #region IVisitExprIL<Expression,Type,Expression,Variable,Unit,string> Members public string Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, Unit data) { return null; } public string Isinst(Expression pc, Type type, Variable dest, Expression obj, Unit data) { return null; } public string Ldconst(Expression pc, object constant, Type type, Variable dest, Unit data) { return "Constant(" + constant.ToString() + ")"; } public string Ldnull(Expression pc, Variable dest, Unit data) { return null; } public string Sizeof(Expression pc, Type type, Variable dest, Unit data) { return null; } public string Unary(Expression pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Expression source, Unit data) { return null; } #endregion } #endif private class VisitorForIsNull : QueryVisitor { public static bool IsNull(Expression exp, Decoder decoder) { return Decode(exp, decoder.visitorForIsNull, decoder); } public override bool Ldnull(Expression pc, Variable dest, Unit data) { return true; } } private class VisitorForDispatch : IVisitValueExprIL<Expression, Type, Expression, Variable, IBoxedExpressionVisitor, Unit> { private Decoder decoder; public VisitorForDispatch(Decoder decoder) { Contract.Requires(decoder != null); this.decoder = decoder; } public Unit SymbolicConstant(Expression pc, Variable symbol, IBoxedExpressionVisitor data) { data.Variable(symbol, null, null); return Unit.Value; } public Unit Binary(Expression pc, BinaryOperator op, Variable dest, Expression s1, Expression s2, IBoxedExpressionVisitor data) { data.Binary(op, BoxedExpression.For(s1, decoder), BoxedExpression.For(s2, decoder), null); return Unit.Value; } public Unit Isinst(Expression pc, Type type, Variable dest, Expression obj, IBoxedExpressionVisitor data) { data.IsInst(type, BoxedExpression.For(obj, decoder), null); return Unit.Value; } public Unit Ldconst(Expression pc, object constant, Type type, Variable dest, IBoxedExpressionVisitor data) { data.Constant(type, constant, null); return Unit.Value; } public Unit Ldnull(Expression pc, Variable dest, IBoxedExpressionVisitor data) { data.Constant<Type>(default(Type), null, null); return Unit.Value; } public Unit Sizeof(Expression pc, Type type, Variable dest, IBoxedExpressionVisitor data) { int size; if (!decoder.TrySizeOfAsConstant(pc, out size)) { size = 0; } data.SizeOf(type, size, null); return Unit.Value; } public Unit Unary(Expression pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Expression source, IBoxedExpressionVisitor data) { data.Unary(op, BoxedExpression.For(source, decoder), null); return Unit.Value; } public Unit Box(Expression pc, Type type, Variable dest, Expression source, IBoxedExpressionVisitor data) { // TODO: dispatch to box, once we have BOX in BoxedExpressions return Unit.Value; } internal void Dispatch(Expression exp, IBoxedExpressionVisitor visitor) { var expContext = decoder.Context.ExpressionContext; expContext.Decode<IBoxedExpressionVisitor, Unit, VisitorForDispatch>(exp, this, visitor); } } #endregion #region IFullExpressionDecoder<Type,Field,Expression> Members public Type System_Int32 { get { return this.decoderForMetaData.System_Int32; } } public bool IsReferenceType(Type type) { return this.decoderForMetaData.IsReferenceType(type); } public bool TrySizeOfAsConstant(Expression exp, out int value) { return TrySizeOf(exp, out value); } public bool TrySizeOf(Expression exp, out int value) { Type type; if (VisitorForSizeOf.IsSizeOf(exp, out type, this)) { int size = this.decoderForMetaData.TypeSize(type); if (size != -1) { value = size; return true; } else { value = -1; return false; } } else { value = -1; return false; } } public bool IsNull(Expression exp) { return this.context.ExpressionContext.IsZero(exp); // return this.context.Decode<Unit, bool, VisitorForIsNull>(exp, this.visitorForIsNull, Unit.Value); } public bool TryGetAssociatedExpression(APC pc, Expression e, AssociatedInfo infoKind, out Expression info) { Variable var = this.context.ExpressionContext.Unrefine(e); return TryGetAssociatedExpression(this.context.ExpressionContext.Refine(pc, var), infoKind, out info); } public bool TryGetAssociatedExpression(Expression e, AssociatedInfo infoKind, out Expression info) { switch (infoKind) { case AssociatedInfo.WritableBytes: return this.context.ExpressionContext.TryGetWritableBytes(e, out info); case AssociatedInfo.ArrayLength: return this.context.ExpressionContext.TryGetArrayLength(e, out info); default: info = default(Expression); return false; } } public void Dispatch(Expression exp, IBoxedExpressionVisitor visitor) { visitorForDispatch.Dispatch(exp, visitor); } #endregion } #endregion } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Migrations.Operations; using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal; using Pomelo.EntityFrameworkCore.MySql.Internal; using Pomelo.EntityFrameworkCore.MySql.Metadata.Internal; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Migrations { /// <summary> /// MySql-specific implementation of <see cref="MigrationsSqlGenerator" />. /// </summary> public class MySqlMigrationsSqlGenerator : MigrationsSqlGenerator { private static readonly Regex _typeRe = new Regex(@"([a-z0-9]+)\s*?(?:\(\s*(\d+)?\s*\))?", RegexOptions.IgnoreCase); private readonly IMigrationsAnnotationProvider _migrationsAnnotations; private readonly IMySqlOptions _options; private IReadOnlyList<MigrationOperation> _operations; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> /// <param name="dependencies"> Parameter object containing dependencies for this service. </param> /// <param name="migrationsAnnotations"> Provider-specific Migrations annotations to use. </param> /// <param name="options">IMySqlOptions</param> public MySqlMigrationsSqlGenerator( [NotNull] MigrationsSqlGeneratorDependencies dependencies, [NotNull] IMigrationsAnnotationProvider migrationsAnnotations, [NotNull] IMySqlOptions options) : base(dependencies) { _migrationsAnnotations = migrationsAnnotations; _options = options; } /// <summary> /// Generates commands from a list of operations. /// </summary> /// <param name="operations"> The operations. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <returns> The list of commands to be executed or scripted. </returns> public override IReadOnlyList<MigrationCommand> Generate(IReadOnlyList<MigrationOperation> operations, IModel model = null) { _operations = operations; try { return base.Generate(operations, model); } finally { _operations = null; } } /// <summary> /// <para> /// Builds commands for the given <see cref="MigrationOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />. /// </para> /// <para> /// This method uses a double-dispatch mechanism to call one of the 'Generate' methods that are /// specific to a certain subtype of <see cref="MigrationOperation" />. Typically database providers /// will override these specific methods rather than this method. However, providers can override /// this methods to handle provider-specific operations. /// </para> /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); var dropDatabaseOperation = operation as MySqlDropDatabaseOperation; if (operation is MySqlCreateDatabaseOperation createDatabaseOperation) { Generate(createDatabaseOperation, model, builder); } else if (dropDatabaseOperation != null) { Generate(dropDatabaseOperation, model, builder); } else { base.Generate(operation, model, builder); } } /// <summary> /// Builds commands for the given <see cref="AlterColumnOperation" /> /// by making calls on the given <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( AlterColumnOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)) .Append(" MODIFY COLUMN "); ColumnDefinition( operation.Schema, operation.Table, operation.Name, operation.ClrType, operation.ColumnType, operation.IsUnicode, operation.MaxLength, operation.IsFixedLength, operation.IsRowVersion, operation.IsNullable, operation.DefaultValue, operation.DefaultValueSql, operation.ComputedColumnSql, /*identity:*/ false, operation, model, builder); builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); builder.EndCommand(); } /// <summary> /// Builds commands for the given <see cref="RenameIndexOperation" /> /// by making calls on the given <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( RenameIndexOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); if (operation.NewName != null) { if (_options.ServerVersion.SupportsRenameIndex) { builder.Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)) .Append(" RENAME INDEX ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)) .Append(" TO ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.NewName)) .AppendLine(";"); EndStatement(builder); } else { var index = FindEntityTypes(model, operation.Schema, operation.Table) ?.SelectMany(e => e.GetDeclaredIndexes()) .FirstOrDefault(i => i.Relational().Name == operation.NewName); if (index == null) { throw new InvalidOperationException( $"Could not find the model index: {Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)}.{Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.NewName)}. Upgrade to Mysql 5.7+ or split the 'RenameIndex' call into 'DropIndex' and 'CreateIndex'"); } Generate(new DropIndexOperation { Schema = operation.Schema, Table = operation.Table, Name = operation.Name }, model, builder); var createIndexOperation = new CreateIndexOperation { Schema = operation.Schema, Table = operation.Table, Name = operation.NewName, Columns = index.Properties.Select(p => p.Relational().ColumnName).ToArray(), IsUnique = index.IsUnique, Filter = index.Relational().Filter }; createIndexOperation.AddAnnotations(_migrationsAnnotations.For(index)); createIndexOperation.AddAnnotations(operation.GetAnnotations()); Generate(createIndexOperation, model, builder); } } } /// <summary> /// Builds commands for the given <see cref="RestartSequenceOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />, and then terminates the final command. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( RestartSequenceOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("ALTER SEQUENCE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)) .Append(" RESTART WITH ") .Append(IntegerConstant(operation.StartValue)) .AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); EndStatement(builder); } /// <summary> /// Builds commands for the given <see cref="RenameTableOperation" /> /// by making calls on the given <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( RenameTableOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)) .Append(" RENAME ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.NewName, operation.NewSchema)) .AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); EndStatement(builder); } /// <summary> /// Builds commands for the given <see cref="CreateIndexOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />, and then terminates the final command. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( CreateIndexOperation operation, IModel model, MigrationCommandListBuilder builder) => Generate(operation, model, builder, terminate: true); /// <summary> /// Builds commands for the given <see cref="CreateIndexOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> /// <param name="terminate"> Indicates whether or not to terminate the command after generating SQL for the operation. </param> protected override void Generate( CreateIndexOperation operation, IModel model, MigrationCommandListBuilder builder, bool terminate) { operation.Filter = null; operation.Name = Truncate(operation.Name, 64); base.Generate(operation, model, builder, terminate); } /// <summary> /// Builds commands for the given <see cref="EnsureSchemaOperation" /> /// by making calls on the given <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate(EnsureSchemaOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("CREATE DATABASE IF NOT EXISTS ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)) .AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator) .EndCommand(); } /// <summary> /// Builds commands for the given <see cref="CreateSequenceOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />, and then terminates the final command. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( CreateSequenceOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("CREATE SEQUENCE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)); if (operation.ClrType != typeof(long)) { var typeMapping = Dependencies.TypeMappingSource.GetMapping(operation.ClrType); builder .Append(" AS ") .Append(typeMapping.StoreType); } builder .Append(" START WITH ") .Append(IntegerConstant(operation.StartValue)); SequenceOptions(operation, model, builder); builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); EndStatement(builder); } /// <summary> /// Builds commands for the given <see cref="MySqlCreateDatabaseOperation" /> /// by making calls on the given <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected virtual void Generate( [NotNull] MySqlCreateDatabaseOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("CREATE DATABASE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)); builder .AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator) .EndCommand(); } private static string ExpandFileName(string fileName) { Check.NotNull(fileName, nameof(fileName)); if (fileName.StartsWith("|DataDirectory|", StringComparison.OrdinalIgnoreCase)) { var dataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory") as string; if (string.IsNullOrEmpty(dataDirectory)) { dataDirectory = AppDomain.CurrentDomain.BaseDirectory; } fileName = Path.Combine(dataDirectory, fileName.Substring("|DataDirectory|".Length)); } return Path.GetFullPath(fileName); } /// <summary> /// Builds commands for the given <see cref="MySqlDropDatabaseOperation" /> /// by making calls on the given <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected virtual void Generate( [NotNull] MySqlDropDatabaseOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("DROP DATABASE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)) .Append(Dependencies.SqlGenerationHelper.StatementTerminator) .AppendLine(Dependencies.SqlGenerationHelper.BatchTerminator); EndStatement(builder); } /// <summary> /// Builds commands for the given <see cref="DropIndexOperation" /> /// by making calls on the given <see cref="MigrationCommandListBuilder" />, and then terminates the final command. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( DropIndexOperation operation, IModel model, MigrationCommandListBuilder builder) => Generate(operation, model, builder, terminate: true); /// <summary> /// Builds commands for the given <see cref="DropIndexOperation" /> /// by making calls on the given <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> /// <param name="terminate"> Indicates whether or not to terminate the command after generating SQL for the operation. </param> protected virtual void Generate( [NotNull] DropIndexOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder, bool terminate) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)) .Append(" DROP INDEX ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)); if (terminate) { builder .AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator) .EndCommand(); } } /// <summary> /// Builds commands for the given <see cref="DropColumnOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />, and then terminates the final command. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( DropColumnOperation operation, IModel model, MigrationCommandListBuilder builder) => Generate(operation, model, builder, terminate: true); /// <summary> /// Builds commands for the given <see cref="DropUniqueConstraintOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />, and then terminates the final command. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( DropUniqueConstraintOperation operation, IModel model, MigrationCommandListBuilder builder) => Generate(operation, model, builder, terminate: true); /// <summary> /// Builds commands for the given <see cref="DropUniqueConstraintOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />, and then terminates the final command. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> /// <param name="terminate"> Indicates whether or not to terminate the command after generating SQL for the operation. </param> protected virtual void Generate( DropUniqueConstraintOperation operation, IModel model, MigrationCommandListBuilder builder, bool terminate) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)) .Append(" DROP KEY ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)); if (terminate) { builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); EndStatement(builder); } } /// <summary> /// Builds commands for the given <see cref="DropForeignKeyOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />, and then terminates the final command. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( [NotNull] DropForeignKeyOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder) => Generate(operation, model, builder, terminate: true); /// <summary> /// Builds commands for the given <see cref="DropForeignKeyOperation" /> by making calls on the given /// <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> /// <param name="terminate"> Indicates whether or not to terminate the command after generating SQL for the operation. </param> protected override void Generate( [NotNull] DropForeignKeyOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder, bool terminate) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)) .Append(" DROP FOREIGN KEY ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)); if (terminate) { builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); EndStatement(builder); } } /// <summary> /// Builds commands for the given <see cref="RenameColumnOperation" /> /// by making calls on the given <see cref="MigrationCommandListBuilder" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to build the commands. </param> protected override void Generate( RenameColumnOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder.Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)) .Append(" CHANGE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)) .Append(" "); var property = FindProperty(model, operation.Schema, operation.Table, operation.NewName); if (property == null) { var type = operation[RelationalAnnotationNames.ColumnType]; if (type == null) { throw new InvalidOperationException( $"Could not find the property corresponding to the column: {Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)}.{Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.NewName)}. Specify the column type explicitly on 'RenameColumn' using the \"{RelationalAnnotationNames.ColumnType}\" annotation"); } builder .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.NewName)) .Append(" ") .Append(type) .AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); EndStatement(builder); return; } var typeMapping = Dependencies.TypeMappingSource.GetMapping(property); var converter = typeMapping.Converter; var clrType = (converter?.ProviderClrType ?? typeMapping.ClrType).UnwrapNullableType(); var columnType = (string)(operation[RelationalAnnotationNames.ColumnType] ?? property[RelationalAnnotationNames.ColumnType]); var annotations = property.Relational(); var isNullable = property.IsColumnNullable(); var defaultValue = annotations.DefaultValue; defaultValue = converter != null ? converter.ConvertToProvider(defaultValue) : defaultValue; defaultValue = (defaultValue == DBNull.Value ? null : defaultValue) ?? (isNullable ? null : clrType == typeof(string) ? string.Empty : clrType.IsArray ? Array.CreateInstance(clrType.GetElementType(), 0) : clrType.GetDefaultValue()); var isRowVersion = property.ClrType == typeof(byte[]) && property.IsConcurrencyToken && property.ValueGenerated == ValueGenerated.OnAddOrUpdate; ColumnDefinition( operation.Schema, operation.Table, operation.NewName, clrType, columnType, property.IsUnicode(), property.GetMaxLength(), annotations.IsFixedLength, isRowVersion, isNullable, defaultValue, annotations.DefaultValueSql, annotations.ComputedColumnSql, operation, model, builder); builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); EndStatement(builder); } /// <summary> /// Generates a SQL fragment configuring a sequence with the given options. /// </summary> /// <param name="schema"> The schema that contains the sequence, or <c>null</c> to use the default schema. </param> /// <param name="name"> The sequence name. </param> /// <param name="increment"> The amount to increment by to generate the next value in the sequence. </param> /// <param name="minimumValue"> The minimum value supported by the sequence, or <c>null</c> if none was specified. </param> /// <param name="maximumValue"> The maximum value supported by the sequence, or <c>null</c> if none was specified. </param> /// <param name="cycle"> Indicates whether or not the sequence will start again once the maximum value is reached. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to add the SQL fragment. </param> protected override void SequenceOptions( string schema, string name, int increment, long? minimumValue, long? maximumValue, bool cycle, IModel model, MigrationCommandListBuilder builder) { Check.NotEmpty(name, nameof(name)); Check.NotNull(increment, nameof(increment)); Check.NotNull(cycle, nameof(cycle)); Check.NotNull(builder, nameof(builder)); builder .Append(" INCREMENT BY ") .Append(IntegerConstant(increment)); if (minimumValue.HasValue) { builder .Append(" MINVALUE ") .Append(IntegerConstant(minimumValue.Value)); } else { builder.Append(" NO MINVALUE"); } if (maximumValue.HasValue) { builder .Append(" MAXVALUE ") .Append(IntegerConstant(maximumValue.Value)); } else { builder.Append(" NO MAXVALUE"); } builder.Append(cycle ? " CYCLE" : " NO CYCLE"); } /// <summary> /// Generates a SQL fragment for a column definition in an <see cref="AddColumnOperation" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to add the SQL fragment. </param> protected override void ColumnDefinition(AddColumnOperation operation, IModel model, MigrationCommandListBuilder builder) => ColumnDefinition( operation.Schema, operation.Table, operation.Name, operation.ClrType, operation.ColumnType, operation.IsUnicode, operation.MaxLength, operation.IsFixedLength, operation.IsRowVersion, operation.IsNullable, operation.DefaultValue, operation.DefaultValueSql, operation.ComputedColumnSql, operation, model, builder); /// <summary> /// Generates a SQL fragment for a column definition for the given column metadata. /// </summary> /// <param name="schema"> The schema that contains the table, or <c>null</c> to use the default schema. </param> /// <param name="table"> The table that contains the column. </param> /// <param name="name"> The column name. </param> /// <param name="clrType"> The CLR <see cref="Type" /> that the column is mapped to. </param> /// <param name="type"> The database/store type for the column, or <c>null</c> if none has been specified. </param> /// <param name="unicode"> /// Indicates whether or not the column can contain Unicode data, or <c>null</c> if this is not applicable or not specified. /// </param> /// <param name="maxLength"> /// The maximum amount of data that the column can contain, or <c>null</c> if this is not applicable or not specified. /// </param> /// <param name="fixedLength"> Indicates whether or not the column is constrained to fixed-length data. </param> /// <param name="rowVersion"> /// Indicates whether or not this column is an automatic concurrency token, such as a MySql timestamp/rowversion. /// </param> /// <param name="nullable"> Indicates whether or not the column can store <c>NULL</c> values. </param> /// <param name="defaultValue"> The default value for the column. </param> /// <param name="defaultValueSql"> The SQL expression to use for the column's default constraint. </param> /// <param name="computedColumnSql"> The SQL expression to use to compute the column value. </param> /// <param name="annotatable"> The <see cref="MigrationOperation" /> to use to find any custom annotations. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to add the SQL fragment. </param> protected override void ColumnDefinition( string schema, string table, string name, Type clrType, string type, bool? unicode, int? maxLength, bool? fixedLength, bool rowVersion, bool nullable, object defaultValue, string defaultValueSql, string computedColumnSql, IAnnotatable annotatable, IModel model, MigrationCommandListBuilder builder) { var valueGenerationStrategy = annotatable[ MySqlAnnotationNames.ValueGenerationStrategy] as MySqlValueGenerationStrategy?; ColumnDefinition( schema, table, name, clrType, type, unicode, maxLength, fixedLength, rowVersion, nullable, defaultValue, defaultValueSql, computedColumnSql, valueGenerationStrategy == MySqlValueGenerationStrategy.IdentityColumn, annotatable, model, builder); } /// <summary> /// Generates a SQL fragment for a column definition for the given column metadata. /// </summary> /// <param name="schema"> The schema that contains the table, or <c>null</c> to use the default schema. </param> /// <param name="table"> The table that contains the column. </param> /// <param name="name"> The column name. </param> /// <param name="clrType"> The CLR <see cref="Type" /> that the column is mapped to. </param> /// <param name="type"> The database/store type for the column, or <c>null</c> if none has been specified. </param> /// <param name="unicode"> /// Indicates whether or not the column can contain Unicode data, or <c>null</c> if this is not applicable or not specified. /// </param> /// <param name="maxLength"> /// The maximum amount of data that the column can contain, or <c>null</c> if this is not applicable or not specified. /// </param> /// <param name="rowVersion"> /// Indicates whether or not this column is an automatic concurrency token, such as a MySql timestamp/rowversion. /// </param> /// <param name="nullable"> Indicates whether or not the column can store <c>NULL</c> values. </param> /// <param name="defaultValue"> The default value for the column. </param> /// <param name="defaultValueSql"> The SQL expression to use for the column's default constraint. </param> /// <param name="computedColumnSql"> The SQL expression to use to compute the column value. </param> /// <param name="annotatable"> The <see cref="MigrationOperation" /> to use to find any custom annotations. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to add the SQL fragment. </param> protected override void ColumnDefinition( string schema, string table, string name, Type clrType, string type, bool? unicode, int? maxLength, bool rowVersion, bool nullable, object defaultValue, string defaultValueSql, string computedColumnSql, IAnnotatable annotatable, IModel model, MigrationCommandListBuilder builder) => ColumnDefinition(schema, table, name, clrType, type, unicode, maxLength, null, rowVersion, nullable, defaultValue, defaultValueSql, computedColumnSql, annotatable, model, builder); /// <summary> /// Generates a SQL fragment for a column definition for the given column metadata. /// </summary> /// <param name="schema"> The schema that contains the table, or <c>null</c> to use the default schema. </param> /// <param name="table"> The table that contains the column. </param> /// <param name="name"> The column name. </param> /// <param name="clrType"> The CLR <see cref="Type" /> that the column is mapped to. </param> /// <param name="type"> The database/store type for the column, or <c>null</c> if none has been specified. </param> /// <param name="unicode"> /// Indicates whether or not the column can contain Unicode data, or <c>null</c> if this is not applicable or not specified. /// </param> /// <param name="maxLength"> /// The maximum amount of data that the column can contain, or <c>null</c> if this is not applicable or not specified. /// </param> /// <param name="fixedLength"> Indicates whether or not the column is constrained to fixed-length data. </param> /// <param name="rowVersion"> /// Indicates whether or not this column is an automatic concurrency token, such as a MySql timestamp/rowversion. /// </param> /// <param name="nullable"> Indicates whether or not the column can store <c>NULL</c> values. </param> /// <param name="defaultValue"> The default value for the column. </param> /// <param name="defaultValueSql"> The SQL expression to use for the column's default constraint. </param> /// <param name="computedColumnSql"> The SQL expression to use to compute the column value. </param> /// <param name="identity"> Indicates whether or not the column is an Identity column. </param> /// <param name="annotatable"> The <see cref="MigrationOperation" /> to use to find any custom annotations. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to add the SQL fragment. </param> protected virtual void ColumnDefinition( [CanBeNull] string schema, [NotNull] string table, [NotNull] string name, [NotNull] Type clrType, [CanBeNull] string type, bool? unicode, int? maxLength, bool? fixedLength, bool rowVersion, bool nullable, [CanBeNull] object defaultValue, [CanBeNull] string defaultValueSql, [CanBeNull] string computedColumnSql, bool identity, [NotNull] IAnnotatable annotatable, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder) { Check.NotEmpty(name, nameof(name)); Check.NotNull(clrType, nameof(clrType)); Check.NotNull(annotatable, nameof(annotatable)); Check.NotNull(builder, nameof(builder)); var matchType = type ?? GetColumnType(schema, table, name, clrType, unicode, maxLength, fixedLength, rowVersion, model); var matchLen = ""; var match = _typeRe.Match(matchType ?? "-"); if (match.Success) { matchType = match.Groups[1].Value.ToLower(); if (!string.IsNullOrWhiteSpace(match.Groups[2].Value)) { matchLen = match.Groups[2].Value; } } var valueGenerationStrategy = annotatable[ MySqlAnnotationNames.ValueGenerationStrategy] as MySqlValueGenerationStrategy?; if (!valueGenerationStrategy.HasValue) { var generatedOnAddAnnotation = annotatable[MySqlAnnotationNames.LegacyValueGeneratedOnAdd]; if (generatedOnAddAnnotation != null && (bool)generatedOnAddAnnotation) valueGenerationStrategy = MySqlValueGenerationStrategy.IdentityColumn; var generatedOnAddOrUpdateAnnotation = annotatable[MySqlAnnotationNames.LegacyValueGeneratedOnAddOrUpdate]; if (generatedOnAddOrUpdateAnnotation != null && (bool)generatedOnAddOrUpdateAnnotation) valueGenerationStrategy = MySqlValueGenerationStrategy.ComputedColumn; } var autoIncrement = false; if ((identity || valueGenerationStrategy == MySqlValueGenerationStrategy.IdentityColumn) && string.IsNullOrWhiteSpace(defaultValueSql) && defaultValue == null) { switch (matchType) { case "tinyint": case "smallint": case "mediumint": case "int": case "bigint": autoIncrement = true; break; case "datetime": if (!_options.ServerVersion.SupportsDateTime6) throw new InvalidOperationException( $"Error in {table}.{name}: DATETIME does not support values generated " + "on Add or Update in MySql <= 5.5, try explicitly setting the column type to TIMESTAMP"); goto case "timestamp"; case "timestamp": defaultValueSql = $"CURRENT_TIMESTAMP({matchLen})"; break; } } string onUpdateSql = null; if (rowVersion || valueGenerationStrategy == MySqlValueGenerationStrategy.ComputedColumn) { switch (matchType) { case "datetime": if (!_options.ServerVersion.SupportsDateTime6) { throw new InvalidOperationException( $"Error in {table}.{name}: DATETIME does not support values generated " + "on Add or Update in MySql <= 5.5, try explicitly setting the column type to TIMESTAMP"); } goto case "timestamp"; case "timestamp": if (string.IsNullOrWhiteSpace(defaultValueSql) && defaultValue == null) { defaultValueSql = $"CURRENT_TIMESTAMP({matchLen})"; } onUpdateSql = $"CURRENT_TIMESTAMP({matchLen})"; break; } } if (computedColumnSql == null) { base.ColumnDefinition( schema, table, name, clrType, type, unicode, maxLength, fixedLength, rowVersion, nullable, identity ? null : defaultValue, defaultValueSql, computedColumnSql, annotatable, model, builder); if (autoIncrement) { builder.Append(" AUTO_INCREMENT"); } else { if (onUpdateSql != null) { builder .Append(" ON UPDATE ") .Append(onUpdateSql); } } } else { builder .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(name)) .Append(" ") .Append(type ?? GetColumnType(schema, table, name, clrType, unicode, maxLength, fixedLength, rowVersion, model)); builder .Append(" AS ") .Append($"({computedColumnSql})"); if (nullable) { builder.Append(" NULL"); } } } /// <summary> /// Generates a SQL fragment for the default constraint of a column. /// </summary> /// <param name="defaultValue"> The default value for the column. </param> /// <param name="defaultValueSql"> The SQL expression to use for the column's default constraint. </param> /// <param name="builder"> The command builder to use to add the SQL fragment. </param> protected override void DefaultValue( object defaultValue, string defaultValueSql, MigrationCommandListBuilder builder) { Check.NotNull(builder, nameof(builder)); if (defaultValueSql != null) { builder .Append(" DEFAULT ") .Append(defaultValueSql); } else if (defaultValue != null) { var typeMapping = Dependencies.TypeMappingSource.GetMappingForValue(defaultValue); builder .Append(" DEFAULT ") .Append(typeMapping.GenerateSqlLiteral(defaultValue)); } } protected override void Generate( AddPrimaryKeyOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder .Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)) .Append(" ADD "); PrimaryKeyConstraint(operation, model, builder); builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); if (operation.Columns.Length == 1) { builder.Append(@"DROP PROCEDURE IF EXISTS POMELO_AFTER_ADD_PRIMARY_KEY; CREATE PROCEDURE POMELO_AFTER_ADD_PRIMARY_KEY(IN `SCHEMA_NAME_ARGUMENT` VARCHAR(255), IN `TABLE_NAME_ARGUMENT` VARCHAR(255), IN `COLUMN_NAME_ARGUMENT` VARCHAR(255)) BEGIN DECLARE HAS_AUTO_INCREMENT_ID INT(11); DECLARE PRIMARY_KEY_COLUMN_NAME VARCHAR(255); DECLARE PRIMARY_KEY_TYPE VARCHAR(255); DECLARE SQL_EXP VARCHAR(1000); SELECT COUNT(*) INTO HAS_AUTO_INCREMENT_ID FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA` = (SELECT IFNULL(SCHEMA_NAME_ARGUMENT, SCHEMA())) AND `TABLE_NAME` = TABLE_NAME_ARGUMENT AND `COLUMN_NAME` = COLUMN_NAME_ARGUMENT AND `COLUMN_TYPE` LIKE '%int%' AND `COLUMN_KEY` = 'PRI'; IF HAS_AUTO_INCREMENT_ID THEN SELECT `COLUMN_TYPE` INTO PRIMARY_KEY_TYPE FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA` = (SELECT IFNULL(SCHEMA_NAME_ARGUMENT, SCHEMA())) AND `TABLE_NAME` = TABLE_NAME_ARGUMENT AND `COLUMN_NAME` = COLUMN_NAME_ARGUMENT AND `COLUMN_TYPE` LIKE '%int%' AND `COLUMN_KEY` = 'PRI'; SELECT `COLUMN_NAME` INTO PRIMARY_KEY_COLUMN_NAME FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA` = (SELECT IFNULL(SCHEMA_NAME_ARGUMENT, SCHEMA())) AND `TABLE_NAME` = TABLE_NAME_ARGUMENT AND `COLUMN_NAME` = COLUMN_NAME_ARGUMENT AND `COLUMN_TYPE` LIKE '%int%' AND `COLUMN_KEY` = 'PRI'; SET SQL_EXP = CONCAT('ALTER TABLE `', (SELECT IFNULL(SCHEMA_NAME_ARGUMENT, SCHEMA())), '`.`', TABLE_NAME_ARGUMENT, '` MODIFY COLUMN `', PRIMARY_KEY_COLUMN_NAME, '` ', PRIMARY_KEY_TYPE, ' NOT NULL AUTO_INCREMENT;'); SET @SQL_EXP = SQL_EXP; PREPARE SQL_EXP_EXECUTE FROM @SQL_EXP; EXECUTE SQL_EXP_EXECUTE; DEALLOCATE PREPARE SQL_EXP_EXECUTE; END IF; END;".Replace("\r", string.Empty).Replace("\n", Environment.NewLine)); builder.AppendLine(); if (operation.Schema == null) { builder.Append( $"CALL POMELO_AFTER_ADD_PRIMARY_KEY(NULL, '{operation.Table}', '{operation.Columns.First()}');"); } else { builder.Append( $"CALL POMELO_AFTER_ADD_PRIMARY_KEY('{operation.Schema}', '{operation.Table}', '{operation.Columns.First()}');"); } builder.AppendLine(); builder.Append($"DROP PROCEDURE IF EXISTS POMELO_AFTER_ADD_PRIMARY_KEY;"); builder.AppendLine(); } EndStatement(builder); } protected override void Generate( DropPrimaryKeyOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); builder.Append(@"DROP PROCEDURE IF EXISTS POMELO_BEFORE_DROP_PRIMARY_KEY; CREATE PROCEDURE POMELO_BEFORE_DROP_PRIMARY_KEY(IN `SCHEMA_NAME_ARGUMENT` VARCHAR(255), IN `TABLE_NAME_ARGUMENT` VARCHAR(255)) BEGIN DECLARE HAS_AUTO_INCREMENT_ID TINYINT(1); DECLARE PRIMARY_KEY_COLUMN_NAME VARCHAR(255); DECLARE PRIMARY_KEY_TYPE VARCHAR(255); DECLARE SQL_EXP VARCHAR(1000); SELECT COUNT(*) INTO HAS_AUTO_INCREMENT_ID FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA` = (SELECT IFNULL(SCHEMA_NAME_ARGUMENT, SCHEMA())) AND `TABLE_NAME` = TABLE_NAME_ARGUMENT AND `Extra` = 'auto_increment' AND `COLUMN_KEY` = 'PRI' LIMIT 1; IF HAS_AUTO_INCREMENT_ID THEN SELECT `COLUMN_TYPE` INTO PRIMARY_KEY_TYPE FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA` = (SELECT IFNULL(SCHEMA_NAME_ARGUMENT, SCHEMA())) AND `TABLE_NAME` = TABLE_NAME_ARGUMENT AND `COLUMN_KEY` = 'PRI' LIMIT 1; SELECT `COLUMN_NAME` INTO PRIMARY_KEY_COLUMN_NAME FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA` = (SELECT IFNULL(SCHEMA_NAME_ARGUMENT, SCHEMA())) AND `TABLE_NAME` = TABLE_NAME_ARGUMENT AND `COLUMN_KEY` = 'PRI' LIMIT 1; SET SQL_EXP = CONCAT('ALTER TABLE `', (SELECT IFNULL(SCHEMA_NAME_ARGUMENT, SCHEMA())), '`.`', TABLE_NAME_ARGUMENT, '` MODIFY COLUMN `', PRIMARY_KEY_COLUMN_NAME, '` ', PRIMARY_KEY_TYPE, ' NOT NULL;'); SET @SQL_EXP = SQL_EXP; PREPARE SQL_EXP_EXECUTE FROM @SQL_EXP; EXECUTE SQL_EXP_EXECUTE; DEALLOCATE PREPARE SQL_EXP_EXECUTE; END IF; END;".Replace("\r", string.Empty).Replace("\n", Environment.NewLine)); builder.AppendLine(); if (string.IsNullOrWhiteSpace(operation.Schema)) { builder.Append($"CALL POMELO_BEFORE_DROP_PRIMARY_KEY(NULL, '{operation.Table}');"); } else { builder.Append($"CALL POMELO_BEFORE_DROP_PRIMARY_KEY('{operation.Schema}', '{operation.Table}');"); } builder.AppendLine(); builder.Append($"DROP PROCEDURE IF EXISTS POMELO_BEFORE_DROP_PRIMARY_KEY;"); builder.AppendLine(); builder .Append("ALTER TABLE ") .Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)) .Append(" DROP PRIMARY KEY;") .AppendLine(); EndStatement(builder); } /// <summary> /// Generates a SQL fragment for a foreign key constraint of an <see cref="AddForeignKeyOperation" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to add the SQL fragment. </param> protected override void ForeignKeyConstraint( AddForeignKeyOperation operation, IModel model, MigrationCommandListBuilder builder) { operation.Name = Truncate(operation.Name, 64); base.ForeignKeyConstraint(operation, model, builder); } /// <summary> /// Generates a SQL fragment for traits of an index from a <see cref="CreateIndexOperation" />, /// <see cref="AddPrimaryKeyOperation" />, or <see cref="AddUniqueConstraintOperation" />. /// </summary> /// <param name="operation"> The operation. </param> /// <param name="model"> The target model which may be <c>null</c> if the operations exist without a model. </param> /// <param name="builder"> The command builder to use to add the SQL fragment. </param> protected override void IndexTraits(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); var fullText = operation[MySqlAnnotationNames.FullTextIndex] as bool?; if (fullText == true) { builder.Append("FULLTEXT "); } var spatial = operation[MySqlAnnotationNames.SpatialIndex] as bool?; if (spatial == true) { builder.Append("SPATIAL "); } } /// <summary> /// Generates a SQL fragment for the given referential action. /// </summary> /// <param name="referentialAction"> The referential action. </param> /// <param name="builder"> The command builder to use to add the SQL fragment. </param> protected override void ForeignKeyAction(ReferentialAction referentialAction, MigrationCommandListBuilder builder) { Check.NotNull(builder, nameof(builder)); if (referentialAction == ReferentialAction.Restrict) { builder.Append("RESTRICT"); } else { base.ForeignKeyAction(referentialAction, builder); } } private string IntegerConstant(long value) => string.Format(CultureInfo.InvariantCulture, "{0}", value); private static string Truncate(string source, int maxLength) { if (source == null || source.Length <= maxLength) { return source; } return source.Substring(0, maxLength); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System; using System.ComponentModel; using System.Xml.Serialization; using System.Xml.Schema; using System.Xml.XPath; using System.Diagnostics; using System.Collections; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Globalization; internal abstract class FacetsChecker { private struct FacetsCompiler { private DatatypeImplementation _datatype; private RestrictionFacets _derivedRestriction; private RestrictionFlags _baseFlags; private RestrictionFlags _baseFixedFlags; private RestrictionFlags _validRestrictionFlags; //Helpers private XmlSchemaDatatype _nonNegativeInt; private XmlSchemaDatatype _builtInType; private XmlTypeCode _builtInEnum; private bool _firstPattern; private StringBuilder _regStr; private XmlSchemaPatternFacet _pattern_facet; public FacetsCompiler(DatatypeImplementation baseDatatype, RestrictionFacets restriction) { _firstPattern = true; _regStr = null; _pattern_facet = null; _datatype = baseDatatype; _derivedRestriction = restriction; _baseFlags = _datatype.Restriction != null ? _datatype.Restriction.Flags : 0; _baseFixedFlags = _datatype.Restriction != null ? _datatype.Restriction.FixedFlags : 0; _validRestrictionFlags = _datatype.ValidRestrictionFlags; _nonNegativeInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.NonNegativeInteger).Datatype; _builtInEnum = !(_datatype is Datatype_union || _datatype is Datatype_List) ? _datatype.TypeCode : 0; _builtInType = (int)_builtInEnum > 0 ? DatatypeImplementation.GetSimpleTypeFromTypeCode(_builtInEnum).Datatype : _datatype; } internal void CompileLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.Length, SR.Sch_LengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.Length, SR.Sch_DupLengthFacet); _derivedRestriction.Length = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_LengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.Length) != 0) { if (!_datatype.IsEqual(_datatype.Restriction.Length, _derivedRestriction.Length)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction.Length < _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_LengthGtBaseLength, facet); } } // If the base has the MinLength facet, check that our derived length is not violating it if ((_baseFlags & RestrictionFlags.MinLength) != 0) { if (_datatype.Restriction.MinLength > _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } // If the base has the MaxLength facet, check that our derived length is not violating it if ((_baseFlags & RestrictionFlags.MaxLength) != 0) { if (_datatype.Restriction.MaxLength < _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.Length); } internal void CompileMinLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinLength, SR.Sch_MinLengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinLength, SR.Sch_DupMinLengthFacet); _derivedRestriction.MinLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MinLengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.MinLength) != 0) { if (!_datatype.IsEqual(_datatype.Restriction.MinLength, _derivedRestriction.MinLength)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.MinLength) != 0) { if (_datatype.Restriction.MinLength > _derivedRestriction.MinLength) { throw new XmlSchemaException(SR.Sch_MinLengthGtBaseMinLength, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction.Length < _derivedRestriction.MinLength) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.MinLength); } internal void CompileMaxLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxLength, SR.Sch_MaxLengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxLength, SR.Sch_DupMaxLengthFacet); _derivedRestriction.MaxLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MaxLengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.MaxLength) != 0) { if (!_datatype.IsEqual(_datatype.Restriction.MaxLength, _derivedRestriction.MaxLength)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.MaxLength) != 0) { if (_datatype.Restriction.MaxLength < _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MaxLengthGtBaseMaxLength, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction.Length > _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.MaxLength); } internal void CompilePatternFacet(XmlSchemaPatternFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.Pattern, SR.Sch_PatternFacetProhibited); if (_firstPattern == true) { _regStr = new StringBuilder(); _regStr.Append("("); _regStr.Append(facet.Value); _pattern_facet = facet; _firstPattern = false; } else { _regStr.Append(")|("); _regStr.Append(facet.Value); } SetFlag(facet, RestrictionFlags.Pattern); } internal void CompileEnumerationFacet(XmlSchemaFacet facet, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable) { CheckProhibitedFlag(facet, RestrictionFlags.Enumeration, SR.Sch_EnumerationFacetProhibited); if (_derivedRestriction.Enumeration == null) { _derivedRestriction.Enumeration = new ArrayList(); } _derivedRestriction.Enumeration.Add(ParseFacetValue(_datatype, facet, SR.Sch_EnumerationFacetInvalid, nsmgr, nameTable)); SetFlag(facet, RestrictionFlags.Enumeration); } internal void CompileWhitespaceFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_WhiteSpaceFacetProhibited); CheckDupFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_DupWhiteSpaceFacet); if (facet.Value == "preserve") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Preserve; } else if (facet.Value == "replace") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Replace; } else if (facet.Value == "collapse") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Collapse; } else { throw new XmlSchemaException(SR.Sch_InvalidWhiteSpace, facet.Value, facet); } if ((_baseFixedFlags & RestrictionFlags.WhiteSpace) != 0) { if (!_datatype.IsEqual(_datatype.Restriction.WhiteSpace, _derivedRestriction.WhiteSpace)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } //Check base and derived whitespace facets XmlSchemaWhiteSpace baseWhitespace; if ((_baseFlags & RestrictionFlags.WhiteSpace) != 0) { baseWhitespace = _datatype.Restriction.WhiteSpace; } else { baseWhitespace = _datatype.BuiltInWhitespaceFacet; } if (baseWhitespace == XmlSchemaWhiteSpace.Collapse && (_derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Replace || _derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve) ) { throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction1, facet); } if (baseWhitespace == XmlSchemaWhiteSpace.Replace && _derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve ) { throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction2, facet); } SetFlag(facet, RestrictionFlags.WhiteSpace); } internal void CompileMaxInclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_MaxInclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_DupMaxInclusiveFacet); _derivedRestriction.MaxInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxInclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MaxInclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction.MaxInclusive, _derivedRestriction.MaxInclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MaxInclusive, facet); SetFlag(facet, RestrictionFlags.MaxInclusive); } internal void CompileMaxExclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_MaxExclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_DupMaxExclusiveFacet); _derivedRestriction.MaxExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxExclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MaxExclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction.MaxExclusive, _derivedRestriction.MaxExclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MaxExclusive, facet); SetFlag(facet, RestrictionFlags.MaxExclusive); } internal void CompileMinInclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_MinInclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_DupMinInclusiveFacet); _derivedRestriction.MinInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinInclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MinInclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction.MinInclusive, _derivedRestriction.MinInclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MinInclusive, facet); SetFlag(facet, RestrictionFlags.MinInclusive); } internal void CompileMinExclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_MinExclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_DupMinExclusiveFacet); _derivedRestriction.MinExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinExclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MinExclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction.MinExclusive, _derivedRestriction.MinExclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MinExclusive, facet); SetFlag(facet, RestrictionFlags.MinExclusive); } internal void CompileTotalDigitsFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_TotalDigitsFacetProhibited); CheckDupFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_DupTotalDigitsFacet); XmlSchemaDatatype positiveInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.PositiveInteger).Datatype; _derivedRestriction.TotalDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(positiveInt, facet, SR.Sch_TotalDigitsFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.TotalDigits) != 0) { if (!_datatype.IsEqual(_datatype.Restriction.TotalDigits, _derivedRestriction.TotalDigits)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.TotalDigits) != 0) { if (_derivedRestriction.TotalDigits > _datatype.Restriction.TotalDigits) { throw new XmlSchemaException(SR.Sch_TotalDigitsMismatch, string.Empty); } } SetFlag(facet, RestrictionFlags.TotalDigits); } internal void CompileFractionDigitsFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_FractionDigitsFacetProhibited); CheckDupFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_DupFractionDigitsFacet); _derivedRestriction.FractionDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_FractionDigitsFacetInvalid, null, null)); if ((_derivedRestriction.FractionDigits != 0) && (_datatype.TypeCode != XmlTypeCode.Decimal)) { throw new XmlSchemaException(SR.Sch_FractionDigitsFacetInvalid, SR.Sch_FractionDigitsNotOnDecimal, facet); } if ((_baseFlags & RestrictionFlags.FractionDigits) != 0) { if (_derivedRestriction.FractionDigits > _datatype.Restriction.FractionDigits) { throw new XmlSchemaException(SR.Sch_TotalDigitsMismatch, string.Empty); } } SetFlag(facet, RestrictionFlags.FractionDigits); } internal void FinishFacetCompile() { //Additional check for pattern facet //If facet is XMLSchemaPattern, then the String built inside the loop //needs to be converted to a RegEx if (_firstPattern == false) { if (_derivedRestriction.Patterns == null) { _derivedRestriction.Patterns = new ArrayList(); } try { _regStr.Append(")"); string tempStr = _regStr.ToString(); if (tempStr.Contains('|')) { // ordinal compare _regStr.Insert(0, "("); _regStr.Append(")"); } _derivedRestriction.Patterns.Add(new Regex(Preprocess(_regStr.ToString()), RegexOptions.None)); } catch (Exception e) { throw new XmlSchemaException(SR.Sch_PatternFacetInvalid, new string[] { e.Message }, e, _pattern_facet.SourceUri, _pattern_facet.LineNumber, _pattern_facet.LinePosition, _pattern_facet); } } } private void CheckValue(object value, XmlSchemaFacet facet) { RestrictionFacets restriction = _datatype.Restriction; switch (facet.FacetType) { case FacetType.MaxInclusive: if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0) { //Base facet has maxInclusive if (_datatype.Compare(value, restriction.MaxInclusive) > 0) { throw new XmlSchemaException(SR.Sch_MaxInclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction.MaxExclusive) >= 0) { throw new XmlSchemaException(SR.Sch_MaxIncExlMismatch, string.Empty); } } break; case FacetType.MaxExclusive: if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction.MaxExclusive) > 0) { throw new XmlSchemaException(SR.Sch_MaxExclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0) { //Base facet has maxInclusive if (_datatype.Compare(value, restriction.MaxInclusive) > 0) { throw new XmlSchemaException(SR.Sch_MaxExlIncMismatch, string.Empty); } } break; case FacetType.MinInclusive: if ((_baseFlags & RestrictionFlags.MinInclusive) != 0) { //Base facet has minInclusive if (_datatype.Compare(value, restriction.MinInclusive) < 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MinExclusive) != 0) { //Base facet has minExclusive if (_datatype.Compare(value, restriction.MinExclusive) < 0) { throw new XmlSchemaException(SR.Sch_MinIncExlMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction.MaxExclusive) >= 0) { throw new XmlSchemaException(SR.Sch_MinIncMaxExlMismatch, string.Empty); } } break; case FacetType.MinExclusive: if ((_baseFlags & RestrictionFlags.MinExclusive) != 0) { //Base facet has minExclusive if (_datatype.Compare(value, restriction.MinExclusive) < 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MinInclusive) != 0) { //Base facet has minInclusive if (_datatype.Compare(value, restriction.MinInclusive) < 0) { throw new XmlSchemaException(SR.Sch_MinExlIncMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction.MaxExclusive) >= 0) { throw new XmlSchemaException(SR.Sch_MinExlMaxExlMismatch, string.Empty); } } break; default: Debug.Fail($"Unexpected facet type {facet.FacetType}"); break; } } internal void CompileFacetCombinations() { RestrictionFacets baseRestriction = _datatype.Restriction; //They are not allowed on the same type but allowed on derived types. if ( (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { throw new XmlSchemaException(SR.Sch_MaxInclusiveExclusive, string.Empty); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 ) { throw new XmlSchemaException(SR.Sch_MinInclusiveExclusive, string.Empty); } if ( (_derivedRestriction.Flags & RestrictionFlags.Length) != 0 && (_derivedRestriction.Flags & (RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0 ) { throw new XmlSchemaException(SR.Sch_LengthAndMinMax, string.Empty); } CopyFacetsFromBaseType(); // Check combinations if ( (_derivedRestriction.Flags & RestrictionFlags.MinLength) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxLength) != 0 ) { if (_derivedRestriction.MinLength > _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MinLengthGtMaxLength, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinInclusive, _derivedRestriction.MaxInclusive) > 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxInclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinInclusive, _derivedRestriction.MaxExclusive) > 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxExclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinExclusive, _derivedRestriction.MaxExclusive) > 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxExclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinExclusive, _derivedRestriction.MaxInclusive) > 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxInclusive, string.Empty); } } if ((_derivedRestriction.Flags & (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) == (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) { if (_derivedRestriction.FractionDigits > _derivedRestriction.TotalDigits) { throw new XmlSchemaException(SR.Sch_FractionDigitsGtTotalDigits, string.Empty); } } } private void CopyFacetsFromBaseType() { RestrictionFacets baseRestriction = _datatype.Restriction; // Copy additional facets from the base type if ( (_derivedRestriction.Flags & RestrictionFlags.Length) == 0 && (_baseFlags & RestrictionFlags.Length) != 0 ) { _derivedRestriction.Length = baseRestriction.Length; SetFlag(RestrictionFlags.Length); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinLength) == 0 && (_baseFlags & RestrictionFlags.MinLength) != 0 ) { _derivedRestriction.MinLength = baseRestriction.MinLength; SetFlag(RestrictionFlags.MinLength); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxLength) == 0 && (_baseFlags & RestrictionFlags.MaxLength) != 0 ) { _derivedRestriction.MaxLength = baseRestriction.MaxLength; SetFlag(RestrictionFlags.MaxLength); } if ((_baseFlags & RestrictionFlags.Pattern) != 0) { if (_derivedRestriction.Patterns == null) { _derivedRestriction.Patterns = baseRestriction.Patterns; } else { _derivedRestriction.Patterns.AddRange(baseRestriction.Patterns); } SetFlag(RestrictionFlags.Pattern); } if ((_baseFlags & RestrictionFlags.Enumeration) != 0) { if (_derivedRestriction.Enumeration == null) { _derivedRestriction.Enumeration = baseRestriction.Enumeration; } SetFlag(RestrictionFlags.Enumeration); } if ( (_derivedRestriction.Flags & RestrictionFlags.WhiteSpace) == 0 && (_baseFlags & RestrictionFlags.WhiteSpace) != 0 ) { _derivedRestriction.WhiteSpace = baseRestriction.WhiteSpace; SetFlag(RestrictionFlags.WhiteSpace); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) == 0 && (_baseFlags & RestrictionFlags.MaxInclusive) != 0 ) { _derivedRestriction.MaxInclusive = baseRestriction.MaxInclusive; SetFlag(RestrictionFlags.MaxInclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) == 0 && (_baseFlags & RestrictionFlags.MaxExclusive) != 0 ) { _derivedRestriction.MaxExclusive = baseRestriction.MaxExclusive; SetFlag(RestrictionFlags.MaxExclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) == 0 && (_baseFlags & RestrictionFlags.MinInclusive) != 0 ) { _derivedRestriction.MinInclusive = baseRestriction.MinInclusive; SetFlag(RestrictionFlags.MinInclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) == 0 && (_baseFlags & RestrictionFlags.MinExclusive) != 0 ) { _derivedRestriction.MinExclusive = baseRestriction.MinExclusive; SetFlag(RestrictionFlags.MinExclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.TotalDigits) == 0 && (_baseFlags & RestrictionFlags.TotalDigits) != 0 ) { _derivedRestriction.TotalDigits = baseRestriction.TotalDigits; SetFlag(RestrictionFlags.TotalDigits); } if ( (_derivedRestriction.Flags & RestrictionFlags.FractionDigits) == 0 && (_baseFlags & RestrictionFlags.FractionDigits) != 0 ) { _derivedRestriction.FractionDigits = baseRestriction.FractionDigits; SetFlag(RestrictionFlags.FractionDigits); } } private object ParseFacetValue(XmlSchemaDatatype datatype, XmlSchemaFacet facet, string code, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable) { object typedValue; Exception ex = datatype.TryParseValue(facet.Value, nameTable, nsmgr, out typedValue); if (ex == null) { return typedValue; } else { throw new XmlSchemaException(code, new string[] { ex.Message }, ex, facet.SourceUri, facet.LineNumber, facet.LinePosition, facet); } } private struct Map { internal Map(char m, string r) { match = m; replacement = r; } internal char match; internal string replacement; }; private static readonly Map[] s_map = { new Map('c', "\\p{_xmlC}"), new Map('C', "\\P{_xmlC}"), new Map('d', "\\p{_xmlD}"), new Map('D', "\\P{_xmlD}"), new Map('i', "\\p{_xmlI}"), new Map('I', "\\P{_xmlI}"), new Map('w', "\\p{_xmlW}"), new Map('W', "\\P{_xmlW}"), }; private static string Preprocess(string pattern) { StringBuilder bufBld = new StringBuilder(); bufBld.Append("^"); char[] source = pattern.ToCharArray(); int length = pattern.Length; int copyPosition = 0; for (int position = 0; position < length - 2; position++) { if (source[position] == '\\') { if (source[position + 1] == '\\') { position++; // skip it } else { char ch = source[position + 1]; for (int i = 0; i < s_map.Length; i++) { if (s_map[i].match == ch) { if (copyPosition < position) { bufBld.Append(source, copyPosition, position - copyPosition); } bufBld.Append(s_map[i].replacement); position++; copyPosition = position + 1; break; } } } } } if (copyPosition < length) { bufBld.Append(source, copyPosition, length - copyPosition); } bufBld.Append("$"); return bufBld.ToString(); } private void CheckProhibitedFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode) { if ((_validRestrictionFlags & flag) == 0) { throw new XmlSchemaException(errorCode, _datatype.TypeCodeString, facet); } } private void CheckDupFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode) { if ((_derivedRestriction.Flags & flag) != 0) { throw new XmlSchemaException(errorCode, facet); } } private void SetFlag(XmlSchemaFacet facet, RestrictionFlags flag) { _derivedRestriction.Flags |= flag; if (facet.IsFixed) { _derivedRestriction.FixedFlags |= flag; } } private void SetFlag(RestrictionFlags flag) { _derivedRestriction.Flags |= flag; if ((_baseFixedFlags & flag) != 0) { _derivedRestriction.FixedFlags |= flag; } } } internal virtual Exception CheckLexicalFacets(ref string parseString, XmlSchemaDatatype datatype) { CheckWhitespaceFacets(ref parseString, datatype); return CheckPatternFacets(datatype.Restriction, parseString); } internal virtual Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(decimal value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(long value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(int value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(short value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(DateTime value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(double value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(float value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(string value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(byte[] value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype) { return null; } internal void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype) { // before parsing, check whitespace facet RestrictionFacets restriction = datatype.Restriction; switch (datatype.Variety) { case XmlSchemaDatatypeVariety.List: s = s.Trim(); break; case XmlSchemaDatatypeVariety.Atomic: if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Collapse) { s = XmlComplianceUtil.NonCDataNormalize(s); } else if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Replace) { s = XmlComplianceUtil.CDataNormalize(s); } else if (restriction != null && (restriction.Flags & RestrictionFlags.WhiteSpace) != 0) { //Restriction has whitespace facet specified if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Replace) { s = XmlComplianceUtil.CDataNormalize(s); } else if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Collapse) { s = XmlComplianceUtil.NonCDataNormalize(s); } } break; default: break; } } internal Exception CheckPatternFacets(RestrictionFacets restriction, string value) { if (restriction != null && (restriction.Flags & RestrictionFlags.Pattern) != 0) { for (int i = 0; i < restriction.Patterns.Count; ++i) { Regex regex = (Regex)restriction.Patterns[i]; if (!regex.IsMatch(value)) { return new XmlSchemaException(SR.Sch_PatternConstraintFailed, string.Empty); } } } return null; } internal virtual bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return false; } //Compile-time Facet Checking internal virtual RestrictionFacets ConstructRestriction(DatatypeImplementation datatype, XmlSchemaObjectCollection facets, XmlNameTable nameTable) { //Datatype is the type on which this method is called RestrictionFacets derivedRestriction = new RestrictionFacets(); FacetsCompiler facetCompiler = new FacetsCompiler(datatype, derivedRestriction); for (int i = 0; i < facets.Count; ++i) { XmlSchemaFacet facet = (XmlSchemaFacet)facets[i]; if (facet.Value == null) { throw new XmlSchemaException(SR.Sch_InvalidFacet, facet); } IXmlNamespaceResolver nsmgr = new SchemaNamespaceManager(facet); switch (facet.FacetType) { case FacetType.Length: facetCompiler.CompileLengthFacet(facet); break; case FacetType.MinLength: facetCompiler.CompileMinLengthFacet(facet); break; case FacetType.MaxLength: facetCompiler.CompileMaxLengthFacet(facet); break; case FacetType.Pattern: facetCompiler.CompilePatternFacet(facet as XmlSchemaPatternFacet); break; case FacetType.Enumeration: facetCompiler.CompileEnumerationFacet(facet, nsmgr, nameTable); break; case FacetType.Whitespace: facetCompiler.CompileWhitespaceFacet(facet); break; case FacetType.MinInclusive: facetCompiler.CompileMinInclusiveFacet(facet); break; case FacetType.MinExclusive: facetCompiler.CompileMinExclusiveFacet(facet); break; case FacetType.MaxInclusive: facetCompiler.CompileMaxInclusiveFacet(facet); break; case FacetType.MaxExclusive: facetCompiler.CompileMaxExclusiveFacet(facet); break; case FacetType.TotalDigits: facetCompiler.CompileTotalDigitsFacet(facet); break; case FacetType.FractionDigits: facetCompiler.CompileFractionDigitsFacet(facet); break; default: throw new XmlSchemaException(SR.Sch_UnknownFacet, facet); } } facetCompiler.FinishFacetCompile(); facetCompiler.CompileFacetCombinations(); return derivedRestriction; } internal static decimal Power(int x, int y) { //Returns X raised to the power Y decimal returnValue = 1m; decimal decimalValue = (decimal)x; if (y > 28) { //CLR decimal cannot handle more than 29 digits (10 power 28.) return decimal.MaxValue; } for (int i = 0; i < y; i++) { returnValue = returnValue * decimalValue; } return returnValue; } } internal class Numeric10FacetsChecker : FacetsChecker { private static readonly char[] s_signs = new char[] { '+', '-' }; private decimal _maxValue; private decimal _minValue; internal Numeric10FacetsChecker(decimal minVal, decimal maxVal) { _minValue = minVal; _maxValue = maxVal; } internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { decimal decimalValue = datatype.ValueConverter.ToDecimal(value); return CheckValueFacets(decimalValue, datatype); } internal override Exception CheckValueFacets(decimal value, XmlSchemaDatatype datatype) { RestrictionFacets restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; //Check built-in facets if (value > _maxValue || value < _minValue) { return new OverflowException(SR.Format(SR.XmlConvert_Overflow, value.ToString(CultureInfo.InvariantCulture), datatype.TypeCodeString)); } //Check user-defined facets if (flags != 0) { if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (value > valueConverter.ToDecimal(restriction.MaxInclusive)) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (value >= valueConverter.ToDecimal(restriction.MaxExclusive)) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (value < valueConverter.ToDecimal(restriction.MinInclusive)) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (value <= valueConverter.ToDecimal(restriction.MinExclusive)) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration, valueConverter)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return CheckTotalAndFractionDigits(value, restriction.TotalDigits, restriction.FractionDigits, ((flags & RestrictionFlags.TotalDigits) != 0), ((flags & RestrictionFlags.FractionDigits) != 0)); } return null; } internal override Exception CheckValueFacets(long value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override Exception CheckValueFacets(int value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override Exception CheckValueFacets(short value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDecimal(value), enumeration, datatype.ValueConverter); } internal bool MatchEnumeration(decimal value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { if (value == valueConverter.ToDecimal(enumeration[i])) { return true; } } return false; } internal Exception CheckTotalAndFractionDigits(decimal value, int totalDigits, int fractionDigits, bool checkTotal, bool checkFraction) { decimal maxValue = FacetsChecker.Power(10, totalDigits) - 1; //(decimal)Math.Pow(10, totalDigits) - 1 ; int powerCnt = 0; if (value < 0) { value = decimal.Negate(value); //Need to compare maxValue allowed against the absolute value } while (decimal.Truncate(value) != value) { //Till it has a fraction value = value * 10; powerCnt++; } if (checkTotal && (value > maxValue || powerCnt > totalDigits)) { return new XmlSchemaException(SR.Sch_TotalDigitsConstraintFailed, string.Empty); } if (checkFraction && powerCnt > fractionDigits) { return new XmlSchemaException(SR.Sch_FractionDigitsConstraintFailed, string.Empty); } return null; } } internal class Numeric2FacetsChecker : FacetsChecker { internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { double doubleValue = datatype.ValueConverter.ToDouble(value); return CheckValueFacets(doubleValue, datatype); } internal override Exception CheckValueFacets(double value, XmlSchemaDatatype datatype) { RestrictionFacets restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (value > valueConverter.ToDouble(restriction.MaxInclusive)) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (value >= valueConverter.ToDouble(restriction.MaxExclusive)) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (value < (valueConverter.ToDouble(restriction.MinInclusive))) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (value <= valueConverter.ToDouble(restriction.MinExclusive)) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration, valueConverter)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override Exception CheckValueFacets(float value, XmlSchemaDatatype datatype) { double doubleValue = (double)value; return CheckValueFacets(doubleValue, datatype); } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDouble(value), enumeration, datatype.ValueConverter); } private bool MatchEnumeration(double value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { if (value == valueConverter.ToDouble(enumeration[i])) { return true; } } return false; } } internal class DurationFacetsChecker : FacetsChecker { internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { TimeSpan timeSpanValue = (TimeSpan)datatype.ValueConverter.ChangeType(value, typeof(TimeSpan)); return CheckValueFacets(timeSpanValue, datatype); } internal override Exception CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype) { RestrictionFacets restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction.MaxInclusive) > 0) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction.MaxExclusive) >= 0) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction.MinInclusive) < 0) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction.MinExclusive) <= 0) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((TimeSpan)value, enumeration); } private bool MatchEnumeration(TimeSpan value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { if (TimeSpan.Compare(value, (TimeSpan)enumeration[i]) == 0) { return true; } } return false; } } internal class DateTimeFacetsChecker : FacetsChecker { internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { DateTime dateTimeValue = datatype.ValueConverter.ToDateTime(value); return CheckValueFacets(dateTimeValue, datatype); } internal override Exception CheckValueFacets(DateTime value, XmlSchemaDatatype datatype) { RestrictionFacets restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction.MaxInclusive) > 0) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction.MaxExclusive) >= 0) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction.MinInclusive) < 0) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction.MinExclusive) <= 0) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDateTime(value), enumeration, datatype); } private bool MatchEnumeration(DateTime value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, (DateTime)enumeration[i]) == 0) { return true; } } return false; } } internal class StringFacetsChecker : FacetsChecker { //All types derived from string & anyURI private static Regex s_languagePattern; private static Regex LanguagePattern { get { if (s_languagePattern == null) { Regex langRegex = new Regex("^([a-zA-Z]{1,8})(-[a-zA-Z0-9]{1,8})*$", RegexOptions.None); Interlocked.CompareExchange(ref s_languagePattern, langRegex, null); } return s_languagePattern; } } internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { string stringValue = datatype.ValueConverter.ToString(value); return CheckValueFacets(stringValue, datatype, true); } internal override Exception CheckValueFacets(string value, XmlSchemaDatatype datatype) { return CheckValueFacets(value, datatype, true); } internal Exception CheckValueFacets(string value, XmlSchemaDatatype datatype, bool verifyUri) { //Length, MinLength, MaxLength int length = value.Length; RestrictionFacets restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; Exception exception; exception = CheckBuiltInFacets(value, datatype.TypeCode, verifyUri); if (exception != null) return exception; if (flags != 0) { if ((flags & RestrictionFlags.Length) != 0) { if (restriction.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToString(value), enumeration, datatype); } private bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaDatatype datatype) { if (datatype.TypeCode == XmlTypeCode.AnyUri) { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals(((Uri)enumeration[i]).OriginalString)) { return true; } } } else { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals((string)enumeration[i])) { return true; } } } return false; } private Exception CheckBuiltInFacets(string s, XmlTypeCode typeCode, bool verifyUri) { Exception exception = null; switch (typeCode) { case XmlTypeCode.AnyUri: if (verifyUri) { Uri uri; exception = XmlConvert.TryToUri(s, out uri); } break; case XmlTypeCode.NormalizedString: exception = XmlConvert.TryVerifyNormalizedString(s); break; case XmlTypeCode.Token: exception = XmlConvert.TryVerifyTOKEN(s); break; case XmlTypeCode.Language: if (s == null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } if (!LanguagePattern.IsMatch(s)) { return new XmlSchemaException(SR.Sch_InvalidLanguageId, string.Empty); } break; case XmlTypeCode.NmToken: exception = XmlConvert.TryVerifyNMTOKEN(s); break; case XmlTypeCode.Name: exception = XmlConvert.TryVerifyName(s); break; case XmlTypeCode.NCName: case XmlTypeCode.Id: case XmlTypeCode.Idref: case XmlTypeCode.Entity: exception = XmlConvert.TryVerifyNCName(s); break; default: break; } return exception; } } internal class QNameFacetsChecker : FacetsChecker { internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { XmlQualifiedName qualifiedNameValue = (XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)); return CheckValueFacets(qualifiedNameValue, datatype); } internal override Exception CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype) { RestrictionFacets restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if (flags != 0) { //If there are facets defined string strValue = value.ToString(); int length = strValue.Length; if ((flags & RestrictionFlags.Length) != 0) { if (restriction.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)), enumeration); } private bool MatchEnumeration(XmlQualifiedName value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals((XmlQualifiedName)enumeration[i])) { return true; } } return false; } } internal class MiscFacetsChecker : FacetsChecker { //For bool, anySimpleType } internal class BinaryFacetsChecker : FacetsChecker { //hexBinary & Base64Binary internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { byte[] byteArrayValue = (byte[])value; return CheckValueFacets(byteArrayValue, datatype); } internal override Exception CheckValueFacets(byte[] value, XmlSchemaDatatype datatype) { //Length, MinLength, MaxLength RestrictionFacets restriction = datatype.Restriction; int length = value.Length; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if (flags != 0) { //if it has facets defined if ((flags & RestrictionFlags.Length) != 0) { if (restriction.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((byte[])value, enumeration, datatype); } private bool MatchEnumeration(byte[] value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, (byte[])enumeration[i]) == 0) { return true; } } return false; } } internal class ListFacetsChecker : FacetsChecker { internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { //Check for facets allowed on lists - Length, MinLength, MaxLength Array values = value as Array; Debug.Assert(values != null); RestrictionFacets restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & (RestrictionFlags.Length | RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0) { int length = values.Length; if ((flags & RestrictionFlags.Length) != 0) { if (restriction.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, enumeration[i]) == 0) { return true; } } return false; } } internal class UnionFacetsChecker : FacetsChecker { internal override Exception CheckValueFacets(object value, XmlSchemaDatatype datatype) { RestrictionFacets restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, enumeration[i]) == 0) { //Compare on Datatype_union will compare two XsdSimpleValue return true; } } return false; } } }
using NuGet.Test.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Xunit; namespace NuGet.Test { public class XmlExtensionsTest { [Fact] public void MergingWithSameTagDifferentAttributesWithNoConflictsMergesAttributes() { // Arrange XElement a = XElement.Parse(@"<foo><bar a=""aValue"" /></foo>"); XElement b = XElement.Parse(@"<foo><bar b=""bValue"" /></foo>"); // Act var result = a.MergeWith(b); // Assert Assert.Equal(1, result.Elements("bar").Count()); XElement barElement = result.Element("bar"); Assert.NotNull(barElement); Assert.Equal(2, barElement.Attributes().Count()); AssertAttributeValue(barElement, "a", "aValue"); AssertAttributeValue(barElement, "b", "bValue"); } [Fact] public void MergingWithNodeActions() { // Arrange XElement a = XElement.Parse(@"<foo><baz /></foo>"); XElement b = XElement.Parse(@"<foo><bar /></foo>"); // Act var result = a.MergeWith(b, new Dictionary<XName, Action<XElement, XElement>> { { "bar", (parent, element) => parent.AddFirst(element) } }); // Assert var elements = result.Elements().ToList(); Assert.Equal(2, elements.Count); Assert.Equal("bar", elements[0].Name); Assert.Equal("baz", elements[1].Name); } [Fact] public void MergingWithoutInsertionMappingsAddsToEnd() { // Arrange XElement a = XElement.Parse(@"<foo><baz /></foo>"); XElement b = XElement.Parse(@"<foo><bar /></foo>"); // Act var result = a.MergeWith(b); // Assert var elements = result.Elements().ToList(); Assert.Equal(2, elements.Count); Assert.Equal("baz", elements[0].Name); Assert.Equal("bar", elements[1].Name); } [Fact] public void MergingElementsWithMultipleSameAttributeNamesAndValuesDoesntDuplicateEntries() { // Act XElement a = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); XElement b = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); // Act var result = a.MergeWith(b); // Assert var elements = result.Elements("test").ToList(); Assert.Equal(2, elements.Count); AssertAttributeValue(elements[0], "name", "one"); AssertAttributeValue(elements[0], "value", "foo"); AssertAttributeValue(elements[1], "name", "two"); AssertAttributeValue(elements[1], "value", "bar"); } [Fact] public void MergingElementsMergeComments() { // Act XElement a = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <special> </special> <!-- old comment --> </tests>"); XElement b = XElement.Parse(@"<tests> <!-- this is a comment --> <test name=""one"" value=""foo""> <!-- this is a comment inside element --> <child> <!-- this is a nested comment --> </child> <!-- comment before new element --> <!-- second comment before new element --> <rock /> </test> <!-- comment at the end --> </tests>"); // Act var result = a.MergeWith(b).ToString(); // Assert XmlAssert.Equal(@"<tests> <!-- this is a comment --> <test name=""one"" value=""foo""> <!-- this is a comment inside element --> <child> <!-- this is a nested comment --> </child> <!-- comment before new element --> <!-- second comment before new element --> <rock /> </test> <special></special> <!-- old comment --> <!-- comment at the end --> </tests>", result); } [Fact] public void MergingElementsMergeCommentsWhenThereIsNoChildElement() { // Act XElement a = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> </tests>"); XElement b = XElement.Parse(@"<tests> <!-- this file contains only comment hahaha, you like that? --> <!-- dark knight rises --> </tests>"); // Act var result = a.MergeWith(b).ToString(); // Assert XmlAssert.Equal(@"<tests> <test name=""one"" value=""foo"" /> <!-- this file contains only comment hahaha, you like that? --> <!-- dark knight rises --> </tests>", result); } [Fact] public void MergingElementsWithMultipleEntiresAddsEntryIfNotExists() { // Act XElement a = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); XElement b = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> <test name=""three"" value=""baz"" /> </tests>"); // Act var result = a.MergeWith(b); // Assert var elements = result.Elements("test").ToList(); Assert.Equal(3, elements.Count); AssertAttributeValue(elements[0], "name", "one"); AssertAttributeValue(elements[0], "value", "foo"); AssertAttributeValue(elements[1], "name", "two"); AssertAttributeValue(elements[1], "value", "bar"); AssertAttributeValue(elements[2], "name", "three"); AssertAttributeValue(elements[2], "value", "baz"); } [Fact] public void MergingTagWithConflictsAddsTag() { // Arrange XElement a = XElement.Parse(@"<connectionStrings><add name=""sqlce"" connectionString=""|DataDirectory|\foo.sdf"" /></connectionStrings>"); XElement b = XElement.Parse(@"<connectionStrings><add name=""sqlserver"" connectionString=""foo.bar"" /></connectionStrings>"); // Act var result = a.MergeWith(b); // Assert var elements = result.Elements("add").ToList(); Assert.Equal(2, elements.Count); AssertAttributeValue(elements[0], "name", "sqlce"); AssertAttributeValue(elements[0], "connectionString", @"|DataDirectory|\foo.sdf"); AssertAttributeValue(elements[1], "name", "sqlserver"); AssertAttributeValue(elements[1], "connectionString", "foo.bar"); } [Fact] public void ExceptWithTagsNoConflicts() { // Arrange XElement a = XElement.Parse(@"<foo><bar b=""2"" /></foo>"); XElement b = XElement.Parse(@"<foo><bar a=""1"" b=""2"" /></foo>"); // Act var result = a.Except(b); // Assert Assert.Equal(0, result.Elements("bar").Count()); } [Fact] public void ExceptWithTagsWithConflicts() { // Arrange XElement a = XElement.Parse(@"<foo><bar b=""2"" a=""g"" /></foo>"); XElement b = XElement.Parse(@"<foo><bar a=""1"" b=""2"" /></foo>"); // Act var result = a.Except(b); // Assert Assert.Equal(1, result.Elements("bar").Count()); XElement barElement = result.Element("bar"); Assert.NotNull(barElement); Assert.Equal(2, barElement.Attributes().Count()); AssertAttributeValue(barElement, "a", "g"); AssertAttributeValue(barElement, "b", "2"); } [Fact] public void ExceptRemoveComments() { // Act XElement a = XElement.Parse(@"<tests> <test name=""One"" value=""foo"" /> <test name=""two"" value=""bar"" /> <!-- comment --> </tests>"); XElement b = XElement.Parse(@"<tests> <!-- comment --> <test name=""two"" value=""bar"" /> </tests>"); // Act var result = a.Except(b); // Assert XmlAssert.Equal(@"<tests> <test name=""One"" value=""foo"" /> </tests>", result.ToString()); } [Fact] public void ExceptDoNotRemoveCommentIfCommentsDoNotMatch() { // Act XElement a = XElement.Parse(@"<tests> <test name=""One"" value=""foo"" /> <test name=""two"" value=""bar"" /> <!-- this is a comment --> </tests>"); XElement b = XElement.Parse(@"<tests> <!-- comment --> <test name=""two"" value=""bar"" /> </tests>"); // Act var result = a.Except(b); // Assert XmlAssert.Equal(@"<tests> <test name=""One"" value=""foo"" /> <!-- this is a comment --> </tests>", result.ToString()); } [Fact] public void ExceptWithSimilarTagsRemovesTagsThatChanged() { // Act XElement a = XElement.Parse(@"<tests> <test name=""One"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); XElement b = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); // Act var result = a.Except(b); // Assert XmlAssert.Equal(@"<tests> <test name=""One"" value=""foo"" /> </tests>", result.ToString()); } [Fact] public void ExceptWithSimilarTagsRemovesTagsThatWereReordered() { // Act XElement a = XElement.Parse(@" <configuration> <tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests> </configuration>"); XElement b = XElement.Parse(@" <configuration> <tests> <test name=""two"" value=""bar"" /> <test name=""one"" value=""foo"" /> </tests> </configuration>"); // Act var result = a.Except(b); #if !MONO // Assert XmlAssert.Equal("<configuration />", result.ToString()); #else //Mono doesn't automagically collapse "empty" elements, .Net XElement does. :-/ XmlAssert.Equal("<configuration></configuration>", result.ToString()); #endif } private static void AssertAttributeValue(XElement element, string attributeName, string expectedAttributeValue) { XAttribute attr = element.Attribute(attributeName); Assert.NotNull(attr); Assert.Equal(expectedAttributeValue, attr.Value); } } }
using System; namespace Org.BouncyCastle.Crypto.Utilities { internal sealed class Pack { private Pack() { } internal static void UInt16_To_BE(ushort n, byte[] bs) { bs[0] = (byte)(n >> 8); bs[1] = (byte)(n); } internal static void UInt16_To_BE(ushort n, byte[] bs, int off) { bs[off] = (byte)(n >> 8); bs[off + 1] = (byte)(n); } internal static ushort BE_To_UInt16(byte[] bs) { uint n = (uint)bs[0] << 8 | (uint)bs[1]; return (ushort)n; } internal static ushort BE_To_UInt16(byte[] bs, int off) { uint n = (uint)bs[off] << 8 | (uint)bs[off + 1]; return (ushort)n; } internal static void UInt32_To_BE(uint n, byte[] bs) { bs[0] = (byte)(n >> 24); bs[1] = (byte)(n >> 16); bs[2] = (byte)(n >> 8); bs[3] = (byte)(n); } internal static void UInt32_To_BE(uint n, byte[] bs, int off) { bs[off] = (byte)(n >> 24); bs[off + 1] = (byte)(n >> 16); bs[off + 2] = (byte)(n >> 8); bs[off + 3] = (byte)(n); } internal static void UInt32_To_BE(uint[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt32_To_BE(ns[i], bs, off); off += 4; } } internal static uint BE_To_UInt32(byte[] bs) { return (uint)bs[0] << 24 | (uint)bs[1] << 16 | (uint)bs[2] << 8 | (uint)bs[3]; } internal static uint BE_To_UInt32(byte[] bs, int off) { return (uint)bs[off] << 24 | (uint)bs[off + 1] << 16 | (uint)bs[off + 2] << 8 | (uint)bs[off + 3]; } internal static void BE_To_UInt32(byte[] bs, int off, uint[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = BE_To_UInt32(bs, off); off += 4; } } internal static ulong BE_To_UInt64(byte[] bs) { uint hi = BE_To_UInt32(bs); uint lo = BE_To_UInt32(bs, 4); return ((ulong)hi << 32) | (ulong)lo; } internal static ulong BE_To_UInt64(byte[] bs, int off) { uint hi = BE_To_UInt32(bs, off); uint lo = BE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; } internal static void UInt64_To_BE(ulong n, byte[] bs) { UInt32_To_BE((uint)(n >> 32), bs); UInt32_To_BE((uint)(n), bs, 4); } internal static void UInt64_To_BE(ulong n, byte[] bs, int off) { UInt32_To_BE((uint)(n >> 32), bs, off); UInt32_To_BE((uint)(n), bs, off + 4); } internal static void UInt16_To_LE(ushort n, byte[] bs) { bs[0] = (byte)(n); bs[1] = (byte)(n >> 8); } internal static void UInt16_To_LE(ushort n, byte[] bs, int off) { bs[off] = (byte)(n); bs[off + 1] = (byte)(n >> 8); } internal static ushort LE_To_UInt16(byte[] bs) { uint n = (uint)bs[0] | (uint)bs[1] << 8; return (ushort)n; } internal static ushort LE_To_UInt16(byte[] bs, int off) { uint n = (uint)bs[off] | (uint)bs[off + 1] << 8; return (ushort)n; } internal static void UInt32_To_LE(uint n, byte[] bs) { bs[0] = (byte)(n); bs[1] = (byte)(n >> 8); bs[2] = (byte)(n >> 16); bs[3] = (byte)(n >> 24); } internal static void UInt32_To_LE(uint n, byte[] bs, int off) { bs[off] = (byte)(n); bs[off + 1] = (byte)(n >> 8); bs[off + 2] = (byte)(n >> 16); bs[off + 3] = (byte)(n >> 24); } internal static void UInt32_To_LE(uint[] ns, byte[] bs, int off) { for (int i = 0; i < ns.Length; ++i) { UInt32_To_LE(ns[i], bs, off); off += 4; } } internal static uint LE_To_UInt32(byte[] bs) { return (uint)bs[0] | (uint)bs[1] << 8 | (uint)bs[2] << 16 | (uint)bs[3] << 24; } internal static uint LE_To_UInt32(byte[] bs, int off) { return (uint)bs[off] | (uint)bs[off + 1] << 8 | (uint)bs[off + 2] << 16 | (uint)bs[off + 3] << 24; } internal static void LE_To_UInt32(byte[] bs, int off, uint[] ns) { for (int i = 0; i < ns.Length; ++i) { ns[i] = LE_To_UInt32(bs, off); off += 4; } } internal static ulong LE_To_UInt64(byte[] bs) { uint lo = LE_To_UInt32(bs); uint hi = LE_To_UInt32(bs, 4); return ((ulong)hi << 32) | (ulong)lo; } internal static ulong LE_To_UInt64(byte[] bs, int off) { uint lo = LE_To_UInt32(bs, off); uint hi = LE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; } internal static void UInt64_To_LE(ulong n, byte[] bs) { UInt32_To_LE((uint)(n), bs); UInt32_To_LE((uint)(n >> 32), bs, 4); } internal static void UInt64_To_LE(ulong n, byte[] bs, int off) { UInt32_To_LE((uint)(n), bs, off); UInt32_To_LE((uint)(n >> 32), bs, off + 4); } } }
// dnlib: See LICENSE.txt for more info namespace dnlib.DotNet.MD { #pragma warning disable 1591 // Missing XML comment for publicly visible type or member /// <summary> /// Raw contents of an uncompressed Module table row /// </summary> public readonly struct RawModuleRow { public readonly ushort Generation; public readonly uint Name; public readonly uint Mvid; public readonly uint EncId; public readonly uint EncBaseId; public RawModuleRow(ushort Generation, uint Name, uint Mvid, uint EncId, uint EncBaseId) { this.Generation = Generation; this.Name = Name; this.Mvid = Mvid; this.EncId = EncId; this.EncBaseId = EncBaseId; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Generation, 1 => Name, 2 => Mvid, 3 => EncId, 4 => EncBaseId, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed TypeRef table row /// </summary> public readonly struct RawTypeRefRow { public readonly uint ResolutionScope; public readonly uint Name; public readonly uint Namespace; public RawTypeRefRow(uint ResolutionScope, uint Name, uint Namespace) { this.ResolutionScope = ResolutionScope; this.Name = Name; this.Namespace = Namespace; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => ResolutionScope, 1 => Name, 2 => Namespace, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed TypeDef table row /// </summary> public readonly struct RawTypeDefRow { public readonly uint Flags; public readonly uint Name; public readonly uint Namespace; public readonly uint Extends; public readonly uint FieldList; public readonly uint MethodList; public RawTypeDefRow(uint Flags, uint Name, uint Namespace, uint Extends, uint FieldList, uint MethodList) { this.Flags = Flags; this.Name = Name; this.Namespace = Namespace; this.Extends = Extends; this.FieldList = FieldList; this.MethodList = MethodList; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Flags, 1 => Name, 2 => Namespace, 3 => Extends, 4 => FieldList, 5 => MethodList, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed FieldPtr table row /// </summary> public readonly struct RawFieldPtrRow { public readonly uint Field; public RawFieldPtrRow(uint Field) => this.Field = Field; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Field, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed Field table row /// </summary> public readonly struct RawFieldRow { public readonly ushort Flags; public readonly uint Name; public readonly uint Signature; public RawFieldRow(ushort Flags, uint Name, uint Signature) { this.Flags = Flags; this.Name = Name; this.Signature = Signature; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Flags, 1 => Name, 2 => Signature, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed MethodPtr table row /// </summary> public readonly struct RawMethodPtrRow { public readonly uint Method; public RawMethodPtrRow(uint Method) => this.Method = Method; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Method, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed Method table row /// </summary> public readonly struct RawMethodRow { public readonly uint RVA; public readonly ushort ImplFlags; public readonly ushort Flags; public readonly uint Name; public readonly uint Signature; public readonly uint ParamList; public RawMethodRow(uint RVA, ushort ImplFlags, ushort Flags, uint Name, uint Signature, uint ParamList) { this.RVA = RVA; this.ImplFlags = ImplFlags; this.Flags = Flags; this.Name = Name; this.Signature = Signature; this.ParamList = ParamList; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => RVA, 1 => ImplFlags, 2 => Flags, 3 => Name, 4 => Signature, 5 => ParamList, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed ParamPtr table row /// </summary> public readonly struct RawParamPtrRow { public readonly uint Param; public RawParamPtrRow(uint Param) => this.Param = Param; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Param, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed Param table row /// </summary> public readonly struct RawParamRow { public readonly ushort Flags; public readonly ushort Sequence; public readonly uint Name; public RawParamRow(ushort Flags, ushort Sequence, uint Name) { this.Flags = Flags; this.Sequence = Sequence; this.Name = Name; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Flags, 1 => Sequence, 2 => Name, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed InterfaceImpl table row /// </summary> public readonly struct RawInterfaceImplRow { public readonly uint Class; public readonly uint Interface; public RawInterfaceImplRow(uint Class, uint Interface) { this.Class = Class; this.Interface = Interface; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Class, 1 => Interface, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed MemberRef table row /// </summary> public readonly struct RawMemberRefRow { public readonly uint Class; public readonly uint Name; public readonly uint Signature; public RawMemberRefRow(uint Class, uint Name, uint Signature) { this.Class = Class; this.Name = Name; this.Signature = Signature; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Class, 1 => Name, 2 => Signature, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed Constant table row /// </summary> public readonly struct RawConstantRow { public readonly byte Type; public readonly byte Padding; public readonly uint Parent; public readonly uint Value; public RawConstantRow(byte Type, byte Padding, uint Parent, uint Value) { this.Type = Type; this.Padding = Padding; this.Parent = Parent; this.Value = Value; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Type, 1 => Padding, 2 => Parent, 3 => Value, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed CustomAttribute table row /// </summary> public readonly struct RawCustomAttributeRow { public readonly uint Parent; public readonly uint Type; public readonly uint Value; public RawCustomAttributeRow(uint Parent, uint Type, uint Value) { this.Parent = Parent; this.Type = Type; this.Value = Value; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Parent, 1 => Type, 2 => Value, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed FieldMarshal table row /// </summary> public readonly struct RawFieldMarshalRow { public readonly uint Parent; public readonly uint NativeType; public RawFieldMarshalRow(uint Parent, uint NativeType) { this.Parent = Parent; this.NativeType = NativeType; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Parent, 1 => NativeType, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed DeclSecurity table row /// </summary> public readonly struct RawDeclSecurityRow { public readonly short Action; public readonly uint Parent; public readonly uint PermissionSet; public RawDeclSecurityRow(short Action, uint Parent, uint PermissionSet) { this.Action = Action; this.Parent = Parent; this.PermissionSet = PermissionSet; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => (uint)(int)Action, 1 => Parent, 2 => PermissionSet, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed ClassLayout table row /// </summary> public readonly struct RawClassLayoutRow { public readonly ushort PackingSize; public readonly uint ClassSize; public readonly uint Parent; public RawClassLayoutRow(ushort PackingSize, uint ClassSize, uint Parent) { this.PackingSize = PackingSize; this.ClassSize = ClassSize; this.Parent = Parent; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => PackingSize, 1 => ClassSize, 2 => Parent, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed FieldLayout table row /// </summary> public readonly struct RawFieldLayoutRow { public readonly uint OffSet; public readonly uint Field; public RawFieldLayoutRow(uint OffSet, uint Field) { this.OffSet = OffSet; this.Field = Field; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => OffSet, 1 => Field, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed StandAloneSig table row /// </summary> public readonly struct RawStandAloneSigRow { public readonly uint Signature; public RawStandAloneSigRow(uint Signature) => this.Signature = Signature; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Signature, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed EventMap table row /// </summary> public readonly struct RawEventMapRow { public readonly uint Parent; public readonly uint EventList; public RawEventMapRow(uint Parent, uint EventList) { this.Parent = Parent; this.EventList = EventList; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Parent, 1 => EventList, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed EventPtr table row /// </summary> public readonly struct RawEventPtrRow { public readonly uint Event; public RawEventPtrRow(uint Event) => this.Event = Event; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Event, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed Event table row /// </summary> public readonly struct RawEventRow { public readonly ushort EventFlags; public readonly uint Name; public readonly uint EventType; public RawEventRow(ushort EventFlags, uint Name, uint EventType) { this.EventFlags = EventFlags; this.Name = Name; this.EventType = EventType; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => EventFlags, 1 => Name, 2 => EventType, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed PropertyMap table row /// </summary> public readonly struct RawPropertyMapRow { public readonly uint Parent; public readonly uint PropertyList; public RawPropertyMapRow(uint Parent, uint PropertyList) { this.Parent = Parent; this.PropertyList = PropertyList; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Parent, 1 => PropertyList, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed PropertyPtr table row /// </summary> public readonly struct RawPropertyPtrRow { public readonly uint Property; public RawPropertyPtrRow(uint Property) => this.Property = Property; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Property, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed Property table row /// </summary> public readonly struct RawPropertyRow { public readonly ushort PropFlags; public readonly uint Name; public readonly uint Type; public RawPropertyRow(ushort PropFlags, uint Name, uint Type) { this.PropFlags = PropFlags; this.Name = Name; this.Type = Type; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => PropFlags, 1 => Name, 2 => Type, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed MethodSemantics table row /// </summary> public readonly struct RawMethodSemanticsRow { public readonly ushort Semantic; public readonly uint Method; public readonly uint Association; public RawMethodSemanticsRow(ushort Semantic, uint Method, uint Association) { this.Semantic = Semantic; this.Method = Method; this.Association = Association; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Semantic, 1 => Method, 2 => Association, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed MethodImpl table row /// </summary> public readonly struct RawMethodImplRow { public readonly uint Class; public readonly uint MethodBody; public readonly uint MethodDeclaration; public RawMethodImplRow(uint Class, uint MethodBody, uint MethodDeclaration) { this.Class = Class; this.MethodBody = MethodBody; this.MethodDeclaration = MethodDeclaration; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Class, 1 => MethodBody, 2 => MethodDeclaration, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed ModuleRef table row /// </summary> public readonly struct RawModuleRefRow { public readonly uint Name; public RawModuleRefRow(uint Name) => this.Name = Name; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Name, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed TypeSpec table row /// </summary> public readonly struct RawTypeSpecRow { public readonly uint Signature; public RawTypeSpecRow(uint Signature) => this.Signature = Signature; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Signature, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed ImplMap table row /// </summary> public readonly struct RawImplMapRow { public readonly ushort MappingFlags; public readonly uint MemberForwarded; public readonly uint ImportName; public readonly uint ImportScope; public RawImplMapRow(ushort MappingFlags, uint MemberForwarded, uint ImportName, uint ImportScope) { this.MappingFlags = MappingFlags; this.MemberForwarded = MemberForwarded; this.ImportName = ImportName; this.ImportScope = ImportScope; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => MappingFlags, 1 => MemberForwarded, 2 => ImportName, 3 => ImportScope, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed FieldRVA table row /// </summary> public readonly struct RawFieldRVARow { public readonly uint RVA; public readonly uint Field; public RawFieldRVARow(uint RVA, uint Field) { this.RVA = RVA; this.Field = Field; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => RVA, 1 => Field, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed ENCLog table row /// </summary> public readonly struct RawENCLogRow { public readonly uint Token; public readonly uint FuncCode; public RawENCLogRow(uint Token, uint FuncCode) { this.Token = Token; this.FuncCode = FuncCode; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Token, 1 => FuncCode, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed ENCMap table row /// </summary> public readonly struct RawENCMapRow { public readonly uint Token; public RawENCMapRow(uint Token) => this.Token = Token; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Token, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed Assembly table row /// </summary> public readonly struct RawAssemblyRow { public readonly uint HashAlgId; public readonly ushort MajorVersion; public readonly ushort MinorVersion; public readonly ushort BuildNumber; public readonly ushort RevisionNumber; public readonly uint Flags; public readonly uint PublicKey; public readonly uint Name; public readonly uint Locale; public RawAssemblyRow(uint HashAlgId, ushort MajorVersion, ushort MinorVersion, ushort BuildNumber, ushort RevisionNumber, uint Flags, uint PublicKey, uint Name, uint Locale) { this.HashAlgId = HashAlgId; this.MajorVersion = MajorVersion; this.MinorVersion = MinorVersion; this.BuildNumber = BuildNumber; this.RevisionNumber = RevisionNumber; this.Flags = Flags; this.PublicKey = PublicKey; this.Name = Name; this.Locale = Locale; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => HashAlgId, 1 => MajorVersion, 2 => MinorVersion, 3 => BuildNumber, 4 => RevisionNumber, 5 => Flags, 6 => PublicKey, 7 => Name, 8 => Locale, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed AssemblyProcessor table row /// </summary> public readonly struct RawAssemblyProcessorRow { public readonly uint Processor; public RawAssemblyProcessorRow(uint Processor) => this.Processor = Processor; /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Processor, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed AssemblyOS table row /// </summary> public readonly struct RawAssemblyOSRow { public readonly uint OSPlatformId; public readonly uint OSMajorVersion; public readonly uint OSMinorVersion; public RawAssemblyOSRow(uint OSPlatformId, uint OSMajorVersion, uint OSMinorVersion) { this.OSPlatformId = OSPlatformId; this.OSMajorVersion = OSMajorVersion; this.OSMinorVersion = OSMinorVersion; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => OSPlatformId, 1 => OSMajorVersion, 2 => OSMinorVersion, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed AssemblyRef table row /// </summary> public readonly struct RawAssemblyRefRow { public readonly ushort MajorVersion; public readonly ushort MinorVersion; public readonly ushort BuildNumber; public readonly ushort RevisionNumber; public readonly uint Flags; public readonly uint PublicKeyOrToken; public readonly uint Name; public readonly uint Locale; public readonly uint HashValue; public RawAssemblyRefRow(ushort MajorVersion, ushort MinorVersion, ushort BuildNumber, ushort RevisionNumber, uint Flags, uint PublicKeyOrToken, uint Name, uint Locale, uint HashValue) { this.MajorVersion = MajorVersion; this.MinorVersion = MinorVersion; this.BuildNumber = BuildNumber; this.RevisionNumber = RevisionNumber; this.Flags = Flags; this.PublicKeyOrToken = PublicKeyOrToken; this.Name = Name; this.Locale = Locale; this.HashValue = HashValue; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => MajorVersion, 1 => MinorVersion, 2 => BuildNumber, 3 => RevisionNumber, 4 => Flags, 5 => PublicKeyOrToken, 6 => Name, 7 => Locale, 8 => HashValue, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed AssemblyRefProcessor table row /// </summary> public readonly struct RawAssemblyRefProcessorRow { public readonly uint Processor; public readonly uint AssemblyRef; public RawAssemblyRefProcessorRow(uint Processor, uint AssemblyRef) { this.Processor = Processor; this.AssemblyRef = AssemblyRef; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Processor, 1 => AssemblyRef, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed AssemblyRefOS table row /// </summary> public readonly struct RawAssemblyRefOSRow { public readonly uint OSPlatformId; public readonly uint OSMajorVersion; public readonly uint OSMinorVersion; public readonly uint AssemblyRef; public RawAssemblyRefOSRow(uint OSPlatformId, uint OSMajorVersion, uint OSMinorVersion, uint AssemblyRef) { this.OSPlatformId = OSPlatformId; this.OSMajorVersion = OSMajorVersion; this.OSMinorVersion = OSMinorVersion; this.AssemblyRef = AssemblyRef; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => OSPlatformId, 1 => OSMajorVersion, 2 => OSMinorVersion, 3 => AssemblyRef, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed File table row /// </summary> public readonly struct RawFileRow { public readonly uint Flags; public readonly uint Name; public readonly uint HashValue; public RawFileRow(uint Flags, uint Name, uint HashValue) { this.Flags = Flags; this.Name = Name; this.HashValue = HashValue; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Flags, 1 => Name, 2 => HashValue, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed ExportedType table row /// </summary> public readonly struct RawExportedTypeRow { public readonly uint Flags; public readonly uint TypeDefId; public readonly uint TypeName; public readonly uint TypeNamespace; public readonly uint Implementation; public RawExportedTypeRow(uint Flags, uint TypeDefId, uint TypeName, uint TypeNamespace, uint Implementation) { this.Flags = Flags; this.TypeDefId = TypeDefId; this.TypeName = TypeName; this.TypeNamespace = TypeNamespace; this.Implementation = Implementation; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Flags, 1 => TypeDefId, 2 => TypeName, 3 => TypeNamespace, 4 => Implementation, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed ManifestResource table row /// </summary> public readonly struct RawManifestResourceRow { public readonly uint Offset; public readonly uint Flags; public readonly uint Name; public readonly uint Implementation; public RawManifestResourceRow(uint Offset, uint Flags, uint Name, uint Implementation) { this.Offset = Offset; this.Flags = Flags; this.Name = Name; this.Implementation = Implementation; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Offset, 1 => Flags, 2 => Name, 3 => Implementation, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed NestedClass table row /// </summary> public readonly struct RawNestedClassRow { public readonly uint NestedClass; public readonly uint EnclosingClass; public RawNestedClassRow(uint NestedClass, uint EnclosingClass) { this.NestedClass = NestedClass; this.EnclosingClass = EnclosingClass; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => NestedClass, 1 => EnclosingClass, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed GenericParam table row /// </summary> public readonly struct RawGenericParamRow { public readonly ushort Number; public readonly ushort Flags; public readonly uint Owner; public readonly uint Name; public readonly uint Kind; public RawGenericParamRow(ushort Number, ushort Flags, uint Owner, uint Name, uint Kind) { this.Number = Number; this.Flags = Flags; this.Owner = Owner; this.Name = Name; this.Kind = Kind; } public RawGenericParamRow(ushort Number, ushort Flags, uint Owner, uint Name) { this.Number = Number; this.Flags = Flags; this.Owner = Owner; this.Name = Name; Kind = 0; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Number, 1 => Flags, 2 => Owner, 3 => Name, 4 => Kind, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed MethodSpec table row /// </summary> public readonly struct RawMethodSpecRow { public readonly uint Method; public readonly uint Instantiation; public RawMethodSpecRow(uint Method, uint Instantiation) { this.Method = Method; this.Instantiation = Instantiation; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Method, 1 => Instantiation, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed GenericParamConstraint table row /// </summary> public readonly struct RawGenericParamConstraintRow { public readonly uint Owner; public readonly uint Constraint; public RawGenericParamConstraintRow(uint Owner, uint Constraint) { this.Owner = Owner; this.Constraint = Constraint; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Owner, 1 => Constraint, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed Document table row /// </summary> public readonly struct RawDocumentRow { public readonly uint Name; public readonly uint HashAlgorithm; public readonly uint Hash; public readonly uint Language; public RawDocumentRow(uint Name, uint HashAlgorithm, uint Hash, uint Language) { this.Name = Name; this.HashAlgorithm = HashAlgorithm; this.Hash = Hash; this.Language = Language; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Name, 1 => HashAlgorithm, 2 => Hash, 3 => Language, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed MethodDebugInformation table row /// </summary> public readonly struct RawMethodDebugInformationRow { public readonly uint Document; public readonly uint SequencePoints; public RawMethodDebugInformationRow(uint Document, uint SequencePoints) { this.Document = Document; this.SequencePoints = SequencePoints; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Document, 1 => SequencePoints, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed LocalScope table row /// </summary> public readonly struct RawLocalScopeRow { public readonly uint Method; public readonly uint ImportScope; public readonly uint VariableList; public readonly uint ConstantList; public readonly uint StartOffset; public readonly uint Length; public RawLocalScopeRow(uint Method, uint ImportScope, uint VariableList, uint ConstantList, uint StartOffset, uint Length) { this.Method = Method; this.ImportScope = ImportScope; this.VariableList = VariableList; this.ConstantList = ConstantList; this.StartOffset = StartOffset; this.Length = Length; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Method, 1 => ImportScope, 2 => VariableList, 3 => ConstantList, 4 => StartOffset, 5 => Length, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed LocalVariable table row /// </summary> public readonly struct RawLocalVariableRow { public readonly ushort Attributes; public readonly ushort Index; public readonly uint Name; public RawLocalVariableRow(ushort Attributes, ushort Index, uint Name) { this.Attributes = Attributes; this.Index = Index; this.Name = Name; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Attributes, 1 => Index, 2 => Name, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed LocalConstant table row /// </summary> public readonly struct RawLocalConstantRow { public readonly uint Name; public readonly uint Signature; public RawLocalConstantRow(uint Name, uint Signature) { this.Name = Name; this.Signature = Signature; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Name, 1 => Signature, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed ImportScope table row /// </summary> public readonly struct RawImportScopeRow { public readonly uint Parent; public readonly uint Imports; public RawImportScopeRow(uint Parent, uint Imports) { this.Parent = Parent; this.Imports = Imports; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Parent, 1 => Imports, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed StateMachineMethod table row /// </summary> public readonly struct RawStateMachineMethodRow { public readonly uint MoveNextMethod; public readonly uint KickoffMethod; public RawStateMachineMethodRow(uint MoveNextMethod, uint KickoffMethod) { this.MoveNextMethod = MoveNextMethod; this.KickoffMethod = KickoffMethod; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => MoveNextMethod, 1 => KickoffMethod, _ => 0, }; } /// <summary> /// Raw contents of an uncompressed CustomDebugInformation table row /// </summary> public readonly struct RawCustomDebugInformationRow { public readonly uint Parent; public readonly uint Kind; public readonly uint Value; public RawCustomDebugInformationRow(uint Parent, uint Kind, uint Value) { this.Parent = Parent; this.Kind = Kind; this.Value = Value; } /// <summary> /// Gets a column /// </summary> /// <param name="index">Index of column</param> /// <returns></returns> public uint this[int index] => index switch { 0 => Parent, 1 => Kind, 2 => Value, _ => 0, }; } #pragma warning restore 1591 // Missing XML comment for publicly visible type or member }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// VM Protection Policy /// First published in XenServer 5.6 FP1. /// </summary> public partial class VMPP : XenObject<VMPP> { public VMPP() { } public VMPP(string uuid, string name_label, string name_description, bool is_policy_enabled, vmpp_backup_type backup_type, long backup_retention_value, vmpp_backup_frequency backup_frequency, Dictionary<string, string> backup_schedule, bool is_backup_running, DateTime backup_last_run_time, vmpp_archive_target_type archive_target_type, Dictionary<string, string> archive_target_config, vmpp_archive_frequency archive_frequency, Dictionary<string, string> archive_schedule, bool is_archive_running, DateTime archive_last_run_time, List<XenRef<VM>> VMs, bool is_alarm_enabled, Dictionary<string, string> alarm_config, string[] recent_alerts) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.is_policy_enabled = is_policy_enabled; this.backup_type = backup_type; this.backup_retention_value = backup_retention_value; this.backup_frequency = backup_frequency; this.backup_schedule = backup_schedule; this.is_backup_running = is_backup_running; this.backup_last_run_time = backup_last_run_time; this.archive_target_type = archive_target_type; this.archive_target_config = archive_target_config; this.archive_frequency = archive_frequency; this.archive_schedule = archive_schedule; this.is_archive_running = is_archive_running; this.archive_last_run_time = archive_last_run_time; this.VMs = VMs; this.is_alarm_enabled = is_alarm_enabled; this.alarm_config = alarm_config; this.recent_alerts = recent_alerts; } /// <summary> /// Creates a new VMPP from a Proxy_VMPP. /// </summary> /// <param name="proxy"></param> public VMPP(Proxy_VMPP proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(VMPP update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; is_policy_enabled = update.is_policy_enabled; backup_type = update.backup_type; backup_retention_value = update.backup_retention_value; backup_frequency = update.backup_frequency; backup_schedule = update.backup_schedule; is_backup_running = update.is_backup_running; backup_last_run_time = update.backup_last_run_time; archive_target_type = update.archive_target_type; archive_target_config = update.archive_target_config; archive_frequency = update.archive_frequency; archive_schedule = update.archive_schedule; is_archive_running = update.is_archive_running; archive_last_run_time = update.archive_last_run_time; VMs = update.VMs; is_alarm_enabled = update.is_alarm_enabled; alarm_config = update.alarm_config; recent_alerts = update.recent_alerts; } internal void UpdateFromProxy(Proxy_VMPP proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; name_label = proxy.name_label == null ? null : (string)proxy.name_label; name_description = proxy.name_description == null ? null : (string)proxy.name_description; is_policy_enabled = (bool)proxy.is_policy_enabled; backup_type = proxy.backup_type == null ? (vmpp_backup_type) 0 : (vmpp_backup_type)Helper.EnumParseDefault(typeof(vmpp_backup_type), (string)proxy.backup_type); backup_retention_value = proxy.backup_retention_value == null ? 0 : long.Parse((string)proxy.backup_retention_value); backup_frequency = proxy.backup_frequency == null ? (vmpp_backup_frequency) 0 : (vmpp_backup_frequency)Helper.EnumParseDefault(typeof(vmpp_backup_frequency), (string)proxy.backup_frequency); backup_schedule = proxy.backup_schedule == null ? null : Maps.convert_from_proxy_string_string(proxy.backup_schedule); is_backup_running = (bool)proxy.is_backup_running; backup_last_run_time = proxy.backup_last_run_time; archive_target_type = proxy.archive_target_type == null ? (vmpp_archive_target_type) 0 : (vmpp_archive_target_type)Helper.EnumParseDefault(typeof(vmpp_archive_target_type), (string)proxy.archive_target_type); archive_target_config = proxy.archive_target_config == null ? null : Maps.convert_from_proxy_string_string(proxy.archive_target_config); archive_frequency = proxy.archive_frequency == null ? (vmpp_archive_frequency) 0 : (vmpp_archive_frequency)Helper.EnumParseDefault(typeof(vmpp_archive_frequency), (string)proxy.archive_frequency); archive_schedule = proxy.archive_schedule == null ? null : Maps.convert_from_proxy_string_string(proxy.archive_schedule); is_archive_running = (bool)proxy.is_archive_running; archive_last_run_time = proxy.archive_last_run_time; VMs = proxy.VMs == null ? null : XenRef<VM>.Create(proxy.VMs); is_alarm_enabled = (bool)proxy.is_alarm_enabled; alarm_config = proxy.alarm_config == null ? null : Maps.convert_from_proxy_string_string(proxy.alarm_config); recent_alerts = proxy.recent_alerts == null ? new string[] {} : (string [])proxy.recent_alerts; } public Proxy_VMPP ToProxy() { Proxy_VMPP result_ = new Proxy_VMPP(); result_.uuid = uuid ?? ""; result_.name_label = name_label ?? ""; result_.name_description = name_description ?? ""; result_.is_policy_enabled = is_policy_enabled; result_.backup_type = vmpp_backup_type_helper.ToString(backup_type); result_.backup_retention_value = backup_retention_value.ToString(); result_.backup_frequency = vmpp_backup_frequency_helper.ToString(backup_frequency); result_.backup_schedule = Maps.convert_to_proxy_string_string(backup_schedule); result_.is_backup_running = is_backup_running; result_.backup_last_run_time = backup_last_run_time; result_.archive_target_type = vmpp_archive_target_type_helper.ToString(archive_target_type); result_.archive_target_config = Maps.convert_to_proxy_string_string(archive_target_config); result_.archive_frequency = vmpp_archive_frequency_helper.ToString(archive_frequency); result_.archive_schedule = Maps.convert_to_proxy_string_string(archive_schedule); result_.is_archive_running = is_archive_running; result_.archive_last_run_time = archive_last_run_time; result_.VMs = (VMs != null) ? Helper.RefListToStringArray(VMs) : new string[] {}; result_.is_alarm_enabled = is_alarm_enabled; result_.alarm_config = Maps.convert_to_proxy_string_string(alarm_config); result_.recent_alerts = recent_alerts; return result_; } /// <summary> /// Creates a new VMPP from a Hashtable. /// </summary> /// <param name="table"></param> public VMPP(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); name_label = Marshalling.ParseString(table, "name_label"); name_description = Marshalling.ParseString(table, "name_description"); is_policy_enabled = Marshalling.ParseBool(table, "is_policy_enabled"); backup_type = (vmpp_backup_type)Helper.EnumParseDefault(typeof(vmpp_backup_type), Marshalling.ParseString(table, "backup_type")); backup_retention_value = Marshalling.ParseLong(table, "backup_retention_value"); backup_frequency = (vmpp_backup_frequency)Helper.EnumParseDefault(typeof(vmpp_backup_frequency), Marshalling.ParseString(table, "backup_frequency")); backup_schedule = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "backup_schedule")); is_backup_running = Marshalling.ParseBool(table, "is_backup_running"); backup_last_run_time = Marshalling.ParseDateTime(table, "backup_last_run_time"); archive_target_type = (vmpp_archive_target_type)Helper.EnumParseDefault(typeof(vmpp_archive_target_type), Marshalling.ParseString(table, "archive_target_type")); archive_target_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "archive_target_config")); archive_frequency = (vmpp_archive_frequency)Helper.EnumParseDefault(typeof(vmpp_archive_frequency), Marshalling.ParseString(table, "archive_frequency")); archive_schedule = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "archive_schedule")); is_archive_running = Marshalling.ParseBool(table, "is_archive_running"); archive_last_run_time = Marshalling.ParseDateTime(table, "archive_last_run_time"); VMs = Marshalling.ParseSetRef<VM>(table, "VMs"); is_alarm_enabled = Marshalling.ParseBool(table, "is_alarm_enabled"); alarm_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "alarm_config")); recent_alerts = Marshalling.ParseStringArray(table, "recent_alerts"); } public bool DeepEquals(VMPP other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._is_policy_enabled, other._is_policy_enabled) && Helper.AreEqual2(this._backup_type, other._backup_type) && Helper.AreEqual2(this._backup_retention_value, other._backup_retention_value) && Helper.AreEqual2(this._backup_frequency, other._backup_frequency) && Helper.AreEqual2(this._backup_schedule, other._backup_schedule) && Helper.AreEqual2(this._is_backup_running, other._is_backup_running) && Helper.AreEqual2(this._backup_last_run_time, other._backup_last_run_time) && Helper.AreEqual2(this._archive_target_type, other._archive_target_type) && Helper.AreEqual2(this._archive_target_config, other._archive_target_config) && Helper.AreEqual2(this._archive_frequency, other._archive_frequency) && Helper.AreEqual2(this._archive_schedule, other._archive_schedule) && Helper.AreEqual2(this._is_archive_running, other._is_archive_running) && Helper.AreEqual2(this._archive_last_run_time, other._archive_last_run_time) && Helper.AreEqual2(this._VMs, other._VMs) && Helper.AreEqual2(this._is_alarm_enabled, other._is_alarm_enabled) && Helper.AreEqual2(this._alarm_config, other._alarm_config) && Helper.AreEqual2(this._recent_alerts, other._recent_alerts); } public override string SaveChanges(Session session, string opaqueRef, VMPP server) { if (opaqueRef == null) { Proxy_VMPP p = this.ToProxy(); return session.proxy.vmpp_create(session.uuid, p).parse(); } else { if (!Helper.AreEqual2(_name_label, server._name_label)) { VMPP.set_name_label(session, opaqueRef, _name_label); } if (!Helper.AreEqual2(_name_description, server._name_description)) { VMPP.set_name_description(session, opaqueRef, _name_description); } if (!Helper.AreEqual2(_is_policy_enabled, server._is_policy_enabled)) { VMPP.set_is_policy_enabled(session, opaqueRef, _is_policy_enabled); } if (!Helper.AreEqual2(_backup_type, server._backup_type)) { VMPP.set_backup_type(session, opaqueRef, _backup_type); } if (!Helper.AreEqual2(_backup_retention_value, server._backup_retention_value)) { VMPP.set_backup_retention_value(session, opaqueRef, _backup_retention_value); } if (!Helper.AreEqual2(_backup_frequency, server._backup_frequency)) { VMPP.set_backup_frequency(session, opaqueRef, _backup_frequency); } if (!Helper.AreEqual2(_backup_schedule, server._backup_schedule)) { VMPP.set_backup_schedule(session, opaqueRef, _backup_schedule); } if (!Helper.AreEqual2(_archive_target_type, server._archive_target_type)) { VMPP.set_archive_target_type(session, opaqueRef, _archive_target_type); } if (!Helper.AreEqual2(_archive_target_config, server._archive_target_config)) { VMPP.set_archive_target_config(session, opaqueRef, _archive_target_config); } if (!Helper.AreEqual2(_archive_frequency, server._archive_frequency)) { VMPP.set_archive_frequency(session, opaqueRef, _archive_frequency); } if (!Helper.AreEqual2(_archive_schedule, server._archive_schedule)) { VMPP.set_archive_schedule(session, opaqueRef, _archive_schedule); } if (!Helper.AreEqual2(_is_alarm_enabled, server._is_alarm_enabled)) { VMPP.set_is_alarm_enabled(session, opaqueRef, _is_alarm_enabled); } if (!Helper.AreEqual2(_alarm_config, server._alarm_config)) { VMPP.set_alarm_config(session, opaqueRef, _alarm_config); } return null; } } /// <summary> /// Get a record containing the current state of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static VMPP get_record(Session session, string _vmpp) { return new VMPP((Proxy_VMPP)session.proxy.vmpp_get_record(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get a reference to the VMPP instance with the specified UUID. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VMPP> get_by_uuid(Session session, string _uuid) { return XenRef<VMPP>.Create(session.proxy.vmpp_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Create a new VMPP instance, and return its handle. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<VMPP> create(Session session, VMPP _record) { return XenRef<VMPP>.Create(session.proxy.vmpp_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Create a new VMPP instance, and return its handle. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, VMPP _record) { return XenRef<Task>.Create(session.proxy.async_vmpp_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified VMPP instance. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static void destroy(Session session, string _vmpp) { session.proxy.vmpp_destroy(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Destroy the specified VMPP instance. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static XenRef<Task> async_destroy(Session session, string _vmpp) { return XenRef<Task>.Create(session.proxy.async_vmpp_destroy(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get all the VMPP instances with the given label. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<VMPP>> get_by_name_label(Session session, string _label) { return XenRef<VMPP>.Create(session.proxy.vmpp_get_by_name_label(session.uuid, _label ?? "").parse()); } /// <summary> /// Get the uuid field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static string get_uuid(Session session, string _vmpp) { return (string)session.proxy.vmpp_get_uuid(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Get the name/label field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static string get_name_label(Session session, string _vmpp) { return (string)session.proxy.vmpp_get_name_label(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Get the name/description field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static string get_name_description(Session session, string _vmpp) { return (string)session.proxy.vmpp_get_name_description(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Get the is_policy_enabled field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static bool get_is_policy_enabled(Session session, string _vmpp) { return (bool)session.proxy.vmpp_get_is_policy_enabled(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Get the backup_type field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static vmpp_backup_type get_backup_type(Session session, string _vmpp) { return (vmpp_backup_type)Helper.EnumParseDefault(typeof(vmpp_backup_type), (string)session.proxy.vmpp_get_backup_type(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the backup_retention_value field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static long get_backup_retention_value(Session session, string _vmpp) { return long.Parse((string)session.proxy.vmpp_get_backup_retention_value(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the backup_frequency field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static vmpp_backup_frequency get_backup_frequency(Session session, string _vmpp) { return (vmpp_backup_frequency)Helper.EnumParseDefault(typeof(vmpp_backup_frequency), (string)session.proxy.vmpp_get_backup_frequency(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the backup_schedule field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static Dictionary<string, string> get_backup_schedule(Session session, string _vmpp) { return Maps.convert_from_proxy_string_string(session.proxy.vmpp_get_backup_schedule(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the is_backup_running field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static bool get_is_backup_running(Session session, string _vmpp) { return (bool)session.proxy.vmpp_get_is_backup_running(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Get the backup_last_run_time field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static DateTime get_backup_last_run_time(Session session, string _vmpp) { return session.proxy.vmpp_get_backup_last_run_time(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Get the archive_target_type field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static vmpp_archive_target_type get_archive_target_type(Session session, string _vmpp) { return (vmpp_archive_target_type)Helper.EnumParseDefault(typeof(vmpp_archive_target_type), (string)session.proxy.vmpp_get_archive_target_type(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the archive_target_config field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static Dictionary<string, string> get_archive_target_config(Session session, string _vmpp) { return Maps.convert_from_proxy_string_string(session.proxy.vmpp_get_archive_target_config(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the archive_frequency field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static vmpp_archive_frequency get_archive_frequency(Session session, string _vmpp) { return (vmpp_archive_frequency)Helper.EnumParseDefault(typeof(vmpp_archive_frequency), (string)session.proxy.vmpp_get_archive_frequency(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the archive_schedule field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static Dictionary<string, string> get_archive_schedule(Session session, string _vmpp) { return Maps.convert_from_proxy_string_string(session.proxy.vmpp_get_archive_schedule(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the is_archive_running field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static bool get_is_archive_running(Session session, string _vmpp) { return (bool)session.proxy.vmpp_get_is_archive_running(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Get the archive_last_run_time field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static DateTime get_archive_last_run_time(Session session, string _vmpp) { return session.proxy.vmpp_get_archive_last_run_time(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Get the VMs field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static List<XenRef<VM>> get_VMs(Session session, string _vmpp) { return XenRef<VM>.Create(session.proxy.vmpp_get_vms(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the is_alarm_enabled field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static bool get_is_alarm_enabled(Session session, string _vmpp) { return (bool)session.proxy.vmpp_get_is_alarm_enabled(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Get the alarm_config field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static Dictionary<string, string> get_alarm_config(Session session, string _vmpp) { return Maps.convert_from_proxy_string_string(session.proxy.vmpp_get_alarm_config(session.uuid, _vmpp ?? "").parse()); } /// <summary> /// Get the recent_alerts field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static string[] get_recent_alerts(Session session, string _vmpp) { return (string [])session.proxy.vmpp_get_recent_alerts(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// Set the name/label field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_label">New value to set</param> public static void set_name_label(Session session, string _vmpp, string _label) { session.proxy.vmpp_set_name_label(session.uuid, _vmpp ?? "", _label ?? "").parse(); } /// <summary> /// Set the name/description field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_description">New value to set</param> public static void set_name_description(Session session, string _vmpp, string _description) { session.proxy.vmpp_set_name_description(session.uuid, _vmpp ?? "", _description ?? "").parse(); } /// <summary> /// Set the is_policy_enabled field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_is_policy_enabled">New value to set</param> public static void set_is_policy_enabled(Session session, string _vmpp, bool _is_policy_enabled) { session.proxy.vmpp_set_is_policy_enabled(session.uuid, _vmpp ?? "", _is_policy_enabled).parse(); } /// <summary> /// Set the backup_type field of the given VMPP. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_backup_type">New value to set</param> public static void set_backup_type(Session session, string _vmpp, vmpp_backup_type _backup_type) { session.proxy.vmpp_set_backup_type(session.uuid, _vmpp ?? "", vmpp_backup_type_helper.ToString(_backup_type)).parse(); } /// <summary> /// This call executes the protection policy immediately /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> public static string protect_now(Session session, string _vmpp) { return (string)session.proxy.vmpp_protect_now(session.uuid, _vmpp ?? "").parse(); } /// <summary> /// This call archives the snapshot provided as a parameter /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_snapshot">The snapshot to archive</param> public static string archive_now(Session session, string _snapshot) { return (string)session.proxy.vmpp_archive_now(session.uuid, _snapshot ?? "").parse(); } /// <summary> /// This call fetches a history of alerts for a given protection policy /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_hours_from_now">how many hours in the past the oldest record to fetch is</param> public static string[] get_alerts(Session session, string _vmpp, long _hours_from_now) { return (string [])session.proxy.vmpp_get_alerts(session.uuid, _vmpp ?? "", _hours_from_now.ToString()).parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the value to set</param> public static void set_backup_retention_value(Session session, string _vmpp, long _value) { session.proxy.vmpp_set_backup_retention_value(session.uuid, _vmpp ?? "", _value.ToString()).parse(); } /// <summary> /// Set the value of the backup_frequency field /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the backup frequency</param> public static void set_backup_frequency(Session session, string _vmpp, vmpp_backup_frequency _value) { session.proxy.vmpp_set_backup_frequency(session.uuid, _vmpp ?? "", vmpp_backup_frequency_helper.ToString(_value)).parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the value to set</param> public static void set_backup_schedule(Session session, string _vmpp, Dictionary<string, string> _value) { session.proxy.vmpp_set_backup_schedule(session.uuid, _vmpp ?? "", Maps.convert_to_proxy_string_string(_value)).parse(); } /// <summary> /// Set the value of the archive_frequency field /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the archive frequency</param> public static void set_archive_frequency(Session session, string _vmpp, vmpp_archive_frequency _value) { session.proxy.vmpp_set_archive_frequency(session.uuid, _vmpp ?? "", vmpp_archive_frequency_helper.ToString(_value)).parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the value to set</param> public static void set_archive_schedule(Session session, string _vmpp, Dictionary<string, string> _value) { session.proxy.vmpp_set_archive_schedule(session.uuid, _vmpp ?? "", Maps.convert_to_proxy_string_string(_value)).parse(); } /// <summary> /// Set the value of the archive_target_config_type field /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the archive target config type</param> public static void set_archive_target_type(Session session, string _vmpp, vmpp_archive_target_type _value) { session.proxy.vmpp_set_archive_target_type(session.uuid, _vmpp ?? "", vmpp_archive_target_type_helper.ToString(_value)).parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the value to set</param> public static void set_archive_target_config(Session session, string _vmpp, Dictionary<string, string> _value) { session.proxy.vmpp_set_archive_target_config(session.uuid, _vmpp ?? "", Maps.convert_to_proxy_string_string(_value)).parse(); } /// <summary> /// Set the value of the is_alarm_enabled field /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">true if alarm is enabled for this policy</param> public static void set_is_alarm_enabled(Session session, string _vmpp, bool _value) { session.proxy.vmpp_set_is_alarm_enabled(session.uuid, _vmpp ?? "", _value).parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the value to set</param> public static void set_alarm_config(Session session, string _vmpp, Dictionary<string, string> _value) { session.proxy.vmpp_set_alarm_config(session.uuid, _vmpp ?? "", Maps.convert_to_proxy_string_string(_value)).parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_key">the key to add</param> /// <param name="_value">the value to add</param> public static void add_to_backup_schedule(Session session, string _vmpp, string _key, string _value) { session.proxy.vmpp_add_to_backup_schedule(session.uuid, _vmpp ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_key">the key to add</param> /// <param name="_value">the value to add</param> public static void add_to_archive_target_config(Session session, string _vmpp, string _key, string _value) { session.proxy.vmpp_add_to_archive_target_config(session.uuid, _vmpp ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_key">the key to add</param> /// <param name="_value">the value to add</param> public static void add_to_archive_schedule(Session session, string _vmpp, string _key, string _value) { session.proxy.vmpp_add_to_archive_schedule(session.uuid, _vmpp ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_key">the key to add</param> /// <param name="_value">the value to add</param> public static void add_to_alarm_config(Session session, string _vmpp, string _key, string _value) { session.proxy.vmpp_add_to_alarm_config(session.uuid, _vmpp ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_key">the key to remove</param> public static void remove_from_backup_schedule(Session session, string _vmpp, string _key) { session.proxy.vmpp_remove_from_backup_schedule(session.uuid, _vmpp ?? "", _key ?? "").parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_key">the key to remove</param> public static void remove_from_archive_target_config(Session session, string _vmpp, string _key) { session.proxy.vmpp_remove_from_archive_target_config(session.uuid, _vmpp ?? "", _key ?? "").parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_key">the key to remove</param> public static void remove_from_archive_schedule(Session session, string _vmpp, string _key) { session.proxy.vmpp_remove_from_archive_schedule(session.uuid, _vmpp ?? "", _key ?? "").parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_key">the key to remove</param> public static void remove_from_alarm_config(Session session, string _vmpp, string _key) { session.proxy.vmpp_remove_from_alarm_config(session.uuid, _vmpp ?? "", _key ?? "").parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the value to set</param> public static void set_backup_last_run_time(Session session, string _vmpp, DateTime _value) { session.proxy.vmpp_set_backup_last_run_time(session.uuid, _vmpp ?? "", _value).parse(); } /// <summary> /// /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> /// <param name="_vmpp">The opaque_ref of the given vmpp</param> /// <param name="_value">the value to set</param> public static void set_archive_last_run_time(Session session, string _vmpp, DateTime _value) { session.proxy.vmpp_set_archive_last_run_time(session.uuid, _vmpp ?? "", _value).parse(); } /// <summary> /// Return a list of all the VMPPs known to the system. /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VMPP>> get_all(Session session) { return XenRef<VMPP>.Create(session.proxy.vmpp_get_all(session.uuid).parse()); } /// <summary> /// Get all the VMPP Records at once, in a single XML RPC call /// First published in XenServer 5.6 FP1. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VMPP>, VMPP> get_all_records(Session session) { return XenRef<VMPP>.Create<Proxy_VMPP>(session.proxy.vmpp_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description; /// <summary> /// enable or disable this policy /// </summary> public virtual bool is_policy_enabled { get { return _is_policy_enabled; } set { if (!Helper.AreEqual(value, _is_policy_enabled)) { _is_policy_enabled = value; Changed = true; NotifyPropertyChanged("is_policy_enabled"); } } } private bool _is_policy_enabled; /// <summary> /// type of the backup sub-policy /// </summary> public virtual vmpp_backup_type backup_type { get { return _backup_type; } set { if (!Helper.AreEqual(value, _backup_type)) { _backup_type = value; Changed = true; NotifyPropertyChanged("backup_type"); } } } private vmpp_backup_type _backup_type; /// <summary> /// maximum number of backups that should be stored at any time /// </summary> public virtual long backup_retention_value { get { return _backup_retention_value; } set { if (!Helper.AreEqual(value, _backup_retention_value)) { _backup_retention_value = value; Changed = true; NotifyPropertyChanged("backup_retention_value"); } } } private long _backup_retention_value; /// <summary> /// frequency of the backup schedule /// </summary> public virtual vmpp_backup_frequency backup_frequency { get { return _backup_frequency; } set { if (!Helper.AreEqual(value, _backup_frequency)) { _backup_frequency = value; Changed = true; NotifyPropertyChanged("backup_frequency"); } } } private vmpp_backup_frequency _backup_frequency; /// <summary> /// schedule of the backup containing 'hour', 'min', 'days'. Date/time-related information is in Local Timezone /// </summary> public virtual Dictionary<string, string> backup_schedule { get { return _backup_schedule; } set { if (!Helper.AreEqual(value, _backup_schedule)) { _backup_schedule = value; Changed = true; NotifyPropertyChanged("backup_schedule"); } } } private Dictionary<string, string> _backup_schedule; /// <summary> /// true if this protection policy's backup is running /// </summary> public virtual bool is_backup_running { get { return _is_backup_running; } set { if (!Helper.AreEqual(value, _is_backup_running)) { _is_backup_running = value; Changed = true; NotifyPropertyChanged("is_backup_running"); } } } private bool _is_backup_running; /// <summary> /// time of the last backup /// </summary> public virtual DateTime backup_last_run_time { get { return _backup_last_run_time; } set { if (!Helper.AreEqual(value, _backup_last_run_time)) { _backup_last_run_time = value; Changed = true; NotifyPropertyChanged("backup_last_run_time"); } } } private DateTime _backup_last_run_time; /// <summary> /// type of the archive target config /// </summary> public virtual vmpp_archive_target_type archive_target_type { get { return _archive_target_type; } set { if (!Helper.AreEqual(value, _archive_target_type)) { _archive_target_type = value; Changed = true; NotifyPropertyChanged("archive_target_type"); } } } private vmpp_archive_target_type _archive_target_type; /// <summary> /// configuration for the archive, including its 'location', 'username', 'password' /// </summary> public virtual Dictionary<string, string> archive_target_config { get { return _archive_target_config; } set { if (!Helper.AreEqual(value, _archive_target_config)) { _archive_target_config = value; Changed = true; NotifyPropertyChanged("archive_target_config"); } } } private Dictionary<string, string> _archive_target_config; /// <summary> /// frequency of the archive schedule /// </summary> public virtual vmpp_archive_frequency archive_frequency { get { return _archive_frequency; } set { if (!Helper.AreEqual(value, _archive_frequency)) { _archive_frequency = value; Changed = true; NotifyPropertyChanged("archive_frequency"); } } } private vmpp_archive_frequency _archive_frequency; /// <summary> /// schedule of the archive containing 'hour', 'min', 'days'. Date/time-related information is in Local Timezone /// </summary> public virtual Dictionary<string, string> archive_schedule { get { return _archive_schedule; } set { if (!Helper.AreEqual(value, _archive_schedule)) { _archive_schedule = value; Changed = true; NotifyPropertyChanged("archive_schedule"); } } } private Dictionary<string, string> _archive_schedule; /// <summary> /// true if this protection policy's archive is running /// </summary> public virtual bool is_archive_running { get { return _is_archive_running; } set { if (!Helper.AreEqual(value, _is_archive_running)) { _is_archive_running = value; Changed = true; NotifyPropertyChanged("is_archive_running"); } } } private bool _is_archive_running; /// <summary> /// time of the last archive /// </summary> public virtual DateTime archive_last_run_time { get { return _archive_last_run_time; } set { if (!Helper.AreEqual(value, _archive_last_run_time)) { _archive_last_run_time = value; Changed = true; NotifyPropertyChanged("archive_last_run_time"); } } } private DateTime _archive_last_run_time; /// <summary> /// all VMs attached to this protection policy /// </summary> public virtual List<XenRef<VM>> VMs { get { return _VMs; } set { if (!Helper.AreEqual(value, _VMs)) { _VMs = value; Changed = true; NotifyPropertyChanged("VMs"); } } } private List<XenRef<VM>> _VMs; /// <summary> /// true if alarm is enabled for this policy /// </summary> public virtual bool is_alarm_enabled { get { return _is_alarm_enabled; } set { if (!Helper.AreEqual(value, _is_alarm_enabled)) { _is_alarm_enabled = value; Changed = true; NotifyPropertyChanged("is_alarm_enabled"); } } } private bool _is_alarm_enabled; /// <summary> /// configuration for the alarm /// </summary> public virtual Dictionary<string, string> alarm_config { get { return _alarm_config; } set { if (!Helper.AreEqual(value, _alarm_config)) { _alarm_config = value; Changed = true; NotifyPropertyChanged("alarm_config"); } } } private Dictionary<string, string> _alarm_config; /// <summary> /// recent alerts /// </summary> public virtual string[] recent_alerts { get { return _recent_alerts; } set { if (!Helper.AreEqual(value, _recent_alerts)) { _recent_alerts = value; Changed = true; NotifyPropertyChanged("recent_alerts"); } } } private string[] _recent_alerts; } }
/* * ResourcePermissionBase.cs - Implementation of the * "System.Diagnostics.ResourcePermissionBase" 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.Security.Permissions { #if CONFIG_PERMISSIONS && !ECMA_COMPAT using System.Collections; [Serializable] public abstract class ResourcePermissionBase : CodeAccessPermission, IUnrestrictedPermission { // Internal state. private PermissionState state; private Type accessType; private String[] tagNames; private ArrayList permissions; // Special resource values. public const String Any = "*"; public const String Local = "."; // Constructors. protected ResourcePermissionBase() { this.state = PermissionState.None; this.permissions = new ArrayList(); } protected ResourcePermissionBase(PermissionState state) { this.state = state; this.permissions = new ArrayList(); } // Make a copy of this permission object. public override IPermission Copy() { ResourcePermissionBase perm = (ResourcePermissionBase) Activator.CreateInstance(GetType()); perm.state = state; perm.accessType = accessType; perm.tagNames = tagNames; perm.permissions.AddRange(permissions); return perm; } // Convert an XML element into a permission object. public override void FromXml(SecurityElement securityElement) { String value; if(securityElement == null) { throw new ArgumentNullException("securityElement"); } if(securityElement.Attribute("version") != "1") { throw new ArgumentException(S._("Arg_PermissionVersion")); } value = securityElement.Attribute("Unrestricted"); Clear(); if(value != null && Boolean.Parse(value)) { state = PermissionState.Unrestricted; } else { // TODO: read the children } } // Form the intersection of two permission objects. public override IPermission Intersect(IPermission target) { if(target == null) { return target; } else if(target.GetType() != GetType()) { throw new ArgumentException(S._("Arg_PermissionMismatch")); } else if(((ResourcePermissionBase)target).IsUnrestricted()) { return Copy(); } else if(IsUnrestricted()) { return target.Copy(); } ResourcePermissionBase perm; perm = (ResourcePermissionBase)(target.Copy()); perm.Clear(); foreach(ResourcePermissionBaseEntry entry in permissions) { if(((ResourcePermissionBase)target).Contains(entry)) { perm.AddPermissionAccess(entry); } } return perm; } // Determine if this permission object is a subset of another. public override bool IsSubsetOf(IPermission target) { if(target == null) { return (state == PermissionState.None && permissions.Count == 0); } else if(target.GetType() != GetType()) { throw new ArgumentException(S._("Arg_PermissionMismatch")); } else if(((ResourcePermissionBase)target).IsUnrestricted()) { return true; } else if(IsUnrestricted()) { return false; } foreach(ResourcePermissionBaseEntry entry in permissions) { if(!((ResourcePermissionBase)target).Contains(entry)) { return false; } } return true; } // Determine if this permission object is unrestricted. public bool IsUnrestricted() { return (state == PermissionState.Unrestricted); } // Convert this permission object into an XML element. public override SecurityElement ToXml() { SecurityElement element; element = new SecurityElement("IPermission"); element.AddAttribute ("class", SecurityElement.Escape(GetType().AssemblyQualifiedName)); element.AddAttribute("version", "1"); if(state == PermissionState.Unrestricted) { element.AddAttribute("Unrestricted", "true"); } else { // TODO: add the children. } return element; } // Form the union of two permission objects. public override IPermission Union(IPermission target) { if(target == null) { return Copy(); } else if(target.GetType() != GetType()) { throw new ArgumentException(S._("Arg_PermissionMismatch")); } else if(IsUnrestricted() || ((ResourcePermissionBase)target).IsUnrestricted()) { return (ResourcePermissionBase)Activator.CreateInstance (GetType(), new Object [] {PermissionState.Unrestricted}); } else { ResourcePermissionBase perm; perm = (ResourcePermissionBase)(target.Copy()); foreach(ResourcePermissionBaseEntry entry in permissions) { if(!perm.Contains(entry)) { perm.AddPermissionAccess(entry); } } return perm; } } // Get or set the permission access type. protected Type PermissionAccessType { get { return accessType; } set { if(value == null) { throw new ArgumentNullException("value"); } else if(!(value.IsEnum)) { throw new ArgumentException (S._("Arg_NotEnumType")); } accessType = value; } } // Get or set the tag names used by this type of permission. protected String[] TagNames { get { return tagNames; } set { if(value == null) { throw new ArgumentNullException("value"); } else if(value.Length == 0) { throw new ArgumentException (S._("Arg_EmptyArray")); } tagNames = value; } } // Determine if a particular entry is in this permission set. private bool Contains(ResourcePermissionBaseEntry entry) { foreach(ResourcePermissionBaseEntry e in permissions) { if(String.Compare(e.StringPath, entry.StringPath, true) == 0) { return true; } } return false; } // Add a permission entry to this object. protected void AddPermissionAccess(ResourcePermissionBaseEntry entry) { if(entry == null) { throw new ArgumentNullException("entry"); } else if(tagNames == null || entry.PermissionAccessPath.Length != tagNames.Length) { throw new InvalidOperationException (S._("Invalid_PathMismatch")); } else if(Contains(entry)) { throw new InvalidOperationException (S._("Invalid_PermissionPresent")); } permissions.Add(entry); } // Clear all permission entries from this object. protected void Clear() { permissions.Clear(); } // Get the permission entries in this object. protected ResourcePermissionBaseEntry[] GetPermissionEntries() { ResourcePermissionBaseEntry[] array; array = new ResourcePermissionBaseEntry [permissions.Count]; permissions.CopyTo(array, 0); return array; } // Remove a permission entry from this object. protected void RemovePermissionAccess(ResourcePermissionBaseEntry entry) { if(entry == null) { throw new ArgumentNullException("entry"); } else if(tagNames == null || entry.PermissionAccessPath.Length != tagNames.Length) { throw new InvalidOperationException (S._("Invalid_PathMismatch")); } else if(!permissions.Contains(entry)) { throw new InvalidOperationException (S._("Invalid_PermissionNotPresent")); } permissions.Remove(entry); } }; // class ResourcePermissionBase #endif // CONFIG_PERMISSIONS && !ECMA_COMPAT }; // namespace System.Security.Permissions
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Responses/GetIncensePokemonResponse.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Networking.Responses { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/GetIncensePokemonResponse.proto</summary> public static partial class GetIncensePokemonResponseReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Responses/GetIncensePokemonResponse.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GetIncensePokemonResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cj9QT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL0dldEluY2Vuc2VQ", "b2tlbW9uUmVzcG9uc2UucHJvdG8SH1BPR09Qcm90b3MuTmV0d29ya2luZy5S", "ZXNwb25zZXMaIFBPR09Qcm90b3MvRW51bXMvUG9rZW1vbklkLnByb3RvIoUD", "ChlHZXRJbmNlbnNlUG9rZW1vblJlc3BvbnNlElEKBnJlc3VsdBgBIAEoDjJB", "LlBPR09Qcm90b3MuTmV0d29ya2luZy5SZXNwb25zZXMuR2V0SW5jZW5zZVBv", "a2Vtb25SZXNwb25zZS5SZXN1bHQSLwoKcG9rZW1vbl9pZBgCIAEoDjIbLlBP", "R09Qcm90b3MuRW51bXMuUG9rZW1vbklkEhAKCGxhdGl0dWRlGAMgASgBEhEK", "CWxvbmdpdHVkZRgEIAEoARIaChJlbmNvdW50ZXJfbG9jYXRpb24YBSABKAkS", "FAoMZW5jb3VudGVyX2lkGAYgASgGEh4KFmRpc2FwcGVhcl90aW1lc3RhbXBf", "bXMYByABKAMibQoGUmVzdWx0Eh0KGUlOQ0VOU0VfRU5DT1VOVEVSX1VOS05P", "V04QABIfChtJTkNFTlNFX0VOQ09VTlRFUl9BVkFJTEFCTEUQARIjCh9JTkNF", "TlNFX0VOQ09VTlRFUl9OT1RfQVZBSUxBQkxFEAJiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Enums.PokemonIdReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.GetIncensePokemonResponse), global::POGOProtos.Networking.Responses.GetIncensePokemonResponse.Parser, new[]{ "Result", "PokemonId", "Latitude", "Longitude", "EncounterLocation", "EncounterId", "DisappearTimestampMs" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.GetIncensePokemonResponse.Types.Result) }, null) })); } #endregion } #region Messages public sealed partial class GetIncensePokemonResponse : pb::IMessage<GetIncensePokemonResponse> { private static readonly pb::MessageParser<GetIncensePokemonResponse> _parser = new pb::MessageParser<GetIncensePokemonResponse>(() => new GetIncensePokemonResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetIncensePokemonResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Responses.GetIncensePokemonResponseReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetIncensePokemonResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetIncensePokemonResponse(GetIncensePokemonResponse other) : this() { result_ = other.result_; pokemonId_ = other.pokemonId_; latitude_ = other.latitude_; longitude_ = other.longitude_; encounterLocation_ = other.encounterLocation_; encounterId_ = other.encounterId_; disappearTimestampMs_ = other.disappearTimestampMs_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetIncensePokemonResponse Clone() { return new GetIncensePokemonResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::POGOProtos.Networking.Responses.GetIncensePokemonResponse.Types.Result result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Responses.GetIncensePokemonResponse.Types.Result Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "pokemon_id" field.</summary> public const int PokemonIdFieldNumber = 2; private global::POGOProtos.Enums.PokemonId pokemonId_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Enums.PokemonId PokemonId { get { return pokemonId_; } set { pokemonId_ = value; } } /// <summary>Field number for the "latitude" field.</summary> public const int LatitudeFieldNumber = 3; private double latitude_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Latitude { get { return latitude_; } set { latitude_ = value; } } /// <summary>Field number for the "longitude" field.</summary> public const int LongitudeFieldNumber = 4; private double longitude_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Longitude { get { return longitude_; } set { longitude_ = value; } } /// <summary>Field number for the "encounter_location" field.</summary> public const int EncounterLocationFieldNumber = 5; private string encounterLocation_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string EncounterLocation { get { return encounterLocation_; } set { encounterLocation_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "encounter_id" field.</summary> public const int EncounterIdFieldNumber = 6; private ulong encounterId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong EncounterId { get { return encounterId_; } set { encounterId_ = value; } } /// <summary>Field number for the "disappear_timestamp_ms" field.</summary> public const int DisappearTimestampMsFieldNumber = 7; private long disappearTimestampMs_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long DisappearTimestampMs { get { return disappearTimestampMs_; } set { disappearTimestampMs_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetIncensePokemonResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetIncensePokemonResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if (PokemonId != other.PokemonId) return false; if (Latitude != other.Latitude) return false; if (Longitude != other.Longitude) return false; if (EncounterLocation != other.EncounterLocation) return false; if (EncounterId != other.EncounterId) return false; if (DisappearTimestampMs != other.DisappearTimestampMs) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); if (PokemonId != 0) hash ^= PokemonId.GetHashCode(); if (Latitude != 0D) hash ^= Latitude.GetHashCode(); if (Longitude != 0D) hash ^= Longitude.GetHashCode(); if (EncounterLocation.Length != 0) hash ^= EncounterLocation.GetHashCode(); if (EncounterId != 0UL) hash ^= EncounterId.GetHashCode(); if (DisappearTimestampMs != 0L) hash ^= DisappearTimestampMs.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 (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } if (PokemonId != 0) { output.WriteRawTag(16); output.WriteEnum((int) PokemonId); } if (Latitude != 0D) { output.WriteRawTag(25); output.WriteDouble(Latitude); } if (Longitude != 0D) { output.WriteRawTag(33); output.WriteDouble(Longitude); } if (EncounterLocation.Length != 0) { output.WriteRawTag(42); output.WriteString(EncounterLocation); } if (EncounterId != 0UL) { output.WriteRawTag(49); output.WriteFixed64(EncounterId); } if (DisappearTimestampMs != 0L) { output.WriteRawTag(56); output.WriteInt64(DisappearTimestampMs); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } if (PokemonId != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PokemonId); } if (Latitude != 0D) { size += 1 + 8; } if (Longitude != 0D) { size += 1 + 8; } if (EncounterLocation.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(EncounterLocation); } if (EncounterId != 0UL) { size += 1 + 8; } if (DisappearTimestampMs != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(DisappearTimestampMs); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetIncensePokemonResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } if (other.PokemonId != 0) { PokemonId = other.PokemonId; } if (other.Latitude != 0D) { Latitude = other.Latitude; } if (other.Longitude != 0D) { Longitude = other.Longitude; } if (other.EncounterLocation.Length != 0) { EncounterLocation = other.EncounterLocation; } if (other.EncounterId != 0UL) { EncounterId = other.EncounterId; } if (other.DisappearTimestampMs != 0L) { DisappearTimestampMs = other.DisappearTimestampMs; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::POGOProtos.Networking.Responses.GetIncensePokemonResponse.Types.Result) input.ReadEnum(); break; } case 16: { pokemonId_ = (global::POGOProtos.Enums.PokemonId) input.ReadEnum(); break; } case 25: { Latitude = input.ReadDouble(); break; } case 33: { Longitude = input.ReadDouble(); break; } case 42: { EncounterLocation = input.ReadString(); break; } case 49: { EncounterId = input.ReadFixed64(); break; } case 56: { DisappearTimestampMs = input.ReadInt64(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the GetIncensePokemonResponse message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum Result { [pbr::OriginalName("INCENSE_ENCOUNTER_UNKNOWN")] IncenseEncounterUnknown = 0, [pbr::OriginalName("INCENSE_ENCOUNTER_AVAILABLE")] IncenseEncounterAvailable = 1, [pbr::OriginalName("INCENSE_ENCOUNTER_NOT_AVAILABLE")] IncenseEncounterNotAvailable = 2, } } #endregion } #endregion } #endregion Designer generated code
using Nito.AsyncEx; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Crypto.Randomness; using WalletWasabi.Io; using WalletWasabi.Tests.Helpers; using Xunit; namespace WalletWasabi.Tests.UnitTests { public class IoTests { [Fact] public async Task IoManagerTestsAsync() { var file = Path.Combine(Common.GetWorkDir(), $"file1.dat"); List<string> lines = new List<string>(); for (int i = 0; i < 1000; i++) { string line = RandomString.AlphaNumeric(100); lines.Add(line); } // Single thread file operations. DigestableSafeIoManager ioman1 = new DigestableSafeIoManager(file); // Delete the file if Exist. ioman1.DeleteMe(); Assert.False(ioman1.Exists()); Assert.False(File.Exists(ioman1.DigestFilePath)); // Write the data to the file. await ioman1.WriteAllLinesAsync(lines); Assert.True(ioman1.Exists()); // Check if the digest file is created. Assert.True(File.Exists(ioman1.DigestFilePath)); // Read back the content and check. static bool IsStringArraysEqual(string[] lines1, string[] lines2) { if (lines1.Length != lines2.Length) { return false; } for (int i = 0; i < lines1.Length; i++) { string line = lines2[i]; var readLine = lines1[i]; if (!line.Equals(readLine)) { return false; } } return true; } var readLines = await ioman1.ReadAllLinesAsync(); Assert.True(IsStringArraysEqual(readLines, lines.ToArray())); // Check digest file, and write only differ logic. // Write the same content, file should not be written. var currentDate = File.GetLastWriteTimeUtc(ioman1.FilePath); await Task.Delay(500); await ioman1.WriteAllLinesAsync(lines); var noChangeDate = File.GetLastWriteTimeUtc(ioman1.FilePath); Assert.Equal(currentDate, noChangeDate); // Write different content, file should be written. currentDate = File.GetLastWriteTimeUtc(ioman1.FilePath); await Task.Delay(500); lines.Add("Lorem ipsum dolor sit amet, consectetur adipiscing elit."); await ioman1.WriteAllLinesAsync(lines); var newContentDate = File.GetLastWriteTimeUtc(ioman1.FilePath); Assert.NotEqual(currentDate, newContentDate); await ioman1.WriteAllLinesAsync(lines); // Simulate file write error and recovery logic. // We have only *.new and *.old files. File.Copy(ioman1.FilePath, ioman1.OldFilePath); File.Move(ioman1.FilePath, ioman1.NewFilePath); // At this point there is now OriginalFile. var newFile = await ioman1.ReadAllLinesAsync(); Assert.True(IsStringArraysEqual(newFile, lines.ToArray())); // Add one more line to have different data. lines.Add("Lorem ipsum dolor sit amet, consectetur adipiscing elit."); await ioman1.WriteAllLinesAsync(lines); // Check recovery mechanism. Assert.True( File.Exists(ioman1.FilePath) && !File.Exists(ioman1.OldFilePath) && !File.Exists(ioman1.NewFilePath)); ioman1.DeleteMe(); Assert.False(ioman1.Exists()); // Check if directory is empty. var fileCount = Directory.EnumerateFiles(Path.GetDirectoryName(ioman1.FilePath)).Count(); Assert.Equal(0, fileCount); // TryReplace test. var dummyFilePath = $"{ioman1.FilePath}dummy"; var dummyContent = new string[] { "banana", "peach" }; await File.WriteAllLinesAsync(dummyFilePath, dummyContent); await ioman1.WriteAllLinesAsync(lines); ioman1.TryReplaceMeWith(dummyFilePath); var fruits = await ioman1.ReadAllLinesAsync(); Assert.True(IsStringArraysEqual(dummyContent, fruits)); Assert.False(File.Exists(dummyFilePath)); ioman1.DeleteMe(); } [Fact] public async Task IoTestsAsync() { var file = Path.Combine(Common.GetWorkDir(), $"file.dat"); AsyncLock asyncLock = new AsyncLock(); DigestableSafeIoManager ioman = new DigestableSafeIoManager(file); ioman.DeleteMe(); await ioman.WriteAllLinesAsync(Array.Empty<string>()); Assert.False(File.Exists(ioman.FilePath)); IoHelpers.EnsureContainingDirectoryExists(ioman.FilePath); File.Create(ioman.FilePath).Dispose(); static string RandomString() { StringBuilder builder = new StringBuilder(); var rnd = new Random(); char ch; for (int i = 0; i < rnd.Next(10, 100); i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rnd.NextDouble() + 65))); builder.Append(ch); } return builder.ToString(); }; var list = new List<string>(); async Task WriteNextLineAsync() { var next = RandomString(); lock (list) { list.Add(next); } using (await asyncLock.LockAsync()) { var lines = (await ioman.ReadAllLinesAsync()).ToList(); lines.Add(next); await ioman.WriteAllLinesAsync(lines); } }; const int Iterations = 200; var t1 = new Thread(() => { for (var i = 0; i < Iterations; i++) { /* We have to block the Thread. * If we use async/await pattern then Join() function at the end will indicate that the Thread is finished - * which is not true because the WriteNextLineAsync() is not yet finished. The reason is that await will return execution * the to the calling thread it is detected as the thread is done. t1 and t2 and t3 will still run in parallel! */ WriteNextLineAsync().Wait(); } }); var t2 = new Thread(() => { for (var i = 0; i < Iterations; i++) { WriteNextLineAsync().Wait(); } }); var t3 = new Thread(() => { for (var i = 0; i < Iterations; i++) { WriteNextLineAsync().Wait(); } }); t1.Start(); t2.Start(); t3.Start(); await Task.Delay(100); t1.Join(); t2.Join(); t3.Join(); Assert.False(t1.IsAlive); Assert.False(t2.IsAlive); Assert.False(t3.IsAlive); var allLines = File.ReadAllLines(file); Assert.NotEmpty(allLines); /* Lines were added to the list and to the file parallel so the two data should be equal. * If we "substract" them from each other we should get empty array. */ var diff = allLines.Except(list); Assert.Empty(diff); } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace SyNet.GuiHelpers.DragDropManager { public static class DragDropManager { private static readonly string DragOffsetFormat = "DnD.DragOffset"; public static readonly DependencyProperty DragSourceAdvisorProperty = DependencyProperty.RegisterAttached("DragSourceAdvisor", typeof(IDragSourceAdvisor), typeof(DragDropManager), new FrameworkPropertyMetadata( new PropertyChangedCallback(OnDragSourceAdvisorChanged))); public static readonly DependencyProperty DropTargetAdvisorProperty = DependencyProperty.RegisterAttached("DropTargetAdvisor", typeof(IDropTargetAdvisor), typeof(DragDropManager), new FrameworkPropertyMetadata( new PropertyChangedCallback(OnDropTargetAdvisorChanged))); private static UIElement _draggedElt; private static Point _dragStartPoint; private static bool _isMouseDown = false; private static Point _offsetPoint; private static DropPreviewAdorner _overlayElt; private static IDragSourceAdvisor s_currentDragSourceAdvisor; private static IDropTargetAdvisor s_currentDropTargetAdvisor = null; private static IDragSourceAdvisor CurrentDragSourceAdvisor { get { return s_currentDragSourceAdvisor; } set { s_currentDragSourceAdvisor = value; } } private static IDropTargetAdvisor CurrentDropTargetAdvisor { get { return s_currentDropTargetAdvisor; } set { s_currentDropTargetAdvisor = value; } } #region Dependency Properties Getter/Setters public static void SetDragSourceAdvisor( DependencyObject depObj, IDragSourceAdvisor advisor ) { depObj.SetValue(DragSourceAdvisorProperty, advisor); } public static void SetDropTargetAdvisor( DependencyObject depObj, IDropTargetAdvisor advisor ) { depObj.SetValue(DropTargetAdvisorProperty, advisor); } public static IDragSourceAdvisor GetDragSourceAdvisor( DependencyObject depObj ) { return depObj.GetValue(DragSourceAdvisorProperty) as IDragSourceAdvisor; } public static IDropTargetAdvisor GetDropTargetAdvisor( DependencyObject depObj ) { return depObj.GetValue(DropTargetAdvisorProperty) as IDropTargetAdvisor; } #endregion #region Property Change handlers private static void OnDragSourceAdvisorChanged( DependencyObject depObj, DependencyPropertyChangedEventArgs args ) { UIElement sourceElt = depObj as UIElement; if (args.NewValue != null && args.OldValue == null) { sourceElt.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(DragSource_PreviewMouseLeftButtonDown); sourceElt.PreviewMouseMove += new MouseEventHandler(DragSource_PreviewMouseMove); sourceElt.PreviewMouseUp += new MouseButtonEventHandler(DragSource_PreviewMouseUp); // Set the Drag source UI IDragSourceAdvisor advisor = args.NewValue as IDragSourceAdvisor; advisor.SourceUI = sourceElt; } else if (args.NewValue == null && args.OldValue != null) { sourceElt.PreviewMouseLeftButtonDown -= DragSource_PreviewMouseLeftButtonDown; sourceElt.PreviewMouseMove -= DragSource_PreviewMouseMove; sourceElt.PreviewMouseUp -= DragSource_PreviewMouseUp; } } private static void OnDropTargetAdvisorChanged( DependencyObject depObj, DependencyPropertyChangedEventArgs args ) { UIElement targetElt = depObj as UIElement; if (args.NewValue != null && args.OldValue == null) { targetElt.PreviewDragEnter += new DragEventHandler(DropTarget_PreviewDragEnter); targetElt.PreviewDragOver += new DragEventHandler(DropTarget_PreviewDragOver); targetElt.PreviewDragLeave += new DragEventHandler(DropTarget_PreviewDragLeave); targetElt.PreviewDrop += new DragEventHandler(DropTarget_PreviewDrop); targetElt.AllowDrop = true; // Set the Drag source UI IDropTargetAdvisor advisor = args.NewValue as IDropTargetAdvisor; advisor.TargetUI = targetElt; } else if (args.NewValue == null && args.OldValue != null) { targetElt.PreviewDragEnter -= DropTarget_PreviewDragEnter; targetElt.PreviewDragOver -= DropTarget_PreviewDragOver; targetElt.PreviewDragLeave -= DropTarget_PreviewDragLeave; targetElt.PreviewDrop -= DropTarget_PreviewDrop; targetElt.AllowDrop = false; } } #endregion /* ____________________________________________________________________ * Drop Target events * ____________________________________________________________________ */ private static void DropTarget_PreviewDrop( object sender, DragEventArgs e ) { if (UpdateEffects(sender, e) == false) return; Point dropPoint = e.GetPosition(sender as UIElement); // Calculate displacement for (Left, Top) Point offset = e.GetPosition(_overlayElt); dropPoint.X = dropPoint.X - offset.X; dropPoint.Y = dropPoint.Y - offset.Y; RemovePreviewAdorner(); _offsetPoint = new Point(0, 0); if (CurrentDropTargetAdvisor.IsValidDataObject(e.Data)) { CurrentDropTargetAdvisor.OnDropCompleted(e.Data, dropPoint); } e.Handled = true; } private static void DropTarget_PreviewDragLeave( object sender, DragEventArgs e ) { if (UpdateEffects(sender, e) == false) return; RemovePreviewAdorner(); e.Handled = true; } private static void DropTarget_PreviewDragOver( object sender, DragEventArgs e ) { if (UpdateEffects(sender, e) == false) return; // Update position of the preview Adorner Point position = e.GetPosition(sender as UIElement); _overlayElt.Left = position.X - _offsetPoint.X; _overlayElt.Top = position.Y - _offsetPoint.Y; e.Handled = true; } private static void DropTarget_PreviewDragEnter( object sender, DragEventArgs e ) { // Get the current drop target advisor CurrentDropTargetAdvisor = GetDropTargetAdvisor(sender as DependencyObject); if (UpdateEffects(sender, e) == false) return; // Setup the preview Adorner UIElement feedbackUI = CurrentDropTargetAdvisor.GetVisualFeedback(e.Data); _offsetPoint = CurrentDropTargetAdvisor.ApplyMouseOffset ? (Point)e.Data.GetData(DragOffsetFormat) : new Point(); CreatePreviewAdorner(sender as UIElement, feedbackUI); e.Handled = true; } private static bool UpdateEffects( object uiObject, DragEventArgs e ) { if (CurrentDropTargetAdvisor.IsValidDataObject(e.Data) == false) { e.Effects = DragDropEffects.None; return true; } if ((e.AllowedEffects & DragDropEffects.Move) == 0 && (e.AllowedEffects & DragDropEffects.Copy) == 0) { e.Effects = DragDropEffects.None; return true; } if ((e.AllowedEffects & DragDropEffects.Move) != 0 && (e.AllowedEffects & DragDropEffects.Copy) != 0) { e.Effects = ((e.KeyStates & DragDropKeyStates.ControlKey) != 0) ? DragDropEffects.Copy : DragDropEffects.Move; } return true; } /// <summary> /// /// </summary> /// <param name="ancestorType"></param> /// <param name="visual"></param> /// <returns></returns> public static FrameworkElement FindAncestor( Type ancestorType, Visual visual ) { while (visual != null && !ancestorType.IsInstanceOfType(visual)) { visual = (Visual)VisualTreeHelper.GetParent(visual); } return visual as FrameworkElement; } /* ____________________________________________________________________ * Drag Source events * ____________________________________________________________________ */ private static void DragSource_PreviewMouseLeftButtonDown( object sender, MouseButtonEventArgs e ) { // Make this the new drag source CurrentDragSourceAdvisor = GetDragSourceAdvisor(sender as DependencyObject); if (CurrentDragSourceAdvisor.IsDraggable(e.Source as UIElement) == false) { // Check to see if we can find an item containe that is draggable Visual visual = e.OriginalSource as Visual; ItemsControl sourceItemsControl = sender as ItemsControl; if (sourceItemsControl == null) return; FrameworkElement sourceItemContainer = Utilities.GetItemContainer(sourceItemsControl, visual); if (sourceItemContainer != null) { if (CurrentDragSourceAdvisor.IsDraggable(sourceItemContainer as UIElement) == false) { return; } _draggedElt = sourceItemContainer as UIElement; } } else { _draggedElt = e.Source as UIElement; } _dragStartPoint = e.GetPosition(CurrentDragSourceAdvisor.GetTopContainer()); _offsetPoint = e.GetPosition(_draggedElt); _isMouseDown = true; } private static void DragSource_PreviewMouseMove( object sender, MouseEventArgs e ) { if (_isMouseDown && IsDragGesture(e.GetPosition(CurrentDragSourceAdvisor.GetTopContainer()))) { DragStarted(sender as UIElement); } } private static void DragSource_PreviewMouseUp( object sender, MouseButtonEventArgs e ) { _isMouseDown = false; Mouse.Capture(null); } private static void DragStarted( UIElement uiElt ) { _isMouseDown = false; Mouse.Capture(uiElt); DataObject data = CurrentDragSourceAdvisor.GetDataObject(_draggedElt); if (data != null) { data.SetData(DragOffsetFormat, _offsetPoint); DragDropEffects supportedEffects = CurrentDragSourceAdvisor.SupportedEffects; // Perform DragDrop DragDropEffects effects = DragDrop.DoDragDrop(_draggedElt, data, supportedEffects); CurrentDragSourceAdvisor.FinishDrag(_draggedElt, effects); // Clean up RemovePreviewAdorner(); } Mouse.Capture(null); _draggedElt = null; } private static bool IsDragGesture( Point point ) { bool hGesture = Math.Abs(point.X - _dragStartPoint.X) > SystemParameters.MinimumHorizontalDragDistance; bool vGesture = Math.Abs(point.Y - _dragStartPoint.Y) > SystemParameters.MinimumVerticalDragDistance; return (hGesture | vGesture); } /* ____________________________________________________________________ * Utility functions * ____________________________________________________________________ */ private static void CreatePreviewAdorner( UIElement adornedElt, UIElement feedbackUI ) { if (_overlayElt != null) return; AdornerLayer layer = AdornerLayer.GetAdornerLayer(CurrentDropTargetAdvisor.GetTopContainer()); _overlayElt = new DropPreviewAdorner(feedbackUI, adornedElt); layer.Add(_overlayElt); } private static void RemovePreviewAdorner() { if (_overlayElt != null) { AdornerLayer.GetAdornerLayer(CurrentDropTargetAdvisor.GetTopContainer()).Remove(_overlayElt); _overlayElt = null; } } } }
using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Newtonsoft.Json.Linq; using Orchard.ContentManagement; using Orchard.Data; using Orchard.DisplayManagement; using Orchard.Forms.Services; using Orchard.Localization; using Orchard.Mvc; using Orchard.Mvc.Extensions; using Orchard.Security; using Orchard.Themes; using System; using Orchard.Settings; using Orchard.UI.Navigation; using Orchard.UI.Notify; using Orchard.Workflows.Models; using Orchard.Workflows.Services; using Orchard.Workflows.ViewModels; using Orchard.Workflows.Helpers; namespace Orchard.Workflows.Controllers { [ValidateInput(false)] public class AdminController : Controller, IUpdateModel { private readonly ISiteService _siteService; private readonly IRepository<WorkflowDefinitionRecord> _workflowDefinitionRecords; private readonly IRepository<WorkflowRecord> _workflowRecords; private readonly IActivitiesManager _activitiesManager; private readonly IFormManager _formManager; public AdminController( IOrchardServices services, IShapeFactory shapeFactory, ISiteService siteService, IRepository<WorkflowDefinitionRecord> workflowDefinitionRecords, IRepository<WorkflowRecord> workflowRecords, IActivitiesManager activitiesManager, IFormManager formManager ) { _siteService = siteService; _workflowDefinitionRecords = workflowDefinitionRecords; _workflowRecords = workflowRecords; _activitiesManager = activitiesManager; _formManager = formManager; Services = services; T = NullLocalizer.Instance; New = shapeFactory; } dynamic New { get; set; } public IOrchardServices Services { get; set; } public Localizer T { get; set; } public ActionResult Index(AdminIndexOptions options, PagerParameters pagerParameters) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows"))) return new HttpUnauthorizedResult(); var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters); // default options if (options == null) options = new AdminIndexOptions(); var queries = _workflowDefinitionRecords.Table; switch (options.Filter) { case WorkflowDefinitionFilter.All: break; default: throw new ArgumentOutOfRangeException(); } if (!String.IsNullOrWhiteSpace(options.Search)) { queries = queries.Where(w => w.Name.Contains(options.Search)); } var pagerShape = New.Pager(pager).TotalItemCount(queries.Count()); switch (options.Order) { case WorkflowDefinitionOrder.Name: queries = queries.OrderBy(u => u.Name); break; } if (pager.GetStartIndex() > 0) { queries = queries.Skip(pager.GetStartIndex()); } if (pager.PageSize > 0) { queries = queries.Take(pager.PageSize); } var results = queries.ToList(); var model = new AdminIndexViewModel { WorkflowDefinitions = results.Select(x => new WorkflowDefinitionEntry { WorkflowDefinitionRecord = x, WokflowDefinitionId = x.Id, Name = x.Name }).ToList(), Options = options, Pager = pagerShape }; // maintain previous route data when generating page links var routeData = new RouteData(); routeData.Values.Add("Options.Filter", options.Filter); routeData.Values.Add("Options.Search", options.Search); routeData.Values.Add("Options.Order", options.Order); pagerShape.RouteData(routeData); return View(model); } public ActionResult List(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows"))) return new HttpUnauthorizedResult(); var contentItem = Services.ContentManager.Get(id, VersionOptions.Latest); if (contentItem == null) { return HttpNotFound(); } var workflows = _workflowRecords.Table.Where(x => x.ContentItemRecord == contentItem.Record).ToList(); var viewModel = New.ViewModel( ContentItem: contentItem, Workflows: workflows ); return View(viewModel); } public ActionResult Create() { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to create workflows"))) return new HttpUnauthorizedResult(); return View(); } [HttpPost, ActionName("Create")] public ActionResult CreatePost(string name) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to create workflows"))) return new HttpUnauthorizedResult(); var workflowDefinitionRecord = new WorkflowDefinitionRecord { Name = name }; _workflowDefinitionRecords.Create(workflowDefinitionRecord); return RedirectToAction("Edit", new { workflowDefinitionRecord.Id }); } public JsonResult State(int? id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) throw new AuthenticationException(""); var workflowDefinitionRecord = id.HasValue ? _workflowDefinitionRecords.Get(id.Value) : null; var isRunning = workflowDefinitionRecord != null && workflowDefinitionRecord.WorkflowRecords.Any(); return Json(new { isRunning = isRunning }, JsonRequestBehavior.AllowGet); } public ActionResult Edit(int id, string localId, int? workflowId) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); // convert the workflow definition into its view model var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id); var workflowDefinitionViewModel = CreateWorkflowDefinitionViewModel(workflowDefinitionRecord); var workflow = workflowId.HasValue ? _workflowRecords.Get(workflowId.Value) : null; var viewModel = new AdminEditViewModel { LocalId = String.IsNullOrEmpty(localId) ? Guid.NewGuid().ToString() : localId, IsLocal = !String.IsNullOrEmpty(localId), WorkflowDefinition = workflowDefinitionViewModel, AllActivities = _activitiesManager.GetActivities(), Workflow = workflow }; return View(viewModel); } [HttpPost] public ActionResult Delete(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage workflows"))) return new HttpUnauthorizedResult(); var workflowDefinition = _workflowDefinitionRecords.Get(id); if (workflowDefinition != null) { _workflowDefinitionRecords.Delete(workflowDefinition); Services.Notifier.Information(T("Workflow {0} deleted", workflowDefinition.Name)); } return RedirectToAction("Index"); } [HttpPost] public ActionResult DeleteWorkflow(int id, string returnUrl) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage workflows"))) return new HttpUnauthorizedResult(); var workflow = _workflowRecords.Get(id); if (workflow != null) { _workflowRecords.Delete(workflow); Services.Notifier.Information(T("Workflow deleted")); } return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); } private WorkflowDefinitionViewModel CreateWorkflowDefinitionViewModel(WorkflowDefinitionRecord workflowDefinitionRecord) { if (workflowDefinitionRecord == null) { throw new ArgumentNullException("workflowDefinitionRecord"); } var workflowDefinitionModel = new WorkflowDefinitionViewModel { Id = workflowDefinitionRecord.Id, Name = workflowDefinitionRecord.Name }; dynamic workflow = new JObject(); workflow.Activities = new JArray(workflowDefinitionRecord.ActivityRecords.Select(x => { dynamic activity = new JObject(); activity.Name = x.Name; activity.Id = x.Id; activity.ClientId = x.GetClientId(); activity.Left = x.X; activity.Top = x.Y; activity.Start = x.Start; activity.State = FormParametersHelper.FromJsonString(x.State); return activity; })); workflow.Connections = new JArray(workflowDefinitionRecord.TransitionRecords.Select(x => { dynamic connection = new JObject(); connection.Id = x.Id; connection.SourceId = x.SourceActivityRecord.Name + "_" + x.SourceActivityRecord.Id; connection.TargetId = x.DestinationActivityRecord.Name + "_" + x.DestinationActivityRecord.Id; connection.SourceEndpoint = x.SourceEndpoint; return connection; })); workflowDefinitionModel.JsonData = FormParametersHelper.ToJsonString(workflow); return workflowDefinitionModel; } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Save")] public ActionResult EditPost(int id, string localId, string data, bool clearWorkflows) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id); if (workflowDefinitionRecord == null) { return HttpNotFound(); } workflowDefinitionRecord.Enabled = true; var state = FormParametersHelper.FromJsonString(data); var activitiesIndex = new Dictionary<string, ActivityRecord>(); workflowDefinitionRecord.ActivityRecords.Clear(); foreach (var activity in state.Activities) { ActivityRecord activityRecord; workflowDefinitionRecord.ActivityRecords.Add(activityRecord = new ActivityRecord { Name = activity.Name, X = activity.Left, Y = activity.Top, Start = activity.Start, State = FormParametersHelper.ToJsonString(activity.State), WorkflowDefinitionRecord = workflowDefinitionRecord }); activitiesIndex.Add((string)activity.ClientId, activityRecord); } workflowDefinitionRecord.TransitionRecords.Clear(); foreach (var connection in state.Connections) { workflowDefinitionRecord.TransitionRecords.Add(new TransitionRecord { SourceActivityRecord = activitiesIndex[(string)connection.SourceId], DestinationActivityRecord = activitiesIndex[(string)connection.TargetId], SourceEndpoint = connection.SourceEndpoint, WorkflowDefinitionRecord = workflowDefinitionRecord }); } if (clearWorkflows) { workflowDefinitionRecord.WorkflowRecords.Clear(); } else { foreach (var workflowRecord in workflowDefinitionRecord.WorkflowRecords) { // Update any awaiting activity records with the new activity record. foreach (var awaitingActivityRecord in workflowRecord.AwaitingActivities) { var clientId = awaitingActivityRecord.ActivityRecord.GetClientId(); if (activitiesIndex.ContainsKey(clientId)) { awaitingActivityRecord.ActivityRecord = activitiesIndex[clientId]; } else { workflowRecord.AwaitingActivities.Remove(awaitingActivityRecord); } } // Remove any workflows with no awaiting activities. if (!workflowRecord.AwaitingActivities.Any()) { workflowDefinitionRecord.WorkflowRecords.Remove(workflowRecord); } } } Services.Notifier.Information(T("Workflow saved successfully")); // Don't pass the localId to force the activites to refresh and use the deterministic clientId. return RedirectToAction("Edit", new { id }); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Cancel")] public ActionResult EditPostCancel() { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); return View(); } [Themed(false)] [HttpPost] public ActionResult RenderActivity(ActivityViewModel model) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var activity = _activitiesManager.GetActivityByName(model.Name); if (activity == null) { return HttpNotFound(); } dynamic shape = New.Activity(activity); if (model.State != null) { var state = FormParametersHelper.ToDynamic(FormParametersHelper.ToString(model.State)); shape.State(state); } else { shape.State(FormParametersHelper.FromJsonString("{}")); } shape.Metadata.Alternates.Add("Activity__" + activity.Name); return new ShapeResult(this, shape); } public ActionResult EditActivity(string localId, string clientId, ActivityViewModel model) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var activity = _activitiesManager.GetActivityByName(model.Name); if (activity == null) { return HttpNotFound(); } // build the form, and let external components alter it var form = activity.Form == null ? null : _formManager.Build(activity.Form); // form is bound on client side var viewModel = New.ViewModel(LocalId: localId, ClientId: clientId, Form: form); return View(viewModel); } [HttpPost, ActionName("EditActivity")] [FormValueRequired("_submit.Save")] public ActionResult EditActivityPost(int id, string localId, string name, string clientId, FormCollection formValues) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var activity = _activitiesManager.GetActivityByName(name); if (activity == null) { return HttpNotFound(); } // validating form values _formManager.Validate(new ValidatingContext { FormName = activity.Form, ModelState = ModelState, ValueProvider = ValueProvider }); // stay on the page if there are validation errors if (!ModelState.IsValid) { // build the form, and let external components alter it var form = activity.Form == null ? null : _formManager.Build(activity.Form); // bind form with existing values. _formManager.Bind(form, ValueProvider); var viewModel = New.ViewModel(Id: id, LocalId: localId, Form: form); return View(viewModel); } var model = new UpdatedActivityModel { ClientId = clientId, Data = HttpUtility.JavaScriptStringEncode(FormParametersHelper.ToJsonString(formValues)) }; TempData["UpdatedViewModel"] = model; return RedirectToAction("Edit", new { id, localId }); } [HttpPost, ActionName("EditActivity")] [FormValueRequired("_submit.Cancel")] public ActionResult EditActivityPostCancel(int id, string localId, string name, string clientId, FormCollection formValues) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); return RedirectToAction("Edit", new {id, localId }); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } public void AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Collections.Generic; using System.ComponentModel; /// <summary> /// Defines available log levels. /// </summary> [TypeConverter(typeof(Attributes.LogLevelTypeConverter))] public sealed class LogLevel : IComparable, IEquatable<LogLevel>, IConvertible { /// <summary> /// Trace log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Trace = new LogLevel("Trace", 0); /// <summary> /// Debug log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Debug = new LogLevel("Debug", 1); /// <summary> /// Info log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Info = new LogLevel("Info", 2); /// <summary> /// Warn log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Warn = new LogLevel("Warn", 3); /// <summary> /// Error log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Error = new LogLevel("Error", 4); /// <summary> /// Fatal log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Fatal = new LogLevel("Fatal", 5); /// <summary> /// Off log level. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] public static readonly LogLevel Off = new LogLevel("Off", 6); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] private static readonly IList<LogLevel> allLevels = new List<LogLevel> { Trace, Debug, Info, Warn, Error, Fatal, Off }.AsReadOnly(); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Type is immutable")] private static readonly IList<LogLevel> allLoggingLevels = new List<LogLevel> { Trace, Debug, Info, Warn, Error, Fatal }.AsReadOnly(); /// <summary> /// Gets all the available log levels (Trace, Debug, Info, Warn, Error, Fatal, Off). /// </summary> public static IEnumerable<LogLevel> AllLevels => allLevels; /// <summary> /// Gets all the log levels that can be used to log events (Trace, Debug, Info, Warn, Error, Fatal) /// i.e <c>LogLevel.Off</c> is excluded. /// </summary> public static IEnumerable<LogLevel> AllLoggingLevels => allLoggingLevels; private readonly int _ordinal; private readonly string _name; /// <summary> /// Initializes a new instance of <see cref="LogLevel"/>. /// </summary> /// <param name="name">The log level name.</param> /// <param name="ordinal">The log level ordinal number.</param> private LogLevel(string name, int ordinal) { _name = name; _ordinal = ordinal; } /// <summary> /// Gets the name of the log level. /// </summary> public string Name => _name; internal static LogLevel MaxLevel => Fatal; internal static LogLevel MinLevel => Trace; /// <summary> /// Gets the ordinal of the log level. /// </summary> public int Ordinal => _ordinal; /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal == level2.Ordinal</c>.</returns> public static bool operator ==(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, null)) { return ReferenceEquals(level2, null); } if (ReferenceEquals(level2, null)) { return false; } return level1.Ordinal == level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is not equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal != level2.Ordinal</c>.</returns> public static bool operator !=(LogLevel level1, LogLevel level2) { if (ReferenceEquals(level1, null)) { return !ReferenceEquals(level2, null); } if (ReferenceEquals(level2, null)) { return true; } return level1.Ordinal != level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is greater than the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &gt; level2.Ordinal</c>.</returns> public static bool operator >(LogLevel level1, LogLevel level2) { if (level1 == null) { throw new ArgumentNullException(nameof(level1)); } if (level2 == null) { throw new ArgumentNullException(nameof(level2)); } return level1.Ordinal > level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is greater than or equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &gt;= level2.Ordinal</c>.</returns> public static bool operator >=(LogLevel level1, LogLevel level2) { if (level1 == null) { throw new ArgumentNullException(nameof(level1)); } if (level2 == null) { throw new ArgumentNullException(nameof(level2)); } return level1.Ordinal >= level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is less than the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &lt; level2.Ordinal</c>.</returns> public static bool operator <(LogLevel level1, LogLevel level2) { if (level1 == null) { throw new ArgumentNullException(nameof(level1)); } if (level2 == null) { throw new ArgumentNullException(nameof(level2)); } return level1.Ordinal < level2.Ordinal; } /// <summary> /// Compares two <see cref="LogLevel"/> objects /// and returns a value indicating whether /// the first one is less than or equal to the second one. /// </summary> /// <param name="level1">The first level.</param> /// <param name="level2">The second level.</param> /// <returns>The value of <c>level1.Ordinal &lt;= level2.Ordinal</c>.</returns> public static bool operator <=(LogLevel level1, LogLevel level2) { if (level1 == null) { throw new ArgumentNullException(nameof(level1)); } if (level2 == null) { throw new ArgumentNullException(nameof(level2)); } return level1.Ordinal <= level2.Ordinal; } /// <summary> /// Gets the <see cref="LogLevel"/> that corresponds to the specified ordinal. /// </summary> /// <param name="ordinal">The ordinal.</param> /// <returns>The <see cref="LogLevel"/> instance. For 0 it returns <see cref="LogLevel.Trace"/>, 1 gives <see cref="LogLevel.Debug"/> and so on.</returns> public static LogLevel FromOrdinal(int ordinal) { switch (ordinal) { case 0: return Trace; case 1: return Debug; case 2: return Info; case 3: return Warn; case 4: return Error; case 5: return Fatal; case 6: return Off; default: throw new ArgumentException("Invalid ordinal."); } } /// <summary> /// Returns the <see cref="T:NLog.LogLevel"/> that corresponds to the supplied <see langword="string" />. /// </summary> /// <param name="levelName">The textual representation of the log level.</param> /// <returns>The enumeration value.</returns> public static LogLevel FromString(string levelName) { if (levelName == null) { throw new ArgumentNullException(nameof(levelName)); } if (levelName.Equals("Trace", StringComparison.OrdinalIgnoreCase)) { return Trace; } if (levelName.Equals("Debug", StringComparison.OrdinalIgnoreCase)) { return Debug; } if (levelName.Equals("Info", StringComparison.OrdinalIgnoreCase)) { return Info; } if (levelName.Equals("Warn", StringComparison.OrdinalIgnoreCase)) { return Warn; } if (levelName.Equals("Error", StringComparison.OrdinalIgnoreCase)) { return Error; } if (levelName.Equals("Fatal", StringComparison.OrdinalIgnoreCase)) { return Fatal; } if (levelName.Equals("Off", StringComparison.OrdinalIgnoreCase)) { return Off; } if (levelName.Equals("None", StringComparison.OrdinalIgnoreCase)) { return Off; // .NET Core Microsoft Extension Logging } if (levelName.Equals("Information", StringComparison.OrdinalIgnoreCase)) { return Info; // .NET Core Microsoft Extension Logging } if (levelName.Equals("Warning", StringComparison.OrdinalIgnoreCase)) { return Warn; // .NET Core Microsoft Extension Logging } throw new ArgumentException($"Unknown log level: {levelName}"); } /// <summary> /// Returns a string representation of the log level. /// </summary> /// <returns>Log level name.</returns> public override string ToString() { return Name; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return Ordinal; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns>Value of <c>true</c> if the specified <see cref="System.Object"/> is equal to /// this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { LogLevel other = obj as LogLevel; if ((object)other == null) { return false; } return Ordinal == other.Ordinal; } /// <summary> /// Determines whether the specified <see cref="NLog.LogLevel"/> instance is equal to this instance. /// </summary> /// <param name="other">The <see cref="NLog.LogLevel"/> to compare with this instance.</param> /// <returns>Value of <c>true</c> if the specified <see cref="NLog.LogLevel"/> is equal to /// this instance; otherwise, <c>false</c>.</returns> public bool Equals(LogLevel other) { return other != null && Ordinal == other.Ordinal; } /// <summary> /// Compares the level to the other <see cref="LogLevel"/> object. /// </summary> /// <param name="obj"> /// The object object. /// </param> /// <returns> /// A value less than zero when this logger's <see cref="Ordinal"/> is /// less than the other logger's ordinal, 0 when they are equal and /// greater than zero when this ordinal is greater than the /// other ordinal. /// </returns> public int CompareTo(object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } // The code below does NOT account if the casting to LogLevel returns null. This is // because as this class is sealed and does not provide any public constructors it // is impossible to create a invalid instance. LogLevel level = (LogLevel)obj; return Ordinal - level.Ordinal; } #region Implementation of IConvertible TypeCode IConvertible.GetTypeCode() { return TypeCode.Object; } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(_ordinal); } bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(_ordinal); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_ordinal); } double IConvertible.ToDouble(IFormatProvider provider) { return _ordinal; } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_ordinal); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(_ordinal); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(_ordinal); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_ordinal); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(_ordinal); } string IConvertible.ToString(IFormatProvider provider) { return _name; } object IConvertible.ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(string)) return Name; else return Convert.ChangeType(_ordinal, conversionType, provider); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_ordinal); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_ordinal); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_ordinal); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using J.Web.Areas.HelpPage.ModelDescriptions; using J.Web.Areas.HelpPage.Models; namespace J.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Diagnostics; using System.IO; using System.Linq; using IG.CommonLogging.Appenders.MailRecipientManagement; using IG.CommonLogging.Serializers.Xml2CSharp; using IG.Extensions; using IG.XmlTools; using log4net; using Newtonsoft.Json; namespace IG.CommonLogging { public enum MailNotificationLevel { Debug = 0, Info = 1, Warn = 2, Error = 3, Fatal = 4, None = 5 } public class LoggerAdapter : ILogger { private readonly ILog _log; public MailNotificationLevel MailNotificationLevel { get; } public bool AlwaysNotifyByMailOnException { get; } internal LoggerAdapter(ILog log) { var configFileName = Path.Combine(typeof(LoggerAdapter).AssemblyDirectory(), "log4net.config"); var xml = File.ReadAllText(configFileName); var log4NetParams = Serialization.Deserialize<Log4NetConfig>(xml).Param; Console.WriteLine("params read from Log4NetConfig: " + string.Join(" ", log4NetParams.Select(x => $@"{{{x.Name}=>{x.Value}}}"))); _log = log; MailNotificationLevel = log4NetParams.FirstOrDefault(x => x.Name == nameof(MailNotificationLevel))?.Value.GetTOrDefault(MailNotificationLevel.Error) ?? MailNotificationLevel.Error; AlwaysNotifyByMailOnException = log4NetParams.FirstOrDefault(x => x.Name == nameof(AlwaysNotifyByMailOnException))?.Value.GetTOrDefault(true) ?? true; } public bool IsDebugEnabled => _log.IsDebugEnabled; public bool IsInfoEnabled => _log.IsInfoEnabled; public bool IsWarnEnabled => _log.IsWarnEnabled; public bool IsErrorEnabled => _log.IsErrorEnabled; public bool IsFatalEnabled => _log.IsFatalEnabled; public void Debug(object message) { if (MailNotificationLevel <= MailNotificationLevel.Debug) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Debug(message); } public void Debug(object message, Exception exception) { if ((MailNotificationLevel <= MailNotificationLevel.Debug) || (AlwaysNotifyByMailOnException && exception != null) ) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Debug(message, exception); } public void DebugFormat(string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Debug) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.DebugFormat(format, args); } public void DebugFormat(string format, object arg0) { if (MailNotificationLevel <= MailNotificationLevel.Debug) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.DebugFormat(format, arg0); } public void DebugFormat(string format, object arg0, object arg1) { if (MailNotificationLevel <= MailNotificationLevel.Debug) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.DebugFormat(format, arg0, arg1); } public void DebugFormat(string format, object arg0, object arg1, object arg2) { if (MailNotificationLevel <= MailNotificationLevel.Debug) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.DebugFormat(format, arg0, arg1, arg2); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Debug) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.DebugFormat(provider, format, args); } public void Info(object message) { if (MailNotificationLevel <= MailNotificationLevel.Info) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Info(message); } public void Info(object message, Exception exception) { if (exception != null) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Info(message, exception); } public void InfoFormat(string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Info) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.InfoFormat(format, args); } public void InfoFormat(string format, object arg0) { if (MailNotificationLevel <= MailNotificationLevel.Info) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.InfoFormat(format, arg0); } public void InfoFormat(string format, object arg0, object arg1) { if (MailNotificationLevel <= MailNotificationLevel.Info) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.InfoFormat(format, arg0, arg1); } public void InfoFormat(string format, object arg0, object arg1, object arg2) { if (MailNotificationLevel <= MailNotificationLevel.Info) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.InfoFormat(format, arg0, arg1, arg2); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Info) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.InfoFormat(provider, format, args); } public void Warn(object message) { if (MailNotificationLevel <= MailNotificationLevel.Warn) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Warn(message); } public void Warn(object message, Exception exception) { if ((MailNotificationLevel <= MailNotificationLevel.Warn) || (AlwaysNotifyByMailOnException && exception != null) ) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Warn(message, exception); } public void WarnFormat(string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Warn) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.WarnFormat(format, args); } public void WarnFormat(string format, object arg0) { if (MailNotificationLevel <= MailNotificationLevel.Warn) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.WarnFormat(format, arg0); } public void WarnFormat(string format, object arg0, object arg1) { if (MailNotificationLevel <= MailNotificationLevel.Warn) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.WarnFormat(format, arg0, arg1); } public void WarnFormat(string format, object arg0, object arg1, object arg2) { if (MailNotificationLevel <= MailNotificationLevel.Warn) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.WarnFormat(format, arg0, arg1, arg2); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Warn) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.WarnFormat(provider, format, args); } public void Error(object message) { if (MailNotificationLevel <= MailNotificationLevel.Error) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Error(message); } public void Error(object message, Exception exception) { if ((MailNotificationLevel <= MailNotificationLevel.Error) || (AlwaysNotifyByMailOnException && exception != null) ) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Error(message, exception); } public void ErrorFormat(string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Error) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.ErrorFormat(format, args); } public void ErrorFormat(string format, object arg0) { if (MailNotificationLevel <= MailNotificationLevel.Error) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.ErrorFormat(format, arg0); } public void ErrorFormat(string format, object arg0, object arg1) { if (MailNotificationLevel <= MailNotificationLevel.Error) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.ErrorFormat(format, arg0, arg1); } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { if (MailNotificationLevel <= MailNotificationLevel.Error) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.ErrorFormat(format, arg0, arg1, arg2); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Error) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.ErrorFormat(provider, format, args); } public void Fatal(object message) { if (MailNotificationLevel <= MailNotificationLevel.Fatal) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Fatal(message); } public void Fatal(object message, Exception exception) { if ((MailNotificationLevel <= MailNotificationLevel.Fatal) || (AlwaysNotifyByMailOnException && exception != null) ) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.Fatal(message, exception); } public void FatalFormat(string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Fatal) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.FatalFormat(format, args); } public void FatalFormat(string format, object arg0) { if (MailNotificationLevel <= MailNotificationLevel.Fatal) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.FatalFormat(format, arg0); } public void FatalFormat(string format, object arg0, object arg1) { if (MailNotificationLevel <= MailNotificationLevel.Fatal) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.FatalFormat(format, arg0, arg1); } public void FatalFormat(string format, object arg0, object arg1, object arg2) { if (MailNotificationLevel <= MailNotificationLevel.Fatal) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.FatalFormat(format, arg0, arg1, arg2); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { if (MailNotificationLevel <= MailNotificationLevel.Fatal) ThreadContext.Properties["notifyEMailRecipients"] = "1"; _log.FatalFormat(provider, format, args); } } }
using System; using QuickGraph.Concepts; using QuickGraph.Concepts.Traversals; using QuickGraph.Concepts.Algorithms; using QuickGraph.Concepts.Collections; using QuickGraph.Collections; using QuickGraph.Collections.Filtered; using QuickGraph.Predicates; using QuickGraph.Algorithms.Visitors; using QuickGraph.Algorithms.Search; namespace QuickGraph.Algorithms.MaximumFlow { /// <summary>Push-Relabel Maximum Flow Algorithm</summary> /// <remarks> /// <para>The <see cref="PushRelabelMaximumFlowAlgorithm"/> class calculates the /// maximum flow of a network. The calculated maximum flow will be the return value of /// the <see cref="PushRelabelMaximumFlowAlgorithm.Compute"/>function. The function /// also calculates the flow values <c>f(u,v)</c> for all <c>(u,v)</c> in E, which /// are returned in the form of the residual capacity <c>r(u,v) = c(u,v) - f(u,v)</c>. /// </para> /// <para> ///There are several special requirements on the input graph and property map ///parameters for this algorithm. First, the directed graph <c>G=(V,E)</c> that ///represents the network must be augmented to include the reverse edge for every ///edge in E. That is, the input graph should be <c>Gin = (V,{E U E^T})</c>. ///The <c>reversedEdges</c> argument must map each edge in the original graph to ///its reverse edge, that is <c>(u,v) -> (v,u)</c> for all <c>(u,v)</c> in E. ///The <c>capacities</c> argument must map each edge in E to a ///positive number, and each edge in E^T to 0. ///</para> ///<para> ///This algorithm was developed by Goldberg. ///</para> /// </remarks> public class PushRelabelMaximumFlowAlgorithm : MaximumFlowAlgorithm { private const double globalUpdateFrequency = 0.5; private const int alpha = 6; private const int beta = 12; private IIndexedVertexListGraph visitedGraph; private int n, nm, maxDistance, minActive, maxActive, workSinceLastUpdate; private IVertex src, sink; private VertexDoubleDictionary excessFlow; private VertexIntDictionary current; private VertexIntDictionary distances; private PreflowLayer[] layers; /// <summary> /// /// </summary> /// <param name="g"></param> /// <param name="capacities"></param> /// <param name="reversedEdges"></param> public PushRelabelMaximumFlowAlgorithm( IIndexedVertexListGraph g, EdgeDoubleDictionary capacities, EdgeEdgeDictionary reversedEdges ) : base(g,capacities,reversedEdges) { this.visitedGraph = g; this.excessFlow = new VertexDoubleDictionary(); this.current = new VertexIntDictionary(); this.distances = new VertexIntDictionary(); } #region Properties new public IIndexedVertexListGraph VisitedGraph { get { return this.visitedGraph; } } public VertexIntDictionary Distances { get { return this.distances; } } internal IVertexListGraph ResidualGraph { get { return new FilteredVertexListGraph( this.VisitedGraph, new ReversedResidualEdgePredicate(this.ResidualCapacities, this.ReversedEdges) ); } } #endregion /// <summary> /// Computes the maximum flow between <paramref name="src"/> and /// <paramref name="sink"/>. /// </summary> /// <param name="src">The source node of the graph.</param> /// <param name="sink">The sink node of the graph.</param> /// <returns>The maximum flow of the graph.</returns> public override double Compute(IVertex src, IVertex sink) { if (src==null) throw new ArgumentNullException("src"); if (sink==null) throw new ArgumentNullException("sink"); this.src = src; this.sink = sink; Initialize(); double flow = MaximumPreflow(); ConvertPreflowToFlow(); return flow; } private void Initialize() { int m = 0; n = VisitedGraph.VerticesCount; foreach (IVertex u in VisitedGraph.Vertices) m += VisitedGraph.OutDegree(u); // Don't count the reverse edges m /= 2; nm = alpha * n + m; excessFlow.Clear(); current.Clear(); distances.Clear(); layers = new PreflowLayer[n]; for (int i = 0; i < n; i++) layers[i] = new PreflowLayer(); // Initialize flow to zero which means initializing // the residual capacity to equal the capacity. foreach (IVertex u in VisitedGraph.Vertices) { foreach (IEdge e in VisitedGraph.OutEdges(u)) this.ResidualCapacities[e] = this.Capacities[e]; excessFlow[u] = 0; current[u] = 0; } bool overflowDetected = false; double testExcess = 0; foreach (IEdge a in VisitedGraph.OutEdges(src)) { if (a.Target != src) testExcess += this.ResidualCapacities[a]; } if (testExcess >= double.MaxValue || double.IsPositiveInfinity(testExcess)) overflowDetected = true; if (overflowDetected) { excessFlow[src] = double.MaxValue; } else { excessFlow[src] = 0; foreach (IEdge a in this.VisitedGraph.OutEdges(src)) { if (a.Target != src) { double delta = this.ResidualCapacities[a]; this.ResidualCapacities[a] -= delta; this.ResidualCapacities[this.ReversedEdges[a]] += delta; this.excessFlow[a.Target] += delta; } } } maxDistance = VisitedGraph.VerticesCount - 1; maxActive = 0; minActive = n; foreach (IVertex u in this.VisitedGraph.Vertices) { if (u == sink) { distances[u] = 0; continue; } else if (u == src && !overflowDetected) { distances[u] = n; } else { distances[u] = 1; } if (excessFlow[u] > 0) this.AddToActiveList(u, layers[1]); else if (distances[u] < n) this.AddToInactiveList(u, layers[1]); } } /// <summary> /// This is the core part of the algorithm, "phase one." /// </summary> /// <returns></returns> private double MaximumPreflow() { workSinceLastUpdate = 0; while (maxActive >= minActive) // "main" loop { PreflowLayer layer = layers[maxActive]; if (layer.ActiveVertices.Count == 0) --maxActive; else { IVertex u = layer.ActiveVertices[0]; RemoveFromActiveList(u); Discharge(u); if (workSinceLastUpdate * globalUpdateFrequency > nm) { GlobalDistanceUpdate(); workSinceLastUpdate = 0; } } } return excessFlow[sink]; } //======================================================================= // remove excess flow, the "second phase" // This does a DFS on the reverse flow graph of nodes with excess flow. // If a cycle is found, cancel it. Unfortunately it seems that we can't // easily take advantage of DepthFirstSearchAlgorithm // Return the nodes with excess flow in topological order. // // Unlike the prefl_to_flow() implementation, we use // "color" instead of "distance" for the DFS labels // "parent" instead of nl_prev for the DFS tree // "topo_next" instead of nl_next for the topological ordering private void ConvertPreflowToFlow() { IVertex r, restart, u; IVertex bos = null, tos = null; VertexVertexDictionary parents = new VertexVertexDictionary(); VertexVertexDictionary topoNext = new VertexVertexDictionary(); foreach (IVertex v in VisitedGraph.Vertices) { //Handle self-loops foreach (IEdge a in VisitedGraph.OutEdges(v)) if (a.Target == v) ResidualCapacities[a] = Capacities[a]; //Initialize Colors[v] = GraphColor.White; parents[v] = v; current[v] = 0; } // eliminate flow cycles and topologically order the vertices IVertexEnumerator vertices = VisitedGraph.Vertices.GetEnumerator(); while (vertices.MoveNext()) { u = vertices.Current; if (Colors[u] == GraphColor.White && excessFlow[u] > 0 && u != src && u != sink) { r = u; Colors[r] = GraphColor.Gray; while(true) { for (; current[u] < VisitedGraph.OutDegree(u); ++current[u]) { IEdge a = VisitedGraph.OutEdges(u)[current[u]]; if (Capacities[a] == 0 && IsResidualEdge(a)) { IVertex v = a.Target; if (Colors[v] == GraphColor.White) { Colors[v] = GraphColor.Gray; parents[v] = u; u = v; break; } else if (Colors[v] == GraphColor.Gray) { //find minimum flow on the cycle double delta = ResidualCapacities[a]; while (true) { IEdge e = VisitedGraph.OutEdges(v)[current[v]]; delta = Math.Min(delta, ResidualCapacities[e]); if (v == u) break; else v = e.Target; } //remove delta flow units v = u; while (true) { a = VisitedGraph.OutEdges(v)[current[v]]; ResidualCapacities[a] -= delta; ResidualCapacities[ReversedEdges[a]] += delta; v = a.Target; if (v == u) break; } // back-out of DFS to the first saturated edge restart = u; for (v = VisitedGraph.OutEdges(u)[current[u]].Target; v != u; v = a.Target) { a = VisitedGraph.OutEdges(v)[current[v]]; if (Colors[v] == GraphColor.White || IsSaturated(a)) { Colors[VisitedGraph.OutEdges(v)[current[v]].Target] = GraphColor.White; if (Colors[v] != GraphColor.White) restart = v; } } if (restart != u) { u = restart; ++current[u]; break; } } } } if (current[u] == VisitedGraph.OutDegree(u)) { // scan of i is complete Colors[u] = GraphColor.Black; if (u != src) { if (bos == null) { bos = u; tos = u; } else { topoNext[u] = tos; tos = u; } } if (u != r) { u = parents[u]; ++current[u]; } else break; } } } } // return excess flows // note that the sink is not on the stack if (bos != null) { IEdgeEnumerator ai; for (u = tos; u != bos; u = topoNext[u]) { ai = VisitedGraph.OutEdges(u).GetEnumerator(); while (excessFlow[u] > 0 && ai.MoveNext()) { if (Capacities[ai.Current] == 0 && IsResidualEdge(ai.Current)) PushFlow(ai.Current); } } // do the bottom u = bos; ai = VisitedGraph.OutEdges(u).GetEnumerator(); while (excessFlow[u] > 0 && ai.MoveNext()) { if (Capacities[ai.Current] == 0 && IsResidualEdge(ai.Current)) PushFlow(ai.Current); } } } //======================================================================= // This is a breadth-first search over the residual graph // (well, actually the reverse of the residual graph). // Would be cool to have a graph view adaptor for hiding certain // edges, like the saturated (non-residual) edges in this case. // Goldberg's implementation abused "distance" for the coloring. private void GlobalDistanceUpdate() { foreach (IVertex u in VisitedGraph.Vertices) { Colors[u] = GraphColor.White; Distances[u] = n; } Distances[sink] = 0; for (int l = 0; l <= maxDistance; ++l) { layers[l].ActiveVertices.Clear(); layers[l].InactiveVertices.Clear(); } maxDistance = maxActive = 0; minActive = n; BreadthFirstSearchAlgorithm bfs = new BreadthFirstSearchAlgorithm( ResidualGraph, new VertexBuffer(), Colors ); DistanceRecorderVisitor vis = new DistanceRecorderVisitor(Distances); bfs.TreeEdge += new EdgeEventHandler(vis.TreeEdge); bfs.DiscoverVertex += new VertexEventHandler(GlobalDistanceUpdateHelper); bfs.Compute(sink); } private void GlobalDistanceUpdateHelper(object sender, VertexEventArgs e) { if (e.Vertex != sink) { current[e.Vertex] = 0; maxDistance = Math.Max(distances[e.Vertex], maxDistance); if (excessFlow[e.Vertex] > 0) AddToActiveList(e.Vertex, layers[distances[e.Vertex]]); else AddToInactiveList(e.Vertex, layers[distances[e.Vertex]]); } } //======================================================================= // This function is called "push" in Goldberg's h_prf implementation, // but it is called "discharge" in the paper and in hi_pr.c. private void Discharge(IVertex u) { while (true) { int ai; for (ai = current[u]; ai < VisitedGraph.OutDegree(u); ai++) { IEdge a = VisitedGraph.OutEdges(u)[ai]; if (IsResidualEdge(a)) { IVertex v = a.Target; if (IsAdmissible(u, v)) { if (v != sink && excessFlow[v] == 0) { RemoveFromInactiveList(v); AddToActiveList(v, layers[distances[v]]); } PushFlow(a); if (excessFlow[u] == 0) break; } } } PreflowLayer layer = layers[distances[u]]; int du = distances[u]; if (ai == VisitedGraph.OutDegree(u)) // i must be relabeled { RelabelDistance(u); if (layer.ActiveVertices.Count == 0 && layer.InactiveVertices.Count == 0) Gap(du); if (distances[u] == n) break; } else { // i is no longer active current[u] = ai; AddToInactiveList(u, layer); break; } } } //======================================================================= // This corresponds to the "push" update operation of the paper, // not the "push" function in Goldberg's h_prf.c implementation. // The idea is to push the excess flow from from vertex u to v. private void PushFlow(IEdge e) { IVertex u = e.Source; IVertex v = e.Target; double flowDelta = Math.Min(excessFlow[u], ResidualCapacities[e]); ResidualCapacities[e] -= flowDelta; ResidualCapacities[ReversedEdges[e]] += flowDelta; excessFlow[u] -= flowDelta; excessFlow[v] += flowDelta; } //======================================================================= // The main purpose of this routine is to set distance[v] // to the smallest value allowed by the valid labeling constraints, // which are: // distance[t] = 0 // distance[u] <= distance[v] + 1 for every residual edge (u,v) // private int RelabelDistance(IVertex u) { int minEdges = 0; workSinceLastUpdate += beta; int minDistance = VisitedGraph.VerticesCount; distances[u] = minDistance; // Examine the residual out-edges of vertex i, choosing the // edge whose target vertex has the minimal distance. for (int ai = 0; ai < VisitedGraph.OutDegree(u); ai++) { ++workSinceLastUpdate; IEdge a = VisitedGraph.OutEdges(u)[ai]; IVertex v = a.Target; if (IsResidualEdge(a) && distances[v] < minDistance) { minDistance = distances[v]; minEdges = ai; } } ++minDistance; if (minDistance < n) { distances[u] = minDistance; // this is the main action current[u] = minEdges; maxDistance = Math.Max(minDistance, maxDistance); } return minDistance; } //======================================================================= // cleanup beyond the gap private void Gap(int emptyDistance) { int r; // distance of layer before the current layer r = emptyDistance - 1; // Set the distance for the vertices beyond the gap to "infinity". for (int l = emptyDistance + 1; l < maxDistance; ++l) { foreach (IVertex v in layers[l].InactiveVertices) distances[v] = n; layers[l].InactiveVertices.Clear(); } maxDistance = r; maxActive = r; } private bool IsFlow() { // check edge flow values foreach (IVertex u in VisitedGraph.Vertices) { foreach (IEdge a in VisitedGraph.OutEdges(u)) { if (Capacities[a] > 0) if ((ResidualCapacities[a] + ResidualCapacities[ReversedEdges[a]] != Capacities[a] + Capacities[ReversedEdges[a]]) || (ResidualCapacities[a] < 0) || (ResidualCapacities[ReversedEdges[a]] < 0)) return false; } } // check conservation double sum; foreach (IVertex u in VisitedGraph.Vertices) { if (u != src && u != sink) { if (excessFlow[u] != 0) return false; sum = 0; foreach (IEdge a in VisitedGraph.OutEdges(u)) if (Capacities[a] > 0) sum -= Capacities[a] - ResidualCapacities[a]; else sum += ResidualCapacities[a]; if (excessFlow[u] != sum) return false; } } return true; } private bool IsOptimal() { // check if mincut is saturated... GlobalDistanceUpdate(); return Distances[src] >= n; } //======================================================================= // Some helper predicates private bool IsAdmissible(IVertex u, IVertex v) { return distances[u] == distances[v] + 1; } private bool IsResidualEdge(IEdge a) { return 0 < ResidualCapacities[a]; } private bool IsSaturated(IEdge a) { return ResidualCapacities[a] == 0; } #region PreflowLayer Management private void AddToActiveList(IVertex u, PreflowLayer layer) { layer.ActiveVertices.Insert(0, u); maxActive = Math.Max(Distances[u], maxActive); minActive = Math.Min(Distances[u], minActive); } private void RemoveFromActiveList(IVertex u) { layers[Distances[u]].ActiveVertices.Remove(u); } private void AddToInactiveList(IVertex u, PreflowLayer layer) { layer.InactiveVertices.Insert(0, u); } private void RemoveFromInactiveList(IVertex u) { layers[distances[u]].InactiveVertices.Remove(u); } private class PreflowLayer { private VertexCollection activeVertices; private VertexCollection inactiveVertices; public PreflowLayer() { this.activeVertices = new VertexCollection(); this.inactiveVertices = new VertexCollection(); } #region Properties public VertexCollection ActiveVertices { get { return this.activeVertices; } } public VertexCollection InactiveVertices { get { return this.inactiveVertices; } } #endregion } #endregion } }
// 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using GgpGrpc.Models; using NUnit.Framework; using YetiCommon.Cloud; using static YetiCommon.Tests.Cloud.LaunchRequestParsingTestData; namespace YetiCommon.Tests.Cloud { /// <summary> /// Tests for both <c>LaunchGameParamsConverter</c> and <c>QueryParametersParser</c>. /// </summary> [TestFixture] class ToLaunchGameRequestTests { QueryParametersParser _queryParametersParser; LaunchGameParamsConverter _parametersConverter; [SetUp] public void Setup() { _queryParametersParser = new QueryParametersParser(); _parametersConverter = new LaunchGameParamsConverter(_queryParametersParser); } [Test] public void ToLaunchGameRequestNoQueryParams() { LaunchParams parameters = ValidParams; parameters.RenderDoc = false; parameters.Rgp = false; parameters.Dive = false; parameters.Orbit = false; parameters.VulkanDriverVariant = string.Empty; ConfigStatus status = _parametersConverter.ToLaunchGameRequest(parameters, out LaunchGameRequest request); Assert.That(status.IsOk, Is.EqualTo(true)); Assert.IsNotNull(request); Assert.That(request.Parent, Is.EqualTo(parameters.TestAccount)); Assert.That(request.GameletName, Is.EqualTo(parameters.GameletName)); Assert.That(request.ApplicationName, Is.EqualTo(parameters.ApplicationName)); Assert.That(request.ExecutablePath, Is.EqualTo("some_bin")); Assert.That(request.CommandLineArguments, Is.EqualTo(new[] { "arg1" })); Assert.That(request.EnvironmentVariablePairs, Is.EqualTo(new Dictionary<string, string> { { "Var1", "1" }, { "vAR2", "3" } })); Assert.That(request.SurfaceEnforcementMode, Is.EqualTo(parameters.SurfaceEnforcementMode)); Assert.That(request.Debug, Is.EqualTo(parameters.Debug)); // Assert another parameters values are default. Assert.That(request.EnablePipelineCacheSourceUpload, Is.EqualTo(null)); Assert.That(request.EnableRetroactiveFrameDump, Is.EqualTo(null)); Assert.That(request.StreamQualityPreset, Is.EqualTo(StreamQualityPreset.Undefined)); Assert.That(request.AddInstanceCompatibilityRequirements.Length, Is.EqualTo(0)); Assert.That(request.RemoveInstanceCompatibilityRequirements.Length, Is.EqualTo(0)); Assert.That(request.DeepLinkParamsIdGameData, Is.EqualTo(null)); Assert.That(request.EnableGameRealtimePriority, Is.EqualTo(null)); Assert.That(request.EnforceProductionRam, Is.EqualTo(null)); Assert.That(request.GameStateName, Is.EqualTo(null)); Assert.That(request.ReleaseName, Is.EqualTo(null)); Assert.That(request.MountDynamicContent, Is.EqualTo(null)); Assert.That(request.MountUploadedPipelineCache, Is.EqualTo(null)); Assert.That(request.OverrideAudioChannelMode, Is.EqualTo(ChannelMode.Unspecified)); Assert.That(request.OverrideClientResolution, Is.EqualTo(VideoResolution.Unspecified)); Assert.That(request.OverrideDisplayPixelDensity, Is.EqualTo(PixelDensity.PixelDensityUndefined)); Assert.That(request.OverrideDynamicRange, Is.EqualTo(DynamicRange.Unspecified)); Assert.That(request.OverridePreferredCodec, Is.EqualTo(Codec.Unspecified)); Assert.That(request.PackageName, Is.EqualTo(null)); Assert.That(request.StartForwardFrameDump, Is.EqualTo(null)); Assert.That(request.StreamerFixedFps, Is.EqualTo(null)); Assert.That(request.StreamerFixedResolution, Is.EqualTo(VideoResolution.Unspecified)); Assert.That(request.StreamerMaximumBandWidthKbps, Is.EqualTo(null)); Assert.That(request.StreamerMinimumBandWidthKbps, Is.EqualTo(null)); } [Test] public void ToLaunchGameRequestEnvironmentVariablesOverlap() { LaunchParams parameters = ValidParams; parameters.RenderDoc = true; parameters.Rgp = true; parameters.Dive = true; parameters.Orbit = true; parameters.GameletEnvironmentVars = "RENDERDOC_TEMP=chrome/params/temp;RENDERDOC_DEBUG_LOG_FILE=chrome/params.log;" + "GGP_DEV_VK_DRIVER_VARIANT=opt;GGP_VK_AMDVLK_USE_LLPC=0;Some_Var=12;other=9" + ";ENABLE_VK_LAYER_VULKAN_COLOR_TOOLS=0"; parameters.QueryParams = "color_tools=1&enable_llpc_in_amdvlk=True&" + "enable_pipeline_cache_source_layer=true&vulkan_driver_variant=optprintasserts" + "&vars=GGP_DEV_VK_DRIVER_VARIANT=dbgtrapasserts;Other=567;OTHER_var=67;" + "RENDERDOC_TEMP=query/params/temp1;ENABLE_VK_LAYER_VULKAN_COLOR_TOOLS=false"; ConfigStatus status = _parametersConverter.ToLaunchGameRequest(parameters, out LaunchGameRequest request); Assert.That(status.IsWarningLevel, Is.EqualTo(true)); Assert.That(status.AllMessages.Count, Is.EqualTo(7)); Assert.That(status.WarningMessages.Count(m => m.Contains("is set multiple times.")), Is.EqualTo(3)); Assert.That( status.WarningMessages.Count(m => m.Contains("overrides the setting variable")), Is.EqualTo(3)); Assert.That(status.WarningMessages.Count(m => m.Contains("edit the setting")), Is.EqualTo(1)); Assert.That(request.EnvironmentVariablePairs, Is.EqualTo(new Dictionary<string, string> { { "GGP_DEV_VK_DRIVER_VARIANT", "dbgtrapasserts" }, { "ENABLE_VULKAN_RENDERDOC_CAPTURE", "1" }, { "RENDERDOC_TEMP", "query/params/temp1" }, { "RENDERDOC_DEBUG_LOG_FILE", "chrome/params.log" }, { "GGP_INTERNAL_LOAD_RGP", "1" }, { "RGP_DEBUG_LOG_FILE", "/var/game/RGPDebug.log" }, { "LD_PRELOAD", "librgpserver.so" }, { "VK_INSTANCE_LAYERS", "VK_LAYER_dive_capture" }, { "ENABLE_ORBIT_VULKAN_LAYER", "1" }, { "ENABLE_VK_LAYER_VULKAN_COLOR_TOOLS", "false" }, { "GGP_VK_AMDVLK_USE_LLPC", "0" }, { "ENABLE_GOOGLE_PIPELINE_DATA_EXPORT_LAYER", "1" }, { "Some_Var", "12" }, { "other", "9" }, { "Other", "567" }, { "OTHER_var", "67" } })); } [Test] public void ToLaunchGameRequestParametersOverlap() { LaunchParams parameters = ValidParams; parameters.SurfaceEnforcementMode = SurfaceEnforcementSetting.Block; parameters.Debug = false; parameters.QueryParams = string.Join( "&", AllValidQueryParams.Select( p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}")); ConfigStatus status = _parametersConverter.ToLaunchGameRequest(parameters, out LaunchGameRequest request); Assert.That(status.IsWarningLevel, Is.EqualTo(true)); Assert.That(status.AllMessages.Count, Is.EqualTo(1)); Assert.That( status.WarningMessage.Contains("The following query parameters will be ignored")); Assert.IsNotNull(request); Assert.That(request.Parent, Is.EqualTo("some_test_account")); Assert.That(request.GameletName, Is.EqualTo(parameters.GameletName)); Assert.That(request.ApplicationName, Is.EqualTo("params_app_name")); Assert.That(request.ExecutablePath, Is.EqualTo("some_bin")); Assert.That(request.CommandLineArguments, Is.EqualTo(new[] { "arg2" })); Assert.That(request.EnvironmentVariablePairs, Is.EqualTo(new Dictionary<string, string> { { "ParamsVar", "val" }, { "Var1", "1" }, { "vAR2", "3" }, { "GGP_DEV_VK_DRIVER_VARIANT", "test_variant" }, { "GGP_INTERNAL_LOAD_RGP", "1" }, { "RGP_DEBUG_LOG_FILE", "/var/game/RGPDebug.log" }, { "VK_INSTANCE_LAYERS", "VK_LAYER_dive_capture" }, { "LD_PRELOAD", "librgpserver.so" } })); Assert.That(request.SurfaceEnforcementMode, Is.EqualTo(SurfaceEnforcementSetting.Warn)); Assert.That(request.Debug, Is.EqualTo(true)); Assert.That(request.EnablePipelineCacheSourceUpload, Is.EqualTo(false)); Assert.That(request.EnableRetroactiveFrameDump, Is.EqualTo(true)); Assert.That(request.StreamQualityPreset, Is.EqualTo(StreamQualityPreset.HighVisualQuality)); Assert.That(request.AddInstanceCompatibilityRequirements, Is.EqualTo(new[] { "r1", "other" })); Assert.That(request.RemoveInstanceCompatibilityRequirements, Is.EqualTo(new[] { "5", "7", " 8" })); Assert.That(request.DeepLinkParamsIdGameData, Is.EqualTo(23475456543)); Assert.That(request.EnableGameRealtimePriority, Is.EqualTo(true)); Assert.That(request.EnforceProductionRam, Is.EqualTo(false)); Assert.That(request.GameStateName, Is.EqualTo("params_game_state_name")); Assert.That(request.ReleaseName, Is.EqualTo(null)); Assert.That(request.MountDynamicContent, Is.EqualTo(true)); Assert.That(request.MountUploadedPipelineCache, Is.EqualTo(true)); Assert.That(request.OverrideAudioChannelMode, Is.EqualTo(ChannelMode.Surround51True)); Assert.That(request.OverrideClientResolution, Is.EqualTo(VideoResolution._720P)); Assert.That(request.OverrideDisplayPixelDensity, Is.EqualTo(PixelDensity.XHigh)); Assert.That(request.OverrideDynamicRange, Is.EqualTo(DynamicRange.Sdr)); Assert.That(request.OverridePreferredCodec, Is.EqualTo(Codec.Vp9)); Assert.That(request.PackageName, Is.EqualTo("params_package_name")); Assert.That(request.StartForwardFrameDump, Is.EqualTo(false)); Assert.That(request.StreamerFixedFps, Is.EqualTo(765)); Assert.That(request.StreamerFixedResolution, Is.EqualTo(VideoResolution._1440P)); Assert.That(request.StreamerMaximumBandWidthKbps, Is.EqualTo(8764)); Assert.That(request.StreamerMinimumBandWidthKbps, Is.EqualTo(23)); } [Test] public void ToLaunchGameRequestExternalParams() { LaunchParams parameters = ValidExternalParams; ConfigStatus status = _parametersConverter.ToLaunchGameRequest(parameters, out LaunchGameRequest request); Assert.That(status.IsOk, Is.True); Assert.IsNotNull(request); Assert.That(request.Parent, Is.EqualTo(parameters.ExternalAccount)); } } }
using Sigma.Core; using Sigma.Core.Architecture; using Sigma.Core.Data.Datasets; using Sigma.Core.Data.Extractors; using Sigma.Core.Data.Iterators; using Sigma.Core.Data.Preprocessors; using Sigma.Core.Data.Readers; using Sigma.Core.Data.Sources; using Sigma.Core.Handlers; using Sigma.Core.Handlers.Backends.SigmaDiff.NativeCpu; using Sigma.Core.Layers.Cost; using Sigma.Core.Layers.External; using Sigma.Core.Layers.Feedforward; using Sigma.Core.MathAbstract; using Sigma.Core.MathAbstract.Backends.SigmaDiff; using Sigma.Core.Persistence; using Sigma.Core.Training; using Sigma.Core.Training.Hooks; using Sigma.Core.Training.Hooks.Reporters; using Sigma.Core.Training.Hooks.Stoppers; using Sigma.Core.Training.Initialisers; using Sigma.Core.Training.Mergers; using Sigma.Core.Training.Operators.Backends.NativeCpu; using Sigma.Core.Utils; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Sigma.Core.Handlers.Backends.Debugging; using Sigma.Core.Handlers.Backends.SigmaDiff.NativeGpu; using Sigma.Core.Layers.Recurrent; using Sigma.Core.Layers.Regularisation; using Sigma.Core.Monitors; using Sigma.Core.Training.Hooks.Saviors; using Sigma.Core.Training.Operators.Backends.NativeGpu; using Sigma.Core.Training.Optimisers.Gradient; using Sigma.Core.Training.Optimisers.Gradient.Memory; namespace Sigma.Tests.Internals.Backend { public static class Program { private static void Main(string[] args) { SigmaEnvironment.EnableLogging(xml: true); SigmaEnvironment.Globals["web_proxy"] = WebUtils.GetProxyFromFileOrDefault(".customproxy"); SampleMnist(); Console.WriteLine("Program ended, waiting for termination, press any key..."); Console.ReadKey(); } private static void SampleHutter() { const long timeWindowSize = 10L; SigmaEnvironment sigma = SigmaEnvironment.Create("recurrent"); IDataSource source = new MultiSource(new FileSource("enwik8"), new CompressedSource(new MultiSource(new FileSource("enwik8.zip"), new UrlSource("http://mattmahoney.net/dc/enwik8.zip")))); IRecordExtractor extractor = new CharacterRecordReader(source, (int)(timeWindowSize + 1), Encoding.ASCII) .Extractor(new ArrayRecordExtractor<short>(ArrayRecordExtractor<short> .ParseExtractorParameters("inputs", new[] { 0L }, new[] { timeWindowSize }, "targets", new[] { 0L }, new[] { timeWindowSize })) .Offset("targets", 1L)) .Preprocess(new PermutePreprocessor(0, 2, 1)) .Preprocess(new OneHotPreprocessor(0, 255)); IDataset dataset = new ExtractedDataset("hutter", ExtractedDataset.BlockSizeAuto, false, extractor); ITrainer trainer = sigma.CreateTrainer("hutter"); trainer.Network.Architecture = InputLayer.Construct(256) + RecurrentLayer.Construct(256) + OutputLayer.Construct(256) + SoftMaxCrossEntropyCostLayer.Construct(); trainer.TrainingDataIterator = new MinibatchIterator(32, dataset); trainer.AddNamedDataIterator("validation", new MinibatchIterator(100, dataset)); trainer.Optimiser = new AdagradOptimiser(baseLearningRate: 0.07); trainer.Operator = new CudaSinglethreadedOperator(); trainer.AddInitialiser("*.*", new GaussianInitialiser(standardDeviation: 0.05)); trainer.AddLocalHook(new AccumulatedValueReporter("optimiser.cost_total", TimeStep.Every(1, TimeScale.Iteration), averageValues: true)); trainer.AddLocalHook(new RunningTimeReporter(TimeStep.Every(10, TimeScale.Iteration))); sigma.PrepareAndRun(); } private static void SampleXor() { SigmaEnvironment sigma = SigmaEnvironment.Create("logical"); sigma.SetRandomSeed(0); sigma.Prepare(); RawDataset dataset = new RawDataset("xor"); dataset.AddRecords("inputs", new[] { 0, 0 }, new[] { 0, 1 }, new[] { 1, 0 }, new[] { 1, 1 }); dataset.AddRecords("targets", new[] { 0 }, new[] { 0 }, new[] { 0 }, new[] { 1 }); ITrainer trainer = sigma.CreateTrainer("xor-trainer"); trainer.Network.Architecture = InputLayer.Construct(2) + FullyConnectedLayer.Construct(2) + FullyConnectedLayer.Construct(1) + OutputLayer.Construct(1) + SquaredDifferenceCostLayer.Construct(); trainer.TrainingDataIterator = new MinibatchIterator(1, dataset); trainer.AddNamedDataIterator("validation", new UndividedIterator(dataset)); trainer.Optimiser = new GradientDescentOptimiser(learningRate: 0.1); trainer.Operator = new CudaSinglethreadedOperator(); trainer.AddInitialiser("*.*", new GaussianInitialiser(standardDeviation: 0.05)); trainer.AddLocalHook(new StopTrainingHook(atEpoch: 10000)); trainer.AddLocalHook(new AccumulatedValueReporter("optimiser.cost_total", TimeStep.Every(1, TimeScale.Epoch), averageValues: true)); trainer.AddLocalHook(new AccumulatedValueReporter("optimiser.cost_total", TimeStep.Every(1, TimeScale.Stop), averageValues: true)); trainer.AddLocalHook(new ValueReporter("network.layers.*<external_output>._outputs.default.activations", TimeStep.Every(1, TimeScale.Stop))); trainer.AddLocalHook(new ValueReporter("network.layers.*-fullyconnected.weights", TimeStep.Every(1, TimeScale.Stop))); trainer.AddLocalHook(new ValueReporter("network.layers.*-fullyconnected.biases", TimeStep.Every(1, TimeScale.Stop))); sigma.Run(); } private static void SampleIris() { SigmaEnvironment sigma = SigmaEnvironment.Create("iris"); sigma.SetRandomSeed(0); sigma.Prepare(); IDataset dataset = Defaults.Datasets.Iris(); ITrainer trainer = sigma.CreateGhostTrainer("iris-trainer"); trainer.Network.Architecture = InputLayer.Construct(4) + FullyConnectedLayer.Construct(12) + FullyConnectedLayer.Construct(3) + OutputLayer.Construct(3) + SquaredDifferenceCostLayer.Construct(); //trainer.Network = Serialisation.ReadBinaryFileIfExists("iris.sgnet", trainer.Network); trainer.TrainingDataIterator = new MinibatchIterator(50, dataset); trainer.AddNamedDataIterator("validation", new UndividedIterator(dataset)); trainer.Optimiser = new GradientDescentOptimiser(learningRate: 0.06); trainer.Operator = new CudaSinglethreadedOperator(); trainer.AddInitialiser("*.*", new GaussianInitialiser(standardDeviation: 0.1)); //trainer.AddGlobalHook(new StopTrainingHook(atEpoch: 100)); //trainer.AddLocalHook(new EarlyStopperHook("optimiser.cost_total", 20, target: ExtremaTarget.Min)); trainer.AddLocalHook(new AccumulatedValueReporter("optimiser.cost_total", TimeStep.Every(1, TimeScale.Epoch), reportEpochIteration: true)); //.On(new ExtremaCriteria("optimiser.cost_total", ExtremaTarget.Min))); //trainer.AddLocalHook(new DiskSaviorHook<INetwork>("network.self", Namers.Dynamic("iris_epoch{0}.sgnet", "epoch"), verbose: true) // .On(new ExtremaCriteria("optimiser.cost_total", ExtremaTarget.Min))); trainer.AddHook(new MultiClassificationAccuracyReporter("validation", TimeStep.Every(1, TimeScale.Epoch), tops: 1)); trainer.AddHook(new StopTrainingHook(new ThresholdCriteria("shared.classification_accuracy_top1", ComparisonTarget.GreaterThanEquals, 0.98))); trainer.AddLocalHook(new RunningTimeReporter(TimeStep.Every(599, TimeScale.Iteration), 128)); trainer.AddLocalHook(new RunningTimeReporter(TimeStep.Every(1, TimeScale.Epoch), 4)); //Serialisation.WriteBinaryFile(trainer, "trainer.sgtrainer"); //trainer = Serialisation.ReadBinaryFile<ITrainer>("trainer.sgtrainer"); sigma.AddTrainer(trainer); sigma.AddMonitor(new HttpMonitor("http://+:8080/sigma/")); sigma.PrepareAndRun(); } private static void SampleWdbc() { SigmaEnvironment sigma = SigmaEnvironment.Create("wdbc"); IDataset dataset = Defaults.Datasets.Wdbc(); ITrainer trainer = sigma.CreateGhostTrainer("wdbc-trainer"); trainer.Network.Architecture = InputLayer.Construct(30) + FullyConnectedLayer.Construct(42) + FullyConnectedLayer.Construct(24) + FullyConnectedLayer.Construct(1) + OutputLayer.Construct(1) + SquaredDifferenceCostLayer.Construct(); trainer.TrainingDataIterator = new MinibatchIterator(72, dataset); trainer.AddNamedDataIterator("validation", new UndividedIterator(dataset)); trainer.Optimiser = new GradientDescentOptimiser(learningRate: 0.005); trainer.AddInitialiser("*.*", new GaussianInitialiser(standardDeviation: 0.1)); trainer.AddLocalHook(new AccumulatedValueReporter("optimiser.cost_total", TimeStep.Every(1, TimeScale.Epoch))); trainer.AddHook(new UniClassificationAccuracyReporter("validation", 0.5, TimeStep.Every(1, TimeScale.Epoch))); sigma.AddTrainer(trainer); sigma.AddMonitor(new HttpMonitor("http://+:8080/sigma/")); sigma.PrepareAndRun(); } private static void SampleParkinsons() { SigmaEnvironment sigma = SigmaEnvironment.Create("parkinsons"); IDataset dataset = Defaults.Datasets.Parkinsons(); ITrainer trainer = sigma.CreateGhostTrainer("parkinsons-trainer"); trainer.Network.Architecture = InputLayer.Construct(22) + FullyConnectedLayer.Construct(140) + FullyConnectedLayer.Construct(20) + FullyConnectedLayer.Construct(1) + OutputLayer.Construct(1) + SquaredDifferenceCostLayer.Construct(); trainer.TrainingDataIterator = new MinibatchIterator(10, dataset); trainer.AddNamedDataIterator("validation", new UndividedIterator(dataset)); trainer.Optimiser = new AdagradOptimiser(baseLearningRate: 0.01); trainer.AddInitialiser("*.*", new GaussianInitialiser(standardDeviation: 0.1)); trainer.AddLocalHook(new AccumulatedValueReporter("optimiser.cost_total", TimeStep.Every(1, TimeScale.Epoch))); trainer.AddHook(new UniClassificationAccuracyReporter("validation", 0.5, TimeStep.Every(1, TimeScale.Epoch))); sigma.AddTrainer(trainer); sigma.PrepareAndRun(); } private static void SampleMnist() { SigmaEnvironment sigma = SigmaEnvironment.Create("mnist"); sigma.SetRandomSeed(0); IDataset dataset = Defaults.Datasets.Mnist(); ITrainer trainer = sigma.CreateTrainer("mnist-trainer"); trainer.Network = new Network(); trainer.Network.Architecture = InputLayer.Construct(28, 28) + DropoutLayer.Construct(0.2) + FullyConnectedLayer.Construct(1000, activation: "rel") + DropoutLayer.Construct(0.4) + FullyConnectedLayer.Construct(800, activation: "rel") + DropoutLayer.Construct(0.4) + FullyConnectedLayer.Construct(10, activation: "sigmoid") + OutputLayer.Construct(10) + SoftMaxCrossEntropyCostLayer.Construct(); trainer.TrainingDataIterator = new MinibatchIterator(100, dataset); trainer.AddNamedDataIterator("validation", new UndividedIterator(Defaults.Datasets.MnistValidation())); //trainer.Optimiser = new GradientDescentOptimiser(learningRate: 0.01); //trainer.Optimiser = new MomentumGradientOptimiser(learningRate: 0.01, momentum: 0.9); trainer.Optimiser = new AdagradOptimiser(baseLearningRate: 0.02); trainer.Operator = new CudaSinglethreadedOperator(); trainer.AddInitialiser("*.weights", new GaussianInitialiser(standardDeviation: 0.1)); trainer.AddInitialiser("*.bias*", new GaussianInitialiser(standardDeviation: 0.05)); trainer.AddLocalHook(new ValueReporter("optimiser.cost_total", TimeStep.Every(1, TimeScale.Iteration), reportEpochIteration: true) .On(new ExtremaCriteria("optimiser.cost_total", ExtremaTarget.Min))); var validationTimeStep = TimeStep.Every(1, TimeScale.Epoch); trainer.AddHook(new MultiClassificationAccuracyReporter("validation", validationTimeStep, tops: new[] { 1, 2, 3 })); for (int i = 0; i < 10; i++) { trainer.AddGlobalHook(new TargetMaximisationReporter(trainer.Operator.Handler.NDArray(ArrayUtils.OneHot(i, 10), 10), TimeStep.Every(1, TimeScale.Epoch))); } trainer.AddLocalHook(new RunningTimeReporter(TimeStep.Every(10, TimeScale.Iteration), 32)); trainer.AddLocalHook(new RunningTimeReporter(TimeStep.Every(1, TimeScale.Epoch), 4)); trainer.AddHook(new StopTrainingHook(atEpoch: 10)); sigma.PrepareAndRun(); } private static void SampleTicTacToe() { SigmaEnvironment sigma = SigmaEnvironment.Create("tictactoe"); IDataset dataset = Defaults.Datasets.TicTacToe(); ITrainer trainer = sigma.CreateTrainer("tictactoe-trainer"); trainer.Network = new Network(); trainer.Network.Architecture = InputLayer.Construct(9) + FullyConnectedLayer.Construct(63, "tanh") + FullyConnectedLayer.Construct(90, "tanh") + FullyConnectedLayer.Construct(3, "tanh") + OutputLayer.Construct(3) + SoftMaxCrossEntropyCostLayer.Construct(); trainer.TrainingDataIterator = new MinibatchIterator(21, dataset); trainer.AddNamedDataIterator("validation", new UndividedIterator(dataset)); trainer.Optimiser = new MomentumGradientOptimiser(learningRate: 0.01, momentum: 0.9); trainer.Operator = new CpuSinglethreadedOperator(); trainer.AddInitialiser("*.*", new GaussianInitialiser(standardDeviation: 0.1)); trainer.AddLocalHook(new AccumulatedValueReporter("optimiser.cost_total", TimeStep.Every(1, TimeScale.Epoch))); trainer.AddHook(new MultiClassificationAccuracyReporter("validation", TimeStep.Every(1, TimeScale.Epoch), tops: new[] { 1, 2 })); trainer.AddGlobalHook(new DiskSaviorHook<INetwork>(TimeStep.Every(1, TimeScale.Epoch), "network.self", Namers.Static("tictactoe.sgnet"), verbose: true) .On(new ExtremaCriteria("shared.classification_accuracy_top1", ExtremaTarget.Max))); sigma.PrepareAndRun(); } private static void SampleCachedFastIteration() { SigmaEnvironment sigma = SigmaEnvironment.Create("test"); IDataSource dataSource = new CompressedSource(new MultiSource(new FileSource("train-images-idx3-ubyte.gz"), new UrlSource("http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz"))); ByteRecordReader mnistImageReader = new ByteRecordReader(headerLengthBytes: 16, recordSizeBytes: 28 * 28, source: dataSource); IRecordExtractor mnistImageExtractor = mnistImageReader.Extractor("inputs", new[] { 0L, 0L }, new[] { 28L, 28L }).Preprocess(new NormalisingPreprocessor(0, 255)); IDataset dataset = new ExtractedDataset("mnist-training", ExtractedDataset.BlockSizeAuto, mnistImageExtractor); IDataset[] slices = dataset.SplitRecordwise(0.8, 0.2); IDataset trainingData = slices[0]; Stopwatch stopwatch = Stopwatch.StartNew(); IDataIterator iterator = new MinibatchIterator(10, trainingData); foreach (var block in iterator.Yield(new CpuFloat32Handler(), sigma)) { //PrintFormattedBlock(block, PrintUtils.AsciiGreyscalePalette); } Console.Write("\nFirst iteration took " + stopwatch.Elapsed + "\n+=+ Iterating over dataset again +=+ Dramatic pause..."); ArrayUtils.Range(1, 10).ToList().ForEach(i => { Thread.Sleep(500); Console.Write("."); }); stopwatch.Restart(); foreach (var block in iterator.Yield(new CpuFloat32Handler(), sigma)) { //PrintFormattedBlock(block, PrintUtils.AsciiGreyscalePalette); } Console.WriteLine("Second iteration took " + stopwatch.Elapsed); } private static void SampleDotProduct() { IComputationHandler handler = new CpuFloat32Handler(); INDArray a = handler.NDArray(ArrayUtils.Range(1, 6), 3, 2); INDArray b = handler.NDArray(ArrayUtils.Range(1, 6), 2, 3); Console.WriteLine("a = " + ArrayUtils.ToString(a, (ADNDArray<float>.ToStringElement)null, 0, true)); Console.WriteLine("b = " + ArrayUtils.ToString(b, (ADNDArray<float>.ToStringElement)null, 0, true)); INDArray c = handler.Dot(a, b); Console.WriteLine("c = " + ArrayUtils.ToString(c, (ADNDArray<float>.ToStringElement)null, 0, true)); } private static void SamplePermute() { IComputationHandler handler = new CudaFloat32Handler(); INDArray array = handler.NDArray(ArrayUtils.Range(1, 30), 5L, 3L, 2L); Console.WriteLine(ArrayUtils.ToString(array, (ADNDArray<float>.ToStringElement)null, 0, true)); array.PermuteSelf(1, 0, 2); Console.WriteLine(ArrayUtils.ToString(array, (ADNDArray<float>.ToStringElement)null, 0, true)); } private static void SampleNetworkMerging() { SigmaEnvironment sigma = SigmaEnvironment.Create("merge_test"); ITrainer[] trainers = new ITrainer[3]; int[] constantValues = { 2, 10, 70 }; //INetworkMerger merger = new WeightedNetworkMerger(10d, 10d, 1d); INetworkMerger merger = new AverageNetworkMerger(); IComputationHandler handler = new CpuFloat32Handler(); for (int i = 0; i < trainers.Length; i++) { trainers[i] = sigma.CreateTrainer($"MergeTrainer{i}"); trainers[i].Network = new Network($"{i}"); trainers[i].Network.Architecture = InputLayer.Construct(2, 2) + ElementwiseLayer.Construct(2 * 2) + OutputLayer.Construct(2); trainers[i].AddInitialiser("*.weights", new ConstantValueInitialiser(constantValues[i])); trainers[i].Operator = new CpuMultithreadedOperator(5); trainers[i].Initialise(handler); } foreach (ITrainer trainer in trainers) { Console.WriteLine(trainer.Network.Registry); } merger.AddMergeEntry("layers.*.weights"); merger.Merge(trainers[1].Network, trainers[2].Network, handler); Console.WriteLine("*******************"); foreach (ITrainer trainer in trainers) { Console.WriteLine(trainer.Network.Registry); } } private static void SampleNetworkArchitecture() { SigmaEnvironment sigma = SigmaEnvironment.Create("test"); IComputationHandler handler = new CpuFloat32Handler(); ITrainer trainer = sigma.CreateTrainer("test_trainer"); trainer.Network = new Network(); trainer.Network.Architecture = InputLayer.Construct(2, 2) + ElementwiseLayer.Construct(2 * 2) + FullyConnectedLayer.Construct(2) + 2 * (FullyConnectedLayer.Construct(4) + FullyConnectedLayer.Construct(2)) + OutputLayer.Construct(2); trainer.Network = (INetwork)trainer.Network.DeepCopy(); trainer.Operator = new CpuMultithreadedOperator(10); trainer.AddInitialiser("*.weights", new GaussianInitialiser(standardDeviation: 0.1f)); trainer.AddInitialiser("*.bias*", new GaussianInitialiser(standardDeviation: 0.01f, mean: 0.03f)); trainer.Initialise(handler); trainer.Network = (INetwork)trainer.Network.DeepCopy(); Console.WriteLine(trainer.Network.Registry); IRegistryResolver resolver = new RegistryResolver(trainer.Network.Registry); Console.WriteLine("==============="); object[] weights = resolver.ResolveGet<object>("layers.*.weights"); Console.WriteLine(string.Join("\n", weights)); Console.WriteLine("==============="); //foreach (ILayerBuffer buffer in trainer.Network.YieldLayerBuffersOrdered()) //{ // Console.WriteLine(buffer.Layer.Name + ": "); // Console.WriteLine("inputs:"); // foreach (string input in buffer.Inputs.Keys) // { // Console.WriteLine($"\t{input}: {buffer.Inputs[input].GetHashCode()}"); // } // Console.WriteLine("outputs:"); // foreach (string output in buffer.Outputs.Keys) // { // Console.WriteLine($"\t{output}: {buffer.Outputs[output].GetHashCode()}"); // } //} } private static void SampleAutomaticDifferentiation() { IComputationHandler handler = new CpuFloat32Handler(); uint traceTag = handler.BeginTrace(); INDArray array = handler.NDArray(ArrayUtils.Range(1, 6), 2, 3); INumber a = handler.Number(-1.0f), b = handler.Number(3.0f); INumber c = handler.Trace(handler.Add(a, b), traceTag); INumber d = handler.Multiply(c, 2); INumber e = handler.Add(d, handler.Add(c, 3)); INumber f = handler.SquareRoot(e); array = handler.Multiply(array, f); INumber cost = handler.Divide(handler.Sum(array), array.Length); Console.WriteLine("cost: " + cost); handler.ComputeDerivativesTo(cost); Console.WriteLine(array); Console.WriteLine("f: " + handler.GetDerivative(f)); Console.WriteLine("e: " + handler.GetDerivative(e)); Console.WriteLine("d: " + handler.GetDerivative(d)); Console.WriteLine("c: " + handler.GetDerivative(c)); Console.WriteLine("a: " + handler.GetDerivative(array)); handler.ComputeDerivativesTo(f); Console.WriteLine("f: " + handler.GetDerivative(f)); Console.WriteLine("e: " + handler.GetDerivative(e)); Console.WriteLine("d: " + handler.GetDerivative(d)); Console.WriteLine("c: " + handler.GetDerivative(c)); Console.WriteLine("a: " + handler.GetDerivative(array)); } private static void SampleLoadExtractIterate() { SigmaEnvironment sigma = SigmaEnvironment.Create("test"); sigma.Prepare(); //var irisReader = new CsvRecordReader(new MultiSource(new FileSource("iris.data"), new UrlSource("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"))); //IRecordExtractor irisExtractor = irisReader.Extractor("inputs2", new[] { 0, 3 }, "targets2", 4).AddValueMapping(4, "Iris-setosa", "Iris-versicolor", "Iris-virginica"); //irisExtractor = irisExtractor.Preprocess(new OneHotPreprocessor(sectionName: "targets2", minValue: 0, maxValue: 2), new NormalisingPreprocessor(sectionNames: "inputs2", minInputValue: 0, maxInputValue: 6)); ByteRecordReader mnistImageReader = new ByteRecordReader(headerLengthBytes: 16, recordSizeBytes: 28 * 28, source: new CompressedSource(new MultiSource(new FileSource("train-images-idx3-ubyte.gz"), new UrlSource("http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz")))); IRecordExtractor mnistImageExtractor = mnistImageReader.Extractor("inputs", new[] { 0L, 0L }, new[] { 28L, 28L }).Preprocess(new NormalisingPreprocessor(0, 255)); ByteRecordReader mnistTargetReader = new ByteRecordReader(headerLengthBytes: 8, recordSizeBytes: 1, source: new CompressedSource(new MultiSource(new FileSource("train-labels-idx1-ubyte.gz"), new UrlSource("http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz")))); IRecordExtractor mnistTargetExtractor = mnistTargetReader.Extractor("targets", new[] { 0L }, new[] { 1L }).Preprocess(new OneHotPreprocessor(minValue: 0, maxValue: 9)); IComputationHandler handler = new CpuFloat32Handler(); ExtractedDataset dataset = new ExtractedDataset("mnist-training", ExtractedDataset.BlockSizeAuto, mnistImageExtractor, mnistTargetExtractor); IDataset[] slices = dataset.SplitRecordwise(0.8, 0.2); IDataset trainingData = slices[0]; IDataset validationData = slices[1]; MinibatchIterator trainingIterator = new MinibatchIterator(1, trainingData); MinibatchIterator validationIterator = new MinibatchIterator(1, validationData); while (true) { foreach (var block in trainingIterator.Yield(handler, sigma)) { Thread.Sleep(100); PrintFormattedBlock(block, PrintUtils.AsciiGreyscalePalette); Thread.Sleep(1000); } } //Random random = new Random(); //INDArray array = new ADNDArray<float>(3, 1, 2, 2); //new GaussianInitialiser(0.05, 0.05).Initialise(array, Handler, random); //Console.WriteLine(array); //new ConstantValueInitialiser(1).Initialise(array, Handler, random); //Console.WriteLine(array); //dataset.InvalidateAndClearCaches(); } private static void PrintFormatted(INDArray array, char[] palette) { string blockString = ArrayUtils.ToString<float>(array, e => palette[(int)(e * (palette.Length - 1))].ToString(), maxDimensionNewLine: 0, printSeperator: false); Console.WriteLine(blockString); } private static void PrintFormattedBlock(IDictionary<string, INDArray> block, char[] palette) { foreach (string name in block.Keys) { string blockString = ArrayUtils.ToString<float>(block[name], e => palette[(int)(e * (palette.Length - 1))].ToString(), maxDimensionNewLine: 0, printSeperator: false); Console.WriteLine($"[{name}]=\n" + blockString); } } } }
// ************************ CommentRemover : char ************************ // // Parse : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // '/' = ParseCommentType, default = Parse; // ParseCommentType : '/' = ParseSingleComment, '*' = ParseMultiComment, // default = IllegalCommentType; // ParseSingleComment : '\r' = Parse, '\n' = Parse, default = ParseSingleComment; // ParseMultiComment : '*' = TestEndMultiComment, default = ParseMultiComment; // TestEndMultiComment : '/' = EndComment, default = ParseMultiComment; // EndComment : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // '/' = ParseCommentType, default = Parse; // ParseSingleQuotes : ParseSingleQuotes ? Parse : IllegalSingleQuotes; // ParseDoubleQuotes : ParseDoubleQuotes ? Parse : IllegalDoubleQuotes; // // IllegalCommentType : default = decline; // IllegalSingleQuotes : default = decline; // IllegalDoubleQuotes : default = decline; // // // This file was automatically generated from a tool that converted the // above state machine definition into this state machine class. // Any changes to this code will be replaced the next time the code is generated. using System; using System.Collections.Generic; namespace test { public class CommentRemover { public enum States { Parse = 0, ParseCommentType = 1, ParseSingleComment = 2, ParseMultiComment = 3, TestEndMultiComment = 4, EndComment = 5, ParseSingleQuotes = 6, ParseDoubleQuotes = 7, IllegalCommentType = 8, IllegalSingleQuotes = 9, IllegalDoubleQuotes = 10, } private States? state = null; public States? CurrentState { get { return state; } } private char currentCommand; public char CurrentCommand { get { return currentCommand; } } private bool reset = false; private Action<char> onParseState = null; private Action<char> onParseEnter = null; private Action<char> onParseExit = null; private Action<char> onParseCommentTypeState = null; private Action<char> onParseCommentTypeEnter = null; private Action<char> onParseCommentTypeExit = null; private Action<char> onParseSingleCommentState = null; private Action<char> onParseSingleCommentEnter = null; private Action<char> onParseSingleCommentExit = null; private Action<char> onParseMultiCommentState = null; private Action<char> onParseMultiCommentEnter = null; private Action<char> onParseMultiCommentExit = null; private Action<char> onTestEndMultiCommentState = null; private Action<char> onTestEndMultiCommentEnter = null; private Action<char> onTestEndMultiCommentExit = null; private Action<char> onEndCommentState = null; private Action<char> onEndCommentEnter = null; private Action<char> onEndCommentExit = null; private Action<char> onParseSingleQuotesState = null; private Action<char> onParseSingleQuotesEnter = null; private Action<char> onParseSingleQuotesExit = null; private Action<char> onParseDoubleQuotesState = null; private Action<char> onParseDoubleQuotesEnter = null; private Action<char> onParseDoubleQuotesExit = null; private Action<char> onIllegalCommentTypeState = null; private Action<char> onIllegalCommentTypeEnter = null; private Action<char> onIllegalCommentTypeExit = null; private Action<char> onIllegalSingleQuotesState = null; private Action<char> onIllegalSingleQuotesEnter = null; private Action<char> onIllegalSingleQuotesExit = null; private Action<char> onIllegalDoubleQuotesState = null; private Action<char> onIllegalDoubleQuotesEnter = null; private Action<char> onIllegalDoubleQuotesExit = null; private Action<char> onAccept = null; private Action<char> onDecline = null; private Action<char> onEnd = null; public readonly ParseSingleQuotes ParseSingleQuotesMachine = new ParseSingleQuotes(); public readonly ParseDoubleQuotes ParseDoubleQuotesMachine = new ParseDoubleQuotes(); public bool? Input(Queue<char> data) { if (reset) state = null; bool? result = null; if (data == null) return null; bool? nestResult; Reset: reset = false; switch (state) { case null: if (data.Count > 0) { state = States.Parse; goto ResumeParse; } else goto End; case States.Parse: goto ResumeParse; case States.ParseCommentType: goto ResumeParseCommentType; case States.ParseSingleComment: goto ResumeParseSingleComment; case States.ParseMultiComment: goto ResumeParseMultiComment; case States.TestEndMultiComment: goto ResumeTestEndMultiComment; case States.EndComment: goto ResumeEndComment; case States.ParseSingleQuotes: goto ResumeParseSingleQuotes; case States.ParseDoubleQuotes: goto ResumeParseDoubleQuotes; case States.IllegalCommentType: goto ResumeIllegalCommentType; case States.IllegalSingleQuotes: goto ResumeIllegalSingleQuotes; case States.IllegalDoubleQuotes: goto ResumeIllegalDoubleQuotes; } EnterParse: state = States.Parse; if (onParseEnter != null) onParseEnter(currentCommand); Parse: if (onParseState != null) onParseState(currentCommand); ResumeParse: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onParseExit != null) onParseExit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onParseExit != null) onParseExit(currentCommand); goto EnterParseDoubleQuotes; case '/': if (onParseExit != null) onParseExit(currentCommand); goto EnterParseCommentType; default: goto Parse; } EnterParseCommentType: state = States.ParseCommentType; if (onParseCommentTypeEnter != null) onParseCommentTypeEnter(currentCommand); if (onParseCommentTypeState != null) onParseCommentTypeState(currentCommand); ResumeParseCommentType: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '/': if (onParseCommentTypeExit != null) onParseCommentTypeExit(currentCommand); goto EnterParseSingleComment; case '*': if (onParseCommentTypeExit != null) onParseCommentTypeExit(currentCommand); goto EnterParseMultiComment; default: if (onParseCommentTypeExit != null) onParseCommentTypeExit(currentCommand); goto EnterIllegalCommentType; } EnterParseSingleComment: state = States.ParseSingleComment; if (onParseSingleCommentEnter != null) onParseSingleCommentEnter(currentCommand); ParseSingleComment: if (onParseSingleCommentState != null) onParseSingleCommentState(currentCommand); ResumeParseSingleComment: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\r': if (onParseSingleCommentExit != null) onParseSingleCommentExit(currentCommand); goto EnterParse; case '\n': if (onParseSingleCommentExit != null) onParseSingleCommentExit(currentCommand); goto EnterParse; default: goto ParseSingleComment; } EnterParseMultiComment: state = States.ParseMultiComment; if (onParseMultiCommentEnter != null) onParseMultiCommentEnter(currentCommand); ParseMultiComment: if (onParseMultiCommentState != null) onParseMultiCommentState(currentCommand); ResumeParseMultiComment: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '*': if (onParseMultiCommentExit != null) onParseMultiCommentExit(currentCommand); goto EnterTestEndMultiComment; default: goto ParseMultiComment; } EnterTestEndMultiComment: state = States.TestEndMultiComment; if (onTestEndMultiCommentEnter != null) onTestEndMultiCommentEnter(currentCommand); if (onTestEndMultiCommentState != null) onTestEndMultiCommentState(currentCommand); ResumeTestEndMultiComment: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '/': if (onTestEndMultiCommentExit != null) onTestEndMultiCommentExit(currentCommand); goto EnterEndComment; default: if (onTestEndMultiCommentExit != null) onTestEndMultiCommentExit(currentCommand); goto EnterParseMultiComment; } EnterEndComment: state = States.EndComment; if (onEndCommentEnter != null) onEndCommentEnter(currentCommand); if (onEndCommentState != null) onEndCommentState(currentCommand); ResumeEndComment: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onEndCommentExit != null) onEndCommentExit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onEndCommentExit != null) onEndCommentExit(currentCommand); goto EnterParseDoubleQuotes; case '/': if (onEndCommentExit != null) onEndCommentExit(currentCommand); goto EnterParseCommentType; default: if (onEndCommentExit != null) onEndCommentExit(currentCommand); goto EnterParse; } EnterParseSingleQuotes: state = States.ParseSingleQuotes; if (onParseSingleQuotesEnter != null) onParseSingleQuotesEnter(currentCommand); if (onParseSingleQuotesState != null) onParseSingleQuotesState(currentCommand); ResumeParseSingleQuotes: nestResult = ParseSingleQuotesMachine.Input(data); switch (nestResult) { case null: goto End; case true: if (onParseSingleQuotesExit != null) onParseSingleQuotesExit(ParseSingleQuotesMachine.CurrentCommand); goto EnterParse; case false: if (onParseSingleQuotesExit != null) onParseSingleQuotesExit(ParseSingleQuotesMachine.CurrentCommand); goto EnterIllegalSingleQuotes; } EnterParseDoubleQuotes: state = States.ParseDoubleQuotes; if (onParseDoubleQuotesEnter != null) onParseDoubleQuotesEnter(currentCommand); if (onParseDoubleQuotesState != null) onParseDoubleQuotesState(currentCommand); ResumeParseDoubleQuotes: nestResult = ParseDoubleQuotesMachine.Input(data); switch (nestResult) { case null: goto End; case true: if (onParseDoubleQuotesExit != null) onParseDoubleQuotesExit(ParseDoubleQuotesMachine.CurrentCommand); goto EnterParse; case false: if (onParseDoubleQuotesExit != null) onParseDoubleQuotesExit(ParseDoubleQuotesMachine.CurrentCommand); goto EnterIllegalDoubleQuotes; } EnterIllegalCommentType: state = States.IllegalCommentType; if (onIllegalCommentTypeEnter != null) onIllegalCommentTypeEnter(currentCommand); if (onIllegalCommentTypeState != null) onIllegalCommentTypeState(currentCommand); ResumeIllegalCommentType: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { default: if (onIllegalCommentTypeExit != null) onIllegalCommentTypeExit(currentCommand); goto Decline; } EnterIllegalSingleQuotes: state = States.IllegalSingleQuotes; if (onIllegalSingleQuotesEnter != null) onIllegalSingleQuotesEnter(currentCommand); if (onIllegalSingleQuotesState != null) onIllegalSingleQuotesState(currentCommand); ResumeIllegalSingleQuotes: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { default: if (onIllegalSingleQuotesExit != null) onIllegalSingleQuotesExit(currentCommand); goto Decline; } EnterIllegalDoubleQuotes: state = States.IllegalDoubleQuotes; if (onIllegalDoubleQuotesEnter != null) onIllegalDoubleQuotesEnter(currentCommand); if (onIllegalDoubleQuotesState != null) onIllegalDoubleQuotesState(currentCommand); ResumeIllegalDoubleQuotes: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { default: if (onIllegalDoubleQuotesExit != null) onIllegalDoubleQuotesExit(currentCommand); goto Decline; } Decline: result = false; state = null; if (onDecline != null) onDecline(currentCommand); goto End; End: if (onEnd != null) onEnd(currentCommand); if (reset) { goto Reset; } return result; } public void AddOnParse(Action<char> addedFunc) { onParseState += addedFunc; } public void AddOnParseCommentType(Action<char> addedFunc) { onParseCommentTypeState += addedFunc; } public void AddOnParseSingleComment(Action<char> addedFunc) { onParseSingleCommentState += addedFunc; } public void AddOnParseMultiComment(Action<char> addedFunc) { onParseMultiCommentState += addedFunc; } public void AddOnTestEndMultiComment(Action<char> addedFunc) { onTestEndMultiCommentState += addedFunc; } public void AddOnEndComment(Action<char> addedFunc) { onEndCommentState += addedFunc; } public void AddOnParseSingleQuotes(Action<char> addedFunc) { AddOnParseSingleQuotesEnter(addedFunc); ParseSingleQuotesMachine.addOnAllStates(addedFunc); } public void AddOnParseDoubleQuotes(Action<char> addedFunc) { AddOnParseDoubleQuotesEnter(addedFunc); ParseDoubleQuotesMachine.addOnAllStates(addedFunc); } public void AddOnIllegalCommentType(Action<char> addedFunc) { onIllegalCommentTypeState += addedFunc; } public void AddOnIllegalSingleQuotes(Action<char> addedFunc) { onIllegalSingleQuotesState += addedFunc; } public void AddOnIllegalDoubleQuotes(Action<char> addedFunc) { onIllegalDoubleQuotesState += addedFunc; } public void AddOnParseEnter(Action<char> addedFunc) { onParseEnter += addedFunc; } public void AddOnParseCommentTypeEnter(Action<char> addedFunc) { onParseCommentTypeEnter += addedFunc; } public void AddOnParseSingleCommentEnter(Action<char> addedFunc) { onParseSingleCommentEnter += addedFunc; } public void AddOnParseMultiCommentEnter(Action<char> addedFunc) { onParseMultiCommentEnter += addedFunc; } public void AddOnTestEndMultiCommentEnter(Action<char> addedFunc) { onTestEndMultiCommentEnter += addedFunc; } public void AddOnEndCommentEnter(Action<char> addedFunc) { onEndCommentEnter += addedFunc; } public void AddOnParseSingleQuotesEnter(Action<char> addedFunc) { onParseSingleQuotesEnter += addedFunc; } public void AddOnParseDoubleQuotesEnter(Action<char> addedFunc) { onParseDoubleQuotesEnter += addedFunc; } public void AddOnIllegalCommentTypeEnter(Action<char> addedFunc) { onIllegalCommentTypeEnter += addedFunc; } public void AddOnIllegalSingleQuotesEnter(Action<char> addedFunc) { onIllegalSingleQuotesEnter += addedFunc; } public void AddOnIllegalDoubleQuotesEnter(Action<char> addedFunc) { onIllegalDoubleQuotesEnter += addedFunc; } public void AddOnParseExit(Action<char> addedFunc) { onParseExit += addedFunc; } public void AddOnParseCommentTypeExit(Action<char> addedFunc) { onParseCommentTypeExit += addedFunc; } public void AddOnParseSingleCommentExit(Action<char> addedFunc) { onParseSingleCommentExit += addedFunc; } public void AddOnParseMultiCommentExit(Action<char> addedFunc) { onParseMultiCommentExit += addedFunc; } public void AddOnTestEndMultiCommentExit(Action<char> addedFunc) { onTestEndMultiCommentExit += addedFunc; } public void AddOnEndCommentExit(Action<char> addedFunc) { onEndCommentExit += addedFunc; } public void AddOnParseSingleQuotesExit(Action<char> addedFunc) { onParseSingleQuotesExit += addedFunc; } public void AddOnParseDoubleQuotesExit(Action<char> addedFunc) { onParseDoubleQuotesExit += addedFunc; } public void AddOnIllegalCommentTypeExit(Action<char> addedFunc) { onIllegalCommentTypeExit += addedFunc; } public void AddOnIllegalSingleQuotesExit(Action<char> addedFunc) { onIllegalSingleQuotesExit += addedFunc; } public void AddOnIllegalDoubleQuotesExit(Action<char> addedFunc) { onIllegalDoubleQuotesExit += addedFunc; } public void AddOnAccept(Action<char> addedFunc) { onAccept += addedFunc; } public void AddOnDecline(Action<char> addedFunc) { onDecline += addedFunc; } public void AddOnEnd(Action<char> addedFunc) { onEnd += addedFunc; } internal void addOnAllStates( Action<char> addedFunc ) { onParseState += addedFunc; onParseCommentTypeState += addedFunc; onParseSingleCommentState += addedFunc; onParseMultiCommentState += addedFunc; onTestEndMultiCommentState += addedFunc; onEndCommentState += addedFunc; AddOnParseSingleQuotes(addedFunc); AddOnParseDoubleQuotes(addedFunc); onIllegalCommentTypeState += addedFunc; onIllegalSingleQuotesState += addedFunc; onIllegalDoubleQuotesState += addedFunc; } public void ResetStateOnEnd() { state = null; reset = true; ParseSingleQuotesMachine.ResetStateOnEnd(); ParseDoubleQuotesMachine.ResetStateOnEnd(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using NUnit.Framework; using Newtonsoft.Json; using GlmSharp; // ReSharper disable InconsistentNaming namespace GlmSharpTest.Generated.Swizzle { [TestFixture] public class ComplexSwizzleVec2Test { [Test] public void XYZW() { { var ov = new cvec2(new Complex(5.5d, 6.5d), new Complex(-5.5d, -6.5d)); var v = ov.swizzle.xx; Assert.AreEqual(new Complex(5.5d, 6.5d), v.x); Assert.AreEqual(new Complex(5.5d, 6.5d), v.y); } { var ov = new cvec2(new Complex(1.5d, 6.5d), new Complex(-5d, 9d)); var v = ov.swizzle.xxx; Assert.AreEqual(new Complex(1.5d, 6.5d), v.x); Assert.AreEqual(new Complex(1.5d, 6.5d), v.y); Assert.AreEqual(new Complex(1.5d, 6.5d), v.z); } { var ov = new cvec2(new Complex(8.5d, 9.5d), new Complex(-3d, -9.5d)); var v = ov.swizzle.xxxx; Assert.AreEqual(new Complex(8.5d, 9.5d), v.x); Assert.AreEqual(new Complex(8.5d, 9.5d), v.y); Assert.AreEqual(new Complex(8.5d, 9.5d), v.z); Assert.AreEqual(new Complex(8.5d, 9.5d), v.w); } { var ov = new cvec2(new Complex(-1d, -6d), new Complex(-6.5d, 3.5d)); var v = ov.swizzle.xxxy; Assert.AreEqual(new Complex(-1d, -6d), v.x); Assert.AreEqual(new Complex(-1d, -6d), v.y); Assert.AreEqual(new Complex(-1d, -6d), v.z); Assert.AreEqual(new Complex(-6.5d, 3.5d), v.w); } { var ov = new cvec2(new Complex(5d, 6.5d), new Complex(-2d, -6d)); var v = ov.swizzle.xxy; Assert.AreEqual(new Complex(5d, 6.5d), v.x); Assert.AreEqual(new Complex(5d, 6.5d), v.y); Assert.AreEqual(new Complex(-2d, -6d), v.z); } { var ov = new cvec2(new Complex(2d, -3.5d), new Complex(-7.5d, 9.5d)); var v = ov.swizzle.xxyx; Assert.AreEqual(new Complex(2d, -3.5d), v.x); Assert.AreEqual(new Complex(2d, -3.5d), v.y); Assert.AreEqual(new Complex(-7.5d, 9.5d), v.z); Assert.AreEqual(new Complex(2d, -3.5d), v.w); } { var ov = new cvec2(new Complex(7.5d, -4.5d), new Complex(-4.5d, -2.5d)); var v = ov.swizzle.xxyy; Assert.AreEqual(new Complex(7.5d, -4.5d), v.x); Assert.AreEqual(new Complex(7.5d, -4.5d), v.y); Assert.AreEqual(new Complex(-4.5d, -2.5d), v.z); Assert.AreEqual(new Complex(-4.5d, -2.5d), v.w); } { var ov = new cvec2(new Complex(-1.5d, 1.0), new Complex(6d, -5.5d)); var v = ov.swizzle.xy; Assert.AreEqual(new Complex(-1.5d, 1.0), v.x); Assert.AreEqual(new Complex(6d, -5.5d), v.y); } { var ov = new cvec2(new Complex(1.5d, -6d), new Complex(-1.5d, -8.5d)); var v = ov.swizzle.xyx; Assert.AreEqual(new Complex(1.5d, -6d), v.x); Assert.AreEqual(new Complex(-1.5d, -8.5d), v.y); Assert.AreEqual(new Complex(1.5d, -6d), v.z); } { var ov = new cvec2(new Complex(6.5d, -4d), new Complex(-8.5d, 5.5d)); var v = ov.swizzle.xyxx; Assert.AreEqual(new Complex(6.5d, -4d), v.x); Assert.AreEqual(new Complex(-8.5d, 5.5d), v.y); Assert.AreEqual(new Complex(6.5d, -4d), v.z); Assert.AreEqual(new Complex(6.5d, -4d), v.w); } { var ov = new cvec2(new Complex(-3d, 2.5d), new Complex(-7.5d, 9.5d)); var v = ov.swizzle.xyxy; Assert.AreEqual(new Complex(-3d, 2.5d), v.x); Assert.AreEqual(new Complex(-7.5d, 9.5d), v.y); Assert.AreEqual(new Complex(-3d, 2.5d), v.z); Assert.AreEqual(new Complex(-7.5d, 9.5d), v.w); } { var ov = new cvec2(new Complex(7d, -0.5d), new Complex(0.0, -2d)); var v = ov.swizzle.xyy; Assert.AreEqual(new Complex(7d, -0.5d), v.x); Assert.AreEqual(new Complex(0.0, -2d), v.y); Assert.AreEqual(new Complex(0.0, -2d), v.z); } { var ov = new cvec2(new Complex(-2.5d, -5d), new Complex(-7d, 1.0)); var v = ov.swizzle.xyyx; Assert.AreEqual(new Complex(-2.5d, -5d), v.x); Assert.AreEqual(new Complex(-7d, 1.0), v.y); Assert.AreEqual(new Complex(-7d, 1.0), v.z); Assert.AreEqual(new Complex(-2.5d, -5d), v.w); } { var ov = new cvec2(new Complex(6.5d, -8d), new Complex(6.5d, -0.5d)); var v = ov.swizzle.xyyy; Assert.AreEqual(new Complex(6.5d, -8d), v.x); Assert.AreEqual(new Complex(6.5d, -0.5d), v.y); Assert.AreEqual(new Complex(6.5d, -0.5d), v.z); Assert.AreEqual(new Complex(6.5d, -0.5d), v.w); } { var ov = new cvec2(new Complex(-2.5d, -9d), new Complex(-6.5d, 6d)); var v = ov.swizzle.yx; Assert.AreEqual(new Complex(-6.5d, 6d), v.x); Assert.AreEqual(new Complex(-2.5d, -9d), v.y); } { var ov = new cvec2(new Complex(0.5d, 2.5d), new Complex(4d, -1d)); var v = ov.swizzle.yxx; Assert.AreEqual(new Complex(4d, -1d), v.x); Assert.AreEqual(new Complex(0.5d, 2.5d), v.y); Assert.AreEqual(new Complex(0.5d, 2.5d), v.z); } { var ov = new cvec2(new Complex(4.5d, 3d), new Complex(-9d, 6.5d)); var v = ov.swizzle.yxxx; Assert.AreEqual(new Complex(-9d, 6.5d), v.x); Assert.AreEqual(new Complex(4.5d, 3d), v.y); Assert.AreEqual(new Complex(4.5d, 3d), v.z); Assert.AreEqual(new Complex(4.5d, 3d), v.w); } { var ov = new cvec2(new Complex(-3d, 8d), new Complex(4d, 0.0)); var v = ov.swizzle.yxxy; Assert.AreEqual(new Complex(4d, 0.0), v.x); Assert.AreEqual(new Complex(-3d, 8d), v.y); Assert.AreEqual(new Complex(-3d, 8d), v.z); Assert.AreEqual(new Complex(4d, 0.0), v.w); } { var ov = new cvec2(new Complex(5d, -2d), new Complex(5d, 9d)); var v = ov.swizzle.yxy; Assert.AreEqual(new Complex(5d, 9d), v.x); Assert.AreEqual(new Complex(5d, -2d), v.y); Assert.AreEqual(new Complex(5d, 9d), v.z); } { var ov = new cvec2(new Complex(9.5d, -9d), new Complex(5d, -4.5d)); var v = ov.swizzle.yxyx; Assert.AreEqual(new Complex(5d, -4.5d), v.x); Assert.AreEqual(new Complex(9.5d, -9d), v.y); Assert.AreEqual(new Complex(5d, -4.5d), v.z); Assert.AreEqual(new Complex(9.5d, -9d), v.w); } { var ov = new cvec2(new Complex(2.5d, -1d), new Complex(-6.5d, -3.5d)); var v = ov.swizzle.yxyy; Assert.AreEqual(new Complex(-6.5d, -3.5d), v.x); Assert.AreEqual(new Complex(2.5d, -1d), v.y); Assert.AreEqual(new Complex(-6.5d, -3.5d), v.z); Assert.AreEqual(new Complex(-6.5d, -3.5d), v.w); } { var ov = new cvec2(new Complex(7d, -9d), new Complex(-3.5d, 7d)); var v = ov.swizzle.yy; Assert.AreEqual(new Complex(-3.5d, 7d), v.x); Assert.AreEqual(new Complex(-3.5d, 7d), v.y); } { var ov = new cvec2(new Complex(-2.5d, 3d), new Complex(-4.5d, 0.5d)); var v = ov.swizzle.yyx; Assert.AreEqual(new Complex(-4.5d, 0.5d), v.x); Assert.AreEqual(new Complex(-4.5d, 0.5d), v.y); Assert.AreEqual(new Complex(-2.5d, 3d), v.z); } { var ov = new cvec2(new Complex(2d, 2d), new Complex(-7d, 2d)); var v = ov.swizzle.yyxx; Assert.AreEqual(new Complex(-7d, 2d), v.x); Assert.AreEqual(new Complex(-7d, 2d), v.y); Assert.AreEqual(new Complex(2d, 2d), v.z); Assert.AreEqual(new Complex(2d, 2d), v.w); } { var ov = new cvec2(new Complex(0.0, -5d), new Complex(-7.5d, -9d)); var v = ov.swizzle.yyxy; Assert.AreEqual(new Complex(-7.5d, -9d), v.x); Assert.AreEqual(new Complex(-7.5d, -9d), v.y); Assert.AreEqual(new Complex(0.0, -5d), v.z); Assert.AreEqual(new Complex(-7.5d, -9d), v.w); } { var ov = new cvec2(new Complex(2.5d, 7d), new Complex(-1d, -1d)); var v = ov.swizzle.yyy; Assert.AreEqual(new Complex(-1d, -1d), v.x); Assert.AreEqual(new Complex(-1d, -1d), v.y); Assert.AreEqual(new Complex(-1d, -1d), v.z); } { var ov = new cvec2(new Complex(-7d, 2.5d), new Complex(-2.5d, -8.5d)); var v = ov.swizzle.yyyx; Assert.AreEqual(new Complex(-2.5d, -8.5d), v.x); Assert.AreEqual(new Complex(-2.5d, -8.5d), v.y); Assert.AreEqual(new Complex(-2.5d, -8.5d), v.z); Assert.AreEqual(new Complex(-7d, 2.5d), v.w); } { var ov = new cvec2(new Complex(8d, 1.5d), new Complex(-3d, 5.5d)); var v = ov.swizzle.yyyy; Assert.AreEqual(new Complex(-3d, 5.5d), v.x); Assert.AreEqual(new Complex(-3d, 5.5d), v.y); Assert.AreEqual(new Complex(-3d, 5.5d), v.z); Assert.AreEqual(new Complex(-3d, 5.5d), v.w); } } [Test] public void RGBA() { { var ov = new cvec2(new Complex(-9.5d, -5.5d), new Complex(-4d, -2d)); var v = ov.swizzle.rr; Assert.AreEqual(new Complex(-9.5d, -5.5d), v.x); Assert.AreEqual(new Complex(-9.5d, -5.5d), v.y); } { var ov = new cvec2(new Complex(-9.5d, 4d), new Complex(9.5d, -3.5d)); var v = ov.swizzle.rrr; Assert.AreEqual(new Complex(-9.5d, 4d), v.x); Assert.AreEqual(new Complex(-9.5d, 4d), v.y); Assert.AreEqual(new Complex(-9.5d, 4d), v.z); } { var ov = new cvec2(new Complex(-5.5d, -0.5d), new Complex(9.5d, 8d)); var v = ov.swizzle.rrrr; Assert.AreEqual(new Complex(-5.5d, -0.5d), v.x); Assert.AreEqual(new Complex(-5.5d, -0.5d), v.y); Assert.AreEqual(new Complex(-5.5d, -0.5d), v.z); Assert.AreEqual(new Complex(-5.5d, -0.5d), v.w); } { var ov = new cvec2(new Complex(3.5d, 8d), new Complex(-5d, 7d)); var v = ov.swizzle.rrrg; Assert.AreEqual(new Complex(3.5d, 8d), v.x); Assert.AreEqual(new Complex(3.5d, 8d), v.y); Assert.AreEqual(new Complex(3.5d, 8d), v.z); Assert.AreEqual(new Complex(-5d, 7d), v.w); } { var ov = new cvec2(new Complex(5.5d, -4.5d), new Complex(5.5d, 1.5d)); var v = ov.swizzle.rrg; Assert.AreEqual(new Complex(5.5d, -4.5d), v.x); Assert.AreEqual(new Complex(5.5d, -4.5d), v.y); Assert.AreEqual(new Complex(5.5d, 1.5d), v.z); } { var ov = new cvec2(new Complex(-6d, 0.5d), new Complex(-9d, -6d)); var v = ov.swizzle.rrgr; Assert.AreEqual(new Complex(-6d, 0.5d), v.x); Assert.AreEqual(new Complex(-6d, 0.5d), v.y); Assert.AreEqual(new Complex(-9d, -6d), v.z); Assert.AreEqual(new Complex(-6d, 0.5d), v.w); } { var ov = new cvec2(new Complex(5.5d, -6d), new Complex(-2.5d, 0.5d)); var v = ov.swizzle.rrgg; Assert.AreEqual(new Complex(5.5d, -6d), v.x); Assert.AreEqual(new Complex(5.5d, -6d), v.y); Assert.AreEqual(new Complex(-2.5d, 0.5d), v.z); Assert.AreEqual(new Complex(-2.5d, 0.5d), v.w); } { var ov = new cvec2(new Complex(1.0, -5d), new Complex(-8d, -7.5d)); var v = ov.swizzle.rg; Assert.AreEqual(new Complex(1.0, -5d), v.x); Assert.AreEqual(new Complex(-8d, -7.5d), v.y); } { var ov = new cvec2(new Complex(8d, -0.5d), new Complex(-0.5d, 0.0)); var v = ov.swizzle.rgr; Assert.AreEqual(new Complex(8d, -0.5d), v.x); Assert.AreEqual(new Complex(-0.5d, 0.0), v.y); Assert.AreEqual(new Complex(8d, -0.5d), v.z); } { var ov = new cvec2(new Complex(-0.5d, 2.5d), new Complex(0.5d, 1.5d)); var v = ov.swizzle.rgrr; Assert.AreEqual(new Complex(-0.5d, 2.5d), v.x); Assert.AreEqual(new Complex(0.5d, 1.5d), v.y); Assert.AreEqual(new Complex(-0.5d, 2.5d), v.z); Assert.AreEqual(new Complex(-0.5d, 2.5d), v.w); } { var ov = new cvec2(new Complex(3d, 2d), new Complex(-1.5d, -6.5d)); var v = ov.swizzle.rgrg; Assert.AreEqual(new Complex(3d, 2d), v.x); Assert.AreEqual(new Complex(-1.5d, -6.5d), v.y); Assert.AreEqual(new Complex(3d, 2d), v.z); Assert.AreEqual(new Complex(-1.5d, -6.5d), v.w); } { var ov = new cvec2(new Complex(-2.5d, -7d), new Complex(-6d, -8.5d)); var v = ov.swizzle.rgg; Assert.AreEqual(new Complex(-2.5d, -7d), v.x); Assert.AreEqual(new Complex(-6d, -8.5d), v.y); Assert.AreEqual(new Complex(-6d, -8.5d), v.z); } { var ov = new cvec2(new Complex(-1d, 2.5d), new Complex(-1d, 0.5d)); var v = ov.swizzle.rggr; Assert.AreEqual(new Complex(-1d, 2.5d), v.x); Assert.AreEqual(new Complex(-1d, 0.5d), v.y); Assert.AreEqual(new Complex(-1d, 0.5d), v.z); Assert.AreEqual(new Complex(-1d, 2.5d), v.w); } { var ov = new cvec2(new Complex(-4d, 3d), new Complex(-0.5d, 7.5d)); var v = ov.swizzle.rggg; Assert.AreEqual(new Complex(-4d, 3d), v.x); Assert.AreEqual(new Complex(-0.5d, 7.5d), v.y); Assert.AreEqual(new Complex(-0.5d, 7.5d), v.z); Assert.AreEqual(new Complex(-0.5d, 7.5d), v.w); } { var ov = new cvec2(new Complex(-2.5d, 6d), new Complex(4d, 5d)); var v = ov.swizzle.gr; Assert.AreEqual(new Complex(4d, 5d), v.x); Assert.AreEqual(new Complex(-2.5d, 6d), v.y); } { var ov = new cvec2(new Complex(7d, -1.5d), new Complex(-8d, -3.5d)); var v = ov.swizzle.grr; Assert.AreEqual(new Complex(-8d, -3.5d), v.x); Assert.AreEqual(new Complex(7d, -1.5d), v.y); Assert.AreEqual(new Complex(7d, -1.5d), v.z); } { var ov = new cvec2(new Complex(5.5d, -4.5d), new Complex(7d, -2d)); var v = ov.swizzle.grrr; Assert.AreEqual(new Complex(7d, -2d), v.x); Assert.AreEqual(new Complex(5.5d, -4.5d), v.y); Assert.AreEqual(new Complex(5.5d, -4.5d), v.z); Assert.AreEqual(new Complex(5.5d, -4.5d), v.w); } { var ov = new cvec2(new Complex(5d, 0.5d), new Complex(7.5d, -2.5d)); var v = ov.swizzle.grrg; Assert.AreEqual(new Complex(7.5d, -2.5d), v.x); Assert.AreEqual(new Complex(5d, 0.5d), v.y); Assert.AreEqual(new Complex(5d, 0.5d), v.z); Assert.AreEqual(new Complex(7.5d, -2.5d), v.w); } { var ov = new cvec2(new Complex(-1.5d, -0.5d), new Complex(-3d, -4.5d)); var v = ov.swizzle.grg; Assert.AreEqual(new Complex(-3d, -4.5d), v.x); Assert.AreEqual(new Complex(-1.5d, -0.5d), v.y); Assert.AreEqual(new Complex(-3d, -4.5d), v.z); } { var ov = new cvec2(new Complex(-0.5d, -7.5d), new Complex(1.0, -7.5d)); var v = ov.swizzle.grgr; Assert.AreEqual(new Complex(1.0, -7.5d), v.x); Assert.AreEqual(new Complex(-0.5d, -7.5d), v.y); Assert.AreEqual(new Complex(1.0, -7.5d), v.z); Assert.AreEqual(new Complex(-0.5d, -7.5d), v.w); } { var ov = new cvec2(new Complex(3.5d, 6d), new Complex(-3.5d, 2d)); var v = ov.swizzle.grgg; Assert.AreEqual(new Complex(-3.5d, 2d), v.x); Assert.AreEqual(new Complex(3.5d, 6d), v.y); Assert.AreEqual(new Complex(-3.5d, 2d), v.z); Assert.AreEqual(new Complex(-3.5d, 2d), v.w); } { var ov = new cvec2(new Complex(-4d, 3d), new Complex(5.5d, 8d)); var v = ov.swizzle.gg; Assert.AreEqual(new Complex(5.5d, 8d), v.x); Assert.AreEqual(new Complex(5.5d, 8d), v.y); } { var ov = new cvec2(new Complex(-9.5d, -7d), new Complex(-5.5d, 8.5d)); var v = ov.swizzle.ggr; Assert.AreEqual(new Complex(-5.5d, 8.5d), v.x); Assert.AreEqual(new Complex(-5.5d, 8.5d), v.y); Assert.AreEqual(new Complex(-9.5d, -7d), v.z); } { var ov = new cvec2(new Complex(4d, 1.0), new Complex(4.5d, 0.5d)); var v = ov.swizzle.ggrr; Assert.AreEqual(new Complex(4.5d, 0.5d), v.x); Assert.AreEqual(new Complex(4.5d, 0.5d), v.y); Assert.AreEqual(new Complex(4d, 1.0), v.z); Assert.AreEqual(new Complex(4d, 1.0), v.w); } { var ov = new cvec2(new Complex(0.5d, -6d), new Complex(-5.5d, 3d)); var v = ov.swizzle.ggrg; Assert.AreEqual(new Complex(-5.5d, 3d), v.x); Assert.AreEqual(new Complex(-5.5d, 3d), v.y); Assert.AreEqual(new Complex(0.5d, -6d), v.z); Assert.AreEqual(new Complex(-5.5d, 3d), v.w); } { var ov = new cvec2(new Complex(1.0, 8.5d), new Complex(7.5d, 6d)); var v = ov.swizzle.ggg; Assert.AreEqual(new Complex(7.5d, 6d), v.x); Assert.AreEqual(new Complex(7.5d, 6d), v.y); Assert.AreEqual(new Complex(7.5d, 6d), v.z); } { var ov = new cvec2(new Complex(-6.5d, 7.5d), new Complex(-4.5d, 9d)); var v = ov.swizzle.gggr; Assert.AreEqual(new Complex(-4.5d, 9d), v.x); Assert.AreEqual(new Complex(-4.5d, 9d), v.y); Assert.AreEqual(new Complex(-4.5d, 9d), v.z); Assert.AreEqual(new Complex(-6.5d, 7.5d), v.w); } { var ov = new cvec2(new Complex(4d, 0.5d), new Complex(2.5d, 0.0)); var v = ov.swizzle.gggg; Assert.AreEqual(new Complex(2.5d, 0.0), v.x); Assert.AreEqual(new Complex(2.5d, 0.0), v.y); Assert.AreEqual(new Complex(2.5d, 0.0), v.z); Assert.AreEqual(new Complex(2.5d, 0.0), v.w); } } [Test] public void InlineXYZW() { { var v0 = new cvec2(new Complex(7.5d, -7d), new Complex(-5d, -6.5d)); var v1 = new cvec2(new Complex(-7.5d, -1d), new Complex(3.5d, -5d)); var v2 = v0.xy; v0.xy = v1; var v3 = v0.xy; Assert.AreEqual(v1, v3); Assert.AreEqual(new Complex(-7.5d, -1d), v0.x); Assert.AreEqual(new Complex(3.5d, -5d), v0.y); Assert.AreEqual(new Complex(7.5d, -7d), v2.x); Assert.AreEqual(new Complex(-5d, -6.5d), v2.y); } } [Test] public void InlineRGBA() { { var v0 = new cvec2(new Complex(3d, -9.5d), new Complex(-1d, 1.0)); var v1 = new Complex(9d, 6d); var v2 = v0.r; v0.r = v1; var v3 = v0.r; Assert.AreEqual(v1, v3); Assert.AreEqual(new Complex(9d, 6d), v0.x); Assert.AreEqual(new Complex(-1d, 1.0), v0.y); Assert.AreEqual(new Complex(3d, -9.5d), v2); } { var v0 = new cvec2(new Complex(-4.5d, -4d), new Complex(5.5d, -9d)); var v1 = new Complex(7d, 3.5d); var v2 = v0.g; v0.g = v1; var v3 = v0.g; Assert.AreEqual(v1, v3); Assert.AreEqual(new Complex(-4.5d, -4d), v0.x); Assert.AreEqual(new Complex(7d, 3.5d), v0.y); Assert.AreEqual(new Complex(5.5d, -9d), v2); } { var v0 = new cvec2(new Complex(0.5d, 9.5d), new Complex(-7d, -6.5d)); var v1 = new cvec2(new Complex(-6d, -4.5d), new Complex(-3d, 8.5d)); var v2 = v0.rg; v0.rg = v1; var v3 = v0.rg; Assert.AreEqual(v1, v3); Assert.AreEqual(new Complex(-6d, -4.5d), v0.x); Assert.AreEqual(new Complex(-3d, 8.5d), v0.y); Assert.AreEqual(new Complex(0.5d, 9.5d), v2.x); Assert.AreEqual(new Complex(-7d, -6.5d), v2.y); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System.Text; using Npgsql; namespace OpenSim.Data.PGSQL { public class PGSQLGenericTableHandler<T> : PGSqlFramework where T : class, new() { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_ConnectionString; protected PGSQLManager m_database; //used for parameter type translation protected Dictionary<string, FieldInfo> m_Fields = new Dictionary<string, FieldInfo>(); protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>(); protected List<string> m_ColumnNames = null; protected string m_Realm; protected FieldInfo m_DataField = null; protected virtual Assembly Assembly { get { return GetType().Assembly; } } public PGSQLGenericTableHandler(string connectionString, string realm, string storeName) : base(connectionString) { m_Realm = realm; m_ConnectionString = connectionString; if (storeName != String.Empty) { using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) { conn.Open(); Migration m = new Migration(conn, GetType().Assembly, storeName); m.Update(); } } m_database = new PGSQLManager(m_ConnectionString); Type t = typeof(T); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); LoadFieldTypes(); if (fields.Length == 0) return; foreach (FieldInfo f in fields) { if (f.Name != "Data") m_Fields[f.Name] = f; else m_DataField = f; } } private void LoadFieldTypes() { m_FieldTypes = new Dictionary<string, string>(); string query = string.Format(@"select column_name,data_type from INFORMATION_SCHEMA.COLUMNS where table_name = lower('{0}'); ", m_Realm); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { conn.Open(); using (NpgsqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { // query produces 0 to many rows of single column, so always add the first item in each row m_FieldTypes.Add((string)rdr[0], (string)rdr[1]); } } } } private void CheckColumnNames(NpgsqlDataReader reader) { if (m_ColumnNames != null) return; m_ColumnNames = new List<string>(); DataTable schemaTable = reader.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { if (row["ColumnName"] != null && (!m_Fields.ContainsKey(row["ColumnName"].ToString()))) m_ColumnNames.Add(row["ColumnName"].ToString()); } } // TODO GET CONSTRAINTS FROM POSTGRESQL private List<string> GetConstraints() { List<string> constraints = new List<string>(); string query = string.Format(@"SELECT kcu.column_name FROM information_schema.table_constraints tc LEFT JOIN information_schema.key_column_usage kcu ON tc.constraint_catalog = kcu.constraint_catalog AND tc.constraint_schema = kcu.constraint_schema AND tc.constraint_name = kcu.constraint_name LEFT JOIN information_schema.referential_constraints rc ON tc.constraint_catalog = rc.constraint_catalog AND tc.constraint_schema = rc.constraint_schema AND tc.constraint_name = rc.constraint_name LEFT JOIN information_schema.constraint_column_usage ccu ON rc.unique_constraint_catalog = ccu.constraint_catalog AND rc.unique_constraint_schema = ccu.constraint_schema AND rc.unique_constraint_name = ccu.constraint_name where tc.table_name = lower('{0}') and lower(tc.constraint_type) in ('primary key') and kcu.column_name is not null ;", m_Realm); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { conn.Open(); using (NpgsqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { // query produces 0 to many rows of single column, so always add the first item in each row constraints.Add((string)rdr[0]); } } return constraints; } } public virtual T[] Get(string field, string key) { return Get(new string[] { field }, new string[] { key }); } public virtual T[] Get(string[] fields, string[] keys) { if (fields.Length != keys.Length) return new T[0]; List<string> terms = new List<string>(); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { for (int i = 0; i < fields.Length; i++) { if ( m_FieldTypes.ContainsKey(fields[i]) ) cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]])); else cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i])); terms.Add(" \"" + fields[i] + "\" = :" + fields[i]); } string where = String.Join(" AND ", terms.ToArray()); string query = String.Format("SELECT * FROM {0} WHERE {1}", m_Realm, where); cmd.Connection = conn; cmd.CommandText = query; conn.Open(); return DoQuery(cmd); } } protected T[] DoQuery(NpgsqlCommand cmd) { List<T> result = new List<T>(); if (cmd.Connection == null) { cmd.Connection = new NpgsqlConnection(m_connectionString); } if (cmd.Connection.State == ConnectionState.Closed) { cmd.Connection.Open(); } using (NpgsqlDataReader reader = cmd.ExecuteReader()) { if (reader == null) return new T[0]; CheckColumnNames(reader); while (reader.Read()) { T row = new T(); foreach (string name in m_Fields.Keys) { if (m_Fields[name].GetValue(row) is bool) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v != 0 ? true : false); } else if (m_Fields[name].GetValue(row) is UUID) { UUID uuid = UUID.Zero; UUID.TryParse(reader[name].ToString(), out uuid); m_Fields[name].SetValue(row, uuid); } else if (m_Fields[name].GetValue(row) is int) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v); } else { m_Fields[name].SetValue(row, reader[name]); } } if (m_DataField != null) { Dictionary<string, string> data = new Dictionary<string, string>(); foreach (string col in m_ColumnNames) { data[col] = reader[col].ToString(); if (data[col] == null) data[col] = String.Empty; } m_DataField.SetValue(row, data); } result.Add(row); } return result.ToArray(); } } public virtual T[] Get(string where) { using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { string query = String.Format("SELECT * FROM {0} WHERE {1}", m_Realm, where); cmd.Connection = conn; cmd.CommandText = query; //m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where); conn.Open(); return DoQuery(cmd); } } public virtual T[] Get(string where, NpgsqlParameter parameter) { using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { string query = String.Format("SELECT * FROM {0} WHERE {1}", m_Realm, where); cmd.Connection = conn; cmd.CommandText = query; //m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where); cmd.Parameters.Add(parameter); conn.Open(); return DoQuery(cmd); } } public virtual bool Store(T row) { List<string> constraintFields = GetConstraints(); List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>(); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { StringBuilder query = new StringBuilder(); List<String> names = new List<String>(); List<String> values = new List<String>(); foreach (FieldInfo fi in m_Fields.Values) { names.Add(fi.Name); values.Add(":" + fi.Name); // Temporarily return more information about what field is unexpectedly null for // http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the // InventoryTransferModule or we may be required to substitute a DBNull here. if (fi.GetValue(row) == null) throw new NullReferenceException( string.Format( "[PGSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null", fi.Name, row)); if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name)) { constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString() )); } if (m_FieldTypes.ContainsKey(fi.Name)) cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row), m_FieldTypes[fi.Name])); else cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row))); } if (m_DataField != null) { Dictionary<string, string> data = (Dictionary<string, string>)m_DataField.GetValue(row); foreach (KeyValuePair<string, string> kvp in data) { if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key)) { constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key)); } names.Add(kvp.Key); values.Add(":" + kvp.Key); if (m_FieldTypes.ContainsKey(kvp.Key)) cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value, m_FieldTypes[kvp.Key])); else cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value)); } } query.AppendFormat("UPDATE {0} SET ", m_Realm); int i = 0; for (i = 0; i < names.Count - 1; i++) { query.AppendFormat("\"{0}\" = {1}, ", names[i], values[i]); } query.AppendFormat("\"{0}\" = {1} ", names[i], values[i]); if (constraints.Count > 0) { List<string> terms = new List<string>(); for (int j = 0; j < constraints.Count; j++) { terms.Add(String.Format(" \"{0}\" = :{0}", constraints[j].Key)); } string where = String.Join(" AND ", terms.ToArray()); query.AppendFormat(" WHERE {0} ", where); } cmd.Connection = conn; cmd.CommandText = query.ToString(); conn.Open(); if (cmd.ExecuteNonQuery() > 0) { //m_log.WarnFormat("[PGSQLGenericTable]: Updating {0}", m_Realm); return true; } else { // assume record has not yet been inserted query = new StringBuilder(); query.AppendFormat("INSERT INTO {0} (\"", m_Realm); query.Append(String.Join("\",\"", names.ToArray())); query.Append("\") values (" + String.Join(",", values.ToArray()) + ")"); cmd.Connection = conn; cmd.CommandText = query.ToString(); // m_log.WarnFormat("[PGSQLGenericTable]: Inserting into {0} sql {1}", m_Realm, cmd.CommandText); if (conn.State != ConnectionState.Open) conn.Open(); if (cmd.ExecuteNonQuery() > 0) return true; } return false; } } public virtual bool Delete(string field, string key) { return Delete(new string[] { field }, new string[] { key }); } public virtual bool Delete(string[] fields, string[] keys) { if (fields.Length != keys.Length) return false; List<string> terms = new List<string>(); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { for (int i = 0; i < fields.Length; i++) { if (m_FieldTypes.ContainsKey(fields[i])) cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]])); else cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i])); terms.Add(" \"" + fields[i] + "\" = :" + fields[i]); } string where = String.Join(" AND ", terms.ToArray()); string query = String.Format("DELETE FROM {0} WHERE {1}", m_Realm, where); cmd.Connection = conn; cmd.CommandText = query; conn.Open(); if (cmd.ExecuteNonQuery() > 0) { //m_log.Warn("[PGSQLGenericTable]: " + deleteCommand); return true; } return false; } } public long GetCount(string field, string key) { return GetCount(new string[] { field }, new string[] { key }); } public long GetCount(string[] fields, string[] keys) { if (fields.Length != keys.Length) return 0; List<string> terms = new List<string>(); using (NpgsqlCommand cmd = new NpgsqlCommand()) { for (int i = 0; i < fields.Length; i++) { cmd.Parameters.AddWithValue(fields[i], keys[i]); terms.Add("\"" + fields[i] + "\" = :" + fields[i]); } string where = String.Join(" and ", terms.ToArray()); string query = String.Format("select count(*) from {0} where {1}", m_Realm, where); cmd.CommandText = query; Object result = DoQueryScalar(cmd); return Convert.ToInt64(result); } } public long GetCount(string where) { using (NpgsqlCommand cmd = new NpgsqlCommand()) { string query = String.Format("select count(*) from {0} where {1}", m_Realm, where); cmd.CommandText = query; object result = DoQueryScalar(cmd); return Convert.ToInt64(result); } } public object DoQueryScalar(NpgsqlCommand cmd) { using (NpgsqlConnection dbcon = new NpgsqlConnection(m_ConnectionString)) { dbcon.Open(); cmd.Connection = dbcon; return cmd.ExecuteScalar(); } } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using Moq.Properties; namespace Moq { internal static class Extensions { /// <summary> /// Gets the default value for the specified type. This is the Reflection counterpart of C#'s <see langword="default"/> operator. /// </summary> public static object GetDefaultValue(this Type type) { return type.IsValueType ? Activator.CreateInstance(type) : null; } public static object InvokePreserveStack(this Delegate del, params object[] args) { try { return del.DynamicInvoke(args); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } public static bool IsExtensionMethod(this MethodInfo method) { return method.IsStatic && method.IsDefined(typeof(ExtensionAttribute)); } public static bool IsPropertyGetter(this MethodInfo method) { return method.IsSpecialName && method.Name.StartsWith("get_", StringComparison.Ordinal); } public static bool IsPropertyIndexerGetter(this MethodInfo method) { return method.IsSpecialName && method.Name.StartsWith("get_Item", StringComparison.Ordinal); } public static bool IsPropertyIndexerSetter(this MethodInfo method) { return method.IsSpecialName && method.Name.StartsWith("set_Item", StringComparison.Ordinal); } public static bool IsPropertySetter(this MethodInfo method) { return method.IsSpecialName && method.Name.StartsWith("set_", StringComparison.Ordinal); } public static bool IsPropertyAccessor(this MethodInfo method) { return method.IsPropertyGetter() || method.IsPropertySetter(); } public static bool IsPropertyIndexerAccessor(this MethodInfo method) { return method.IsPropertyIndexerGetter() || method.IsPropertyIndexerSetter(); } // NOTE: The following two methods used to first check whether `method.IsSpecialName` was set // as a quick guard against non-event accessor methods. This was removed in commit 44070a90 // to "increase compatibility with F# and COM". More specifically: // // 1. COM does not really have events. Some COM interop assemblies define events, but do not // mark those with the IL `specialname` flag. See: // - https://code.google.com/archive/p/moq/issues/226 // - the `Microsoft.Office.Interop.Word.ApplicationEvents4_Event` interface in Office PIA // // 2. F# does not mark abstract events' accessors with the IL `specialname` flag. See: // - https://github.com/Microsoft/visualfsharp/issues/5834 // - https://code.google.com/archive/p/moq/issues/238 // - the unit tests in `FSharpCompatibilityFixture` public static bool LooksLikeEventAttach(this MethodInfo method) { return method.Name.StartsWith("add_", StringComparison.Ordinal); } public static bool LooksLikeEventDetach(this MethodInfo method) { return method.Name.StartsWith("remove_", StringComparison.Ordinal); } /// <summary> /// Tests if a type is a delegate type (subclasses <see cref="Delegate" />). /// </summary> public static bool IsDelegate(this Type t) { return t.IsSubclassOf(typeof(Delegate)); } public static void ThrowIfNotMockeable(this MemberExpression memberAccess) { if (memberAccess.Member is FieldInfo) throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.FieldsNotSupported, memberAccess.ToStringFixed())); } public static bool IsMockeable(this Type typeToMock) { // A value type does not match any of these three // condition and therefore returns false. return typeToMock.IsInterface || typeToMock.IsAbstract || typeToMock.IsDelegate() || (typeToMock.IsClass && !typeToMock.IsSealed); } public static bool CanOverride(this MethodBase method) { return method.IsVirtual && !method.IsFinal && !method.IsPrivate; } public static bool CanOverrideGet(this PropertyInfo property) { if (property.CanRead) { var getter = property.GetGetMethod(true); return getter != null && getter.CanOverride(); } return false; } public static bool CanOverrideSet(this PropertyInfo property) { if (property.CanWrite) { var setter = property.GetSetMethod(true); return setter != null && setter.CanOverride(); } return false; } public static IEnumerable<MethodInfo> GetMethods(this Type type, string name) { return type.GetMember(name).OfType<MethodInfo>(); } public static bool CompareTo<TTypes, TOtherTypes>(this TTypes types, TOtherTypes otherTypes, bool exact) where TTypes : IReadOnlyList<Type> where TOtherTypes : IReadOnlyList<Type> { var count = otherTypes.Count; if (types.Count != count) { return false; } if (exact) { for (int i = 0; i < count; ++i) { if (types[i] != otherTypes[i]) { return false; } } } else { for (int i = 0; i < count; ++i) { if (types[i].IsAssignableFrom(otherTypes[i]) == false) { return false; } } } return true; } public static ParameterTypes GetParameterTypes(this MethodInfo method) { return new ParameterTypes(method.GetParameters()); } public static bool CompareParameterTypesTo<TOtherTypes>(this Delegate function, TOtherTypes otherTypes) where TOtherTypes : IReadOnlyList<Type> { var method = function.GetMethodInfo(); if (method.GetParameterTypes().CompareTo(otherTypes, exact: false)) { // the backing method for the literal delegate is compatible, DynamicInvoke(...) will succeed return true; } // it's possible for the .Method property (backing method for a delegate) to have // differing parameter types than the actual delegate signature. This occurs in C# when // an instance delegate invocation is created for an extension method (bundled with a receiver) // or at times for DLR code generation paths because the CLR is optimized for instance methods. var invokeMethod = GetInvokeMethodFromUntypedDelegateCallback(function); if (invokeMethod != null && invokeMethod.GetParameterTypes().CompareTo(otherTypes, exact: false)) { // the Invoke(...) method is compatible instead. DynamicInvoke(...) will succeed. return true; } // Neither the literal backing field of the delegate was compatible // nor the delegate invoke signature. return false; } private static MethodInfo GetInvokeMethodFromUntypedDelegateCallback(Delegate callback) { // Section 8.9.3 of 4th Ed ECMA 335 CLI spec requires delegates to have an 'Invoke' method. // However, there is not a requirement for 'public', or for it to be unambiguous. try { return callback.GetType().GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } catch (AmbiguousMatchException) { return null; } } public static bool TryFind(this IEnumerable<Setup> innerMockSetups, InvocationShape expectation, out Setup setup) { Debug.Assert(innerMockSetups.All(s => s.ReturnsInnerMock(out _))); foreach (Setup innerMockSetup in innerMockSetups) { if (innerMockSetup.Expectation.Equals(expectation)) { setup = innerMockSetup; return true; } } setup = default; return false; } public static bool TryFind(this IEnumerable<Setup> innerMockSetups, Invocation invocation, out Setup setup) { foreach (Setup innerMockSetup in innerMockSetups) { if (innerMockSetup.Matches(invocation)) { setup = innerMockSetup; return true; } } setup = default; return false; } } }
/* **************************************************************************** * * 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 * ironpy@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. * * ***************************************************************************/ using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.Project { /// <summary> /// All public properties on Nodeproperties or derived classes are assumed to be used by Automation by default. /// Set this attribute to false on Properties that should not be visible for Automation. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class AutomationBrowsableAttribute : System.Attribute { public AutomationBrowsableAttribute(bool browsable) { this.browsable = browsable; } public bool Browsable { get { return this.browsable; } } private bool browsable; } /// <summary> /// To create your own localizable node properties, subclass this and add public properties /// decorated with your own localized display name, category and description attributes. /// </summary> [CLSCompliant(false), ComVisible(true)] public class NodeProperties : LocalizableProperties, ISpecifyPropertyPages, IVsGetCfgProvider, IVsSpecifyProjectDesignerPages, EnvDTE80.IInternalExtenderProvider, IVsBrowseObject { #region fields private HierarchyNode node; #endregion #region properties [Browsable(false)] [AutomationBrowsable(false)] public HierarchyNode Node { get { return this.node; } } /// <summary> /// Used by Property Pages Frame to set it's title bar. The Caption of the Hierarchy Node is returned. /// </summary> [Browsable(false)] [AutomationBrowsable(false)] public virtual string Name { get { return this.node.Caption; } } #endregion #region ctors public NodeProperties(HierarchyNode node) { if(node == null) { throw new ArgumentNullException("node"); } this.node = node; } #endregion #region ISpecifyPropertyPages methods public virtual void GetPages(CAUUID[] pages) { this.GetCommonPropertyPages(pages); } #endregion #region IVsSpecifyProjectDesignerPages /// <summary> /// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration independent. /// </summary> /// <param name="pages">The pages to return.</param> /// <returns></returns> public virtual int GetProjectDesignerPages(CAUUID[] pages) { this.GetCommonPropertyPages(pages); return VSConstants.S_OK; } #endregion #region IVsGetCfgProvider methods public virtual int GetCfgProvider(out IVsCfgProvider p) { p = null; return VSConstants.E_NOTIMPL; } #endregion #region IVsBrowseObject methods /// <summary> /// Maps back to the hierarchy or project item object corresponding to the browse object. /// </summary> /// <param name="hier">Reference to the hierarchy object.</param> /// <param name="itemid">Reference to the project item.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid) { if(this.node == null) { throw new InvalidOperationException(); } hier = HierarchyNode.GetOuterHierarchy(this.node.ProjectMgr); itemid = this.node.ID; return VSConstants.S_OK; } #endregion #region overridden methods /// <summary> /// Get the Caption of the Hierarchy Node instance. If Caption is null or empty we delegate to base /// </summary> /// <returns>Caption of Hierarchy node instance</returns> public override string GetComponentName() { string caption = this.Node.Caption; if(string.IsNullOrEmpty(caption)) { return base.GetComponentName(); } else { return caption; } } #endregion #region helper methods protected string GetProperty(string name, string def) { string a = this.Node.ItemNode.GetMetadata(name); return (a == null) ? def : a; } protected void SetProperty(string name, string value) { this.Node.ItemNode.SetMetadata(name, value); } /// <summary> /// Retrieves the common property pages. The NodeProperties is the BrowseObject and that will be called to support /// configuration independent properties. /// </summary> /// <param name="pages">The pages to return.</param> private void GetCommonPropertyPages(CAUUID[] pages) { // We do not check whether the supportsProjectDesigner is set to false on the ProjectNode. // We rely that the caller knows what to call on us. if(pages == null) { throw new ArgumentNullException("pages"); } if(pages.Length == 0) { throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages"); } // Only the project should show the property page the rest should show the project properties. if(this.node != null && (this.node is ProjectNode)) { // Retrieve the list of guids from hierarchy properties. // Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy string guidsList = String.Empty; IVsHierarchy hierarchy = HierarchyNode.GetOuterHierarchy(this.Node.ProjectMgr); object variant = null; ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList, out variant)); guidsList = (string)variant; Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList); if(guids == null || guids.Length == 0) { pages[0] = new CAUUID(); pages[0].cElems = 0; } else { pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids); } } else { pages[0] = new CAUUID(); pages[0].cElems = 0; } } #endregion #region IInternalExtenderProvider Members bool EnvDTE80.IInternalExtenderProvider.CanExtend(string extenderCATID, string extenderName, object extendeeObject) { EnvDTE80.IInternalExtenderProvider outerHierarchy = HierarchyNode.GetOuterHierarchy(this.Node) as EnvDTE80.IInternalExtenderProvider; if(outerHierarchy != null) { return outerHierarchy.CanExtend(extenderCATID, extenderName, extendeeObject); } return false; } object EnvDTE80.IInternalExtenderProvider.GetExtender(string extenderCATID, string extenderName, object extendeeObject, EnvDTE.IExtenderSite extenderSite, int cookie) { EnvDTE80.IInternalExtenderProvider outerHierarchy = HierarchyNode.GetOuterHierarchy(this.Node) as EnvDTE80.IInternalExtenderProvider; if(outerHierarchy != null) { return outerHierarchy.GetExtender(extenderCATID, extenderName, extendeeObject, extenderSite, cookie); } return null; } object EnvDTE80.IInternalExtenderProvider.GetExtenderNames(string extenderCATID, object extendeeObject) { EnvDTE80.IInternalExtenderProvider outerHierarchy = HierarchyNode.GetOuterHierarchy(this.Node) as EnvDTE80.IInternalExtenderProvider; if(outerHierarchy != null) { return outerHierarchy.GetExtenderNames(extenderCATID, extendeeObject); } return null; } #endregion #region ExtenderSupport [Browsable(false)] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CATID")] public virtual string ExtenderCATID { get { Guid catid = this.Node.ProjectMgr.GetCATIDForType(this.GetType()); if(Guid.Empty.CompareTo(catid) == 0) { return null; } return catid.ToString("B"); } } [Browsable(false)] public object ExtenderNames() { EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders)); Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object"); if(extenderService == null) { throw new InvalidOperationException(); } return extenderService.GetExtenderNames(this.ExtenderCATID, this); } public object Extender(string extenderName) { EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders)); Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object"); if(extenderService == null) { throw new InvalidOperationException(); } return extenderService.GetExtender(this.ExtenderCATID, extenderName, this); } #endregion } [CLSCompliant(false), ComVisible(true)] public class FileNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Advanced)] [LocDisplayName(SR.BuildAction)] [SRDescriptionAttribute(SR.BuildActionDescription)] public virtual BuildAction BuildAction { get { string value = this.Node.ItemNode.ItemName; if(value == null || value.Length == 0) { return BuildAction.None; } return (BuildAction)Enum.Parse(typeof(BuildAction), value); } set { this.Node.ItemNode.ItemName = value.ToString(); } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] public string FileName { get { return this.Node.Caption; } set { this.Node.SetEditLabel(value); } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public string FullPath { get { return this.Node.Url; } } #region non-browsable properties - used for automation only [Browsable(false)] public string Extension { get { return Path.GetExtension(this.Node.Caption); } } #endregion #endregion #region ctors public FileNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture); } #endregion } [CLSCompliant(false), ComVisible(true)] public class DependentFileNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Advanced)] [LocDisplayName(SR.BuildAction)] [SRDescriptionAttribute(SR.BuildActionDescription)] public virtual BuildAction BuildAction { get { string value = this.Node.ItemNode.ItemName; if(value == null || value.Length == 0) { return BuildAction.None; } return (BuildAction)Enum.Parse(typeof(BuildAction), value); } set { this.Node.ItemNode.ItemName = value.ToString(); } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] public virtual string FileName { get { return this.Node.Caption; } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public string FullPath { get { return this.Node.Url; } } #endregion #region ctors public DependentFileNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture); } #endregion } [CLSCompliant(false), ComVisible(true)] public class SingleFileGeneratorNodeProperties : FileNodeProperties { #region fields private EventHandler<HierarchyNodeEventArgs> onCustomToolChanged; private EventHandler<HierarchyNodeEventArgs> onCustomToolNameSpaceChanged; private string _customTool = ""; private string _customToolNamespace = ""; #endregion #region custom tool events internal event EventHandler<HierarchyNodeEventArgs> OnCustomToolChanged { add { onCustomToolChanged += value; } remove { onCustomToolChanged -= value; } } internal event EventHandler<HierarchyNodeEventArgs> OnCustomToolNameSpaceChanged { add { onCustomToolNameSpaceChanged += value; } remove { onCustomToolNameSpaceChanged -= value; } } #endregion #region properties [SRCategoryAttribute(SR.Advanced)] [LocDisplayName(SR.CustomTool)] [SRDescriptionAttribute(SR.CustomToolDescription)] public virtual string CustomTool { get { _customTool = this.Node.ItemNode.GetMetadata(ProjectFileConstants.Generator); return _customTool; } set { _customTool = value; if(!string.IsNullOrEmpty(_customTool)) { this.Node.ItemNode.SetMetadata(ProjectFileConstants.Generator, _customTool); HierarchyNodeEventArgs args = new HierarchyNodeEventArgs(this.Node); if(onCustomToolChanged != null) { onCustomToolChanged(this.Node, args); } } } } [SRCategoryAttribute(VisualStudio.Project.SR.Advanced)] [LocDisplayName(SR.CustomToolNamespace)] [SRDescriptionAttribute(SR.CustomToolNamespaceDescription)] public virtual string CustomToolNamespace { get { _customToolNamespace = this.Node.ItemNode.GetMetadata(ProjectFileConstants.CustomToolNamespace); return _customToolNamespace; } set { _customToolNamespace = value; if(!string.IsNullOrEmpty(_customToolNamespace)) { this.Node.ItemNode.SetMetadata(ProjectFileConstants.CustomToolNamespace, _customToolNamespace); HierarchyNodeEventArgs args = new HierarchyNodeEventArgs(this.Node); if(onCustomToolNameSpaceChanged != null) { onCustomToolNameSpaceChanged(this.Node, args); } } } } #endregion #region ctors public SingleFileGeneratorNodeProperties(HierarchyNode node) : base(node) { } #endregion } [CLSCompliant(false), ComVisible(true)] public class ProjectNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.ProjectFolder)] [SRDescriptionAttribute(SR.ProjectFolderDescription)] [AutomationBrowsable(false)] public string ProjectFolder { get { return this.Node.ProjectMgr.ProjectFolder; } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.ProjectFile)] [SRDescriptionAttribute(SR.ProjectFileDescription)] [AutomationBrowsable(false)] public string ProjectFile { get { return this.Node.ProjectMgr.ProjectFile; } set { this.Node.ProjectMgr.ProjectFile = value; } } #region non-browsable properties - used for automation only [Browsable(false)] public string FileName { get { return this.Node.ProjectMgr.ProjectFile; } set { this.Node.ProjectMgr.ProjectFile = value; } } [Browsable(false)] public string FullPath { get { string fullPath = this.Node.ProjectMgr.ProjectFolder; if(!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { return fullPath + Path.DirectorySeparatorChar; } else { return fullPath; } } } #endregion #endregion #region ctors public ProjectNodeProperties(ProjectNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.ProjectProperties, CultureInfo.CurrentUICulture); } /// <summary> /// ICustomTypeDescriptor.GetEditor /// To enable the "Property Pages" button on the properties browser /// the browse object (project properties) need to be unmanaged /// or it needs to provide an editor of type ComponentEditor. /// </summary> /// <param name="editorBaseType">Type of the editor</param> /// <returns>Editor</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification="The service provider is used by the PropertiesEditorLauncher")] public override object GetEditor(Type editorBaseType) { // Override the scenario where we are asked for a ComponentEditor // as this is how the Properties Browser calls us if(editorBaseType == typeof(ComponentEditor)) { IOleServiceProvider sp; ErrorHandler.ThrowOnFailure(this.Node.GetSite(out sp)); return new PropertiesEditorLauncher(new ServiceProvider(sp)); } return base.GetEditor(editorBaseType); } public override int GetCfgProvider(out IVsCfgProvider p) { if(this.Node != null && this.Node.ProjectMgr != null) { return this.Node.ProjectMgr.GetCfgProvider(out p); } return base.GetCfgProvider(out p); } #endregion } [CLSCompliant(false), ComVisible(true)] public class FolderNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FolderName)] [SRDescriptionAttribute(SR.FolderNameDescription)] [AutomationBrowsable(false)] public string FolderName { get { return this.Node.Caption; } set { this.Node.SetEditLabel(value); this.Node.ReDraw(UIHierarchyElement.Caption); } } #region properties - used for automation only [Browsable(false)] [AutomationBrowsable(true)] public string FileName { get { return this.Node.Caption; } set { this.Node.SetEditLabel(value); } } [Browsable(false)] [AutomationBrowsable(true)] public string FullPath { get { string fullPath = this.Node.GetMkDocument(); if(!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { return fullPath + Path.DirectorySeparatorChar; } else { return fullPath; } } } #endregion #endregion #region ctors public FolderNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.FolderProperties, CultureInfo.CurrentUICulture); } #endregion } [CLSCompliant(false), ComVisible(true)] public class ReferenceNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.RefName)] [SRDescriptionAttribute(SR.RefNameDescription)] [Browsable(true)] [AutomationBrowsable(true)] public override string Name { get { return this.Node.Caption; } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.CopyToLocal)] [SRDescriptionAttribute(SR.CopyToLocalDescription)] public bool CopyToLocal { get { string copyLocal = this.GetProperty(ProjectFileConstants.Private, "False"); if(copyLocal == null || copyLocal.Length == 0) return true; return bool.Parse(copyLocal); } set { this.SetProperty(ProjectFileConstants.Private, value.ToString()); } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public virtual string FullPath { get { return this.Node.Url; } } #endregion #region ctors public ReferenceNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.ReferenceProperties, CultureInfo.CurrentUICulture); } #endregion } [ComVisible(true)] public class ProjectReferencesProperties : ReferenceNodeProperties { #region ctors public ProjectReferencesProperties(ProjectReferenceNode node) : base(node) { } #endregion #region overriden methods public override string FullPath { get { return ((ProjectReferenceNode)Node).ReferencedProjectOutputPath; } } #endregion } }
// Copyright (c) 2012-2014 Sharpex2D - Kevin Scholz (ThuCommix) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using Sharpex2D.Network.Logic; using Sharpex2D.Network.Packages; using Sharpex2D.Network.Packages.System; namespace Sharpex2D.Network.Protocols.Udp { [Developer("ThuCommix", "developer@sharpex2d.de")] [TestState(TestState.Untested)] public class UdpClient : IClient, IDisposable { private const int IdleMax = 30; private readonly List<IClientListener> _clientListeners; private readonly List<IPackageListener> _packageListeners; private readonly System.Net.Sockets.UdpClient _udpClient; private bool _connected; private int _currentIdle; private int _idleTimeout; private IPAddress _ip; /// <summary> /// Initializes a new UdpClient class. /// </summary> public UdpClient() { _clientListeners = new List<IClientListener>(); _packageListeners = new List<IPackageListener>(); _udpClient = new System.Net.Sockets.UdpClient(2565); } /// <summary> /// Receives data. /// </summary> private void InternalBeginReceive() { while (_connected) { if (_udpClient.Available > 0) { var serverIpEndPoint = new IPEndPoint(IPAddress.Any, 2565); byte[] receivedData = _udpClient.Receive(ref serverIpEndPoint); using (var mStream = new MemoryStream(receivedData)) { IBasePackage package = PackageSerializer.Deserialize(mStream); var binaryPackage = package as BinaryPackage; if (binaryPackage != null) { //binary package foreach (IPackageListener subscriber in GetPackageSubscriber(binaryPackage.OriginType)) { subscriber.OnPackageReceived(binaryPackage); } continue; } //system packages var systemPackage = package as NotificationPackage; if (systemPackage != null) { switch (systemPackage.Mode) { case NotificationMode.ClientJoined: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnClientJoined(systemPackage.Connection[0]); } break; case NotificationMode.ClientExited: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnClientExited(systemPackage.Connection[0]); } break; case NotificationMode.ClientList: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnClientListing(systemPackage.Connection); } break; case NotificationMode.TimeOut: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnClientTimedOut(); } break; case NotificationMode.ServerShutdown: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnServerShutdown(); } break; } } var pingPackage = package as PingPackage; if (pingPackage != null) { //send ping package back Send(pingPackage); } } } else { //no data available Idle(); } } } /// <summary> /// Gets a list of all matching package listeners. /// </summary> /// <param name="type">The Type.</param> /// <returns>List of package listeners</returns> private IEnumerable<IPackageListener> GetPackageSubscriber(Type type) { var listenerContext = new List<IPackageListener>(); for (int i = 0; i <= _packageListeners.Count - 1; i++) { //if listener type is null go to next if (_packageListeners[i].ListenerType == null) { continue; } if (_packageListeners[i].ListenerType == type) { listenerContext.Add(_packageListeners[i]); } } return listenerContext; } /// <summary> /// Idles the thread. /// </summary> private void Idle() { //Idle to save cpu power. _currentIdle++; if (_idleTimeout > 0) { Thread.Sleep(_idleTimeout); } if (_currentIdle < IdleMax) return; _currentIdle = 0; if (_idleTimeout < 15) { _idleTimeout++; } } #region IClient Implemenation /// <summary> /// Sends a package to the given receivers. /// </summary> /// <param name="package">The Package.</param> public void Send(IBasePackage package) { using (var mStream = new MemoryStream()) { PackageSerializer.Serialize(package, mStream); _udpClient.Client.SendTo(mStream.ToArray(), new IPEndPoint(_ip, 2563)); } } /// <summary> /// Sends a package to the given receivers. /// </summary> /// <param name="package">The Package.</param> /// <param name="receiver">The Receiver.</param> public void Send(IBasePackage package, IPAddress receiver) { package.Receiver = receiver; using (var mStream = new MemoryStream()) { PackageSerializer.Serialize(package, mStream); _udpClient.Client.SendTo(mStream.ToArray(), new IPEndPoint(_ip, 2563)); } } /// <summary> /// Receives a package. /// </summary> public void BeginReceive() { var beginHandle = new Thread(InternalBeginReceive) {IsBackground = true}; beginHandle.Start(); } /// <summary> /// Connects to the local server. /// </summary> /// <param name="ip">The Serverip.</param> public void Connect(IPAddress ip) { _ip = ip; using (var mStream = new MemoryStream()) { PackageSerializer.Serialize(new UdpPackage(UdpNotify.Hi), mStream); _udpClient.Client.SendTo(mStream.ToArray(), new IPEndPoint(ip, 2563)); _connected = true; } } /// <summary> /// Disconnect from the local server. /// </summary> public void Disconnect() { using (var mStream = new MemoryStream()) { PackageSerializer.Serialize(new UdpPackage(UdpNotify.Bye), mStream); _udpClient.Client.SendTo(mStream.ToArray(), new IPEndPoint(_ip, 2563)); _connected = false; } _udpClient.Close(); } /// <summary> /// Subscribes to a Client. /// </summary> /// <param name="subscriber">The Subscriber.</param> public void Subscribe(IPackageListener subscriber) { _packageListeners.Add(subscriber); } /// <summary> /// Subscribes to a Client. /// </summary> /// <param name="subscriber">The Subscriber.</param> public void Subscribe(IClientListener subscriber) { _clientListeners.Add(subscriber); } /// <summary> /// Unsubscribes from a Client. /// </summary> /// <param name="unsubscriber">The Unsubscriber.</param> public void Unsubscribe(IPackageListener unsubscriber) { _packageListeners.Remove(unsubscriber); } /// <summary> /// Unsubscribes from a Client. /// </summary> /// <param name="unsubscriber">The Unsubscriber.</param> public void Unsubscribe(IClientListener unsubscriber) { _clientListeners.Remove(unsubscriber); } #endregion #region IDisposable Implementation private bool _isDisposed; /// <summary> /// Disposes the object. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes the object. /// </summary> /// <param name="disposing">Indicates whether managed resources should be disposed.</param> protected virtual void Dispose(bool disposing) { if (!_isDisposed) { _isDisposed = true; if (disposing) { _udpClient.Close(); } } } #endregion } }
//----------------------------------------------------------------------------- // Filename: SDP.cs // // Description: Session Description Protocol implementation as defined in RFC 2327. // // Relevant Bits from the RFC: // "SDP is intended for describing mulitmedia sessions for the purposes of session // announcement, session inviatation, and other forms of multimedia session // initiation." // // SDP Includes: // - Session name and Purpose, // - Time(s) the session is active, // - The media comprising the session, // - Information to receive those media (addresses, ports, formats etc.) // As resources to participate in the session may be limited, some additional information // may also be deisreable: // - Information about the bandwidth to be used, // - Contatc information for the person responsible for the conference. // // Media Information, SDP Includes: // - The type of media (video, audio, etc), // - The transport protocol (RTP/UDP/IP, H.320, ext), // - The format of the media (H.261 video, MPEG video, etc). // // An SDP session description consists of a number of lines of text of the form // <type>=<value> where <type> is always exactly one character and is case-significant. // <value> is a structured test string whose format depends on <type> and is also // case-significant unless the <type> permits otherwise. Whitespace is not permitted // either side of the = sign. // // An announcement consists of a session-level section followed by zero // or more media-level sections. The session-level part starts with a // 'v=' line and continues to the first media-level section. The media // description starts with an `m=' line and continues to the next media // description or end of the whole session description. // // The sequence CRLF (0x0d0a) is used to end a record, although parsers should be // tolerant and also accept records terminated with a single newline character. // // Session description // v= (protocol version) // o= (owner/creator and session identifier). // <username> <session id> <version> <network type> <address type> <address> // s= (session name) // i=* (session information) // // u=* (URI of description) // e=* (email address) // p=* (phone number) // c=* (connection information - not required if included in all media) // b=* (bandwidth information) // One or more time descriptions (see below) // z=* (time zone adjustments) // k=* (encryption key) // a=* (zero or more session attribute lines) // Zero or more media descriptions (see below) // // Time description // t= (time the session is active) // r=* (zero or more repeat times) // // Media description // m= (media name and transport address) // <media> <port> <transport> <fmt list> // i=* (media title) // c=* (connection information - optional if included at session-level) // b=* (bandwidth information) // k=* (encryption key) // a=* (zero or more media attribute lines) // // Example SDP Description: // // v=0 // o=mhandley 2890844526 2890842807 IN IP4 126.16.64.4 // s=SDP Seminar // i=A Seminar on the session description protocol // u=http://www.cs.ucl.ac.uk/staff/M.Handley/sdp.03.ps // e=mjh@isi.edu (Mark Handley) // c=IN IP4 224.2.17.12/127 // t=2873397496 2873404696 // a=recvonly // m=audio 49170 RTP/AVP 0 // m=video 51372 RTP/AVP 31 // m=application 32416 udp wb // a=orient:portrait // // History: // 20 Oct 2005 Aaron Clauson Created. // // License: // Aaron Clauson //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Text.RegularExpressions; using SIPSorcery.Sys; using log4net; namespace SIPSorcery.Net { public class SDP { public const string CRLF = "\r\n"; public const string SDP_MIME_CONTENTTYPE = "application/sdp"; public const decimal SDP_PROTOCOL_VERSION = 0M; public const string ICE_UFRAG_ATTRIBUTE_PREFIX = "ice-ufrag"; public const string ICE_PWD_ATTRIBUTE_PREFIX = "ice-pwd"; public const string ICE_CANDIDATE_ATTRIBUTE_PREFIX = "candidate"; private static ILog logger = AppState.logger; public decimal Version = SDP_PROTOCOL_VERSION; // Owner fields. public string Username = "-"; // Username of the session originator. public string SessionId = "-"; // Unique Id for the session. public int AnnouncementVersion = 0; // Version number for each announcement, number must be increased for each subsequent SDP modification. public string NetworkType = "IN"; // Type of network, IN = Internet. public string AddressType = "IP4"; // Address type, typically IP4 or IP6. public string Address; // IP Address of the machine that created the session, either FQDN or dotted quad or textual for IPv6. public string Owner { get { return Username + " " + SessionId + " " + AnnouncementVersion + " " + NetworkType + " " + AddressType + " " + Address; } } public string SessionName = "-"; // Common name of the session. public string Timing; public List<string> BandwidthAttributes = new List<string>(); // Optional fields. public string SessionDescription; public string URI; // URI for additional information about the session. public string[] OriginatorEmailAddresses; // Email addresses for the person responsible for the session. public string[] OriginatorPhoneNumbers; // Phone numbers for the person responsible for the session. public string IceUfrag; // If ICE is being used the username for the STUN requests. public string IcePwd; // If ICE is being used the password for the STUN requests. public List<IceCandidate> IceCandidates; public SDPConnectionInformation Connection; // Media. public List<SDPMediaAnnouncement> Media = new List<SDPMediaAnnouncement>(); public List<string> ExtraAttributes = new List<string>(); // Attributes that were not recognised. public SDP() { } public SDP(string address) { Address = address; } public static SDP ParseSDPDescription(string sdpDescription) { try { if (sdpDescription != null && sdpDescription.Trim().Length > 0) { SDP sdp = new SDP(); SDPMediaAnnouncement activeAnnouncement = null; string[] sdpLines = Regex.Split(sdpDescription, CRLF); foreach (string sdpLine in sdpLines) { if (sdpLine.Trim().StartsWith("v=")) { if (!Decimal.TryParse(sdpLine.Substring(2), out sdp.Version)) { logger.Warn("The Version value in an SDP description could not be parsed as a decimal: " + sdpLine + "."); } } else if (sdpLine.Trim().StartsWith("o=")) { string[] ownerFields = sdpLine.Substring(2).Split(' '); sdp.Username = ownerFields[0]; sdp.SessionId = ownerFields[1]; Int32.TryParse(ownerFields[2], out sdp.AnnouncementVersion); sdp.NetworkType = ownerFields[3]; sdp.AddressType = ownerFields[4]; sdp.Address = ownerFields[5]; } else if (sdpLine.Trim().StartsWith("s=")) { sdp.SessionName = sdpLine.Substring(2); } else if (sdpLine.Trim().StartsWith("c=")) { if(activeAnnouncement != null) activeAnnouncement.Connection = SDPConnectionInformation.ParseConnectionInformation(sdpLine); else sdp.Connection = SDPConnectionInformation.ParseConnectionInformation(sdpLine); } else if(sdpLine.Trim().StartsWith("b=")) { if(activeAnnouncement != null) activeAnnouncement.BandwidthAttributes.Add(sdpLine.Substring(2)); else sdp.BandwidthAttributes.Add(sdpLine.Substring(2)); } else if (sdpLine.Trim().StartsWith("t=")) { sdp.Timing = sdpLine.Substring(2); } else if (sdpLine.Trim().StartsWith("m=")) { Match mediaMatch = Regex.Match(sdpLine.Substring(2).Trim(), @"(?<type>\w+)\s+(?<port>\d+)\s+(?<transport>\S+)\s+(?<formats>.*)$"); if (mediaMatch.Success) { SDPMediaAnnouncement announcement = new SDPMediaAnnouncement(); announcement.Media = SDPMediaTypes.GetSDPMediaType(mediaMatch.Result("${type}")); Int32.TryParse(mediaMatch.Result("${port}"), out announcement.Port); announcement.Transport = mediaMatch.Result("${transport}"); announcement.ParseMediaFormats(mediaMatch.Result("${formats}")); sdp.Media.Add(announcement); activeAnnouncement = announcement; } else { logger.Warn("A media line in SDP was invalid: " + sdpLine.Substring(2) + "."); } } else if (sdpLine.Trim().StartsWith("a=" + ICE_UFRAG_ATTRIBUTE_PREFIX)) { sdp.IceUfrag = sdpLine.Substring(sdpLine.IndexOf(':') + 1); } else if (sdpLine.Trim().StartsWith("a=" + ICE_PWD_ATTRIBUTE_PREFIX)) { sdp.IcePwd = sdpLine.Substring(sdpLine.IndexOf(':') + 1); } else if (sdpLine.Trim().StartsWith(SDPMediaAnnouncement.MEDIA_FORMAT_ATTRIBUE_PREFIX)) { if (activeAnnouncement != null) { Match formatAttributeMatch = Regex.Match(sdpLine.Trim(), SDPMediaAnnouncement.MEDIA_FORMAT_ATTRIBUE_PREFIX + @"(?<id>\d+)\s+(?<attribute>.*)$"); if (formatAttributeMatch.Success) { int formatID; if (Int32.TryParse(formatAttributeMatch.Result("${id}"), out formatID)) { activeAnnouncement.AddFormatAttribute(formatID, formatAttributeMatch.Result("${attribute}")); } else { logger.Warn("Invalid media format attribute in SDP: " + sdpLine); } } else { activeAnnouncement.AddExtra(sdpLine); } } else { logger.Warn("There was no active media announcement for a media format attribute, ignoring."); } } else if(sdpLine.Trim().StartsWith(SDPMediaAnnouncement.MEDIA_FORMAT_PARAMETERS_ATTRIBUE_PREFIX)) { if(activeAnnouncement != null) { Match formatAttributeMatch = Regex.Match(sdpLine.Trim(), SDPMediaAnnouncement.MEDIA_FORMAT_PARAMETERS_ATTRIBUE_PREFIX + @"(?<id>\d+)\s+(?<attribute>.*)$"); if(formatAttributeMatch.Success) { int formatID; if(Int32.TryParse(formatAttributeMatch.Result("${id}"), out formatID)) { activeAnnouncement.AddFormatParameterAttribute(formatID, formatAttributeMatch.Result("${attribute}")); } else { logger.Warn("Invalid media format parameter attribute in SDP: " + sdpLine); } } else { activeAnnouncement.AddExtra(sdpLine); } } else { logger.Warn("There was no active media announcement for a media format parameter attribute, ignoring."); } } else if (sdpLine.Trim().StartsWith("a=" + ICE_CANDIDATE_ATTRIBUTE_PREFIX)) { if(sdp.IceCandidates == null) { sdp.IceCandidates = new List<IceCandidate>(); } sdp.IceCandidates.Add(IceCandidate.Parse(sdpLine.Substring(sdpLine.IndexOf(':') + 1))); } else { if(activeAnnouncement != null) activeAnnouncement.AddExtra(sdpLine); else sdp.AddExtra(sdpLine); } } return sdp; } else { return null; } } catch (Exception excp) { logger.Error("Exception ParseSDPDescription. " + excp.Message); throw excp; } } public void AddExtra(string attribute) { if(!string.IsNullOrWhiteSpace(attribute)) ExtraAttributes.Add(attribute); } public override string ToString() { string sdp = "v=" + SDP_PROTOCOL_VERSION + CRLF + "o=" + Owner + CRLF + "s=" + SessionName + CRLF + ((Connection != null) ? Connection.ToString() : null) ; foreach(string bandwidth in BandwidthAttributes) { sdp += "b=" + bandwidth + CRLF; } sdp += "t=" + Timing + CRLF; sdp += !string.IsNullOrWhiteSpace(IceUfrag) ? "a=" + ICE_UFRAG_ATTRIBUTE_PREFIX + ":" + IceUfrag + CRLF : null; sdp += !string.IsNullOrWhiteSpace(IcePwd) ? "a=" + ICE_PWD_ATTRIBUTE_PREFIX + ":" + IcePwd + CRLF : null; sdp += string.IsNullOrWhiteSpace(SessionDescription) ? null : "i=" + SessionDescription + CRLF; sdp += string.IsNullOrWhiteSpace(URI) ? null : "u=" + URI + CRLF; if (OriginatorEmailAddresses != null && OriginatorEmailAddresses.Length > 0) { foreach (string originatorAddress in OriginatorEmailAddresses) { sdp += string.IsNullOrWhiteSpace(originatorAddress ) ? null : "e=" + originatorAddress + CRLF; } } if (OriginatorPhoneNumbers != null && OriginatorPhoneNumbers.Length > 0) { foreach (string originatorNumber in OriginatorPhoneNumbers) { sdp += string.IsNullOrWhiteSpace( originatorNumber ) ? null : "p=" + originatorNumber + CRLF; } } foreach(string extra in ExtraAttributes) { sdp += string.IsNullOrWhiteSpace(extra) ? null : extra + CRLF; } foreach(SDPMediaAnnouncement media in Media) { sdp += (media == null) ? null : media.ToString(); } return sdp; } public static IPEndPoint GetSDPRTPEndPoint(string sdpMessage) { // Process the SDP payload. Match portMatch = Regex.Match(sdpMessage, @"m=audio (?<port>\d+)", RegexOptions.Singleline); if (portMatch.Success) { int rtpServerPort = Convert.ToInt32(portMatch.Result("${port}")); Match serverMatch = Regex.Match(sdpMessage, @"c=IN IP4 (?<ipaddress>(\d+\.){3}\d+)", RegexOptions.Singleline); if (serverMatch.Success) { string rtpServerAddress = serverMatch.Result("${ipaddress}"); IPAddress ipAddress = null; if(IPAddress.TryParse(rtpServerAddress, out ipAddress)) { IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, rtpServerPort); return serverEndPoint; } } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Collections.Tests { public static class DictionaryBaseTests { private static FooKey CreateKey(int i) => new FooKey(i, i.ToString()); private static FooValue CreateValue(int i) => new FooValue(i, i.ToString()); private static MyDictionary CreateDictionary(int count) { var dictionary = new MyDictionary(); for (int i = 0; i < count; i++) { dictionary.Add(CreateKey(i), CreateValue(i)); } return dictionary; } [Fact] public static void Add() { var dictBase = new MyDictionary(); for (int i = 0; i < 100; i++) { FooKey key = CreateKey(i); dictBase.Add(key, CreateValue(i)); Assert.True(dictBase.Contains(key)); } Assert.Equal(100, dictBase.Count); for (int i = 0; i < dictBase.Count; i++) { Assert.Equal(CreateValue(i), dictBase[CreateKey(i)]); } FooKey nullKey = CreateKey(101); dictBase.Add(nullKey, null); Assert.Equal(null, dictBase[nullKey]); } [Fact] public static void Remove() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < 100; i++) { FooKey key = CreateKey(i); dictBase.Remove(key); Assert.False(dictBase.Contains(key)); } Assert.Equal(0, dictBase.Count); dictBase.Remove(new FooKey()); // Doesn't exist, but doesn't throw } [Fact] public static void Contains() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < dictBase.Count; i++) { Assert.True(dictBase.Contains(CreateKey(i))); } Assert.False(dictBase.Contains(new FooKey())); } [Fact] public static void Keys() { MyDictionary dictBase = CreateDictionary(100); ICollection keys = dictBase.Keys; Assert.Equal(dictBase.Count, keys.Count); foreach (FooKey key in keys) { Assert.True(dictBase.Contains(key)); } } [Fact] public static void Values() { MyDictionary dictBase = CreateDictionary(100); ICollection values = dictBase.Values; Assert.Equal(dictBase.Count, values.Count); foreach (FooValue value in values) { FooKey key = CreateKey(value.IntValue); Assert.Equal(value, dictBase[key]); } } [Fact] public static void Item_Get() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < dictBase.Count; i++) { Assert.Equal(CreateValue(i), dictBase[CreateKey(i)]); } Assert.Equal(null, dictBase[new FooKey()]); } [Fact] public static void Item_Get_NullKey_ThrowsArgumentNullException() { var dictBase = new MyDictionary(); Assert.Throws<ArgumentNullException>("key", () => dictBase[null]); } [Fact] public static void Item_Set() { MyDictionary dictBase = CreateDictionary(100); for (int i = 0; i < dictBase.Count; i++) { FooKey key = CreateKey(i); FooValue value = CreateValue(dictBase.Count - i - 1); dictBase[key] = value; Assert.Equal(value, dictBase[key]); } FooKey nonExistentKey = CreateKey(101); dictBase[nonExistentKey] = null; Assert.Equal(101, dictBase.Count); // Should add a key/value pair if the key Assert.Equal(null, dictBase[nonExistentKey]); } [Fact] public static void Indexer_Set_NullKey_ThrowsArgumentNullException() { var dictBase = new MyDictionary(); Assert.Throws<ArgumentNullException>("key", () => dictBase[null] = new FooValue()); } [Fact] public static void Clear() { MyDictionary dictBase = CreateDictionary(100); dictBase.Clear(); Assert.Equal(0, dictBase.Count); } [Fact] public static void CopyTo() { MyDictionary dictBase = CreateDictionary(100); // Basic var entries = new DictionaryEntry[dictBase.Count]; dictBase.CopyTo(entries, 0); Assert.Equal(dictBase.Count, entries.Length); for (int i = 0; i < entries.Length; i++) { DictionaryEntry entry = entries[i]; Assert.Equal(CreateKey(entries.Length - i - 1), entry.Key); Assert.Equal(CreateValue(entries.Length - i - 1), entry.Value); } // With index entries = new DictionaryEntry[dictBase.Count * 2]; dictBase.CopyTo(entries, dictBase.Count); Assert.Equal(dictBase.Count * 2, entries.Length); for (int i = dictBase.Count; i < entries.Length; i++) { DictionaryEntry entry = entries[i]; Assert.Equal(CreateKey(entries.Length - i - 1), entry.Key); Assert.Equal(CreateValue(entries.Length - i - 1), entry.Value); } } [Fact] public static void CopyTo_Invalid() { MyDictionary dictBase = CreateDictionary(100); Assert.Throws<ArgumentNullException>("array", () => dictBase.CopyTo(null, 0)); // Array is null Assert.Throws<ArgumentException>(() => dictBase.CopyTo(new object[100, 100], 0)); // Array is multidimensional Assert.Throws<ArgumentOutOfRangeException>("arrayIndex", () => dictBase.CopyTo(new DictionaryEntry[100], -1)); // Index < 0 Assert.Throws<ArgumentException>(null, () => dictBase.CopyTo(new DictionaryEntry[100], 100)); // Index >= count Assert.Throws<ArgumentException>(null, () => dictBase.CopyTo(new DictionaryEntry[100], 50)); // Index + array.Count >= count } [Fact] public static void GetEnumerator_IDictionaryEnumerator() { MyDictionary dictBase = CreateDictionary(100); IDictionaryEnumerator enumerator = dictBase.GetEnumerator(); Assert.NotNull(enumerator); int count = 0; while (enumerator.MoveNext()) { DictionaryEntry entry1 = (DictionaryEntry)enumerator.Current; DictionaryEntry entry2 = enumerator.Entry; Assert.Equal(entry1.Key, entry2.Key); Assert.Equal(entry1.Value, entry2.Value); Assert.Equal(enumerator.Key, entry1.Key); Assert.Equal(enumerator.Value, entry1.Value); Assert.Equal(enumerator.Value, dictBase[(FooKey)enumerator.Key]); count++; } Assert.Equal(dictBase.Count, count); } [Fact] public static void GetEnumerator_IDictionaryEnumerator_Invalid() { MyDictionary dictBase = CreateDictionary(100); IDictionaryEnumerator enumerator = dictBase.GetEnumerator(); // Index < 0 Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Index > dictionary.Count while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current throws after resetting enumerator.Reset(); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); } [Fact] public static void GetEnumerator_IEnumerator() { MyDictionary dictBase = CreateDictionary(100); IEnumerator enumerator = ((IEnumerable)dictBase).GetEnumerator(); Assert.NotNull(enumerator); int count = 0; while (enumerator.MoveNext()) { DictionaryEntry entry = (DictionaryEntry)enumerator.Current; Assert.Equal((FooValue)entry.Value, dictBase[(FooKey)entry.Key]); count++; } Assert.Equal(dictBase.Count, count); } [Fact] public static void GetEnumerator_IEnumerator_Invalid() { MyDictionary dictBase = CreateDictionary(100); IEnumerator enumerator = ((IEnumerable)dictBase).GetEnumerator(); // Index < 0 Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Index >= dictionary.Count while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); // Current throws after resetting enumerator.Reset(); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public static void SyncRoot() { // SyncRoot should be the reference to the underlying dictionary, not to MyDictionary var dictBase = new MyDictionary(); object syncRoot = dictBase.SyncRoot; Assert.NotEqual(syncRoot, dictBase); Assert.Equal(dictBase.SyncRoot, dictBase.SyncRoot); } [Fact] public static void IDictionaryProperties() { var dictBase = new MyDictionary(); Assert.False(dictBase.IsFixedSize); Assert.False(dictBase.IsReadOnly); Assert.False(dictBase.IsSynchronized); } [Fact] public static void Add_Called() { var f = new FooKey(0, "0"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, "hello"); Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnInsertCalled); Assert.True(dictBase.OnInsertCompleteCalled); Assert.True(dictBase.Contains(f)); } [Fact] public static void Add_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase.Add(f, "")); Assert.Equal(0, dictBase.Count); // Throw OnInsert dictBase = new OnMethodCalledDictionary(); dictBase.OnInsertThrow = true; Assert.Throws<Exception>(() => dictBase.Add(f, "")); Assert.Equal(0, dictBase.Count); // Throw OnInsertComplete dictBase = new OnMethodCalledDictionary(); dictBase.OnInsertCompleteThrow = true; Assert.Throws<Exception>(() => dictBase.Add(f, "")); Assert.Equal(0, dictBase.Count); } [Fact] public static void Remove_Called() { var f = new FooKey(0, "0"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateCalled = false; dictBase.Remove(f); Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnRemoveCalled); Assert.True(dictBase.OnRemoveCompleteCalled); Assert.False(dictBase.Contains(f)); } [Fact] public static void Remove_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase.Remove(f)); Assert.Equal(1, dictBase.Count); // Throw OnRemove dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnRemoveThrow = true; Assert.Throws<Exception>(() => dictBase.Remove(f)); Assert.Equal(1, dictBase.Count); // Throw OnRemoveComplete dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnRemoveCompleteThrow = true; Assert.Throws<Exception>(() => dictBase.Remove(f)); Assert.Equal(1, dictBase.Count); } [Fact] public static void Clear_Called() { var f = new FooKey(0, "0"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.Clear(); Assert.True(dictBase.OnClearCalled); Assert.True(dictBase.OnClearCompleteCalled); Assert.Equal(0, dictBase.Count); } [Fact] public static void Clear_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateThrow = true; dictBase.Clear(); Assert.Equal(0, dictBase.Count); // Throw OnClear dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnClearThrow = true; Assert.Throws<Exception>(() => dictBase.Clear()); Assert.Equal(1, dictBase.Count); // Throw OnClearComplete dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnClearCompleteThrow = true; Assert.Throws<Exception>(() => dictBase.Clear()); Assert.Equal(0, dictBase.Count); } [Fact] public static void Set_New_Called() { var f = new FooKey(1, "1"); var dictBase = new OnMethodCalledDictionary(); dictBase.OnValidateCalled = false; dictBase[f] = "hello"; Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnSetCalled); Assert.True(dictBase.OnSetCompleteCalled); Assert.Equal(1, dictBase.Count); Assert.Equal("hello", dictBase[f]); } [Fact] public static void Set_New_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal(0, dictBase.Count); // Throw OnSet dictBase = new OnMethodCalledDictionary(); dictBase.OnSetThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal(0, dictBase.Count); // Throw OnSetComplete dictBase = new OnMethodCalledDictionary(); dictBase.OnSetCompleteThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal(0, dictBase.Count); } [Fact] public static void Set_Existing_Called() { var f = new FooKey(1, "1"); var dictBase = new OnMethodCalledDictionary(); dictBase.Add(new FooKey(), ""); dictBase.OnValidateCalled = false; dictBase[f] = "hello"; Assert.True(dictBase.OnValidateCalled); Assert.True(dictBase.OnSetCalled); Assert.True(dictBase.OnSetCompleteCalled); Assert.Equal("hello", dictBase[f]); } [Fact] public static void Set_Existing_Throws_Called() { var f = new FooKey(0, "0"); // Throw OnValidate var dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnValidateThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal("", dictBase[f]); // Throw OnSet dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnSetThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal("", dictBase[f]); // Throw OnSetComplete dictBase = new OnMethodCalledDictionary(); dictBase.Add(f, ""); dictBase.OnSetCompleteThrow = true; Assert.Throws<Exception>(() => dictBase[f] = "hello"); Assert.Equal("", dictBase[f]); } // DictionaryBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here private class MyDictionary : DictionaryBase { public void Add(FooKey key, FooValue value) => Dictionary.Add(key, value); public FooValue this[FooKey key] { get { return (FooValue)Dictionary[key]; } set { Dictionary[key] = value; } } public bool IsSynchronized { get { return Dictionary.IsSynchronized; } } public object SyncRoot { get { return Dictionary.SyncRoot; } } public bool Contains(FooKey key) => Dictionary.Contains(key); public void Remove(FooKey key) => Dictionary.Remove(key); public bool IsFixedSize { get { return Dictionary.IsFixedSize; } } public bool IsReadOnly { get { return Dictionary.IsReadOnly; } } public ICollection Keys { get { return Dictionary.Keys; } } public ICollection Values { get { return Dictionary.Values; } } } private class FooKey : IComparable { public FooKey() { } public FooKey(int i, string str) { IntValue = i; StringValue = str; } public int IntValue { get; set; } public string StringValue { get; set; } public override bool Equals(object obj) { FooKey foo = obj as FooKey; if (foo == null) return false; return foo.IntValue == IntValue && foo.StringValue == StringValue; } public override int GetHashCode() =>IntValue; public int CompareTo(object obj) { FooKey temp = (FooKey)obj; return IntValue.CompareTo(temp.IntValue); } } private class FooValue : IComparable { public FooValue() { } public FooValue(int intValue, string stringValue) { IntValue = intValue; StringValue = stringValue; } public int IntValue { get; set; } public string StringValue { get; set; } public override bool Equals(object obj) { FooValue foo = obj as FooValue; if (foo == null) return false; return foo.IntValue == IntValue && foo.StringValue == StringValue; } public override int GetHashCode() => IntValue; public int CompareTo(object obj) { FooValue temp = (FooValue)obj; return IntValue.CompareTo(temp.IntValue); } } // DictionaryBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here private class OnMethodCalledDictionary : DictionaryBase { public bool OnValidateCalled; public bool OnSetCalled; public bool OnSetCompleteCalled; public bool OnInsertCalled; public bool OnInsertCompleteCalled; public bool OnClearCalled; public bool OnClearCompleteCalled; public bool OnRemoveCalled; public bool OnRemoveCompleteCalled; public bool OnValidateThrow; public bool OnSetThrow; public bool OnSetCompleteThrow; public bool OnInsertThrow; public bool OnInsertCompleteThrow; public bool OnClearThrow; public bool OnClearCompleteThrow; public bool OnRemoveThrow; public bool OnRemoveCompleteThrow; public void Add(FooKey key, string value) => Dictionary.Add(key, value); public string this[FooKey key] { get { return (string)Dictionary[key]; } set { Dictionary[key] = value; } } public bool Contains(FooKey key) => Dictionary.Contains(key); public void Remove(FooKey key) => Dictionary.Remove(key); protected override void OnSet(object key, object oldValue, object newValue) { Assert.True(OnValidateCalled); Assert.Equal(oldValue, this[(FooKey)key]); OnSetCalled = true; if (OnSetThrow) throw new Exception("OnSet"); } protected override void OnInsert(object key, object value) { Assert.True(OnValidateCalled); Assert.NotEqual(value, this[(FooKey)key]); OnInsertCalled = true; if (OnInsertThrow) throw new Exception("OnInsert"); } protected override void OnClear() { OnClearCalled = true; if (OnClearThrow) throw new Exception("OnClear"); } protected override void OnRemove(object key, object value) { Assert.True(OnValidateCalled); Assert.Equal(value, this[(FooKey)key]); OnRemoveCalled = true; if (OnRemoveThrow) throw new Exception("OnRemove"); } protected override void OnValidate(object key, object value) { OnValidateCalled = true; if (OnValidateThrow) throw new Exception("OnValidate"); } protected override void OnSetComplete(object key, object oldValue, object newValue) { Assert.True(OnSetCalled); Assert.Equal(newValue, this[(FooKey)key]); OnSetCompleteCalled = true; if (OnSetCompleteThrow) throw new Exception("OnSetComplete"); } protected override void OnInsertComplete(object key, object value) { Assert.True(OnInsertCalled); Assert.Equal(value, this[(FooKey)key]); OnInsertCompleteCalled = true; if (OnInsertCompleteThrow) throw new Exception("OnInsertComplete"); } protected override void OnClearComplete() { Assert.True(OnClearCalled); OnClearCompleteCalled = true; if (OnClearCompleteThrow) throw new Exception("OnClearComplete"); } protected override void OnRemoveComplete(object key, object value) { Assert.True(OnRemoveCalled); Assert.False(Contains((FooKey)key)); OnRemoveCompleteCalled = true; if (OnRemoveCompleteThrow) throw new Exception("OnRemoveComplete"); } } } }
// 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.ServiceModel.Channels; using System.Xml; using System.Diagnostics; using System.Net.Security; using System.ServiceModel.Security; using System.ComponentModel; namespace System.ServiceModel.Description { [DebuggerDisplay("Action={Action}, Direction={Direction}, MessageType={MessageType}")] public class MessageDescription { private static Type s_typeOfUntypedMessage; private MessageDescriptionItems _items; private ProtectionLevel _protectionLevel; public MessageDescription(string action, MessageDirection direction) : this(action, direction, null) { } internal MessageDescription(string action, MessageDirection direction, MessageDescriptionItems items) { if (!MessageDirectionHelper.IsDefined(direction)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(direction))); } Action = action; Direction = direction; _items = items; } internal MessageDescription(MessageDescription other) { Action = other.Action; Direction = other.Direction; Items.Body = other.Items.Body.Clone(); foreach (MessageHeaderDescription mhd in other.Items.Headers) { Items.Headers.Add(mhd.Clone() as MessageHeaderDescription); } foreach (MessagePropertyDescription mpd in other.Items.Properties) { Items.Properties.Add(mpd.Clone() as MessagePropertyDescription); } MessageName = other.MessageName; MessageType = other.MessageType; XsdTypeName = other.XsdTypeName; HasProtectionLevel = other.HasProtectionLevel; ProtectionLevel = other.ProtectionLevel; } internal MessageDescription Clone() { return new MessageDescription(this); } public string Action { get; internal set; } public MessageBodyDescription Body { get { return Items.Body; } } public MessageDirection Direction { get; } public MessageHeaderDescriptionCollection Headers { get { return Items.Headers; } } public MessagePropertyDescriptionCollection Properties { get { return Items.Properties; } } internal MessageDescriptionItems Items { get { if (_items == null) { _items = new MessageDescriptionItems(); } return _items; } } public ProtectionLevel ProtectionLevel { get { return _protectionLevel; } set { if (!ProtectionLevelHelper.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value))); } _protectionLevel = value; HasProtectionLevel = true; } } public bool ShouldSerializeProtectionLevel() { return HasProtectionLevel; } public bool HasProtectionLevel { get; private set; } internal static Type TypeOfUntypedMessage { get { if (s_typeOfUntypedMessage == null) { s_typeOfUntypedMessage = typeof(Message); } return s_typeOfUntypedMessage; } } internal XmlName MessageName { get; set; } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime [DefaultValue(null)] public Type MessageType { get; set; } internal bool IsTypedMessage { get { return MessageType != null; } } internal bool IsUntypedMessage { get { return (Body.ReturnValue != null && Body.Parts.Count == 0 && Body.ReturnValue.Type == TypeOfUntypedMessage) || (Body.ReturnValue == null && Body.Parts.Count == 1 && Body.Parts[0].Type == TypeOfUntypedMessage); } } internal bool IsVoid { get { return !IsTypedMessage && Body.Parts.Count == 0 && (Body.ReturnValue == null || Body.ReturnValue.Type == typeof(void)); } } internal XmlQualifiedName XsdTypeName { get; set; } internal void ResetProtectionLevel() { _protectionLevel = ProtectionLevel.None; HasProtectionLevel = false; } } internal class MessageDescriptionItems { private MessageHeaderDescriptionCollection _headers; private MessageBodyDescription _body; private MessagePropertyDescriptionCollection _properties; internal MessageBodyDescription Body { get { if (_body == null) { _body = new MessageBodyDescription(); } return _body; } set { _body = value; } } internal MessageHeaderDescriptionCollection Headers { get { if (_headers == null) { _headers = new MessageHeaderDescriptionCollection(); } return _headers; } } internal MessagePropertyDescriptionCollection Properties { get { if (_properties == null) { _properties = new MessagePropertyDescriptionCollection(); } return _properties; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Logging; using DotNetCore.Localization.Web.Models; using DotNetCore.Localization.Web.Models.AccountViewModels; using DotNetCore.Localization.Web.Services; namespace DotNetCore.Localization.Web.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<AccountController>(); } // // GET: /Account/Login [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation(1, "User logged in."); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new {ReturnUrl = returnUrl, RememberMe = model.RememberMe}); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult Register(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser {UserName = model.Email, Email = model.Email}; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToLocal(returnUrl); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); _logger.LogInformation(4, "User logged out."); return RedirectToAction(nameof(HomeController.Index), "Home"); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new {ReturnUrl = returnUrl}); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return Challenge(properties, provider); } // // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new {ReturnUrl = returnUrl}); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {Email = email}); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser {UserName = model.Email, Email = model.Email}; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } // GET: /Account/ConfirmEmail [HttpGet] [AllowAnonymous] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [HttpGet] [AllowAnonymous] public IActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GeneratePasswordResetTokenAsync(user); //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Reset Password", // $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); //return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [HttpGet] [AllowAnonymous] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); } // // GET: /Account/SendCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem {Text = purpose, Value = purpose}).ToList(); return View(new SendCodeViewModel {Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe}); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new {Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe}); } // // GET: /Account/VerifyCode [HttpGet] [AllowAnonymous] public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { // Require that the user has already logged in via username/password or external login var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } return View(new VerifyCodeViewModel {Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe}); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { _logger.LogWarning(7, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid code."); return View(model); } } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } #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.IO; using System.Xml; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { public partial class TCAttributeAccess : BridgeHelpers { //[Variation("Attribute Access test using ordinal (Ascending Order)", Priority = 0)] public void TestAttributeAccess1() { XmlReader DataReader = GetReader(); string[] astr = new string[10]; string n; string qname; PositionOnElement(DataReader, "ACT0"); int start = 1; int end = DataReader.AttributeCount; for (int i = start; i < end; i++) { astr[i - 1] = DataReader[i]; n = strAttr + (i - 1); qname = "foo:" + n; TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)"); TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)"); TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)"); } PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute"); TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); n = strAttr + i; TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)"); TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)"); TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)"); } } //[Variation("Attribute Access test using ordinal (Descending Order)")] public void TestAttributeAccess2() { XmlReader DataReader = GetReader(); string[] astr = new string[10]; string n; string qname; PositionOnElement(DataReader, "ACT0"); int start = 1; int end = DataReader.AttributeCount; for (int i = end - 1; i >= start; i--) { astr[i - 1] = DataReader[i]; n = strAttr + (i - 1); qname = "foo:" + n; TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)"); TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Compare this(qname) with GetAttribute(qname)"); TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)"); TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)"); } PositionOnElement(DataReader, "ACT1"); for (int i = (DataReader.AttributeCount - 1); i > 0; i--) { n = strAttr + i; TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute"); TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)"); TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)"); TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)"); } } //[Variation("Attribute Access test using ordinal (Odd number)", Priority = 0)] public void TestAttributeAccess3() { XmlReader DataReader = GetReader(); string[] astr = new string[10]; string n; string qname; PositionOnElement(DataReader, "ACT0"); int start = 1; int end = DataReader.AttributeCount; for (int i = start; i < end; i += 2) { astr[i - 1] = DataReader[i]; n = strAttr + (i - 1); qname = "foo:" + n; TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)"); TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Compare this(qname) with GetAttribute(qname)"); TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)"); TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)"); } PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i += 2) { TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute"); TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); n = strAttr + i; TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)"); TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)"); TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)"); } } //[Variation("Attribute Access test using ordinal (Even number)")] public void TestAttributeAccess4() { XmlReader DataReader = GetReader(); string[] astr = new string[10]; string n; string qname; PositionOnElement(DataReader, "ACT0"); int start = 1; int end = DataReader.AttributeCount; for (int i = start; i < end; i += 3) { astr[i - 1] = DataReader[i]; n = strAttr + (i - 1); qname = "foo:" + n; TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); TestLog.Compare(DataReader[n, strNamespace], DataReader.GetAttribute(n, strNamespace), "Compare this(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[i], DataReader[n, strNamespace], "Compare this(i) with this(name,strNamespace)"); TestLog.Compare(DataReader.MoveToAttribute(n, strNamespace), true, "MoveToAttribute(name,strNamespace)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n, strNamespace), "Compare MoveToAttribute(name,strNamespace) with GetAttribute(name,strNamespace)"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Compare this(qname) with GetAttribute(qname)"); TestLog.Compare(DataReader[i], DataReader[qname], "Compare this(i) with this(qname)"); TestLog.Compare(DataReader.MoveToAttribute(qname), true, "MoveToAttribute(qname)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(qname), "Compare MoveToAttribute(qname) with GetAttribute(qname)"); } PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i += 3) { TestLog.Compare(astr[i], DataReader.GetAttribute(i), "Compare value with GetAttribute"); TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Compare this with GetAttribute"); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Compare MoveToAttribute(i) with GetAttribute"); n = strAttr + i; TestLog.Compare(DataReader[n], DataReader.GetAttribute(n), "Compare this(name) with GetAttribute(name)"); TestLog.Compare(DataReader[i], DataReader[n], "Compare this(i) with this(name)"); TestLog.Compare(DataReader.MoveToAttribute(n), true, "MoveToAttribute(name)"); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(n), "Compare MoveToAttribute(name) with GetAttribute(name)"); } } //[Variation("Attribute Access with namespace=null")] public void TestAttributeAccess5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); TestLog.Compare(DataReader[strAttr + 1, null], null, "Item"); TestLog.Compare(DataReader.Name, "ACT1", "Reader changed position"); } } public partial class TCThisName : BridgeHelpers { //[Variation("This[Name] Verify with GetAttribute(Name)", Priority = 0)] public void ThisWithName1() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("This[Name, null] Verify with GetAttribute(Name)")] public void ThisWithName2() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name] Verify with GetAttribute(Name,null)")] public void ThisWithName3() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader.GetAttribute(strName, null), null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name, NamespaceURI] Verify with GetAttribute(Name, NamespaceURI)", Priority = 0)] public void ThisWithName4() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName, strNamespace], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[strName,strNamespace]"); } } //[Variation("This[Name, null] Verify not the same as GetAttribute(Name, NamespaceURI)")] public void ThisWithName5() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name, NamespaceURI] Verify not the same as GetAttribute(Name, null)")] public void ThisWithName6() { string strName; XmlReader DataReader = GetReader(); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); if (DataReader.GetAttribute(strName, null) == DataReader[strName, strNamespace]) throw new TestException(TestResult.Failed, Variation.Desc); } } //[Variation("This[Name] Verify with MoveToAttribute(Name)", Priority = 0)] public void ThisWithName7() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName); TestLog.Compare(DataReader.Value, DataReader[strName], "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("This[Name, null] Verify with MoveToAttribute(Name)")] public void ThisWithName8() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName); TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name] Verify with MoveToAttribute(Name,null)")] public void ThisWithName9() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Ordinal (" + i + "): Reader should not have moved"); } } //[Variation("This[Name, NamespaceURI] Verify not the same as MoveToAttribute(Name, null)", Priority = 0)] public void ThisWithName10() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Ordinal (" + i + "): Reader should not have moved"); } } //[Variation("This[Name, null] Verify not the same as MoveToAttribute(Name, NamespaceURI)")] public void ThisWithName11() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName, strNamespace); TestLog.Compare(DataReader[strName, null], null, "Ordinal (" + i + "): Should have returned null"); } } //[Variation("This[Name, namespace] Verify not the same as MoveToAttribute(Name, namespace)")] public void ThisWithName12() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); DataReader.MoveToAttribute(strName, strNamespace); TestLog.Compare(DataReader.Value, DataReader[strName, strNamespace], "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("This(String.Empty)")] public void ThisWithName13() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader[String.Empty], null, "Should have returned null"); } //[Variation("This[String.Empty,String.Empty]")] public void ThisWithName14() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader[String.Empty, String.Empty], null, "Should have returned null"); } //[Variation("This[QName] Verify with GetAttribute(Name, NamespaceURI)", Priority = 0)] public void ThisWithName15() { string strName; string qname; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + i; qname = "foo:" + strName; TestLog.Compare(DataReader[qname], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[qname]"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Ordinal (" + i + "): Compare GetAttribute(qname) and this[qname]"); } } //[Variation("This[QName] invalid Qname")] public void ThisWithName16() { string strName; string qname; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); int i = 1; strName = strAttr + i; qname = "foo1:" + strName; TestLog.Compare(DataReader.MoveToAttribute(qname), false, "MoveToAttribute(invalid qname)"); TestLog.Compare(DataReader[qname], null, "Compare this[invalid qname] with null"); TestLog.Compare(DataReader.GetAttribute(qname), null, "Compare GetAttribute(invalid qname) with null"); } } public partial class TCMoveToAttributeReader : BridgeHelpers { //[Variation("MoveToAttribute(String.Empty)")] public void MoveToAttributeWithName1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader.MoveToAttribute(String.Empty), false, "Should have returned false"); TestLog.Compare(DataReader.Value, String.Empty, "Compare MoveToAttribute with String.Empty"); } //[Variation("MoveToAttribute(String.Empty,String.Empty)")] public void MoveToAttributeWithName2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader.MoveToAttribute(String.Empty, String.Empty), false, "Compare the call to MoveToAttribute"); TestLog.Compare(DataReader.Value, String.Empty, "Compare MoveToAttribute(strName)"); } } //[TestCase(Name = "GetAttributeOrdinal", Desc = "GetAttributeOrdinal")] public partial class TCGetAttributeOrdinal : BridgeHelpers { //[Variation("GetAttribute(i) Verify with This[i] - Double Quote", Priority = 0)] public void GetAttributeWithGetAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]"); } } //[Variation("GetAttribute[i] Verify with This[i] - Single Quote")] public void OrdinalWithGetAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]"); } } //[Variation("GetAttribute(i) Verify with MoveToAttribute[i] - Double Quote", Priority = 0)] public void GetAttributeWithMoveAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader.GetAttribute(i); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("GetAttribute(i) Verify with MoveToAttribute[i] - Single Quote")] public void GetAttributeWithMoveAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader.GetAttribute(i); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("GetAttribute(i) NegativeOneOrdinal", Priority = 0)] public void NegativeOneOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader.GetAttribute(-1); } //[Variation("GetAttribute(i) FieldCountOrdinal")] public void FieldCountOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string str = DataReader.GetAttribute(DataReader.AttributeCount); } //[Variation("GetAttribute(i) OrdinalPlusOne", Priority = 0)] public void OrdinalPlusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader.GetAttribute(DataReader.AttributeCount + 1); } //[Variation("GetAttribute(i) OrdinalMinusOne")] public void OrdinalMinusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader.GetAttribute(-2); } } //[TestCase(Name = "GetAttributeName", Desc = "GetAttributeName")] public partial class TCGetAttributeName : BridgeHelpers { //[Variation("GetAttribute(Name) Verify with This[Name]", Priority = 0)] public void GetAttributeWithName1() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(Name, null) Verify with This[Name]")] public void GetAttributeWithName2() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(Name) Verify with This[Name,null]")] public void GetAttributeWithName3() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader[strName], DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(Name, NamespaceURI) Verify with This[Name, NamespaceURI]", Priority = 0)] public void GetAttributeWithName4() { string strName; string qname; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + i; qname = "foo:" + strName; TestLog.Compare(DataReader[strName, strNamespace], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[strName,strNamespace]"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName,strNamespace) and this[strName,strNamespace]"); TestLog.Compare(DataReader[qname], DataReader.GetAttribute(qname), "Ordinal (" + i + "): Compare GetAttribute(qname) and this[qname]"); } } //[Variation("GetAttribute(Name, null) Verify not the same as This[Name, NamespaceURI]")] public void GetAttributeWithName5() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); if (DataReader.GetAttribute(strName) == DataReader[strName, strNamespace]) { if (DataReader[strName, strNamespace] == String.Empty) throw new TestException(TestResult.Failed, Variation.Desc); } } } //[Variation("GetAttribute(Name, NamespaceURI) Verify not the same as This[Name, null]")] public void GetAttributeWithName6() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); if (DataReader.GetAttribute(strName, strNamespace) == DataReader[strName]) throw new TestException(TestResult.Failed, Variation.Desc); } } //[Variation("GetAttribute(Name) Verify with MoveToAttribute(Name)")] public void GetAttributeWithName7() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(strName), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(Name,null) Verify with MoveToAttribute(Name)", Priority = 1)] public void GetAttributeWithName8() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName); TestLog.Compare(DataReader.GetAttribute(strName, null), null, "Ordinal (" + i + "): Did not return null"); } } //[Variation("GetAttribute(Name) Verify with MoveToAttribute(Name,null)", Priority = 1)] public void GetAttributeWithName9() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Ordinal (" + i + "): Incorrect move"); TestLog.Compare(DataReader.Value, String.Empty, "Ordinal (" + i + "): DataReader.Value should be empty string"); } } //[Variation("GetAttribute(Name, NamespaceURI) Verify not the same as MoveToAttribute(Name, null)")] public void GetAttributeWithName10() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); TestLog.Compare(DataReader.MoveToAttribute(strName, null), false, "Incorrect move"); TestLog.Compare(DataReader.Value, String.Empty, "Ordinal (" + i + "): DataReader.Value should be empty string"); } } //[Variation("GetAttribute(Name, null) Verify not the same as MoveToAttribute(Name, NamespaceURI)")] public void GetAttributeWithName11() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { strName = strAttr + i; DataReader.MoveToAttribute(strName, strNamespace); TestLog.Compare(DataReader.GetAttribute(strName, null), null, "Should have returned null"); } } //[Variation("GetAttribute(Name, namespace) Verify not the same as MoveToAttribute(Name, namespace)")] public void GetAttributeWithName12() { string strName; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 1; i < DataReader.AttributeCount; i++) { strName = strAttr + (i - 1); DataReader.MoveToAttribute(strName, strNamespace); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(strName, strNamespace), "Ordinal (" + i + "): Compare GetAttribute(strName) and this[strName]"); } } //[Variation("GetAttribute(String.Empty)")] public void GetAttributeWithName13() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); TestLog.Compare(DataReader.GetAttribute(String.Empty), null, "Should have returned null"); } //[Variation("GetAttribute(String.Empty,String.Empty)")] public void GetAttributeWithName14() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); TestLog.Compare(DataReader.GetAttribute(String.Empty, String.Empty), null, "Compare GetAttribute(strName) and this[strName]"); } } //[TestCase(Name = "ThisOrdinal", Desc = "ThisOrdinal")] public partial class TCThisOrdinal : BridgeHelpers { //[Variation("This[i] Verify with GetAttribute[i] - Double Quote", Priority = 0)] public void OrdinalWithGetAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute[i] and this[i]"); } } //[Variation("This[i] Verify with GetAttribute[i] - Single Quote")] public void OrdinalWithGetAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { TestLog.Compare(DataReader[i], DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare GetAttribute[i] and this[i]"); } } //[Variation("This[i] Verify with MoveToAttribute[i] - Double Quote", Priority = 0)] public void OrdinalWithMoveAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader[i]; DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("This[i] Verify with MoveToAttribute[i] - Single Quote")] public void OrdinalWithMoveAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader[i]; DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("ThisOrdinal NegativeOneOrdinal", Priority = 0)] public void NegativeOneOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader[-1]; } //[Variation("ThisOrdinal FieldCountOrdinal")] public void FieldCountOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string str = DataReader[DataReader.AttributeCount]; } //[Variation("ThisOrdinal OrdinalPlusOne", Priority = 0)] public void OrdinalPlusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader[DataReader.AttributeCount + 1]; } //[Variation("ThisOrdinal OrdinalMinusOne")] public void OrdinalMinusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string str = DataReader[-2]; } } //[TestCase(Name = "MoveToAttributeOrdinal", Desc = "MoveToAttributeOrdinal")] public partial class TCMoveToAttributeOrdinal : BridgeHelpers { //[Variation("MoveToAttribute(i) Verify with This[i] - Double Quote", Priority = 0)] public void MoveToAttributeWithGetAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { DataReader.MoveToAttribute(i); TestLog.Compare(DataReader[i], DataReader.Value, "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]"); } } //[Variation("MoveToAttribute(i) Verify with This[i] - Single Quote")] public void MoveToAttributeWithGetAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { DataReader.MoveToAttribute(i); TestLog.Compare(DataReader[i], DataReader.Value, "Ordinal (" + i + "): Compare GetAttribute(i) and this[i]"); } } //[Variation("MoveToAttribute(i) Verify with GetAttribute(i) - Double Quote", Priority = 0)] public void MoveToAttributeWithMoveAttrDoubleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader.GetAttribute(i); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader.GetAttribute(i), "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("MoveToAttribute(i) Verify with GetAttribute[i] - Single Quote")] public void MoveToAttributeWithMoveAttrSingleQ() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); for (int i = 0; i < DataReader.AttributeCount; i++) { string str = DataReader.GetAttribute(i); DataReader.MoveToAttribute(i); TestLog.Compare(DataReader.Value, DataReader[i], "Ordinal (" + i + "): Compare MoveToAttribute[i] and this[i]"); TestLog.Compare(str, DataReader.Value, "Ordinal (" + i + "): Compare MoveToAttribute[i] and string"); } } //[Variation("MoveToAttribute(i) NegativeOneOrdinal", Priority = 0)] public void NegativeOneOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); try { DataReader.MoveToAttribute(-1); } catch (ArgumentOutOfRangeException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("MoveToAttribute(i) FieldCountOrdinal")] public void FieldCountOrdinal() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); try { DataReader.MoveToAttribute(DataReader.AttributeCount); } catch (ArgumentOutOfRangeException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("MoveToAttribute(i) OrdinalPlusOne", Priority = 0)] public void OrdinalPlusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); try { DataReader.MoveToAttribute(DataReader.AttributeCount + 1); } catch (ArgumentOutOfRangeException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("MoveToAttribute(i) OrdinalMinusOne")] public void OrdinalMinusOne() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); try { DataReader.MoveToAttribute(-2); } catch (ArgumentOutOfRangeException) { return; } throw new TestException(TestResult.Failed, ""); } } //[TestCase(Name = "MoveToFirstAttribute", Desc = "MoveToFirstAttribute")] public partial class TCMoveToFirstAttribute : BridgeHelpers { //[Variation("MoveToFirstAttribute() When AttributeCount=0, <EMPTY1/> ", Priority = 0)] public void MoveToFirstAttribute1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc); } //[Variation("MoveToFirstAttribute() When AttributeCount=0, <NONEMPTY1>ABCDE</NONEMPTY1> ")] public void MoveToFirstAttribute2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONEMPTY1"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=0, with namespace")] public void MoveToFirstAttribute3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strFirst; TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=0, without namespace")] public void MoveToFirstAttribute4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strFirst; TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, with namespace")] public void MoveToFirstAttribute5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strFirst; DataReader.MoveToAttribute((int)((DataReader.AttributeCount) / 2)); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, without namespace")] public void MoveToFirstAttribute6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strFirst; DataReader.MoveToAttribute((int)((DataReader.AttributeCount) / 2)); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=end, with namespace")] public void MoveToFirstAttribute7() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strFirst; DataReader.MoveToAttribute((DataReader.AttributeCount) - 1); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=end, without namespace")] public void MoveToFirstAttribute8() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strFirst; DataReader.MoveToAttribute((DataReader.AttributeCount) - 1); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } } public partial class TCMoveToNextAttribute : BridgeHelpers { //[Variation("MoveToNextAttribute() When AttributeCount=0, <EMPTY1/> ", Priority = 0)] public void MoveToNextAttribute1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc); } //[Variation("MoveToNextAttribute() When AttributeCount=0, <NONEMPTY1>ABCDE</NONEMPTY1> ")] public void MoveToNextAttribute2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONEMPTY1"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc); } //[Variation("MoveToNextAttribute() When iOrdinal=0, with namespace")] public void MoveToNextAttribute3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strValue; TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue, DataReader.GetAttribute(0), Variation.Desc); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue, DataReader.GetAttribute(1), Variation.Desc); } //[Variation("MoveToNextAttribute() When iOrdinal=0, without namespace")] public void MoveToNextAttribute4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strValue; TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue, DataReader.GetAttribute(0), Variation.Desc); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue, DataReader.GetAttribute(1), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, with namespace")] public void MoveToFirstAttribute5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strValue0; string strValue; int iMid = (DataReader.AttributeCount) / 2; DataReader.MoveToAttribute(iMid + 1); strValue0 = DataReader.Value; DataReader.MoveToAttribute(iMid); TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue0, strValue, Variation.Desc); TestLog.Compare(strValue, DataReader.GetAttribute(iMid + 1), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=mIddle, without namespace")] public void MoveToFirstAttribute6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strValue0; string strValue; int iMid = (DataReader.AttributeCount) / 2; DataReader.MoveToAttribute(iMid + 1); strValue0 = DataReader.Value; DataReader.MoveToAttribute(iMid); TestLog.Compare(DataReader.MoveToNextAttribute(), true, Variation.Desc); strValue = DataReader.Value; TestLog.Compare(strValue0, strValue, Variation.Desc); TestLog.Compare(strValue, DataReader.GetAttribute(iMid + 1), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=end, with namespace")] public void MoveToFirstAttribute7() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT0"); string strFirst; DataReader.MoveToAttribute((DataReader.AttributeCount) - 1); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } //[Variation("MoveToFirstAttribute() When iOrdinal=end, without namespace")] public void MoveToFirstAttribute8() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ACT1"); string strFirst; DataReader.MoveToAttribute((DataReader.AttributeCount) - 1); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, Variation.Desc); strFirst = DataReader.Value; TestLog.Compare(strFirst, DataReader.GetAttribute(0), Variation.Desc); } } public partial class TCAttributeTest : BridgeHelpers { //[Variation("Attribute Test On None")] public void TestAttributeTestNodeType_None() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.None)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("Attribute Test On Element", Priority = 0)] public void TestAttributeTestNodeType_Element() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.Element)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("Attribute Test On Text", Priority = 0)] public void TestAttributeTestNodeType_Text() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.Text)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("Attribute Test On CDATA")] public void TestAttributeTestNodeType_CDATA() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.CDATA)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("Attribute Test On ProcessingInstruction")] public void TestAttributeTestNodeType_ProcessingInstruction() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On Comment")] public void TestAttributeTestNodeType_Comment() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.Comment)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On DocumentType", Priority = 0)] public void TestAttributeTestNodeType_DocumentType() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.DocumentType)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On Whitespace")] public void TestAttributeTestNodeType_Whitespace() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.Whitespace)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCoung"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On EndElement")] public void TestAttributeTestNodeType_EndElement() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.EndElement)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On XmlDeclaration", Priority = 0)] public void TestAttributeTestNodeType_XmlDeclaration() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.XmlDeclaration)) { int nCount = 3; TestLog.Compare(DataReader.AttributeCount, nCount, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, true, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), true, "Checking MoveToFirstAttribute"); bool bNext = true; TestLog.Compare(DataReader.MoveToNextAttribute(), bNext, "Checking MoveToNextAttribute"); } } //[Variation("AttributeTest On EndEntity")] public void TestAttributeTestNodeType_EndEntity() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.EndEntity)) { TestLog.Compare(DataReader.AttributeCount, 0, "Checking AttributeCount"); TestLog.Compare(DataReader.HasAttributes, false, "Checking HasAttributes"); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, "Checking MoveToFirstAttribute"); TestLog.Compare(DataReader.MoveToNextAttribute(), false, "Checking MoveToNextAttribute"); } } } //[TestCase(Name = "ReadURI", Desc = "Read URI")] public partial class TATextReaderDocType : BridgeHelpers { //[Variation("Valid URI reference as SystemLiteral")] public void TATextReaderDocType_1() { string strxml = "<?xml version='1.0' standalone='no'?><!DOCTYPE ROOT SYSTEM 'se2.dtd'[]><ROOT/>"; XmlReader r = GetReaderStr(strxml); while (r.Read()) ; } void TestUriChar(char ch) { string filename = String.Format("f{0}.dtd", ch); string strxml = String.Format("<!DOCTYPE ROOT SYSTEM '{0}' []><ROOT></ROOT>", filename); XmlReader r = GetReaderStr(strxml); while (r.Read()) ; } // XML 1.0 SE //[Variation("URI reference with disallowed characters in SystemLiteral")] public void TATextReaderDocType_4() { string strDisallowed = " {}^`"; for (int i = 0; i < strDisallowed.Length; i++) TestUriChar(strDisallowed[i]); } } public partial class TCXmlns : BridgeHelpers { private string _ST_ENS1 = "EMPTY_NAMESPACE1"; private string _ST_NS2 = "NAMESPACE2"; //[Variation("Name, LocalName, Prefix and Value with xmlns=ns attribute", Priority = 0)] public void TXmlns1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); DataReader.MoveToAttribute("xmlns"); TestLog.Compare(DataReader.LocalName, "xmlns", "ln"); TestLog.Compare(DataReader.Name, "xmlns", "n"); TestLog.Compare(DataReader.Prefix, String.Empty, "p"); TestLog.Compare(DataReader.Value, "14", "v"); } //[Variation("Name, LocalName, Prefix and Value with xmlns:p=ns attribute")] public void TXmlns2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_NS2); DataReader.MoveToAttribute(0); TestLog.Compare(DataReader.LocalName, "bar", "ln"); TestLog.Compare(DataReader.Name, "xmlns:bar", "n"); TestLog.Compare(DataReader.Prefix, "xmlns", "p"); TestLog.Compare(DataReader.Value, "1", "v"); } //[Variation("LookupNamespace with xmlns=ns attribute")] public void TXmlns3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); DataReader.MoveToAttribute(1); TestLog.Compare(DataReader.LookupNamespace("xmlns"), "http://www.w3.org/2000/xmlns/", "ln"); } //[Variation("MoveToAttribute access on xmlns attribute")] public void TXmlns4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); DataReader.MoveToAttribute(1); TestLog.Compare(DataReader.LocalName, "xmlns", "ln"); TestLog.Compare(DataReader.Name, "xmlns", "n"); TestLog.Compare(DataReader.Prefix, String.Empty, "p"); TestLog.Compare(DataReader.Value, "14", "v"); DataReader.MoveToElement(); TestLog.Compare(DataReader.MoveToAttribute("xmlns"), true, "mta(str)"); TestLog.Compare(DataReader.LocalName, "xmlns", "ln"); TestLog.Compare(DataReader.Name, "xmlns", "n"); TestLog.Compare(DataReader.Prefix, String.Empty, "p"); TestLog.Compare(DataReader.Value, "14", "v"); DataReader.MoveToElement(); TestLog.Compare(DataReader.MoveToAttribute("xmlns"), true, "mta(str, str)"); TestLog.Compare(DataReader.LocalName, "xmlns", "ln"); TestLog.Compare(DataReader.Name, "xmlns", "n"); TestLog.Compare(DataReader.Prefix, String.Empty, "p"); TestLog.Compare(DataReader.Value, "14", "v"); DataReader.MoveToElement(); TestLog.Compare(DataReader.MoveToAttribute("xmlns", "14"), false, "mta inv"); } //[Variation("GetAttribute access on xmlns attribute")] public void TXmlns5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); TestLog.Compare(DataReader.GetAttribute(1), "14", "ga(i)"); TestLog.Compare(DataReader.GetAttribute("xmlns"), "14", "ga(str)"); TestLog.Compare(DataReader.GetAttribute("xmlns"), "14", "ga(str, str)"); TestLog.Compare(DataReader.GetAttribute("xmlns", "14"), null, "ga inv"); } //[Variation("this[xmlns] attribute access")] public void TXmlns6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); TestLog.Compare(DataReader[1], "14", "this[i]"); TestLog.Compare(DataReader["xmlns"], "14", "this[str]"); TestLog.Compare(DataReader["xmlns", "14"], null, "this inv"); } } public partial class TCXmlnsPrefix : BridgeHelpers { private string _ST_ENS1 = "EMPTY_NAMESPACE1"; private string _ST_NS2 = "NAMESPACE2"; private string _strXmlns = "http://www.w3.org/2000/xmlns/"; //[Variation("NamespaceURI of xmlns:a attribute", Priority = 0)] public void TXmlnsPrefix1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_NS2); DataReader.MoveToAttribute(0); TestLog.Compare(DataReader.NamespaceURI, _strXmlns, "nu"); } //[Variation("NamespaceURI of element/attribute with xmlns attribute", Priority = 0)] public void TXmlnsPrefix2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, _ST_ENS1); TestLog.Compare(DataReader.NamespaceURI, "14", "nue"); DataReader.MoveToAttribute("Attr0"); TestLog.Compare(DataReader.NamespaceURI, String.Empty, "nu"); DataReader.MoveToAttribute("xmlns"); TestLog.Compare(DataReader.NamespaceURI, _strXmlns, "nu"); } //[Variation("LookupNamespace with xmlns prefix")] public void TXmlnsPrefix3() { XmlReader DataReader = GetReader(); DataReader.Read(); TestLog.Compare(DataReader.LookupNamespace("xmlns"), null, "ln"); } //[Variation("Define prefix for 'www.w3.org/2000/xmlns'", Priority = 0)] public void TXmlnsPrefix4() { string strxml = "<ROOT xmlns:pxmlns='http://www.w3.org/2000/xmlns/'/>"; try { XmlReader DataReader = GetReaderStr(strxml); DataReader.Read(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } } //[Variation("Redefine namespace attached to xmlns prefix")] public void TXmlnsPrefix5() { string strxml = "<ROOT xmlns:xmlns='http://www.w3.org/2002/xmlns/'/>"; try { XmlReader DataReader = GetReaderStr(strxml); DataReader.Read(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } } } } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.27.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * PageSpeed Insights API Version v2 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/speed/docs/insights/v2/getting-started'>PageSpeed Insights API</a> * <tr><th>API Version<td>v2 * <tr><th>API Rev<td>20161204 (703) * <tr><th>API Docs * <td><a href='https://developers.google.com/speed/docs/insights/v2/getting-started'> * https://developers.google.com/speed/docs/insights/v2/getting-started</a> * <tr><th>Discovery Name<td>pagespeedonline * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using PageSpeed Insights API can be found at * <a href='https://developers.google.com/speed/docs/insights/v2/getting-started'>https://developers.google.com/speed/docs/insights/v2/getting-started</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Pagespeedonline.v2 { /// <summary>The Pagespeedonline Service.</summary> public class PagespeedonlineService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v2"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public PagespeedonlineService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public PagespeedonlineService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { pagespeedapi = new PagespeedapiResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "pagespeedonline"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/pagespeedonline/v2/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "pagespeedonline/v2/"; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://www.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif private readonly PagespeedapiResource pagespeedapi; /// <summary>Gets the Pagespeedapi resource.</summary> public virtual PagespeedapiResource Pagespeedapi { get { return pagespeedapi; } } } ///<summary>A base abstract class for Pagespeedonline requests.</summary> public abstract class PagespeedonlineBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new PagespeedonlineBaseServiceRequest instance.</summary> protected PagespeedonlineBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Pagespeedonline parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "pagespeedapi" collection of methods.</summary> public class PagespeedapiResource { private const string Resource = "pagespeedapi"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public PagespeedapiResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of /// suggestions to make that page faster, and other information.</summary> /// <param name="url">The URL to fetch and analyze</param> public virtual RunpagespeedRequest Runpagespeed(string url) { return new RunpagespeedRequest(service, url); } /// <summary>Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of /// suggestions to make that page faster, and other information.</summary> public class RunpagespeedRequest : PagespeedonlineBaseServiceRequest<Google.Apis.Pagespeedonline.v2.Data.Result> { /// <summary>Constructs a new Runpagespeed request.</summary> public RunpagespeedRequest(Google.Apis.Services.IClientService service, string url) : base(service) { Url = url; InitParameters(); } /// <summary>The URL to fetch and analyze</summary> [Google.Apis.Util.RequestParameterAttribute("url", Google.Apis.Util.RequestParameterType.Query)] public virtual string Url { get; private set; } /// <summary>Indicates if third party resources should be filtered out before PageSpeed analysis.</summary> /// [default: false] [Google.Apis.Util.RequestParameterAttribute("filter_third_party_resources", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> FilterThirdPartyResources { get; set; } /// <summary>The locale used to localize formatted results</summary> [Google.Apis.Util.RequestParameterAttribute("locale", Google.Apis.Util.RequestParameterType.Query)] public virtual string Locale { get; set; } /// <summary>A PageSpeed rule to run; if none are given, all rules are run</summary> [Google.Apis.Util.RequestParameterAttribute("rule", Google.Apis.Util.RequestParameterType.Query)] public virtual Google.Apis.Util.Repeatable<string> Rule { get; set; } /// <summary>Indicates if binary data containing a screenshot should be included</summary> /// [default: false] [Google.Apis.Util.RequestParameterAttribute("screenshot", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Screenshot { get; set; } /// <summary>The analysis strategy to use</summary> [Google.Apis.Util.RequestParameterAttribute("strategy", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<StrategyEnum> Strategy { get; set; } /// <summary>The analysis strategy to use</summary> public enum StrategyEnum { /// <summary>Fetch and analyze the URL for desktop browsers</summary> [Google.Apis.Util.StringValueAttribute("desktop")] Desktop, /// <summary>Fetch and analyze the URL for mobile devices</summary> [Google.Apis.Util.StringValueAttribute("mobile")] Mobile, } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "runpagespeed"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "runPagespeed"; } } /// <summary>Initializes Runpagespeed parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "url", new Google.Apis.Discovery.Parameter { Name = "url", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = @"(?i)http(s)?://.*", }); RequestParameters.Add( "filter_third_party_resources", new Google.Apis.Discovery.Parameter { Name = "filter_third_party_resources", IsRequired = false, ParameterType = "query", DefaultValue = "false", Pattern = null, }); RequestParameters.Add( "locale", new Google.Apis.Discovery.Parameter { Name = "locale", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"[a-zA-Z]+(_[a-zA-Z]+)?", }); RequestParameters.Add( "rule", new Google.Apis.Discovery.Parameter { Name = "rule", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"[a-zA-Z]+", }); RequestParameters.Add( "screenshot", new Google.Apis.Discovery.Parameter { Name = "screenshot", IsRequired = false, ParameterType = "query", DefaultValue = "false", Pattern = null, }); RequestParameters.Add( "strategy", new Google.Apis.Discovery.Parameter { Name = "strategy", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Pagespeedonline.v2.Data { public class PagespeedApiFormatStringV2 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>List of arguments for the format string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("args")] public virtual System.Collections.Generic.IList<PagespeedApiFormatStringV2.ArgsData> Args { get; set; } /// <summary>A localized format string with {{FOO}} placeholders, where 'FOO' is the key of the argument whose /// value should be substituted. For HYPERLINK arguments, the format string will instead contain {{BEGIN_FOO}} /// and {{END_FOO}} for the argument with key 'FOO'.</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } public class ArgsData { /// <summary>The placeholder key for this arg, as a string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("key")] public virtual string Key { get; set; } /// <summary>The screen rectangles being referred to, with dimensions measured in CSS pixels. This is only /// ever used for SNAPSHOT_RECT arguments. If this is absent for a SNAPSHOT_RECT argument, it means that /// that argument refers to the entire snapshot.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rects")] public virtual System.Collections.Generic.IList<ArgsData.RectsData> Rects { get; set; } /// <summary>Secondary screen rectangles being referred to, with dimensions measured in CSS pixels. This is /// only ever used for SNAPSHOT_RECT arguments.</summary> [Newtonsoft.Json.JsonPropertyAttribute("secondary_rects")] public virtual System.Collections.Generic.IList<ArgsData.SecondaryRectsData> SecondaryRects { get; set; } /// <summary>Type of argument. One of URL, STRING_LITERAL, INT_LITERAL, BYTES, DURATION, VERBATIM_STRING, /// PERCENTAGE, HYPERLINK, or SNAPSHOT_RECT.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>Argument value, as a localized string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } public class RectsData { /// <summary>The height of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>The left coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("left")] public virtual System.Nullable<int> Left { get; set; } /// <summary>The top coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("top")] public virtual System.Nullable<int> Top { get; set; } /// <summary>The width of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } } public class SecondaryRectsData { /// <summary>The height of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>The left coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("left")] public virtual System.Nullable<int> Left { get; set; } /// <summary>The top coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("top")] public virtual System.Nullable<int> Top { get; set; } /// <summary>The width of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } } } } public class PagespeedApiImageV2 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Image data base64 encoded.</summary> [Newtonsoft.Json.JsonPropertyAttribute("data")] public virtual string Data { get; set; } /// <summary>Height of screenshot in pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>Unique string key, if any, identifying this image.</summary> [Newtonsoft.Json.JsonPropertyAttribute("key")] public virtual string Key { get; set; } /// <summary>Mime type of image data (e.g. "image/jpeg").</summary> [Newtonsoft.Json.JsonPropertyAttribute("mime_type")] public virtual string MimeType { get; set; } /// <summary>The region of the page that is captured by this image, with dimensions measured in CSS /// pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("page_rect")] public virtual PagespeedApiImageV2.PageRectData PageRect { get; set; } /// <summary>Width of screenshot in pixels.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>The region of the page that is captured by this image, with dimensions measured in CSS /// pixels.</summary> public class PageRectData { /// <summary>The height of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("height")] public virtual System.Nullable<int> Height { get; set; } /// <summary>The left coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("left")] public virtual System.Nullable<int> Left { get; set; } /// <summary>The top coordinate of the rect, in page coordinates.</summary> [Newtonsoft.Json.JsonPropertyAttribute("top")] public virtual System.Nullable<int> Top { get; set; } /// <summary>The width of the rect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("width")] public virtual System.Nullable<int> Width { get; set; } } } public class Result : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and /// run by the server.</summary> [Newtonsoft.Json.JsonPropertyAttribute("formattedResults")] public virtual Result.FormattedResultsData FormattedResults { get; set; } /// <summary>Canonicalized and final URL for the document, after following page redirects (if any).</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>List of rules that were specified in the request, but which the server did not know how to /// instantiate.</summary> [Newtonsoft.Json.JsonPropertyAttribute("invalidRules")] public virtual System.Collections.Generic.IList<string> InvalidRules { get; set; } /// <summary>Kind of result.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, /// etc.</summary> [Newtonsoft.Json.JsonPropertyAttribute("pageStats")] public virtual Result.PageStatsData PageStats { get; set; } /// <summary>Response code for the document. 200 indicates a normal page load. 4xx/5xx indicates an /// error.</summary> [Newtonsoft.Json.JsonPropertyAttribute("responseCode")] public virtual System.Nullable<int> ResponseCode { get; set; } /// <summary>A map with one entry for each rule group in these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ruleGroups")] public virtual System.Collections.Generic.IDictionary<string,Result.RuleGroupsDataElement> RuleGroups { get; set; } /// <summary>Base64-encoded screenshot of the page that was analyzed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("screenshot")] public virtual PagespeedApiImageV2 Screenshot { get; set; } /// <summary>Title of the page, as displayed in the browser's title bar.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The version of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual Result.VersionData Version { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and /// run by the server.</summary> public class FormattedResultsData { /// <summary>The locale of the formattedResults, e.g. "en_US".</summary> [Newtonsoft.Json.JsonPropertyAttribute("locale")] public virtual string Locale { get; set; } /// <summary>Dictionary of formatted rule results, with one entry for each PageSpeed rule instantiated and /// run by the server.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ruleResults")] public virtual System.Collections.Generic.IDictionary<string,FormattedResultsData.RuleResultsDataElement> RuleResults { get; set; } /// <summary>The enum-like identifier for this rule. For instance "EnableKeepAlive" or "AvoidCssImport". Not /// localized.</summary> public class RuleResultsDataElement { /// <summary>List of rule groups that this rule belongs to. Each entry in the list is one of "SPEED" or /// "USABILITY".</summary> [Newtonsoft.Json.JsonPropertyAttribute("groups")] public virtual System.Collections.Generic.IList<string> Groups { get; set; } /// <summary>Localized name of the rule, intended for presentation to a user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("localizedRuleName")] public virtual string LocalizedRuleName { get; set; } /// <summary>The impact (unbounded floating point value) that implementing the suggestions for this rule /// would have on making the page faster. Impact is comparable between rules to determine which rule's /// suggestions would have a higher or lower impact on making a page faster. For instance, if enabling /// compression would save 1MB, while optimizing images would save 500kB, the enable compression rule /// would have 2x the impact of the image optimization rule, all other things being equal.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ruleImpact")] public virtual System.Nullable<double> RuleImpact { get; set; } /// <summary>A brief summary description for the rule, indicating at a high level what should be done to /// follow the rule and what benefit can be gained by doing so.</summary> [Newtonsoft.Json.JsonPropertyAttribute("summary")] public virtual PagespeedApiFormatStringV2 Summary { get; set; } /// <summary>List of blocks of URLs. Each block may contain a heading and a list of URLs. Each URL may /// optionally include additional details.</summary> [Newtonsoft.Json.JsonPropertyAttribute("urlBlocks")] public virtual System.Collections.Generic.IList<RuleResultsDataElement.UrlBlocksData> UrlBlocks { get; set; } public class UrlBlocksData { /// <summary>Heading to be displayed with the list of URLs.</summary> [Newtonsoft.Json.JsonPropertyAttribute("header")] public virtual PagespeedApiFormatStringV2 Header { get; set; } /// <summary>List of entries that provide information about URLs in the url block. /// Optional.</summary> [Newtonsoft.Json.JsonPropertyAttribute("urls")] public virtual System.Collections.Generic.IList<UrlBlocksData.UrlsData> Urls { get; set; } public class UrlsData { /// <summary>List of entries that provide additional details about a single URL. /// Optional.</summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<PagespeedApiFormatStringV2> Details { get; set; } /// <summary>A format string that gives information about the URL, and a list of arguments for /// that format string.</summary> [Newtonsoft.Json.JsonPropertyAttribute("result")] public virtual PagespeedApiFormatStringV2 Result { get; set; } } } } } /// <summary>Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, /// etc.</summary> public class PageStatsData { /// <summary>Number of uncompressed response bytes for CSS resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("cssResponseBytes")] public virtual System.Nullable<long> CssResponseBytes { get; set; } /// <summary>Number of response bytes for flash resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("flashResponseBytes")] public virtual System.Nullable<long> FlashResponseBytes { get; set; } /// <summary>Number of uncompressed response bytes for the main HTML document and all iframes on the /// page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("htmlResponseBytes")] public virtual System.Nullable<long> HtmlResponseBytes { get; set; } /// <summary>Number of response bytes for image resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("imageResponseBytes")] public virtual System.Nullable<long> ImageResponseBytes { get; set; } /// <summary>Number of uncompressed response bytes for JS resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("javascriptResponseBytes")] public virtual System.Nullable<long> JavascriptResponseBytes { get; set; } /// <summary>Number of CSS resources referenced by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberCssResources")] public virtual System.Nullable<int> NumberCssResources { get; set; } /// <summary>Number of unique hosts referenced by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberHosts")] public virtual System.Nullable<int> NumberHosts { get; set; } /// <summary>Number of JavaScript resources referenced by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberJsResources")] public virtual System.Nullable<int> NumberJsResources { get; set; } /// <summary>Number of HTTP resources loaded by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberResources")] public virtual System.Nullable<int> NumberResources { get; set; } /// <summary>Number of static (i.e. cacheable) resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberStaticResources")] public virtual System.Nullable<int> NumberStaticResources { get; set; } /// <summary>Number of response bytes for other resources on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("otherResponseBytes")] public virtual System.Nullable<long> OtherResponseBytes { get; set; } /// <summary>Number of uncompressed response bytes for text resources not covered by other statistics (i.e /// non-HTML, non-script, non-CSS resources) on the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("textResponseBytes")] public virtual System.Nullable<long> TextResponseBytes { get; set; } /// <summary>Total size of all request bytes sent by the page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("totalRequestBytes")] public virtual System.Nullable<long> TotalRequestBytes { get; set; } } /// <summary>The name of this rule group: one of "SPEED" or "USABILITY".</summary> public class RuleGroupsDataElement { /// <summary>The score (0-100) for this rule group, which indicates how much better a page could be in that /// category (e.g. how much faster, or how much more usable). A high score indicates little room for /// improvement, while a lower score indicates more room for improvement.</summary> [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual System.Nullable<int> Score { get; set; } } /// <summary>The version of PageSpeed used to generate these results.</summary> public class VersionData { /// <summary>The major version number of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("major")] public virtual System.Nullable<int> Major { get; set; } /// <summary>The minor version number of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("minor")] public virtual System.Nullable<int> Minor { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading { /// <summary> /// Propagates notification that operations should be canceled. /// </summary> /// <remarks> /// <para> /// A <see cref="CancellationToken"/> may be created directly in an unchangeable canceled or non-canceled state /// using the CancellationToken's constructors. However, to have a CancellationToken that can change /// from a non-canceled to a canceled state, /// <see cref="System.Threading.CancellationTokenSource">CancellationTokenSource</see> must be used. /// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its /// <see cref="System.Threading.CancellationTokenSource.Token">Token</see> property. /// </para> /// <para> /// Once canceled, a token may not transition to a non-canceled state, and a token whose /// <see cref="CanBeCanceled"/> is false will never change to one that can be canceled. /// </para> /// <para> /// All members of this struct are thread-safe and may be used concurrently from multiple threads. /// </para> /// </remarks> [DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")] public readonly struct CancellationToken { // The backing TokenSource. // if null, it implicitly represents the same thing as new CancellationToken(false). // When required, it will be instantiated to reflect this. private readonly CancellationTokenSource _source; //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid private readonly static Action<object> s_actionToActionObjShunt = obj => ((Action)obj)(); /// <summary> /// Returns an empty CancellationToken value. /// </summary> /// <remarks> /// The <see cref="CancellationToken"/> value returned by this property will be non-cancelable by default. /// </remarks> public static CancellationToken None => default; /// <summary> /// Gets whether cancellation has been requested for this token. /// </summary> /// <value>Whether cancellation has been requested for this token.</value> /// <remarks> /// <para> /// This property indicates whether cancellation has been requested for this token, /// either through the token initially being constructed in a canceled state, or through /// calling <see cref="System.Threading.CancellationTokenSource.Cancel()">Cancel</see> /// on the token's associated <see cref="CancellationTokenSource"/>. /// </para> /// <para> /// If this property is true, it only guarantees that cancellation has been requested. /// It does not guarantee that every registered handler /// has finished executing, nor that cancellation requests have finished propagating /// to all registered handlers. Additional synchronization may be required, /// particularly in situations where related objects are being canceled concurrently. /// </para> /// </remarks> public bool IsCancellationRequested => _source != null && _source.IsCancellationRequested; /// <summary> /// Gets whether this token is capable of being in the canceled state. /// </summary> /// <remarks> /// If CanBeCanceled returns false, it is guaranteed that the token will never transition /// into a canceled state, meaning that <see cref="IsCancellationRequested"/> will never /// return true. /// </remarks> public bool CanBeCanceled => _source != null; /// <summary> /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is signaled when the token is canceled.</summary> /// <remarks> /// Accessing this property causes a <see cref="T:System.Threading.WaitHandle">WaitHandle</see> /// to be instantiated. It is preferable to only use this property when necessary, and to then /// dispose the associated <see cref="CancellationTokenSource"/> instance at the earliest opportunity (disposing /// the source will dispose of this allocated handle). The handle should not be closed or disposed directly. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public WaitHandle WaitHandle => (_source ?? CancellationTokenSource.s_neverCanceledSource).WaitHandle; // public CancellationToken() // this constructor is implicit for structs // -> this should behaves exactly as for new CancellationToken(false) /// <summary> /// Internal constructor only a CancellationTokenSource should create a CancellationToken /// </summary> internal CancellationToken(CancellationTokenSource source) => _source = source; /// <summary> /// Initializes the <see cref="T:System.Threading.CancellationToken">CancellationToken</see>. /// </summary> /// <param name="canceled"> /// The canceled state for the token. /// </param> /// <remarks> /// Tokens created with this constructor will remain in the canceled state specified /// by the <paramref name="canceled"/> parameter. If <paramref name="canceled"/> is false, /// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be false. /// If <paramref name="canceled"/> is true, /// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be true. /// </remarks> public CancellationToken(bool canceled) : this(canceled ? CancellationTokenSource.s_canceledSource : null) { } /// <summary> /// Registers a delegate that will be called when this <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action callback) => Register( s_actionToActionObjShunt, callback ?? throw new ArgumentNullException(nameof(callback)), useSynchronizationContext: false, useExecutionContext: true); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) => Register( s_actionToActionObjShunt, callback ?? throw new ArgumentNullException(nameof(callback)), useSynchronizationContext, useExecutionContext: true); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action<object> callback, object state) => Register(callback, state, useSynchronizationContext: false, useExecutionContext: true); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, /// will be captured along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public CancellationTokenRegistration Register(Action<object> callback, object state, bool useSynchronizationContext) => Register(callback, state, useSynchronizationContext, useExecutionContext: true); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the delegate will be run immediately and synchronously. /// Any exception the delegate generates will be propagated out of this method call. /// </para> /// <para> /// <see cref="System.Threading.ExecutionContext">ExecutionContext</see> is not captured nor flowed /// to the callback's invocation. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration UnsafeRegister(Action<object> callback, object state) => Register(callback, state, useSynchronizationContext: false, useExecutionContext: false); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> private CancellationTokenRegistration Register(Action<object> callback, object state, bool useSynchronizationContext, bool useExecutionContext) { if (callback == null) throw new ArgumentNullException(nameof(callback)); CancellationTokenSource source = _source; return source != null ? source.InternalRegister(callback, state, useSynchronizationContext ? SynchronizationContext.Current : null, useExecutionContext ? ExecutionContext.Capture() : null) : default; // Nothing to do for tokens than can never reach the canceled state. Give back a dummy registration. } /// <summary> /// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the /// specified token. /// </summary> /// <param name="other">The other <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to which to compare this /// instance.</param> /// <returns>True if the instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed /// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns> public bool Equals(CancellationToken other) => _source == other._source; /// <summary> /// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the /// specified <see cref="T:System.Object"/>. /// </summary> /// <param name="other">The other object to which to compare this instance.</param> /// <returns>True if <paramref name="other"/> is a <see cref="T:System.Threading.CancellationToken">CancellationToken</see> /// and if the two instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed /// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public override bool Equals(object other) => other is CancellationToken && Equals((CancellationToken)other); /// <summary> /// Serves as a hash function for a <see cref="T:System.Threading.CancellationToken">CancellationToken</see>. /// </summary> /// <returns>A hash code for the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance.</returns> public override int GetHashCode() => (_source ?? CancellationTokenSource.s_neverCanceledSource).GetHashCode(); /// <summary> /// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are equal. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True if the instances are equal; otherwise, false.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public static bool operator ==(CancellationToken left, CancellationToken right) => left.Equals(right); /// <summary> /// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are not equal. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True if the instances are not equal; otherwise, false.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public static bool operator !=(CancellationToken left, CancellationToken right) => !left.Equals(right); /// <summary> /// Throws a <see cref="T:System.OperationCanceledException">OperationCanceledException</see> if /// this token has had cancellation requested. /// </summary> /// <remarks> /// This method provides functionality equivalent to: /// <code> /// if (token.IsCancellationRequested) /// throw new OperationCanceledException(token); /// </code> /// </remarks> /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public void ThrowIfCancellationRequested() { if (IsCancellationRequested) ThrowOperationCanceledException(); } // Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested private void ThrowOperationCanceledException() => throw new OperationCanceledException(SR.OperationCanceled, this); } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id$")] namespace Elmah { #region Imports using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Web; #endregion /// <summary> /// HTTP module implementation that posts tweets (short messages /// usually limited to 140 characters) about unhandled exceptions in /// an ASP.NET Web application to a Twitter account. /// </summary> /// <remarks> /// This module requires that the hosting application has permissions /// send HTTP POST requests to another Internet domain. /// </remarks> public class ErrorTweetModule : HttpModuleBase, IExceptionFiltering { public event ExceptionFilterEventHandler Filtering; private ICredentials _credentials; private string _statusFormat; private Uri _url; private int _maxStatusLength; private string _ellipsis; private string _formFormat; private ArrayList _requests; /// <summary> /// Initializes the module and prepares it to handle requests. /// </summary> protected override void OnInit(HttpApplication application) { if (application == null) throw new ArgumentNullException("application"); // // Get the configuration section of this module. // If it's not there then there is nothing to initialize or do. // In this case, the module is as good as mute. // IDictionary config = (IDictionary) GetConfig(); if (config == null) return; string userName = GetSetting(config, "userName", string.Empty); string password = GetSetting(config, "password", string.Empty); string statusFormat = GetSetting(config, "statusFormat", "{Message}"); int maxStatusLength = int.Parse(GetSetting(config, "maxStatusLength", "140"), NumberStyles.None, CultureInfo.InvariantCulture); string ellipsis = GetSetting(config, "ellipsis", /* ... */ "\x2026"); string formFormat = GetSetting(config, "formFormat", "status={0}"); Uri url = new Uri(GetSetting(config, "url", "http://twitter.com/statuses/update.xml") #if !NET_1_1 && !NET_1_0 , UriKind.Absolute #endif ); _credentials = new NetworkCredential(userName, password); _statusFormat = statusFormat; _url = url; _maxStatusLength = maxStatusLength; _ellipsis = ellipsis; _formFormat = formFormat; _requests = ArrayList.Synchronized(new ArrayList(4)); application.Error += new EventHandler(OnError); ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled); } /// <summary> /// Gets the <see cref="ErrorLog"/> instance to which the module /// will log exceptions. /// </summary> protected virtual ErrorLog GetErrorLog(HttpContext context) { return ErrorLog.GetDefault(context); } /// <summary> /// The handler called when an unhandled exception bubbles up to /// the module. /// </summary> protected virtual void OnError(object sender, EventArgs args) { HttpApplication application = (HttpApplication) sender; LogException(application.Server.GetLastError(), application.Context); } /// <summary> /// The handler called when an exception is explicitly signaled. /// </summary> protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args) { LogException(args.Exception, args.Context); } /// <summary> /// Logs an exception and its context to the error log. /// </summary> protected virtual void LogException(Exception e, HttpContext context) { if (e == null) throw new ArgumentNullException("e"); // // Fire an event to check if listeners want to filter out // logging of the uncaught exception. // ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context); OnFiltering(args); if (args.Dismissed) return; // // Tweet away... // HttpWebRequest request = null; try { string status = StringFormatter.Format(_statusFormat, new Error(e, context)); // // Apply ellipsis if status is too long. If the trimmed // status plus ellipsis yields nothing then just use // the trimmed status without ellipsis. This can happen if // someone gives an ellipsis that is ridiculously long. // int maxLength = _maxStatusLength; if (status.Length > maxLength) { string ellipsis = _ellipsis; int trimmedStatusLength = maxLength - ellipsis.Length; status = trimmedStatusLength >= 0 ? status.Substring(0, trimmedStatusLength) + ellipsis : status.Substring(0, maxLength); } // // Submit the status by posting form data as typically down // by browsers for forms found in HTML. // request = (HttpWebRequest) WebRequest.Create(_url); request.Method = "POST"; // WebRequestMethods.Http.Post; request.ContentType = "application/x-www-form-urlencoded"; if (_credentials != null) // Need Basic authentication? { request.Credentials = _credentials; request.PreAuthenticate = true; } // See http://blogs.msdn.com/shitals/archive/2008/12/27/9254245.aspx request.ServicePoint.Expect100Continue = false; // // URL-encode status into the form and get the bytes to // determine and set the content length. // string encodedForm = string.Format(_formFormat, HttpUtility.UrlEncode(status)); byte[] data = Encoding.ASCII.GetBytes(encodedForm); Debug.Assert(data.Length > 0); request.ContentLength = data.Length; // // Get the request stream into which the form data is to // be written. This is done asynchronously to free up this // thread. // // NOTE: We maintain a (possibly paranoid) list of // outstanding requests and add the request to it so that // it does not get treated as garbage by GC. In effect, // we are creating an explicit root. It is also possible // for this module to get disposed before a request // completes. During the callback, no other member should // be touched except the requests list! // _requests.Add(request); IAsyncResult ar = request.BeginGetRequestStream( new AsyncCallback(OnGetRequestStreamCompleted), AsyncArgs(request, data)); } catch (Exception localException) { // // IMPORTANT! We swallow any exception raised during the // logging and send them out to the trace . The idea // here is that logging of exceptions by itself should not // be critical to the overall operation of the application. // The bad thing is that we catch ANY kind of exception, // even system ones and potentially let them slip by. // OnWebPostError(request, localException); } } private void OnWebPostError(WebRequest request, Exception e) { Debug.Assert(e != null); Trace.WriteLine(e); if (request != null) _requests.Remove(request); } private static object[] AsyncArgs(params object[] args) { return args; } private void OnGetRequestStreamCompleted(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); object[] args = (object[]) ar.AsyncState; OnGetRequestStreamCompleted(ar, (WebRequest) args[0], (byte[]) args[1]); } private void OnGetRequestStreamCompleted(IAsyncResult ar, WebRequest request, byte[] data) { Debug.Assert(ar != null); Debug.Assert(request != null); Debug.Assert(data != null); Debug.Assert(data.Length > 0); try { using (Stream output = request.EndGetRequestStream(ar)) output.Write(data, 0, data.Length); request.BeginGetResponse(new AsyncCallback(OnGetResponseCompleted), request); } catch (Exception e) { OnWebPostError(request, e); } } private void OnGetResponseCompleted(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); OnGetResponseCompleted(ar, (WebRequest) ar.AsyncState); } private void OnGetResponseCompleted(IAsyncResult ar, WebRequest request) { Debug.Assert(ar != null); Debug.Assert(request != null); try { Debug.Assert(request != null); request.EndGetResponse(ar).Close(); // Not interested; assume OK _requests.Remove(request); } catch (Exception e) { OnWebPostError(request, e); } } /// <summary> /// Raises the <see cref="Filtering"/> event. /// </summary> protected virtual void OnFiltering(ExceptionFilterEventArgs args) { ExceptionFilterEventHandler handler = Filtering; if (handler != null) handler(this, args); } /// <summary> /// Determines whether the module will be registered for discovery /// in partial trust environments or not. /// </summary> protected override bool SupportDiscoverability { get { return true; } } /// <summary> /// Gets the configuration object used by <see cref="OnInit"/> to read /// the settings for module. /// </summary> protected virtual object GetConfig() { return Configuration.GetSubsection("errorTweet"); } private static string GetSetting(IDictionary config, string name, string defaultValue) { Debug.Assert(config != null); Debug.AssertStringNotEmpty(name); string value = Mask.NullString((string)config[name]); if (value.Length == 0) { if (defaultValue == null) { throw new ApplicationException(string.Format( "The required configuration setting '{0}' is missing for the error tweeting module.", name)); } value = defaultValue; } return value; } } }
/* * 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.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Land { public class LandChannel : ILandChannel { #region Constants //Land types set with flags in ParcelOverlay. //Only one of these can be used. public const float BAN_LINE_SAFETY_HIEGHT = 100; public const byte LAND_FLAG_PROPERTY_BORDER_SOUTH = 128; //Equals 10000000 public const byte LAND_FLAG_PROPERTY_BORDER_WEST = 64; //Equals 01000000 //RequestResults (I think these are right, they seem to work): public const int LAND_RESULT_MULTIPLE = 1; // The request they made contained more than a single peice of land public const int LAND_RESULT_SINGLE = 0; // The request they made contained only a single piece of land //ParcelSelectObjects public const int LAND_SELECT_OBJECTS_GROUP = 4; public const int LAND_SELECT_OBJECTS_OTHER = 8; public const int LAND_SELECT_OBJECTS_OWNER = 2; public const byte LAND_TYPE_IS_BEING_AUCTIONED = 5; //Equals 00000101 public const byte LAND_TYPE_IS_FOR_SALE = 4; //Equals 00000100 public const byte LAND_TYPE_OWNED_BY_GROUP = 2; //Equals 00000010 public const byte LAND_TYPE_OWNED_BY_OTHER = 1; //Equals 00000001 public const byte LAND_TYPE_OWNED_BY_REQUESTER = 3; //Equals 00000011 public const byte LAND_TYPE_PUBLIC = 0; //Equals 00000000 //These are other constants. Yay! public const int START_LAND_LOCAL_ID = 1; #endregion private readonly Scene m_scene; private readonly LandManagementModule m_landManagementModule; public LandChannel(Scene scene, LandManagementModule landManagementMod) { m_scene = scene; m_landManagementModule = landManagementMod; } #region ILandChannel Members public ILandObject GetLandObject(float x_float, float y_float) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x_float, y_float); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.LandData.Name = "NO LAND"; return obj; } public ILandObject GetLandObject(int localID) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(localID); } return null; } public ILandObject GetLandObject(Vector3 position) { return GetLandObject(position.X, position.Y); } public ILandObject GetLandObject(int x, int y) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x, y); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.LandData.Name = "NO LAND"; return obj; } public List<ILandObject> AllParcels() { if (m_landManagementModule != null) { return m_landManagementModule.AllParcels(); } return new List<ILandObject>(); } public void Clear(bool setupDefaultParcel) { if (m_landManagementModule != null) m_landManagementModule.Clear(setupDefaultParcel); } public List<ILandObject> ParcelsNearPoint(Vector3 position) { if (m_landManagementModule != null) { return m_landManagementModule.ParcelsNearPoint(position); } return new List<ILandObject>(); } public bool IsForcefulBansAllowed() { if (m_landManagementModule != null) { return m_landManagementModule.AllowedForcefulBans; } return false; } public void UpdateLandObject(int localID, LandData data) { if (m_landManagementModule != null) { m_landManagementModule.UpdateLandObject(localID, data); } } public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { if (m_landManagementModule != null) { m_landManagementModule.Join(start_x, start_y, end_x, end_y, attempting_user_id); } } public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { if (m_landManagementModule != null) { m_landManagementModule.Subdivide(start_x, start_y, end_x, end_y, attempting_user_id); } } public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) { if (m_landManagementModule != null) { m_landManagementModule.ReturnObjectsInParcel(localID, returnType, agentIDs, taskIDs, remoteClient); } } public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setParcelObjectMaxOverride(overrideDel); } } public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setSimulatorObjectMaxOverride(overrideDel); } } public void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime) { if (m_landManagementModule != null) { m_landManagementModule.setParcelOtherCleanTime(remoteClient, localID, otherCleanTime); } } #endregion } }
/* * C# port of Mozilla Character Set Detector * https://code.google.com/p/chardetsharp/ * * Original Mozilla License Block follows * */ #region License Block // Version: MPL 1.1/GPL 2.0/LGPL 2.1 // // The contents of this file are subject to the Mozilla Public License Version // 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License // for the specific language governing rights and limitations under the // License. // // The Original Code is Mozilla Universal charset detector code. // // The Initial Developer of the Original Code is // Netscape Communications Corporation. // Portions created by the Initial Developer are Copyright (C) 2001 // the Initial Developer. All Rights Reserved. // // Contributor(s): // // Alternatively, the contents of this file may be used under the terms of // either the GNU General Public License Version 2 or later (the "GPL"), or // the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), // in which case the provisions of the GPL or the LGPL are applicable instead // of those above. If you wish to allow use of your version of this file only // under the terms of either the GPL or the LGPL, and not to allow others to // use your version of this file under the terms of the MPL, indicate your // decision by deleting the provisions above and replace them with the notice // and other provisions required by the GPL or the LGPL. If you do not delete // the provisions above, a recipient may use your version of this file under // the terms of any one of the MPL, the GPL or the LGPL. #endregion namespace Cloney.Core.CharsetDetection { internal partial class SequenceModel { //***************************************************************** // 255: Control characters that usually does not exist in any text // 254: Carriage/Return // 253: symbol (punctuation) that does not belong to word // 252: 0 - 9 //***************************************************************** static readonly byte[] Latin7_CharToOrderMap = new byte[] { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253, 82,100,104, 94, 98,101,116,102,111,187,117, 92, 88,113, 85, //40 79,118,105, 83, 67,114,119, 95, 99,109,188,253,253,253,253,253, //50 253, 72, 70, 80, 81, 60, 96, 93, 89, 68,120, 97, 77, 86, 69, 55, //60 78,115, 65, 66, 58, 76,106,103, 87,107,112,253,253,253,253,253, //70 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //80 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //90 253,233, 90,253,253,253,253,253,253,253,253,253,253, 74,253,253, //a0 253,253,253,253,247,248, 61, 36, 46, 71, 73,253, 54,253,108,123, //b0 110, 31, 51, 43, 41, 34, 91, 40, 52, 47, 44, 53, 38, 49, 59, 39, //c0 35, 48,250, 37, 33, 45, 56, 50, 84, 57,120,121, 17, 18, 22, 15, //d0 124, 1, 29, 20, 21, 3, 32, 13, 25, 5, 11, 16, 10, 6, 30, 4, //e0 9, 8, 14, 7, 2, 12, 28, 23, 42, 24, 64, 75, 19, 26, 27,253, //f0 }; static readonly byte[] win1253_CharToOrderMap = new byte[] { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253, 82,100,104, 94, 98,101,116,102,111,187,117, 92, 88,113, 85, //40 79,118,105, 83, 67,114,119, 95, 99,109,188,253,253,253,253,253, //50 253, 72, 70, 80, 81, 60, 96, 93, 89, 68,120, 97, 77, 86, 69, 55, //60 78,115, 65, 66, 58, 76,106,103, 87,107,112,253,253,253,253,253, //70 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //80 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //90 253,233, 61,253,253,253,253,253,253,253,253,253,253, 74,253,253, //a0 253,253,253,253,247,253,253, 36, 46, 71, 73,253, 54,253,108,123, //b0 110, 31, 51, 43, 41, 34, 91, 40, 52, 47, 44, 53, 38, 49, 59, 39, //c0 35, 48,250, 37, 33, 45, 56, 50, 84, 57,120,121, 17, 18, 22, 15, //d0 124, 1, 29, 20, 21, 3, 32, 13, 25, 5, 11, 16, 10, 6, 30, 4, //e0 9, 8, 14, 7, 2, 12, 28, 23, 42, 24, 64, 75, 19, 26, 27,253, //f0 }; //Model Table: //total sequences: 100% //first 512 sequences: 98.2851% //first 1024 sequences:1.7001% //rest sequences: 0.0359% //negative sequences: 0.0148% static readonly byte[] GreekLangModel = new byte[] { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,2,2,3,3,3,3,3,3,3,3,1,3,3,3,0,2,2,3,3,0,3,0,3,2,0,3,3,3,0, 3,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,0,3,3,0,3,2,3,3,0,3,2,3,3,3,0,0,3,0,3,0,3,3,2,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0, 0,2,3,2,2,3,3,3,3,3,3,3,3,0,3,3,3,3,0,2,3,3,0,3,3,3,3,2,3,3,3,0, 2,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,2,1,3,3,3,3,2,3,3,2,3,3,2,0, 0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,2,3,3,0, 2,0,1,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,2,3,0,0,0,0,3,3,0,3,1,3,3,3,0,3,3,0,3,3,3,3,0,0,0,0, 2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,0,3,0,3,3,3,3,3,0,3,2,2,2,3,0,2,3,3,3,3,3,2,3,3,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,3,2,2,2,3,3,3,3,0,3,1,3,3,3,3,2,3,3,3,3,3,3,3,2,2,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,2,0,3,0,0,0,3,3,2,3,3,3,3,3,0,0,3,2,3,0,2,3,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,3,0,0,3,3,0,2,3,0,3,0,3,3,3,0,0,3,0,3,0,2,2,3,3,0,0, 0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,2,0,3,2,3,3,3,3,0,3,3,3,3,3,0,3,3,2,3,2,3,3,2,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,2,3,2,3,3,3,3,3,3,0,2,3,2,3,2,2,2,3,2,3,3,2,3,0,2,2,2,3,0, 2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,0,3,3,3,2,3,3,0,0,3,0,3,0,0,0,3,2,0,3,0,3,0,0,2,0,2,0, 0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,0,3,0,0,0,3,3,0,3,3,3,0,0,1,2,3,0, 3,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,2,0,0,3,2,2,3,3,0,3,3,3,3,3,2,1,3,0,3,2,3,3,2,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,3,0,2,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,3,0,3,2,3,0,0,3,3,3,0, 3,0,0,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,0,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,2,0,3,2,3,0,0,3,2,3,0, 2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,1,2,2,3,3,3,3,3,3,0,2,3,0,3,0,0,0,3,3,0,3,0,2,0,0,2,3,1,0, 2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,3,0,3,0,3,3,2,3,0,3,3,3,3,3,3,0,3,3,3,0,2,3,0,0,3,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,0,0,3,0,0,0,3,3,0,3,0,2,3,3,0,0,3,0,3,0,3,3,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,0,3,3,3,3,3,3,0,0,3,0,2,0,0,0,3,3,0,3,0,3,0,0,2,0,2,0, 0,0,0,0,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,3,0,3,0,2,0,3,2,0,3,2,3,2,3,0,0,3,2,3,2,3,3,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,2,3,3,3,3,3,0,0,0,3,0,2,1,0,0,3,2,2,2,0,3,0,0,2,2,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,2,0,3,0,3,0,3,3,0,2,1,2,3,3,0,0,3,0,3,0,3,3,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,3,3,3,0,3,3,3,3,3,3,0,2,3,0,3,0,0,0,2,1,0,2,2,3,0,0,2,2,2,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,2,3,3,3,2,3,0,0,1,3,0,2,0,0,0,0,3,0,1,0,2,0,0,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,1,0,3,0,0,0,3,2,0,3,2,3,3,3,0,0,3,0,3,2,2,2,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,0,0,3,0,0,0,0,2,0,2,3,3,2,2,2,2,3,0,2,0,2,2,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,2,0,0,0,0,0,0,2,3,0,2,0,2,3,2,0,0,3,0,3,0,3,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,3,2,3,3,2,2,3,0,2,0,3,0,0,0,2,0,0,0,0,1,2,0,2,0,2,0, 0,2,0,2,0,2,2,0,0,1,0,2,2,2,0,2,2,2,0,2,2,2,0,0,2,0,0,1,0,0,0,0, 0,2,0,3,3,2,0,0,0,0,0,0,1,3,0,2,0,2,2,2,0,0,2,0,3,0,0,2,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,2,3,2,0,2,2,0,2,0,2,2,0,2,0,2,2,2,0,0,0,0,0,0,2,3,0,0,0,2, 0,1,2,0,0,0,0,2,2,0,0,0,2,1,0,2,2,0,0,0,0,0,0,1,0,2,0,0,0,0,0,0, 0,0,2,1,0,2,3,2,2,3,2,3,2,0,0,3,3,3,0,0,3,2,0,0,0,1,1,0,2,0,2,2, 0,2,0,2,0,2,2,0,0,2,0,2,2,2,0,2,2,2,2,0,0,2,0,0,0,2,0,1,0,0,0,0, 0,3,0,3,3,2,2,0,3,0,0,0,2,2,0,2,2,2,1,2,0,0,1,2,2,0,0,3,0,0,0,2, 0,1,2,0,0,0,1,2,0,0,0,0,0,0,0,2,2,0,1,0,0,2,0,0,0,2,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,3,3,2,2,0,0,0,2,0,2,3,3,0,2,0,0,0,0,0,0,2,2,2,0,2,2,0,2,0,2, 0,2,2,0,0,2,2,2,2,1,0,0,2,2,0,2,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0, 0,2,0,3,2,3,0,0,0,3,0,0,2,2,0,2,0,2,2,2,0,0,2,0,0,0,0,0,0,0,0,2, 0,0,2,2,0,0,2,2,2,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,3,2,0,2,2,2,2,2,0,0,0,2,0,0,0,0,2,0,1,0,0,2,0,1,0,0,0, 0,2,2,2,0,2,2,0,1,2,0,2,2,2,0,2,2,2,2,1,2,2,0,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,2,0,2,0,2,2,0,0,0,0,1,2,1,0,0,2,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,3,2,3,0,0,2,0,0,0,2,2,0,2,0,0,0,1,0,0,2,0,2,0,2,2,0,0,0,0, 0,0,2,0,0,0,0,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0, 0,2,2,3,2,2,0,0,0,0,0,0,1,3,0,2,0,2,2,0,0,0,1,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,2,0,3,2,0,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 0,0,2,0,0,0,0,1,1,0,0,2,1,2,0,2,2,0,1,0,0,1,0,0,0,2,0,0,0,0,0,0, 0,3,0,2,2,2,0,0,2,0,0,0,2,0,0,0,2,3,0,2,0,0,0,0,0,0,2,2,0,0,0,2, 0,1,2,0,0,0,1,2,2,1,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,1,2,0,2,2,0,2,0,0,2,0,0,0,0,1,2,1,0,2,1,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,0,3,1,2,2,0,2,0,0,0,0,2,0,0,0,2,0,0,3,0,0,0,0,2,2,2,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,1,0,2,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0,2, 0,2,2,0,0,2,2,2,2,2,0,1,2,0,0,0,2,2,0,1,0,2,0,0,2,2,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,3,0,0,2,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,2, 0,1,2,0,0,0,0,2,2,1,0,1,0,1,0,2,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0, 0,2,0,1,2,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,0,0,0,0,1,0,0,0,0,0,0,2, 0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0,0, 0,2,2,2,2,0,0,0,3,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,1, 0,0,2,0,0,0,0,1,2,0,0,0,0,0,0,2,2,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0, 0,2,0,2,2,2,0,0,2,0,0,0,0,0,0,0,2,2,2,0,0,0,2,0,0,0,0,0,0,0,0,2, 0,0,1,0,0,0,0,2,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,3,0,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,2, 0,0,2,0,0,0,0,2,2,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,2,2,1,0,0,0,0,0,0,2,0,0,2,0,2,2,2,0,0,0,0,0,0,2,0,0,0,0,2, 0,0,2,0,0,2,0,2,2,0,0,0,0,2,0,2,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0, 0,0,3,0,0,0,2,2,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0,0,0,0, 0,2,2,2,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1, 0,0,0,0,0,0,0,2,1,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,2,0,0,0,2,0,0,0,0,0,1,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,2,0,0,0, 0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,2,0,2,0,0,0, 0,0,0,0,0,0,0,0,2,1,0,0,0,0,0,0,2,0,0,0,1,2,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; public static readonly SequenceModel Latin7Model = new SequenceModel( Latin7_CharToOrderMap, GreekLangModel, 0.982851f, false, "ISO-8859-7" ); public static readonly SequenceModel Win1253Model = new SequenceModel( win1253_CharToOrderMap, GreekLangModel, 0.982851f, false, "windows-1253" ); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: crm/guests/guest_checked_in.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 HOLMS.Types.CRM.Guests { /// <summary>Holder for reflection information generated from crm/guests/guest_checked_in.proto</summary> public static partial class GuestCheckedInReflection { #region Descriptor /// <summary>File descriptor for crm/guests/guest_checked_in.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GuestCheckedInReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiFjcm0vZ3Vlc3RzL2d1ZXN0X2NoZWNrZWRfaW4ucHJvdG8SFmhvbG1zLnR5", "cGVzLmNybS5ndWVzdHMaH3ByaW1pdGl2ZS9tb25ldGFyeV9hbW91bnQucHJv", "dG8aHXByaW1pdGl2ZS9wYl9sb2NhbF9kYXRlLnByb3RvGi5ib29raW5nL2lu", "ZGljYXRvcnMvcmVzZXJ2YXRpb25faW5kaWNhdG9yLnByb3RvGiBjcm0vZ3Vl", "c3RzL2d1ZXN0X2luZGljYXRvci5wcm90byLcAgoOR3Vlc3RDaGVja2VkSW4S", "OQoNY2hlY2tfaW5fZGF0ZRgBIAEoCzIiLmhvbG1zLnR5cGVzLnByaW1pdGl2", "ZS5QYkxvY2FsRGF0ZRI7CgxhdmVyYWdlX3JhdGUYAiABKAsyJS5ob2xtcy50", "eXBlcy5wcmltaXRpdmUuTW9uZXRhcnlBbW91bnQSIgoacmVzZXJ2YXRpb25f", "Ym9va2luZ19udW1iZXIYAyABKAkSTAoOcmVzZXJ2YXRpb25faWQYBCABKAsy", "NC5ob2xtcy50eXBlcy5ib29raW5nLmluZGljYXRvcnMuUmVzZXJ2YXRpb25J", "bmRpY2F0b3ISEwoLcm9vbV9udW1iZXIYBSABKAkSOAoIZ3Vlc3RfaWQYBiAB", "KAsyJi5ob2xtcy50eXBlcy5jcm0uZ3Vlc3RzLkd1ZXN0SW5kaWNhdG9yEhEK", "CXJvb21fdHlwZRgHIAEoCUIlWgpjcm0vZ3Vlc3RzqgIWSE9MTVMuVHlwZXMu", "Q1JNLkd1ZXN0c2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.CRM.Guests.GuestIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.CRM.Guests.GuestCheckedIn), global::HOLMS.Types.CRM.Guests.GuestCheckedIn.Parser, new[]{ "CheckInDate", "AverageRate", "ReservationBookingNumber", "ReservationId", "RoomNumber", "GuestId", "RoomType" }, null, null, null) })); } #endregion } #region Messages public sealed partial class GuestCheckedIn : pb::IMessage<GuestCheckedIn> { private static readonly pb::MessageParser<GuestCheckedIn> _parser = new pb::MessageParser<GuestCheckedIn>(() => new GuestCheckedIn()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GuestCheckedIn> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.CRM.Guests.GuestCheckedInReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GuestCheckedIn() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GuestCheckedIn(GuestCheckedIn other) : this() { CheckInDate = other.checkInDate_ != null ? other.CheckInDate.Clone() : null; AverageRate = other.averageRate_ != null ? other.AverageRate.Clone() : null; reservationBookingNumber_ = other.reservationBookingNumber_; ReservationId = other.reservationId_ != null ? other.ReservationId.Clone() : null; roomNumber_ = other.roomNumber_; GuestId = other.guestId_ != null ? other.GuestId.Clone() : null; roomType_ = other.roomType_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GuestCheckedIn Clone() { return new GuestCheckedIn(this); } /// <summary>Field number for the "check_in_date" field.</summary> public const int CheckInDateFieldNumber = 1; private global::HOLMS.Types.Primitive.PbLocalDate checkInDate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate CheckInDate { get { return checkInDate_; } set { checkInDate_ = value; } } /// <summary>Field number for the "average_rate" field.</summary> public const int AverageRateFieldNumber = 2; private global::HOLMS.Types.Primitive.MonetaryAmount averageRate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount AverageRate { get { return averageRate_; } set { averageRate_ = value; } } /// <summary>Field number for the "reservation_booking_number" field.</summary> public const int ReservationBookingNumberFieldNumber = 3; private string reservationBookingNumber_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ReservationBookingNumber { get { return reservationBookingNumber_; } set { reservationBookingNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "reservation_id" field.</summary> public const int ReservationIdFieldNumber = 4; private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservationId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.ReservationIndicator ReservationId { get { return reservationId_; } set { reservationId_ = value; } } /// <summary>Field number for the "room_number" field.</summary> public const int RoomNumberFieldNumber = 5; private string roomNumber_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string RoomNumber { get { return roomNumber_; } set { roomNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "guest_id" field.</summary> public const int GuestIdFieldNumber = 6; private global::HOLMS.Types.CRM.Guests.GuestIndicator guestId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.CRM.Guests.GuestIndicator GuestId { get { return guestId_; } set { guestId_ = value; } } /// <summary>Field number for the "room_type" field.</summary> public const int RoomTypeFieldNumber = 7; private string roomType_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string RoomType { get { return roomType_; } set { roomType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GuestCheckedIn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GuestCheckedIn other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(CheckInDate, other.CheckInDate)) return false; if (!object.Equals(AverageRate, other.AverageRate)) return false; if (ReservationBookingNumber != other.ReservationBookingNumber) return false; if (!object.Equals(ReservationId, other.ReservationId)) return false; if (RoomNumber != other.RoomNumber) return false; if (!object.Equals(GuestId, other.GuestId)) return false; if (RoomType != other.RoomType) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (checkInDate_ != null) hash ^= CheckInDate.GetHashCode(); if (averageRate_ != null) hash ^= AverageRate.GetHashCode(); if (ReservationBookingNumber.Length != 0) hash ^= ReservationBookingNumber.GetHashCode(); if (reservationId_ != null) hash ^= ReservationId.GetHashCode(); if (RoomNumber.Length != 0) hash ^= RoomNumber.GetHashCode(); if (guestId_ != null) hash ^= GuestId.GetHashCode(); if (RoomType.Length != 0) hash ^= RoomType.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 (checkInDate_ != null) { output.WriteRawTag(10); output.WriteMessage(CheckInDate); } if (averageRate_ != null) { output.WriteRawTag(18); output.WriteMessage(AverageRate); } if (ReservationBookingNumber.Length != 0) { output.WriteRawTag(26); output.WriteString(ReservationBookingNumber); } if (reservationId_ != null) { output.WriteRawTag(34); output.WriteMessage(ReservationId); } if (RoomNumber.Length != 0) { output.WriteRawTag(42); output.WriteString(RoomNumber); } if (guestId_ != null) { output.WriteRawTag(50); output.WriteMessage(GuestId); } if (RoomType.Length != 0) { output.WriteRawTag(58); output.WriteString(RoomType); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (checkInDate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CheckInDate); } if (averageRate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(AverageRate); } if (ReservationBookingNumber.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ReservationBookingNumber); } if (reservationId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReservationId); } if (RoomNumber.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(RoomNumber); } if (guestId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(GuestId); } if (RoomType.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(RoomType); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GuestCheckedIn other) { if (other == null) { return; } if (other.checkInDate_ != null) { if (checkInDate_ == null) { checkInDate_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } CheckInDate.MergeFrom(other.CheckInDate); } if (other.averageRate_ != null) { if (averageRate_ == null) { averageRate_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } AverageRate.MergeFrom(other.AverageRate); } if (other.ReservationBookingNumber.Length != 0) { ReservationBookingNumber = other.ReservationBookingNumber; } if (other.reservationId_ != null) { if (reservationId_ == null) { reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } ReservationId.MergeFrom(other.ReservationId); } if (other.RoomNumber.Length != 0) { RoomNumber = other.RoomNumber; } if (other.guestId_ != null) { if (guestId_ == null) { guestId_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator(); } GuestId.MergeFrom(other.GuestId); } if (other.RoomType.Length != 0) { RoomType = other.RoomType; } } [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: { if (checkInDate_ == null) { checkInDate_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(checkInDate_); break; } case 18: { if (averageRate_ == null) { averageRate_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(averageRate_); break; } case 26: { ReservationBookingNumber = input.ReadString(); break; } case 34: { if (reservationId_ == null) { reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } input.ReadMessage(reservationId_); break; } case 42: { RoomNumber = input.ReadString(); break; } case 50: { if (guestId_ == null) { guestId_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator(); } input.ReadMessage(guestId_); break; } case 58: { RoomType = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The core assembly for the DotSpatial 6.0 distribution. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is DotSpatial.dll // // The Initial Developer of this Original Code is Jiri Kadlec. Created 5/26/2009 12:49:10 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // ------------------|------------|--------------------------------------------------------------- // Ted Dunsford | 8/28/2009 | Cleaned up some code formatting using resharper // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// ExportFeature /// </summary> public class AddCustomSymbolDialog : Form { private Button _btnCancel; private Button _btnOk; private ComboBox _cmbSymbolCategory; private Label _lblCategory; private Label _lblName; private TextBox _txtSymbolName; #region Private Variables private readonly List<string> _categories = new List<string>(); private readonly IFeatureSymbolizer _symbolizer; private CustomSymbolizer _customSymbolizer; #endregion #region Windows Form Designer generated code /// <summary> /// Required designer variable. /// </summary> protected IContainer components; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AddCustomSymbolDialog)); this._btnCancel = new System.Windows.Forms.Button(); this._btnOk = new System.Windows.Forms.Button(); this._lblName = new System.Windows.Forms.Label(); this._lblCategory = new System.Windows.Forms.Label(); this._cmbSymbolCategory = new System.Windows.Forms.ComboBox(); this._txtSymbolName = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // _btnCancel // resources.ApplyResources(this._btnCancel, "_btnCancel"); this._btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._btnCancel.Name = "_btnCancel"; this._btnCancel.UseVisualStyleBackColor = true; this._btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // _btnOk // resources.ApplyResources(this._btnOk, "_btnOk"); this._btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this._btnOk.Name = "_btnOk"; this._btnOk.UseVisualStyleBackColor = true; this._btnOk.Click += new System.EventHandler(this.btnOK_Click); // // _lblName // resources.ApplyResources(this._lblName, "_lblName"); this._lblName.Name = "_lblName"; this._lblName.Click += new System.EventHandler(this._lblName_Click); // // _lblCategory // resources.ApplyResources(this._lblCategory, "_lblCategory"); this._lblCategory.Name = "_lblCategory"; // // _cmbSymbolCategory // resources.ApplyResources(this._cmbSymbolCategory, "_cmbSymbolCategory"); this._cmbSymbolCategory.FormattingEnabled = true; this._cmbSymbolCategory.Name = "_cmbSymbolCategory"; // // _txtSymbolName // resources.ApplyResources(this._txtSymbolName, "_txtSymbolName"); this._txtSymbolName.Name = "_txtSymbolName"; // // AddCustomSymbolDialog // resources.ApplyResources(this, "$this"); this.Controls.Add(this._txtSymbolName); this.Controls.Add(this._cmbSymbolCategory); this.Controls.Add(this._lblCategory); this.Controls.Add(this._lblName); this.Controls.Add(this._btnOk); this.Controls.Add(this._btnCancel); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "AddCustomSymbolDialog"; this.ShowIcon = false; this.ResumeLayout(false); this.PerformLayout(); } #endregion #region Constructors /// <summary> /// This looks like a function created by Mr. Jiri and not commented on. /// </summary> /// <param name="symbolCategories"></param> /// <param name="symbolizer"></param> public AddCustomSymbolDialog(List<string> symbolCategories, IFeatureSymbolizer symbolizer) { InitializeComponent(); _symbolizer = symbolizer; _categories = symbolCategories; UpdateCategories(); } #endregion #region Methods #endregion #region Properties /// <summary> /// The custom symbolizer edited by this form /// </summary> public CustomSymbolizer CustomSymbolizer { get { return _customSymbolizer; } } #endregion #region Events #endregion #region Event Handlers #endregion #region Private Functions private void UpdateCategories() { //the default new category will be called 'My Symbols'. if (!_categories.Contains("My Symbols")) { _categories.Insert(0, "My Symbols"); } _cmbSymbolCategory.SuspendLayout(); _cmbSymbolCategory.Items.Clear(); foreach (string cat in _categories) { _cmbSymbolCategory.Items.Add(cat); } _cmbSymbolCategory.SelectedIndex = 0; _cmbSymbolCategory.ResumeLayout(); } /// <summary> /// Creates the new custom symbolizer with the specified name and category /// </summary> /// <returns>the custom symbolizer</returns> private CustomSymbolizer CreateCustomSymbolizer() { CustomSymbolizer custSym = null; if (_symbolizer is PointSymbolizer) { custSym = new CustomPointSymbolizer(); } else if (_symbolizer is LineSymbolizer) { custSym = new CustomLineSymbolizer(); } else if (_symbolizer is PolygonSymbolizer) { custSym = new CustomPolygonSymbolizer(); } if (custSym != null) { custSym.Symbolizer = _symbolizer; custSym.Name = _txtSymbolName.Text; custSym.Category = _cmbSymbolCategory.Text; return custSym; } return null; } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #endregion private void btnOK_Click(object sender, EventArgs e) { //creates the new custom symbolizer CustomSymbolizer newCustSym = CreateCustomSymbolizer(); if (newCustSym != null) { _customSymbolizer = newCustSym; } Close(); } private void btnCancel_Click(object sender, EventArgs e) { Close(); } private void _lblName_Click(object sender, EventArgs e) { } } }
// 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 gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAdGroupAdLabelServiceClientTest { [Category("Autogenerated")][Test] public void GetAdGroupAdLabelRequestObject() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdLabelRequest request = new GetAdGroupAdLabelRequest { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }; gagvr::AdGroupAdLabel expectedResponse = new gagvr::AdGroupAdLabel { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), AdGroupAdAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupAdLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAdLabel response = client.GetAdGroupAdLabel(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupAdLabelRequestObjectAsync() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdLabelRequest request = new GetAdGroupAdLabelRequest { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }; gagvr::AdGroupAdLabel expectedResponse = new gagvr::AdGroupAdLabel { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), AdGroupAdAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupAdLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupAdLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAdLabel responseCallSettings = await client.GetAdGroupAdLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupAdLabel responseCancellationToken = await client.GetAdGroupAdLabelAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupAdLabel() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdLabelRequest request = new GetAdGroupAdLabelRequest { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }; gagvr::AdGroupAdLabel expectedResponse = new gagvr::AdGroupAdLabel { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), AdGroupAdAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupAdLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAdLabel response = client.GetAdGroupAdLabel(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupAdLabelAsync() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdLabelRequest request = new GetAdGroupAdLabelRequest { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }; gagvr::AdGroupAdLabel expectedResponse = new gagvr::AdGroupAdLabel { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), AdGroupAdAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupAdLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupAdLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAdLabel responseCallSettings = await client.GetAdGroupAdLabelAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupAdLabel responseCancellationToken = await client.GetAdGroupAdLabelAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupAdLabelResourceNames() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdLabelRequest request = new GetAdGroupAdLabelRequest { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }; gagvr::AdGroupAdLabel expectedResponse = new gagvr::AdGroupAdLabel { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), AdGroupAdAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupAdLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAdLabel response = client.GetAdGroupAdLabel(request.ResourceNameAsAdGroupAdLabelName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupAdLabelResourceNamesAsync() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupAdLabelRequest request = new GetAdGroupAdLabelRequest { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), }; gagvr::AdGroupAdLabel expectedResponse = new gagvr::AdGroupAdLabel { ResourceNameAsAdGroupAdLabelName = gagvr::AdGroupAdLabelName.FromCustomerAdGroupAdLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]", "[LABEL_ID]"), AdGroupAdAsAdGroupAdName = gagvr::AdGroupAdName.FromCustomerAdGroupAd("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[AD_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupAdLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupAdLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupAdLabel responseCallSettings = await client.GetAdGroupAdLabelAsync(request.ResourceNameAsAdGroupAdLabelName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupAdLabel responseCancellationToken = await client.GetAdGroupAdLabelAsync(request.ResourceNameAsAdGroupAdLabelName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupAdLabelsRequestObject() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupAdLabelsRequest request = new MutateAdGroupAdLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupAdLabelOperation(), }, PartialFailure = false, ValidateOnly = true, }; MutateAdGroupAdLabelsResponse expectedResponse = new MutateAdGroupAdLabelsResponse { Results = { new MutateAdGroupAdLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupAdLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupAdLabelsResponse response = client.MutateAdGroupAdLabels(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupAdLabelsRequestObjectAsync() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupAdLabelsRequest request = new MutateAdGroupAdLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupAdLabelOperation(), }, PartialFailure = false, ValidateOnly = true, }; MutateAdGroupAdLabelsResponse expectedResponse = new MutateAdGroupAdLabelsResponse { Results = { new MutateAdGroupAdLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupAdLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupAdLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupAdLabelsResponse responseCallSettings = await client.MutateAdGroupAdLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupAdLabelsResponse responseCancellationToken = await client.MutateAdGroupAdLabelsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupAdLabels() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupAdLabelsRequest request = new MutateAdGroupAdLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupAdLabelOperation(), }, }; MutateAdGroupAdLabelsResponse expectedResponse = new MutateAdGroupAdLabelsResponse { Results = { new MutateAdGroupAdLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupAdLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupAdLabelsResponse response = client.MutateAdGroupAdLabels(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupAdLabelsAsync() { moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupAdLabelService.AdGroupAdLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupAdLabelsRequest request = new MutateAdGroupAdLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupAdLabelOperation(), }, }; MutateAdGroupAdLabelsResponse expectedResponse = new MutateAdGroupAdLabelsResponse { Results = { new MutateAdGroupAdLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupAdLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupAdLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupAdLabelServiceClient client = new AdGroupAdLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupAdLabelsResponse responseCallSettings = await client.MutateAdGroupAdLabelsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupAdLabelsResponse responseCancellationToken = await client.MutateAdGroupAdLabelsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using MatterHackers.Agg.Font; using MatterHackers.Agg.Image; using MatterHackers.Agg.RasterizerScanline; using MatterHackers.Agg.Transform; using MatterHackers.Agg.UI; using MatterHackers.Agg.VertexSource; using MatterHackers.VectorMath; using System; namespace MatterHackers.Agg { public class FontHinter : GuiWidget { private Slider pixelSizeSlider; private Slider gammaSlider; public FontHinter() { AnchorAll(); FlowLayoutWidget topToBottom = new FlowLayoutWidget(FlowDirection.TopToBottom); topToBottom.AnchorAll(); pixelSizeSlider = new Slider(new Vector2(30, 30), 600 - 60); gammaSlider = new Slider(new Vector2(30, 70), 600 - 60); pixelSizeSlider.Text = "Pixel size={0:F3}"; pixelSizeSlider.SetRange(2, 20); pixelSizeSlider.NumTicks = 23; pixelSizeSlider.Value = 6; gammaSlider.Text = "Gamma={0:F3}"; gammaSlider.SetRange(0.0, 3.0); gammaSlider.Value = 1.0; topToBottom.AddChild(pixelSizeSlider); topToBottom.AddChild(gammaSlider); AddChild(topToBottom); } public override void OnDraw(Graphics2D graphics2D) { GammaLookUpTable gamma = new GammaLookUpTable(gammaSlider.Value); IRecieveBlenderByte NormalBlender = new BlenderBGR(); IRecieveBlenderByte GammaBlender = new BlenderGammaBGR(gamma); ImageBuffer rasterNormal = new ImageBuffer(); rasterNormal.Attach(graphics2D.DestImage, NormalBlender); ImageBuffer rasterGamma = new ImageBuffer(); rasterGamma.Attach(graphics2D.DestImage, GammaBlender); ImageClippingProxy clippingProxyNormal = new ImageClippingProxy(rasterNormal); ImageClippingProxy clippingProxyGamma = new ImageClippingProxy(rasterGamma); clippingProxyNormal.clear(new RGBA_Floats(1, 1, 1)); ScanlineRasterizer ras = new ScanlineRasterizer(); scanline_unpacked_8 sl = new scanline_unpacked_8(); int size_mul = (int)pixelSizeSlider.Value; renderer_enlarged ren_en = new renderer_enlarged(size_mul); StyledTypeFace type = new StyledTypeFace(LiberationSansFont.Instance, 12); IVertexSource character = type.GetGlyphForCharacter('E'); character.rewind(0); ras.reset(); ras.add_path(character); ren_en.RenderSolid(clippingProxyGamma, ras, sl, RGBA_Bytes.Black); ScanlineRenderer scanlineRenderer = new ScanlineRenderer(); scanlineRenderer.RenderSolid(clippingProxyGamma, ras, sl, RGBA_Bytes.Black); ras.gamma(new gamma_none()); PathStorage ps = new PathStorage(); Stroke pg = new Stroke(ps); pg.width(2); DrawBigA(graphics2D); base.OnDraw(graphics2D); } private void DrawBigA(Graphics2D graphics2D) { ScanlineRasterizer m_ras = new ScanlineRasterizer(); m_ras.SetVectorClipBox(0, 0, Width, Height); TypeFacePrinter bigAPrinter = new TypeFacePrinter("a", 150); FlattenCurves flattenedBigA = new FlattenCurves(bigAPrinter); VertexSourceApplyTransform scaleAndTranslate = new VertexSourceApplyTransform(flattenedBigA, Affine.NewTranslation(155, 55)); ScanlineCachePacked8 m_sl = new ScanlineCachePacked8(); ScanlineRenderer scanlineRenderer = new ScanlineRenderer(); #if false ImageProxySubpxelLcd24 clippingProxy = new ImageProxySubpxelLcd24(graphics2D.DestImage, new lcd_distribution_lut()); VertexSourceApplyTransform scaledWide = new VertexSourceApplyTransform(scaleAndTranslate, Affine.NewScaling(3, 1)); m_ras.add_path(scaledWide); scanlineRenderer.render_scanlines_aa_solid(clippingProxy, m_ras, m_sl, RGBA_Bytes.Black); #else m_ras.add_path(scaleAndTranslate); ImageClippingProxy clippingProxy = new ImageClippingProxy(graphics2D.DestImage); scanlineRenderer.RenderSolid(clippingProxy, m_ras, m_sl, RGBA_Bytes.Black); #endif } [STAThread] public static void Main(string[] args) { AppWidgetFactory appWidget = new BlurFactory(); appWidget.CreateWidgetAndRunInWindow(SystemWindow.PixelTypes.Depth24); } } public class BlurFactory : AppWidgetFactory { public override GuiWidget NewWidget() { return new FontHinter(); } public override AppWidgetInfo GetAppParameters() { AppWidgetInfo appWidgetInfo = new AppWidgetInfo( "Bitmap", "Font Hinter", @"", 440, 330); return appWidgetInfo; } } public class lcd_distribution_lut { private byte[] m_primary = new byte[256]; private byte[] m_secondary = new byte[256]; private byte[] m_tertiary = new byte[256]; public lcd_distribution_lut(double prim = 1.0/3.0, double second = 2.0/9.0, double tert = 1.0/9.0) { double norm = 1.0 / (prim + second * 2 + tert * 2); prim *= norm; second *= norm; tert *= norm; for (int i = 0; i < 256; i++) { m_primary[i] = (byte)Math.Floor(prim * i); m_secondary[i] = (byte)Math.Floor(second * i); m_tertiary[i] = (byte)Math.Floor(tert * i); } } public uint primary(uint v) { return m_primary[v]; } public uint secondary(uint v) { return m_secondary[v]; } public uint tertiary(uint v) { return m_tertiary[v]; } } public class ImageProxySubpxelLcd24 : ImageProxy { private lcd_distribution_lut m_lut; public ImageProxySubpxelLcd24(IImageByte bufferToProxy, lcd_distribution_lut lut) : base(bufferToProxy) { m_lut = lut; } public override int Width { get { return base.Width * 3; } } public override void blend_hline(int x1, int y, int x2, RGBA_Bytes c, byte cover) { byte[] buffer = linkedImage.GetBuffer(); int index = linkedImage.GetBufferOffsetY(y) + x1;// +x1 + x1; int alpha = (int)cover * c.alpha; int len = x2 - x1; len /= 3; do { buffer[index + ImageBuffer.OrderR] = (byte)((((c.red - buffer[index + ImageBuffer.OrderR]) * alpha) + (buffer[index + ImageBuffer.OrderR] << 16)) >> 16); buffer[index + ImageBuffer.OrderG] = (byte)((((c.green - buffer[index + ImageBuffer.OrderG]) * alpha) + (buffer[index + ImageBuffer.OrderG] << 16)) >> 16); buffer[index + ImageBuffer.OrderB] = (byte)((((c.blue - buffer[index + ImageBuffer.OrderB]) * alpha) + (buffer[index + ImageBuffer.OrderB] << 16)) >> 16); index += 3; } while (--len > 0); } private byte[] c3 = new byte[2048 * 3]; public override void blend_solid_hspan(int x, int y, int len, RGBA_Bytes c, byte[] covers, int coversIndex) { if (c3.Length < len + 4) { c3 = new byte[len + 4]; } agg_basics.memset(c3, 0, 0, len + 4); int i; for (i = 0; i < len; i++) { c3[i + 0] += (byte)m_lut.tertiary(covers[coversIndex + i]); c3[i + 1] += (byte)m_lut.secondary(covers[coversIndex + i]); c3[i + 2] += (byte)m_lut.primary(covers[coversIndex + i]); c3[i + 3] += (byte)m_lut.secondary(covers[coversIndex + i]); c3[i + 4] += (byte)m_lut.tertiary(covers[coversIndex + i]); } x -= 2; len += 4; if (x < 0) { len -= x; x = 0; } i = x % 3; int c3Index = 0; byte[] rgb = new byte[] { c.blue, c.green, c.red }; byte[] buffer = linkedImage.GetBuffer(); int index = linkedImage.GetBufferOffsetY(y) + x; do { int alpha = c3[c3Index++] * c.alpha; if (alpha > 0) { if (alpha == 255 * 255) { buffer[index] = (byte)rgb[i]; } else { buffer[index] = (byte)((((rgb[i] - buffer[index]) * alpha) + (buffer[index] << 16)) >> 16); } } index++; i++; if (i >= 3) { i = 0; } } while (--len > 0); } } public class square { private double m_size; public square(double size) { m_size = size; } public void draw(ScanlineRasterizer ras, IScanlineCache sl, IImageByte destImage, RGBA_Bytes color, double x, double y) { ras.reset(); ras.move_to_d(x * m_size, y * m_size); ras.line_to_d(x * m_size + m_size, y * m_size); ras.line_to_d(x * m_size + m_size, y * m_size + m_size); ras.line_to_d(x * m_size, y * m_size + m_size); ScanlineRenderer scanlineRenderer = new ScanlineRenderer(); scanlineRenderer.RenderSolid(destImage, ras, sl, color); } } internal class renderer_enlarged : ScanlineRenderer { private double m_size; private square m_square; private scanline_unpacked_8 m_sl = new scanline_unpacked_8(); public renderer_enlarged(double size) { m_size = size; m_square = new square(size); } protected override void RenderSolidSingleScanLine(IImageByte destImage, IScanlineCache scanLineCache, RGBA_Bytes color) { int y = scanLineCache.y(); int num_spans = scanLineCache.num_spans(); ScanlineSpan scanlineSpan = scanLineCache.begin(); byte[] ManagedCoversArray = scanLineCache.GetCovers(); for (; ; ) { int x = scanlineSpan.x; int num_pix = scanlineSpan.len; int coverIndex = scanlineSpan.cover_index; do { int a = (ManagedCoversArray[coverIndex++] * color.Alpha0To255) >> 8; m_square.draw(destImage.NewGraphics2D().Rasterizer, m_sl, destImage, new RGBA_Bytes(color.Red0To255, color.Green0To255, color.Blue0To255, a), x, y); ++x; } while (--num_pix > 0); if (--num_spans == 0) break; scanlineSpan = scanLineCache.GetNextScanlineSpan(); } } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using System.Threading.Tasks; using Grpc.Core; using StackExchange.Redis; using Google.Protobuf; namespace cartservice.cartstore { public class RedisCartStore : ICartStore { private const string CART_FIELD_NAME = "cart"; private const int REDIS_RETRY_NUM = 30; private volatile ConnectionMultiplexer redis; private volatile bool isRedisConnectionOpened = false; private readonly object locker = new object(); private readonly byte[] emptyCartBytes; private readonly string connectionString; private readonly ConfigurationOptions redisConnectionOptions; public RedisCartStore(string redisAddress) { // Serialize empty cart into byte array. var cart = new Hipstershop.Cart(); emptyCartBytes = cart.ToByteArray(); connectionString = $"{redisAddress},ssl=false,allowAdmin=true,abortConnect=false"; redisConnectionOptions = ConfigurationOptions.Parse(connectionString); // Try to reconnect multiple times if the first retry fails. redisConnectionOptions.ConnectRetry = REDIS_RETRY_NUM; redisConnectionOptions.ReconnectRetryPolicy = new ExponentialRetry(1000); redisConnectionOptions.KeepAlive = 180; } public Task InitializeAsync() { EnsureRedisConnected(); return Task.CompletedTask; } private void EnsureRedisConnected() { if (isRedisConnectionOpened) { return; } // Connection is closed or failed - open a new one but only at the first thread lock (locker) { if (isRedisConnectionOpened) { return; } Console.WriteLine("Connecting to Redis: " + connectionString); redis = ConnectionMultiplexer.Connect(redisConnectionOptions); if (redis == null || !redis.IsConnected) { Console.WriteLine("Wasn't able to connect to redis"); // We weren't able to connect to Redis despite some retries with exponential backoff. throw new ApplicationException("Wasn't able to connect to redis"); } Console.WriteLine("Successfully connected to Redis"); var cache = redis.GetDatabase(); Console.WriteLine("Performing small test"); cache.StringSet("cart", "OK" ); object res = cache.StringGet("cart"); Console.WriteLine($"Small test result: {res}"); redis.InternalError += (o, e) => { Console.WriteLine(e.Exception); }; redis.ConnectionRestored += (o, e) => { isRedisConnectionOpened = true; Console.WriteLine("Connection to redis was retored successfully"); }; redis.ConnectionFailed += (o, e) => { Console.WriteLine("Connection failed. Disposing the object"); isRedisConnectionOpened = false; }; isRedisConnectionOpened = true; } } public async Task AddItemAsync(string userId, string productId, int quantity) { Console.WriteLine($"AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}"); try { EnsureRedisConnected(); var db = redis.GetDatabase(); // Access the cart from the cache var value = await db.HashGetAsync(userId, CART_FIELD_NAME); Hipstershop.Cart cart; if (value.IsNull) { cart = new Hipstershop.Cart(); cart.UserId = userId; cart.Items.Add(new Hipstershop.CartItem { ProductId = productId, Quantity = quantity }); } else { cart = Hipstershop.Cart.Parser.ParseFrom(value); var existingItem = cart.Items.SingleOrDefault(i => i.ProductId == productId); if (existingItem == null) { cart.Items.Add(new Hipstershop.CartItem { ProductId = productId, Quantity = quantity }); } else { existingItem.Quantity += quantity; } } await db.HashSetAsync(userId, new[]{ new HashEntry(CART_FIELD_NAME, cart.ToByteArray()) }); } catch (Exception ex) { throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}")); } } public async Task EmptyCartAsync(string userId) { Console.WriteLine($"EmptyCartAsync called with userId={userId}"); try { EnsureRedisConnected(); var db = redis.GetDatabase(); // Update the cache with empty cart for given user await db.HashSetAsync(userId, new[] { new HashEntry(CART_FIELD_NAME, emptyCartBytes) }); } catch (Exception ex) { throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}")); } } public async Task<Hipstershop.Cart> GetCartAsync(string userId) { Console.WriteLine($"GetCartAsync called with userId={userId}"); try { EnsureRedisConnected(); var db = redis.GetDatabase(); // Access the cart from the cache var value = await db.HashGetAsync(userId, CART_FIELD_NAME); if (!value.IsNull) { return Hipstershop.Cart.Parser.ParseFrom(value); } // We decided to return empty cart in cases when user wasn't in the cache before return new Hipstershop.Cart(); } catch (Exception ex) { throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}")); } } public bool Ping() { try { var cache = redis.GetDatabase(); var res = cache.Ping(); return res != TimeSpan.Zero; } catch (Exception) { return false; } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using fyiReporting.RDL; using System.IO; using System.Collections; using System.Drawing.Imaging; using System.Text; using System.Xml; using System.Globalization; using System.Drawing; namespace fyiReporting.RDL { ///<summary> /// Renders a report to HTML. This handles some page formating but does not do true page formatting. ///</summary> internal class RenderHtml: IPresent { Report r; // report StringWriter tw; // temporary location where the output is going IStreamGen _sg; // stream generater Hashtable _styles; // hash table of styles we've generated int cssId=1; // ID for css when names are usable or available bool bScriptToggle=false; // need to generate toggle javascript in header bool bScriptTableSort=false; // need to generate table sort javascript in header Bitmap _bm=null; // bm and Graphics _g=null; // g are needed when calculating string heights bool _Asp=false; // denotes ASP.NET compatible HTML; e.g. no <html>, <body> // separate JavaScript and CSS string _Prefix=""; // prefix to generating all HTML names (e.g. css, ... string _CSS; // when ASP we put the CSS into a string string _JavaScript; // as well as any required javascript int _SkipMatrixCols=0; // # of matrix columns to skip public RenderHtml(Report rep, IStreamGen sg) { r = rep; _sg = sg; // We need this in future tw = new StringWriter(); // will hold the bulk of the HTML until we generate // final file _styles = new Hashtable(); } public void Dispose() { // These should already be cleaned up; but in case of an unexpected error // these still need to be disposed of if (_bm != null) _bm.Dispose(); if (_g != null) _g.Dispose(); } public Report Report() { return r; } public bool Asp { get {return _Asp;} set {_Asp = value;} } public string JavaScript { get {return _JavaScript;} } public string CSS { get {return _CSS;} } public string Prefix { get {return _Prefix;} set { _Prefix = value==null? "": value; if (_Prefix.Length > 0 && _Prefix[0] == '_') _Prefix = "a" + _Prefix; // not perfect but underscores as first letter don't work } } public bool IsPagingNeeded() { return false; } public void Start() { return; } string FixupRelativeName(string relativeName) { if (_sg is OneFileStreamGen) { if (relativeName[0] == Path.DirectorySeparatorChar || relativeName[0] == Path.AltDirectorySeparatorChar) relativeName = relativeName.Substring(1); } else if (!(relativeName[0] == Path.DirectorySeparatorChar || relativeName[0] == Path.AltDirectorySeparatorChar)) { if (_Asp) relativeName = "/" + relativeName; // Hack for Firefox else relativeName = Path.DirectorySeparatorChar + relativeName; } return relativeName; } // puts the JavaScript into the header private void ScriptGenerate(TextWriter ftw) { if (bScriptToggle || bScriptTableSort) { ftw.WriteLine("<script language=\"javascript\">"); } if (bScriptToggle) { ftw.WriteLine("var dname='';"); ftw.WriteLine(@"function hideShow(node, hideCount, showID) { if (navigator.appName.toLowerCase().indexOf('netscape') > -1) dname = 'table-row'; else dname = 'block'; var tNode; for (var ci=0;ci<node.childNodes.length;ci++) { if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'img') tNode = node.childNodes[ci]; } var rows = findObject(showID); if (rows[0].style.display == dname) {hideRows(rows, hideCount); tNode.src='plus.gif';} else { tNode.src='minus.gif'; for (var i = 0; i < rows.length; i++) { rows[i].style.display = dname; } } } function hideRows(rows, count) { var row; if (navigator.appName.toLowerCase().indexOf('netscape') > -1) { for (var r=0; r < rows.length; r++) { row = rows[r]; row.style.display = 'none'; var imgs = row.getElementsByTagName('img'); for (var ci=0;ci<imgs.length;ci++) { if (imgs[ci].className == 'toggle') { imgs[ci].src='plus.gif'; } } } return; } if (rows.tagName == 'TR') row = rows; else row = rows[0]; while (count > 0) { row.style.display = 'none'; var imgs = row.getElementsByTagName('img'); for (var ci=0;ci<imgs.length;ci++) { if (imgs[ci].className == 'toggle') { imgs[ci].src='plus.gif'; } } row = row.nextSibling; count--; } } function findObject(id) { if (navigator.appName.toLowerCase().indexOf('netscape') > -1) { var a = new Array(); var count=0; for (var i=0; i < document.all.length; i++) { if (document.all[i].id == id) a[count++] = document.all[i]; } return a; } else { var o = document.all[id]; if (o.tagName == 'TR') { var a = new Array(); a[0] = o; return a; } return o; } } "); } if (bScriptTableSort) { ftw.WriteLine("var SORT_INDEX;"); ftw.WriteLine("var SORT_DIR;"); ftw.WriteLine("function sort_getInnerText(element) {"); ftw.WriteLine(" if (typeof element == 'string') return element;"); ftw.WriteLine(" if (typeof element == 'undefined') return element;"); ftw.WriteLine(" if (element.innerText) return element.innerText;"); ftw.WriteLine(" var s = '';"); ftw.WriteLine(" var cn = element.childNodes;"); ftw.WriteLine(" for (var i = 0; i < cn.length; i++) {"); ftw.WriteLine(" switch (cn[i].nodeType) {"); ftw.WriteLine(" case 1:"); // element node ftw.WriteLine(" s += sort_getInnerText(cn[i]);"); ftw.WriteLine(" break;"); ftw.WriteLine(" case 3:"); // text node ftw.WriteLine(" s += cn[i].nodeValue;"); ftw.WriteLine(" break;"); ftw.WriteLine(" }"); ftw.WriteLine(" }"); ftw.WriteLine(" return s;"); ftw.WriteLine("}"); ftw.WriteLine("function sort_table(node, sortfn, header_rows, footer_rows) {"); ftw.WriteLine(" var arrowNode;"); // arrow node ftw.WriteLine(" for (var ci=0;ci<node.childNodes.length;ci++) {"); ftw.WriteLine(" if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'span') arrowNode = node.childNodes[ci];"); ftw.WriteLine(" }"); ftw.WriteLine(" var td = node.parentNode;"); ftw.WriteLine(" SORT_INDEX = td.cellIndex;"); // need to remember SORT_INDEX in compare function ftw.WriteLine(" var table = sort_getTable(td);"); ftw.WriteLine(" var sortnext;"); ftw.WriteLine(" if (arrowNode.getAttribute('sortdir') == 'down') {"); ftw.WriteLine(" arrow = '&nbsp;&nbsp;&uarr;';"); ftw.WriteLine(" SORT_DIR = -1;"); // descending SORT_DIR in compare function ftw.WriteLine(" sortnext = 'up';"); ftw.WriteLine(" } else {"); ftw.WriteLine(" arrow = '&nbsp;&nbsp;&darr;';"); ftw.WriteLine(" SORT_DIR = 1;"); // ascending SORT_DIR in compare function ftw.WriteLine(" sortnext = 'down';"); ftw.WriteLine(" }"); ftw.WriteLine(" var newRows = new Array();"); ftw.WriteLine(" for (j=header_rows;j<table.rows.length-footer_rows;j++) { newRows[j-header_rows] = table.rows[j]; }"); ftw.WriteLine(" newRows.sort(sortfn);"); // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones ftw.WriteLine(" for (i=0;i<newRows.length;i++) {table.tBodies[0].appendChild(newRows[i]);}"); // Reset all arrows and directions for next time ftw.WriteLine(" var spans = document.getElementsByTagName('span');"); ftw.WriteLine(" for (var ci=0;ci<spans.length;ci++) {"); ftw.WriteLine(" if (spans[ci].className == 'sortarrow') {"); // in the same table as us? ftw.WriteLine(" if (sort_getTable(spans[ci]) == sort_getTable(node)) {"); ftw.WriteLine(" spans[ci].innerHTML = '&nbsp;&nbsp;&nbsp;';"); ftw.WriteLine(" spans[ci].setAttribute('sortdir','up');"); ftw.WriteLine(" }"); ftw.WriteLine(" }"); ftw.WriteLine(" }"); ftw.WriteLine(" arrowNode.innerHTML = arrow;"); ftw.WriteLine(" arrowNode.setAttribute('sortdir',sortnext);"); ftw.WriteLine("}"); ftw.WriteLine("function sort_getTable(el) {"); ftw.WriteLine(" if (el == null) return null;"); ftw.WriteLine(" else if (el.nodeType == 1 && el.tagName.toLowerCase() == 'table')"); ftw.WriteLine(" return el;"); ftw.WriteLine(" else"); ftw.WriteLine(" return sort_getTable(el.parentNode);"); ftw.WriteLine("}"); ftw.WriteLine("function sort_cmp_date(c1,c2) {"); ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);"); ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);"); ftw.WriteLine(" dt1 = new Date(t1);"); ftw.WriteLine(" dt2 = new Date(t2);"); ftw.WriteLine(" if (dt1==dt2) return 0;"); ftw.WriteLine(" if (dt1<dt2) return -SORT_DIR;"); ftw.WriteLine(" return SORT_DIR;"); ftw.WriteLine("}"); // numeric - removes any extraneous formating characters before parsing ftw.WriteLine("function sort_cmp_number(c1,c2) {"); ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');"); ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');"); ftw.WriteLine(" n1 = parseFloat(t1);"); ftw.WriteLine(" n2 = parseFloat(t2);"); ftw.WriteLine(" if (isNaN(n1)) n1 = Number.MAX_VALUE"); ftw.WriteLine(" if (isNaN(n2)) n2 = Number.MAX_VALUE"); ftw.WriteLine(" return (n1 - n2)*SORT_DIR;"); ftw.WriteLine("}"); // For string we first do a case insensitive comparison; // when equal we then do a case sensitive comparison ftw.WriteLine("function sort_cmp_string(c1,c2) {"); ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).toLowerCase();"); ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).toLowerCase();"); ftw.WriteLine(" if (t1==t2) return sort_cmp_casesensitive(c1,c2);"); ftw.WriteLine(" if (t1<t2) return -SORT_DIR;"); ftw.WriteLine(" return SORT_DIR;"); ftw.WriteLine("}"); ftw.WriteLine("function sort_cmp_casesensitive(c1,c2) {"); ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);"); ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);"); ftw.WriteLine(" if (t1==t2) return 0;"); ftw.WriteLine(" if (t2<t2) return -SORT_DIR;"); ftw.WriteLine(" return SORT_DIR;"); ftw.WriteLine("}"); } if (bScriptToggle || bScriptTableSort) { ftw.WriteLine("</script>"); } return; } // handle the Action tag private string Action(Action a, Row r, string t, string tooltip) { if (a == null) return t; string result = t; if (a.Hyperlink != null) { // Handle a hyperlink string url = a.HyperLinkValue(this.r, r); if (tooltip == null) result = String.Format("<a target=\"_top\" href=\"{0}\">{1}</a>", url, t); else result = String.Format("<a target=\"_top\" href=\"{0}\" title=\"{1}\">{2}</a>", url, tooltip, t); } else if (a.Drill != null) { // Handle a drill through StringBuilder args= new StringBuilder("<a target=\"_top\" href=\""); if (_Asp) // for ASP we go thru the default page and pass it as an argument args.Append("Default.aspx?rs:url="); args.Append(a.Drill.ReportName); args.Append(".rdl"); if (a.Drill.DrillthroughParameters != null) { bool bFirst = !_Asp; // ASP already have an argument foreach (DrillthroughParameter dtp in a.Drill.DrillthroughParameters.Items) { if (!dtp.OmitValue(this.r, r)) { if (bFirst) { // First parameter - prefixed by '?' args.Append('?'); bFirst = false; } else { // Subsequant parameters - prefixed by '&' args.Append('&'); } args.Append(dtp.Name.Nm); args.Append('='); args.Append(dtp.ValueValue(this.r, r)); } } } args.Append('"'); if (tooltip != null) args.Append(String.Format(" title=\"{0}\"", tooltip)); args.Append(">"); args.Append(t); args.Append("</a>"); result = args.ToString(); } else if (a.BookmarkLink != null) { // Handle a bookmark string bm = a.BookmarkLinkValue(this.r, r); if (tooltip == null) result = String.Format("<a href=\"#{0}\">{1}</a>", bm, t); else result = String.Format("<a href=\"#{0}\" title=\"{1}\">{2}</a>", bm, tooltip, t); } return result; } private string Bookmark(string bm, string t) { if (bm == null) return t; return String.Format("<div id=\"{0}\">{1}</div>", bm, t); } // Generate the CSS styles and put them in the header private void CssGenerate(TextWriter ftw) { if (_styles.Count <= 0) return; if (!_Asp) ftw.WriteLine("<style type='text/css'>"); foreach (CssCacheEntry cce in _styles.Values) { int i = cce.Css.IndexOf('{'); if (cce.Name.IndexOf('#') >= 0) ftw.WriteLine("{0} {1}", cce.Name, cce.Css.Substring(i)); else ftw.WriteLine(".{0} {1}", cce.Name, cce.Css.Substring(i)); } if (!_Asp) ftw.WriteLine("</style>"); } private string CssAdd(Style s, ReportLink rl, Row row) { return CssAdd(s, rl, row, false, float.MinValue, float.MinValue); } private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative) { return CssAdd(s, rl, row, bForceRelative, float.MinValue, float.MinValue); } private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative, float h, float w) { string css; string prefix = CssPrefix(s, rl); if (_Asp && prefix == "table#") bForceRelative = true; if (s != null) css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + s.GetCSS(this.r, row, true) + "}"; else if (rl is Table || rl is Matrix) css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "border-collapse:collapse;}"; else css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "}"; CssCacheEntry cce = (CssCacheEntry) _styles[css]; if (cce == null) { string name = prefix + this.Prefix + "css" + cssId++.ToString(); cce = new CssCacheEntry(css, name); _styles.Add(cce.Css, cce); } int i = cce.Name.IndexOf('#'); if (i > 0) return cce.Name.Substring(i+1); else return cce.Name; } private string CssPosition(ReportLink rl,Row row, bool bForceRelative, float h, float w) { if (!(rl is ReportItem)) // if not a report item then no position return ""; // no positioning within a table for (ReportLink p=rl.Parent; p != null; p=p.Parent) { if (p is TableCell) return ""; if (p is RowGrouping || p is MatrixCell || p is ColumnGrouping || p is Corner) { StringBuilder sb2 = new StringBuilder(); if (h != float.MinValue) sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", h); if (w != float.MinValue) sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}pt; ", w); return sb2.ToString(); } } // TODO: optimize by putting this into ReportItem and caching result??? ReportItem ri = (ReportItem) rl; StringBuilder sb = new StringBuilder(); if (ri.Left != null && ri.Left.Size > 0) { sb.AppendFormat(NumberFormatInfo.InvariantInfo, "left: {0}; ", ri.Left.CSS); } if (ri is Matrix || ri is Image || ri is Chart) { } else { if (ri.Width != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}; ", ri.Width.CSS); } if (ri.Top != null && ri.Top.Size > 0) { sb.AppendFormat(NumberFormatInfo.InvariantInfo, "top: {0}pt; ", ri.Gap(this.r)); } if (ri is List) { List l = ri as List; sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", l.HeightOfList(this.r, GetGraphics,row)); } else if (ri is Matrix || ri is Table || ri is Image || ri is Chart) {} else if (ri.Height != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}; ", ri.Height.CSS); if (sb.Length > 0) { if (bForceRelative || ri.YParents != null) sb.Insert(0, "position: relative; "); else sb.Insert(0, "position: absolute; "); } return sb.ToString(); } private Graphics GetGraphics { get { if (_g == null) { _bm = new Bitmap(10, 10); _g = Graphics.FromImage(_bm); } return _g; } } private string CssPrefix(Style s, ReportLink rl) { string cssPrefix=null; ReportLink p; if (rl is Table || rl is Matrix || rl is Rectangle) { cssPrefix = "table#"; } else if (rl is Body) { cssPrefix = "body#"; } else if (rl is Line) { cssPrefix = "table#"; } else if (rl is List) { cssPrefix = ""; } else if (rl is Subreport) { cssPrefix = ""; } else if (rl is Chart) { cssPrefix = ""; } if (cssPrefix != null) return cssPrefix; // now find what the style applies to for (p=rl.Parent; p != null; p=p.Parent) { if (p is TableCell) { bool bHead = false; ReportLink p2; for (p2=p.Parent; p2 != null; p2=p2.Parent) { Type t2 = p2.GetType(); if (t2 == typeof(Header)) { if (p2.Parent is Table) bHead=true; break; } } if (bHead) cssPrefix = "th#"; else cssPrefix = "td#"; break; } else if (p is RowGrouping || p is MatrixCell || p is ColumnGrouping || p is Corner) { cssPrefix = "td#"; break; } } return cssPrefix == null? "": cssPrefix; } public void End() { string bodyCssId; if (r.ReportDefinition.Body != null) bodyCssId = CssAdd(r.ReportDefinition.Body.Style, r.ReportDefinition.Body, null); // add the style for the body else bodyCssId = null; TextWriter ftw = _sg.GetTextWriter(); // the final text writer location if (_Asp) { // do any required JavaScript StringWriter sw = new StringWriter(); ScriptGenerate(sw); _JavaScript = sw.ToString(); sw.Close(); // do any required CSS sw = new StringWriter(); CssGenerate(sw); _CSS = sw.ToString(); sw.Close(); } else { ftw.WriteLine("<html>"); // handle the <head>: description, javascript and CSS goes here ftw.WriteLine("<head>"); ScriptGenerate(ftw); CssGenerate(ftw); if (r.Description != null) // Use description as title if provided ftw.WriteLine(string.Format(@"<title>{0}</title>", XmlUtil.XmlAnsi(r.Description))); ftw.WriteLine(@"</head>"); } // Always want an HTML body - even if report doesn't have a body stmt if (this._Asp) { ftw.WriteLine("<table style=\"position: relative;\">"); } else if (bodyCssId != null) ftw.WriteLine(@"<body id='{0}'><table>", bodyCssId); else ftw.WriteLine("<body><table>"); ftw.Write(tw.ToString()); if (this._Asp) ftw.WriteLine(@"</table>"); else ftw.WriteLine(@"</table></body></html>"); if (_g != null) { _g.Dispose(); _g = null; } if (_bm != null) { _bm.Dispose(); _bm = null; } return; } // Body: main container for the report public void BodyStart(Body b) { if (b.ReportItems != null && b.ReportItems.Items.Count > 0) tw.WriteLine("<tr><td><div style=\"POSITION: relative; \">"); } public void BodyEnd(Body b) { if (b.ReportItems != null && b.ReportItems.Items.Count > 0) tw.WriteLine("</div></td></tr>"); } public void PageHeaderStart(PageHeader ph) { if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0) tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", ph.Height.CSS); } public void PageHeaderEnd(PageHeader ph) { if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0) tw.WriteLine("</div></td></tr>"); } public void PageFooterStart(PageFooter pf) { if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0) tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", pf.Height.CSS); } public void PageFooterEnd(PageFooter pf) { if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0) tw.WriteLine("</div></td></tr>"); } public void Textbox(Textbox tb, string t, Row row) { if (tb.IsHtml(this.r, row)) // we leave the text as is (except to handle unicode) when request is to treat as html { // this can screw up the generated HTML if not properly formed HTML t = XmlUtil.HtmlAnsi(t); } else { // make all the characters browser readable t = XmlUtil.XmlAnsi(t); // handle any specified bookmark t = Bookmark(tb.BookmarkValue(this.r, row), t); // handle any specified actions t = Action(tb.Action, row, t, tb.ToolTipValue(this.r, row)); } // determine if we're in a tablecell Type tp = tb.Parent.Parent.GetType(); bool bCell; if (tp == typeof(TableCell) || tp == typeof(Corner) || tp == typeof(DynamicColumns) || tp == typeof(DynamicRows) || tp == typeof(StaticRow) || tp == typeof(StaticColumn) || tp == typeof(Subtotal) || tp == typeof(MatrixCell)) bCell = true; else bCell = false; if (tp == typeof(Rectangle)) tw.Write("<td>"); if (bCell) { // The cell has the formatting for this text if (t == "") tw.Write("<br />"); // must have something in cell for formating else tw.Write(t); } else { // Formatting must be specified string cssName = CssAdd(tb.Style, tb, row); // get the style name for this item tw.Write("<div class='{0}'>{1}</div>", cssName, t); } if (tp == typeof(Rectangle)) tw.Write("</td>"); } public void DataRegionNoRows(DataRegion d, string noRowsMsg) // no rows in table { if (noRowsMsg == null) noRowsMsg = ""; bool bTableCell = d.Parent.Parent.GetType() == typeof(TableCell); if (bTableCell) { if (noRowsMsg == "") tw.Write("<br />"); else tw.Write(noRowsMsg); } else { string cssName = CssAdd(d.Style, d, null); // get the style name for this item tw.Write("<div class='{0}'>{1}</div>", cssName, noRowsMsg); } } // Lists public bool ListStart(List l, Row r) { // identifiy reportitem it if necessary string bookmark = l.BookmarkValue(this.r, r); if (bookmark != null) // tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style return true; } public void ListEnd(List l, Row r) { string bookmark = l.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("</div>"); } public void ListEntryBegin(List l, Row r) { string cssName = CssAdd(l.Style, l, r, true); // get the style name for this item; force to be relative tw.WriteLine(); tw.WriteLine("<div class={0}>", cssName); } public void ListEntryEnd(List l, Row r) { tw.WriteLine(); tw.WriteLine("</div>"); } // Tables // Report item table public bool TableStart(Table t, Row row) { string cssName = CssAdd(t.Style, t, row); // get the style name for this item // Determine if report custom defn want this table to be sortable if (IsTableSortable(t)) { this.bScriptTableSort = true; } string bookmark = t.BookmarkValue(this.r, row); if (bookmark != null) tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style // Calculate the width of all the columns int width = t.WidthInPixels(this.r, row); if (width <= 0) tw.WriteLine("<table id='{0}'>", cssName); else tw.WriteLine("<table id='{0}' width={1}>", cssName, width); return true; } public bool IsTableSortable(Table t) { if (t.TableGroups != null || t.Details == null || t.Details.TableRows == null || t.Details.TableRows.Items.Count != 1) return false; // can't have tableGroups; must have 1 detail row // Determine if report custom defn want this table to be sortable bool bReturn = false; if (t.Custom != null) { // Loop thru all the child nodes foreach(XmlNode xNodeLoop in t.Custom.CustomXmlNode.ChildNodes) { if (xNodeLoop.Name == "HTML") { if (xNodeLoop.LastChild.InnerText.ToLower() == "true") { bReturn = true; } break; } } } return bReturn; } public void TableEnd(Table t, Row row) { string bookmark = t.BookmarkValue(this.r, row); if (bookmark != null) tw.WriteLine("</div>"); tw.WriteLine("</table>"); return; } public void TableBodyStart(Table t, Row row) { tw.WriteLine("<tbody>"); } public void TableBodyEnd(Table t, Row row) { tw.WriteLine("</tbody>"); } public void TableFooterStart(Footer f, Row row) { tw.WriteLine("<tfoot>"); } public void TableFooterEnd(Footer f, Row row) { tw.WriteLine("</tfoot>"); } public void TableHeaderStart(Header h, Row row) { tw.WriteLine("<thead>"); } public void TableHeaderEnd(Header h, Row row) { tw.WriteLine("</thead>"); } public void TableRowStart(TableRow tr, Row row) { tw.Write("\t<tr"); ReportLink rl = tr.Parent.Parent; Visibility v=null; Textbox togText=null; // holds the toggle text box if any if (rl is Details) { Details d = (Details) rl; v = d.Visibility; togText = d.ToggleTextbox; } else if (rl.Parent is TableGroup) { TableGroup tg = (TableGroup) rl.Parent; v = tg.Visibility; togText = tg.ToggleTextbox; } if (v != null && v.Hidden != null) { bool bHide = v.Hidden.EvaluateBoolean(this.r, row); if (bHide) tw.Write(" style=\"display:none;\""); } if (togText != null && togText.Name != null) { string name = togText.Name.Nm + "_" + togText.RunCount(this.r).ToString(); tw.Write(" id='{0}'", name); } tw.Write(">"); } public void TableRowEnd(TableRow tr, Row row) { tw.WriteLine("</tr>"); } public void TableCellStart(TableCell t, Row row) { string cellType = t.InTableHeader? "th": "td"; ReportItem r = t.ReportItems.Items[0]; string cssName = CssAdd(r.Style, r, row); // get the style name for this item tw.Write("<{0} id='{1}'", cellType, cssName); // calculate width of column if (t.InTableHeader && t.OwnerTable.TableColumns != null) { // Calculate the width across all the spanned columns int width = 0; for (int ci=t.ColIndex; ci < t.ColIndex + t.ColSpan; ci++) { TableColumn tc = t.OwnerTable.TableColumns.Items[ci] as TableColumn; if (tc != null && tc.Width != null) width += tc.Width.PixelsX; } if (width > 0) tw.Write(" width={0}", width); } if (t.ColSpan > 1) tw.Write(" colspan={0}", t.ColSpan); Textbox tb = r as Textbox; if (tb != null && // have textbox tb.IsToggle && // and its a toggle tb.Name != null) // and need name as well { int groupNestCount = t.OwnerTable.GetGroupNestCount(this.r); if (groupNestCount > 0) // anything to toggle? { string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString(); bScriptToggle = true; // need both hand and pointer because IE and Firefox use different names tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand';style.cursor ='pointer'\">", groupNestCount, name); tw.Write("<img class='toggle' src=\"plus.gif\" align=\"top\"/>"); } else tw.Write("<img src=\"empty.gif\" align=\"top\"/>"); } else tw.Write(">"); if (t.InTableHeader) { // put the second half of the sort tags for the column; if needed // first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;"> // next half follows text ---- <span class="sortarrow">&nbsp;&nbsp;&nbsp;</span></a></th> string sortcmp = SortType(t, tb); // obtain the sort type if (sortcmp != null) // null if sort not needed { int headerRows, footerRows; headerRows = t.OwnerTable.Header.TableRows.Items.Count; // since we're in header we know we have some rows if (t.OwnerTable.Footer != null && t.OwnerTable.Footer.TableRows != null) footerRows = t.OwnerTable.Footer.TableRows.Items.Count; else footerRows = 0; tw.Write("<a href=\"#\" title='Sort' onclick=\"sort_table(this,{0},{1},{2});return false;\">",sortcmp, headerRows, footerRows); } } return; } private string SortType(TableCell tc, Textbox tb) { // return of null means don't sort if (tb == null || !IsTableSortable(tc.OwnerTable)) return null; // default is true if table is sortable; // but user may place override on Textbox custom tag if (tb.Custom != null) { // Loop thru all the child nodes foreach(XmlNode xNodeLoop in tb.Custom.CustomXmlNode.ChildNodes) { if (xNodeLoop.Name == "HTML") { if (xNodeLoop.LastChild.InnerText.ToLower() == "false") { return null; } break; } } } // Must find out the type of the detail column Details d = tc.OwnerTable.Details; if (d == null) return null; TableRow tr = d.TableRows.Items[0] as TableRow; if (tr == null) return null; TableCell dtc = tr.TableCells.Items[tc.ColIndex] as TableCell; if (dtc == null) return null; Textbox dtb = dtc.ReportItems.Items[0] as Textbox; if (dtb == null) return null; string sortcmp; switch (dtb.Value.Type) { case TypeCode.DateTime: sortcmp = "sort_cmp_date"; break; case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.Single: case TypeCode.Double: sortcmp = "sort_cmp_number"; break; case TypeCode.String: sortcmp = "sort_cmp_string"; break; case TypeCode.Empty: // Not a type we know how to sort default: sortcmp = null; break; } return sortcmp; } public void TableCellEnd(TableCell t, Row row) { string cellType = t.InTableHeader? "th": "td"; Textbox tb = t.ReportItems.Items[0] as Textbox; if (cellType == "th" && SortType(t, tb) != null) { // put the second half of the sort tags for the column // first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;"> // next half follows text ---- <span class="sortarrow">&nbsp;&nbsp;&nbsp;</span></a></th> tw.Write("<span class=\"sortarrow\">&nbsp;&nbsp;&nbsp;</span></a>"); } tw.Write("</{0}>", cellType); return; } public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first { string bookmark = m.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style // output some of the table styles string cssName = CssAdd(m.Style, m, r); // get the style name for this item tw.WriteLine("<table id='{0}'>", cssName); return true; } public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart { } public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan) { if (ri == null) // Empty cell? { if (_SkipMatrixCols == 0) tw.Write("<td>"); return; } string cssName = CssAdd(ri.Style, ri, r, false, h, w); // get the style name for this item tw.Write("<td id='{0}'", cssName); if (colSpan != 1) { tw.Write(" colspan={0}", colSpan); _SkipMatrixCols=-(colSpan-1); // start it as negative as indicator that we need this </td> } else _SkipMatrixCols=0; if (ri is Textbox) { Textbox tb = (Textbox) ri; if (tb.IsToggle && tb.Name != null) // name is required for this { string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString(); bScriptToggle = true; // we need to generate JavaScript in header // TODO -- need to calculate the hide count correctly tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand'\"", 0, name); } } tw.Write(">"); } public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r) { if (_SkipMatrixCols == 0) tw.Write("</td>"); else if (_SkipMatrixCols < 0) { tw.Write("</td>"); _SkipMatrixCols = -_SkipMatrixCols; } else _SkipMatrixCols--; return; } public void MatrixRowStart(Matrix m, int row, Row r) { tw.Write("\t<tr"); tw.Write(">"); } public void MatrixRowEnd(Matrix m, int row, Row r) { tw.WriteLine("</tr>"); } public void MatrixEnd(Matrix m, Row r) // called last { tw.Write("</table>"); string bookmark = m.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("</div>"); return; } public void Chart(Chart c, Row r, ChartBase cb) { string relativeName; Stream io = _sg.GetIOStream(out relativeName, "png"); try { cb.Save(this.r, io, ImageFormat.Png); } finally { io.Flush(); io.Close(); } relativeName = FixupRelativeName(relativeName); // Create syntax in a string buffer StringWriter sw = new StringWriter(); string bookmark = c.BookmarkValue(this.r, r); if (bookmark != null) sw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style string cssName = CssAdd(c.Style, c, null); // get the style name for this item sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName); string tooltip = c.ToolTipValue(this.r, r); if (tooltip != null) sw.Write(" alt=\"{0}\"", tooltip); if (c.Height != null) sw.Write(" height=\"{0}\"", c.Height.PixelsY.ToString()); if (c.Width != null) sw.Write(" width=\"{0}\"", c.Width.PixelsX.ToString()); sw.Write(">"); if (bookmark != null) sw.Write("</div>"); tw.Write(Action(c.Action, r, sw.ToString(), tooltip)); return; } public void Image(Image i, Row r, string mimeType, Stream ioin) { string relativeName; string suffix; switch (mimeType) { case "image/bmp": suffix = "bmp"; break; case "image/jpeg": suffix = "jpeg"; break; case "image/gif": suffix = "gif"; break; case "image/png": case "image/x-png": suffix = "png"; break; default: suffix = "unk"; break; } Stream io = _sg.GetIOStream(out relativeName, suffix); try { if (ioin.CanSeek) // ioin.Length requires Seek support { byte[] ba = new byte[ioin.Length]; ioin.Read(ba, 0, ba.Length); io.Write(ba, 0, ba.Length); } else { byte[] ba = new byte[1000]; // read a 1000 bytes at a time while (true) { int length = ioin.Read(ba, 0, ba.Length); if (length <= 0) break; io.Write(ba, 0, length); } } } finally { io.Flush(); io.Close(); } relativeName = FixupRelativeName(relativeName); // Create syntax in a string buffer StringWriter sw = new StringWriter(); string bookmark = i.BookmarkValue(this.r, r); if (bookmark != null) sw.WriteLine("<div id=\"{0}\">", bookmark); // we're using for css style string cssName = CssAdd(i.Style, i, null); // get the style name for this item sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName); string tooltip = i.ToolTipValue(this.r, r); if (tooltip != null) sw.Write(" alt=\"{0}\"", tooltip); int h = i.Height == null? -1: i.Height.PixelsY; int w = i.Width == null ? -1 : i.Width.PixelsX; switch (i.Sizing) { case ImageSizingEnum.AutoSize: break; // this is right case ImageSizingEnum.Clip: break; // not sure how to clip it case ImageSizingEnum.Fit: if (h > 0) sw.Write(" height=\"{0}\"", h.ToString()); if (w > 0) sw.Write(" width=\"{0}\"", w.ToString()); break; case ImageSizingEnum.FitProportional: break; // would have to create an image to handle this } sw.Write("/>"); if (bookmark != null) sw.Write("</div>"); tw.Write(Action(i.Action, r, sw.ToString(), tooltip)); return; } public void Line(Line l, Row r) { bool bVertical; string t; if (l.Height == null || l.Height.PixelsY > 0) // only handle horizontal rule { if (l.Width == null || l.Width.PixelsX > 0) // and vertical rules return; bVertical = true; t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"WIDTH:{0}\"><TD style=\"WIDTH:{0}\"></TD></TR></TBODY></TABLE>"; } else { bVertical = false; t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"HEIGHT:{3}\"><TD style=\"HEIGHT:{3}\"></TD></TR></TBODY></TABLE>"; } string width, left, top, height, color; Style s = l.Style; left = l.Left == null? "0px": l.Left.CSS; top = l.Top == null? "0px": l.Top.CSS; if (bVertical) { height = l.Height == null? "0px": l.Height.CSS; // width comes from the BorderWidth if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null) width = s.BorderWidth.Default.EvaluateString(this.r, r); else width = "1px"; } else { width = l.Width == null? "0px": l.Width.CSS; // height comes from the BorderWidth if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null) height = s.BorderWidth.Default.EvaluateString(this.r, r); else height = "1px"; } if (s != null && s.BorderColor != null && s.BorderColor.Default != null) color = s.BorderColor.Default.EvaluateString(this.r, r); else color = "black"; tw.WriteLine(t, width, left, top, height, color); return; } public bool RectangleStart(RDL.Rectangle rect, Row r) { string cssName = CssAdd(rect.Style, rect, r); // get the style name for this item string bookmark = rect.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style // Calculate the width of all the columns int width = rect.Width == null? -1: rect.Width.PixelsX; if (width < 0) tw.WriteLine("<table id='{0}'><tr>", cssName); else tw.WriteLine("<table id='{0}' width={1}><tr>", cssName, width); return true; } public void RectangleEnd(RDL.Rectangle rect, Row r) { tw.WriteLine("</tr></table>"); string bookmark = rect.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("</div>"); return; } // Subreport: public void Subreport(Subreport s, Row r) { string cssName = CssAdd(s.Style, s, r); // get the style name for this item tw.WriteLine("<div class='{0}'>", cssName); s.ReportDefn.Run(this); tw.WriteLine("</div>"); } public void GroupingStart(Grouping g) // called at start of grouping { } public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance { } public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance { } public void GroupingEnd(Grouping g) // called at end of grouping { } public void RunPages(Pages pgs) // we don't have paging turned on for html { } } class CssCacheEntry { string _Css; // css string _Name; // name of entry public CssCacheEntry(string css, string name) { _Css = css; _Name = name; } public string Css { get { return _Css; } set { _Css = value; } } public string Name { get { return _Name; } set { _Name = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using IronPython.Runtime.Operations; using Microsoft.Scripting.Runtime; namespace IronPython.Runtime { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [PythonType("xrange")] [DontMapIEnumerableToContains] public sealed class XRange : ICollection, IEnumerable, IEnumerable<int>, ICodeFormattable, IList, IReversible { private int _start, _stop, _step, _length; public XRange(int stop) : this(0, stop, 1) { } public XRange(int start, int stop) : this(start, stop, 1) { } public XRange(int start, int stop, int step) { Initialize(start, stop, step); } private void Initialize(int start, int stop, int step) { if (step == 0) { throw PythonOps.ValueError("step must not be zero"); } else if (step > 0) { if (start > stop) stop = start; } else { if (start < stop) stop = start; } _start = start; _stop = stop; _step = step; _length = GetLengthHelper(); _stop = start + step * _length; // make stop precise } public int Start { [PythonHidden] get { return _start; } } public int Stop { [PythonHidden] get { return _stop; } } public int Step { [PythonHidden] get { return _step; } } #region ISequence Members public int __len__() { return _length; } private int GetLengthHelper() { long temp; if (_step > 0) { temp = (0L + _stop - _start + _step - 1) / _step; } else { temp = (0L + _stop - _start + _step + 1) / _step; } if (temp > Int32.MaxValue) { throw PythonOps.OverflowError("xrange() result has too many items"); } return (int)temp; } public object this[int index] { get { if (index < 0) index += _length; if (index >= _length || index < 0) throw PythonOps.IndexError("xrange object index out of range"); int ind = index * _step + _start; return ScriptingRuntimeHelpers.Int32ToObject(ind); } } public object this[object index] { get { return this[Converter.ConvertToIndex(index)]; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public object this[Slice slice] { get { throw PythonOps.TypeError("sequence index must be integer"); } } #endregion public IEnumerator __reversed__() { return new XRangeIterator(new XRange(_stop - _step, _start - _step, -_step)); } IEnumerator IEnumerable.GetEnumerator() { return new XRangeIterator(this); } #region IEnumerable<int> Members IEnumerator<int> IEnumerable<int>.GetEnumerator() { return new XRangeIterator(this); } #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { if (_step == 1) { if (_start == 0) { return string.Format("xrange({0})", _stop); } else { return string.Format("xrange({0}, {1})", _start, _stop); } } else { return string.Format("xrange({0}, {1}, {2})", _start, _stop, _step); } } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { foreach (object o in this) { array.SetValue(o, index++); } } int ICollection.Count { get { return _length; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return null; } } #endregion #region IList Members int IList.Add(object value) { throw new InvalidOperationException(); } void IList.Clear() { throw new InvalidOperationException(); } bool IList.Contains(object value) { return ((IList)this).IndexOf(value) != -1; } int IList.IndexOf(object value) { int index = 0; foreach (object o in this) { if (o == value) { return index; } index++; } return -1; } void IList.Insert(int index, object value) { throw new InvalidOperationException(); } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } void IList.Remove(object value) { throw new InvalidOperationException(); } void IList.RemoveAt(int index) { throw new InvalidOperationException(); } object IList.this[int index] { get { int curIndex = 0; foreach (object o in this) { if (curIndex == index) { return o; } curIndex++; } throw new IndexOutOfRangeException(); } set { throw new InvalidOperationException(); } } #endregion } [PythonType("rangeiterator")] public sealed class XRangeIterator : IEnumerable, IEnumerator, IEnumerator<int> { private XRange _xrange; private int _value; private int _position; public XRangeIterator(XRange xrange) { _xrange = xrange; _value = xrange.Start - xrange.Step; // this could cause overflow, fine } public object Current { get { return ScriptingRuntimeHelpers.Int32ToObject(_value); } } public bool MoveNext() { if (_position >= _xrange.__len__()) { return false; } _position++; _value = _value + _xrange.Step; return true; } public void Reset() { _value = _xrange.Start - _xrange.Step; _position = 0; } #region IEnumerator<int> Members int IEnumerator<int>.Current { get { return _value; } } #endregion #region IDisposable Members public void Dispose() { } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return this; } #endregion } }
using System; using System.Threading; using Microsoft.Research.Joins; using System.Diagnostics; // Micro-benchmark pitting Comega OnePlaceBuffer (hand-translated) against Joins version. namespace Comega { internal class CallQ<A> { internal class CyclicList { internal A mHead; internal CyclicList mTail; internal CyclicList(A head, CyclicList context) { mHead = head; mTail = context.mTail; context.mTail = this; } internal CyclicList(A head) { mHead = head; mTail = this; } } private CyclicList mLast; internal void Init() { mLast = null; } internal void Add(A a) { if (mLast == null) mLast = new CyclicList(a); else { new CyclicList(a, mLast); mLast = mLast.mTail; } } internal A Get() { A a = mLast.mTail.mHead; if ((mLast.mTail) == mLast) mLast = null; else mLast.mTail = mLast.mTail.mTail; return a; } internal bool Empty { get { return mLast == null; } } public override string ToString() { return (mLast == null) ? "empty" : (mLast.mTail == mLast) ? mLast.mTail.mHead.ToString() : mLast.mTail.mHead + ",...," + mLast.mHead; } } public sealed class VoidQ { private int n; public VoidQ() { n = 0; } public void Add() { n++; } public void Get() { n--; } public bool Empty() { return (n == 0); } } public class ThreadQ { private bool Signalled = false; private int Count = 0; public bool Empty() { return (Count == 0); } public void Yield(object myCurrentLock) { Count++; Monitor.Exit(myCurrentLock); lock (this) { while (!Signalled) { Monitor.Wait(this); } Signalled = false; } Monitor.Enter(myCurrentLock); Count--; } public void WakeUp() { lock (this) { if (!Signalled) { Signalled = true; Monitor.Pulse(this); } } } } public class OnePlaceBuffer { // Methods public OnePlaceBuffer() { this._state = 0; this._lock = new object(); this._callQ00000001 = new VoidQ(); this._callQ00000002 = new CallQ<string>(); this._threadQ00000004 = new ThreadQ(); this._threadQ00000008 = new ThreadQ(); this.empty(); } private void _scan() { if ((~this._state & 5) == 0) { this._threadQ00000004.WakeUp(); } else if ((~this._state & 10) == 0) { this._threadQ00000008.WakeUp(); } } private void contains(string s) { object obj1 = this._lock; lock (obj1) { this._callQ00000002.Add(s); if ((((~this._state & 2) == 0) ? 1 : 0) == 0) { this._state |= 2; this._scan(); } } } private void empty() { object obj1 = this._lock; lock (obj1) { this._callQ00000001.Add(); if ((((~this._state & 1) == 0) ? 1 : 0) == 0) { this._state |= 1; this._scan(); } } } public string Get() { string text2; Monitor.Enter(this._lock); if ((((~this._state & 8) == 0) ? 1 : 0) == 0) { goto Label_0073; } Label_003C: this._threadQ00000008.Yield(this._lock); if (this._threadQ00000008.Empty()) { this._state &= 0xfffffff7; } Label_0073: if ((~this._state & 2) == 0) { string obj1 = this._callQ00000002.Get(); if (this._callQ00000002.Empty) { this._state &= 0xfffffffd; } this._scan(); Monitor.Exit(this._lock); string text1 = obj1; this.empty(); text2 = text1; } else { this._state |= 8; goto Label_003C; } string text3 = text2; return text2; } public void Put(string s) { Monitor.Enter(this._lock); if ((((~this._state & 4) == 0) ? 1 : 0) == 0) { goto Label_0073; } Label_003C: this._threadQ00000004.Yield(this._lock); if (this._threadQ00000004.Empty()) { this._state &= 0xfffffffb; } Label_0073: if ((~this._state & 1) == 0) { this._callQ00000001.Get(); if (this._callQ00000001.Empty()) { this._state &= 0xfffffffe; } this._scan(); Monitor.Exit(this._lock); this.contains(s); } else { this._state |= 4; goto Label_003C; } } // Fields private VoidQ _callQ00000001; private CallQ<string> _callQ00000002; private object _lock; private uint _state; private ThreadQ _threadQ00000004; private ThreadQ _threadQ00000008; } } namespace Joins { public class OnePlaceBuffer { private readonly Asynchronous.Channel Empty; private readonly Asynchronous.Channel<string> Contains; public readonly Synchronous.Channel<string> Put; public readonly Synchronous<string>.Channel Get; public OnePlaceBuffer() { Join j = Join.Create(); j.Initialize(out Empty); j.Initialize(out Contains); j.Initialize(out Put); j.Initialize(out Get); /* Empty = j.CreateAsynchronousChannel(); Contains = j.CreateAsynchronousChannel<string>(); Put = j.CreateVoidSynchronousChannel<string>(); Get = j.CreateSynchronousChannel<string>(); */ j.When(Put).And(Empty).Do(delegate(string s) { Contains(s); }); j.When(Get).And(Contains).Do(delegate(string s) { Empty(); return s; }); Empty(); } } class Program { static Joins.OnePlaceBuffer jb = new Joins.OnePlaceBuffer(); static Comega.OnePlaceBuffer cb = new Comega.OnePlaceBuffer(); public static void Main() { int n = 1000; Comega.OnePlaceBuffer[] cbs = new Comega.OnePlaceBuffer[n]; Joins.OnePlaceBuffer[] jbs = new Joins.OnePlaceBuffer[n]; Stopwatch sw = new Stopwatch(); loop: GC.Collect(); int gcs = GC.CollectionCount(0); sw.Reset(); sw.Start(); for (int i = 0; i < n; i++) { cbs[i] = new Comega.OnePlaceBuffer(); } sw.Stop(); long cTicks = sw.ElapsedTicks; Console.WriteLine("Comega allocation: {0}", sw.Elapsed); gcs = GC.CollectionCount(0) - gcs; Console.WriteLine("Collections: {0}", gcs); GC.Collect(); gcs = GC.CollectionCount(0); sw.Reset(); sw.Start(); for (int i = 0; i < n; i++) { jbs[i] = new Joins.OnePlaceBuffer(); } sw.Stop(); long jTicks = sw.ElapsedTicks; Console.WriteLine("Joins allocation: {0}", sw.Elapsed); gcs = GC.CollectionCount(0) - gcs; Console.WriteLine("Collections: {0}", gcs); Console.WriteLine(" allocation ratio: {0}", Ratio(jTicks, cTicks)); sw.Reset(); sw.Start(); for (int i = 0; i < n; i++) { cb.Put(""); cb.Get(); } sw.Stop(); cTicks = sw.ElapsedTicks; Console.WriteLine("Comega Put/Get: {0}", sw.Elapsed); sw.Reset(); sw.Start(); for (int i = 0; i < n; i++) { jb.Put(""); jb.Get(); } sw.Stop(); jTicks = sw.ElapsedTicks; Console.WriteLine("Joins Put/Get: {0}", sw.Elapsed); Console.WriteLine("Joins/Comega Ratio: {0}", Ratio(jTicks,cTicks)); sw.Reset(); sw.Start(); Thread producer = new Thread(delegate() { for (int i = 0; i < n; i++) { cb.Put(""); // Thread.Sleep(0); } }); Thread consumer = new Thread(delegate() { for (int i = 0; i < n; i++) { string s = cb.Get(); // Thread.Sleep(0); } }); producer.Start(); consumer.Start(); consumer.Join(); sw.Stop(); cTicks = sw.ElapsedTicks; Console.WriteLine("Comega Threads: {0}", sw.Elapsed); sw.Reset(); sw.Start(); producer = new Thread(delegate() { for (int i = 0; i < n; i++) { jb.Put(""); //Thread.Sleep(0); } }); consumer = new Thread(delegate() { for (int i = 0; i < n; i++) { string s = jb.Get(); // Thread.Sleep(0); } }); producer.Start(); consumer.Start(); consumer.Join(); sw.Stop(); jTicks = sw.ElapsedTicks; Console.WriteLine("Joins Threads: {0}", sw.Elapsed); Console.WriteLine("Joins/Comega Ratio: {0}", Ratio(jTicks,cTicks)); System.Console.WriteLine("Hit any key to try again."); Console.ReadLine(); goto loop; } static Double Ratio(long num, long div) { return (Double)num / (Double)div; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.UnitTests; using Avalonia.VisualTree; using Moq; using System; using System.Linq; using Xunit; namespace Avalonia.Controls.UnitTests.Presenters { /// <summary> /// Tests for ContentControls that aren't hosted in a control template. /// </summary> public class ContentPresenterTests_Standalone { [Fact] public void Should_Set_Childs_Parent_To_Itself_Standalone() { var content = new Border(); var target = new ContentPresenter { Content = content }; target.UpdateChild(); Assert.Same(target, content.Parent); } [Fact] public void Should_Add_Child_To_Own_LogicalChildren_Standalone() { var content = new Border(); var target = new ContentPresenter { Content = content }; target.UpdateChild(); var logicalChildren = target.GetLogicalChildren(); Assert.Equal(1, logicalChildren.Count()); Assert.Equal(content, logicalChildren.First()); } [Fact] public void Should_Raise_DetachedFromLogicalTree_On_Content_Changed_Standalone() { var target = new ContentPresenter { ContentTemplate = new FuncDataTemplate<string>(t => new ContentControl() { Content = t }, false) }; var parentMock = new Mock<Control>(); parentMock.As<IContentPresenterHost>(); parentMock.As<IStyleRoot>(); (target as ISetLogicalParent).SetParent(parentMock.Object); target.Content = "foo"; target.UpdateChild(); var foo = target.Child as ContentControl; bool foodetached = false; Assert.NotNull(foo); Assert.Equal("foo", foo.Content); foo.DetachedFromLogicalTree += delegate { foodetached = true; }; target.Content = "bar"; target.UpdateChild(); var bar = target.Child as ContentControl; Assert.NotNull(bar); Assert.True(bar != foo); Assert.False((foo as IControl).IsAttachedToLogicalTree); Assert.True(foodetached); } [Fact] public void Should_Raise_DetachedFromLogicalTree_In_ContentControl_On_Content_Changed_Standalone() { var contentControl = new ContentControl { Template = new FuncControlTemplate<ContentControl>(c => new ContentPresenter() { Name = "PART_ContentPresenter", [~ContentPresenter.ContentProperty] = c[~ContentControl.ContentProperty], [~ContentPresenter.ContentTemplateProperty] = c[~ContentControl.ContentTemplateProperty] }), ContentTemplate = new FuncDataTemplate<string>(t => new ContentControl() { Content = t }, false) }; var parentMock = new Mock<Control>(); parentMock.As<IStyleRoot>(); parentMock.As<ILogical>().SetupGet(l => l.IsAttachedToLogicalTree).Returns(true); (contentControl as ISetLogicalParent).SetParent(parentMock.Object); contentControl.ApplyTemplate(); var target = contentControl.Presenter as ContentPresenter; contentControl.Content = "foo"; target.UpdateChild(); var tbfoo = target.Child as ContentControl; bool foodetached = false; Assert.NotNull(tbfoo); Assert.Equal("foo", tbfoo.Content); tbfoo.DetachedFromLogicalTree += delegate { foodetached = true; }; contentControl.Content = "bar"; target.UpdateChild(); var tbbar = target.Child as ContentControl; Assert.NotNull(tbbar); Assert.True(tbbar != tbfoo); Assert.False((tbfoo as IControl).IsAttachedToLogicalTree); Assert.True(foodetached); } [Fact] public void Should_Raise_DetachedFromLogicalTree_On_Detached_Standalone() { var target = new ContentPresenter { ContentTemplate = new FuncDataTemplate<string>(t => new ContentControl() { Content = t }, false) }; var parentMock = new Mock<Control>(); parentMock.As<IContentPresenterHost>(); parentMock.As<IStyleRoot>(); (target as ISetLogicalParent).SetParent(parentMock.Object); target.Content = "foo"; target.UpdateChild(); var foo = target.Child as ContentControl; bool foodetached = false; Assert.NotNull(foo); Assert.Equal("foo", foo.Content); foo.DetachedFromLogicalTree += delegate { foodetached = true; }; (target as ISetLogicalParent).SetParent(null); Assert.False((foo as IControl).IsAttachedToLogicalTree); Assert.True(foodetached); } [Fact] public void Should_Remove_Old_Child_From_LogicalChildren_On_ContentChanged_Standalone() { var target = new ContentPresenter { ContentTemplate = new FuncDataTemplate<string>(t => new ContentControl() { Content = t }, false) }; target.Content = "foo"; target.UpdateChild(); var foo = target.Child as ContentControl; Assert.NotNull(foo); var logicalChildren = target.GetLogicalChildren(); Assert.Equal(1, logicalChildren.Count()); target.Content = "bar"; target.UpdateChild(); Assert.Equal(null, foo.Parent); logicalChildren = target.GetLogicalChildren(); Assert.Equal(1, logicalChildren.Count()); Assert.NotEqual(foo, logicalChildren.First()); } } }
// 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.Globalization; using System.IO; using System.Threading; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Diagnostics; using System.Collections; using System.Collections.Generic; namespace MS.Internal.Xml.Cache { /// <summary> /// Although the XPath data model does not differentiate between text and whitespace, Managed Xml 1.0 /// does. Therefore, when building from an XmlReader, we must preserve these designations in order /// to remain backwards-compatible. /// </summary> internal enum TextBlockType { None = 0, Text = XPathNodeType.Text, SignificantWhitespace = XPathNodeType.SignificantWhitespace, Whitespace = XPathNodeType.Whitespace, }; /// <summary> /// Implementation of XmlRawWriter that builds nodes in an XPathDocument. /// </summary> internal sealed class XPathDocumentBuilder : XmlRawWriter { private NodePageFactory _nodePageFact; // Creates non-namespace node pages private NodePageFactory _nmspPageFact; // Creates namespace node pages private TextBlockBuilder _textBldr; // Concatenates adjacent text blocks private Stack<XPathNodeRef> _stkNmsp; // In-scope namespaces private XPathNodeInfoTable _infoTable; // Atomization table for shared node information private XPathDocument _doc; // Currently building document private IXmlLineInfo _lineInfo; // Line information provider private XmlNameTable _nameTable; // Atomization table for all names in the document private bool _atomizeNames; // True if all names should be atomized (false if they are pre-atomized) private XPathNode[] _pageNmsp; // Page of last in-scope namespace node private int _idxNmsp; // Page index of last in-scope namespace node private XPathNode[] _pageParent; // Page of last parent-type node (Element or Root) private int _idxParent; // Page index of last parent-type node (Element or Root) private XPathNode[] _pageSibling; // Page of previous sibling node (may be null if no previous sibling) private int _idxSibling; // Page index of previous sibling node private int _lineNumBase; // Line number from which offsets are computed private int _linePosBase; // Line position from which offsets are computed private XmlQualifiedName _idAttrName; // Cached name of an ID attribute private Hashtable _elemIdMap; // Map from element name to ID attribute name private XPathNodeRef[] _elemNameIndex; // Elements with the same name are linked together so that they can be searched quickly private const int ElementIndexSize = 64; /// <summary> /// Create a new XPathDocumentBuilder which creates nodes in "doc". /// </summary> public XPathDocumentBuilder(XPathDocument doc, IXmlLineInfo lineInfo, string baseUri, XPathDocument.LoadFlags flags) { // Allocate the initial node (for non-namespaces) page, and the initial namespace page _nodePageFact.Init(256); _nmspPageFact.Init(16); _stkNmsp = new Stack<XPathNodeRef>(); Initialize(doc, lineInfo, baseUri, flags); } /// <summary> /// Start construction of a new document. This must be called before any other methods are called. /// It may also be called after Close(), in order to build further documents. /// </summary> public void Initialize(XPathDocument doc, IXmlLineInfo lineInfo, string baseUri, XPathDocument.LoadFlags flags) { XPathNode[] page; int idx; _doc = doc; _nameTable = doc.NameTable; _atomizeNames = (flags & XPathDocument.LoadFlags.AtomizeNames) != 0; _idxParent = _idxSibling = 0; _elemNameIndex = new XPathNodeRef[ElementIndexSize]; // Prepare line number information _textBldr.Initialize(lineInfo); _lineInfo = lineInfo; _lineNumBase = 0; _linePosBase = 0; // Allocate the atomization table _infoTable = new XPathNodeInfoTable(); // Allocate singleton collapsed text node idx = NewNode(out page, XPathNodeType.Text, string.Empty, string.Empty, string.Empty, string.Empty); _doc.SetCollapsedTextNode(page, idx); // Allocate xmlns:xml namespace node _idxNmsp = NewNamespaceNode(out _pageNmsp, _nameTable.Add("xml"), _nameTable.Add(XmlReservedNs.NsXml), null, 0); _doc.SetXmlNamespaceNode(_pageNmsp, _idxNmsp); if ((flags & XPathDocument.LoadFlags.Fragment) == 0) { // This tree has a document root node _idxParent = NewNode(out _pageParent, XPathNodeType.Root, string.Empty, string.Empty, string.Empty, baseUri); _doc.SetRootNode(_pageParent, _idxParent); } else { // This tree is an XQuery fragment (no document root node), so root will be next node in the current page _doc.SetRootNode(_nodePageFact.NextNodePage, _nodePageFact.NextNodeIndex); } } //----------------------------------------------- // XmlWriter interface //----------------------------------------------- /// <summary> /// XPathDocument ignores the DocType information. /// </summary> public override void WriteDocType(string name, string pubid, string sysid, string subset) { } /// <summary> /// Shortcut for calling WriteStartElement with elemType == null. /// </summary> public override void WriteStartElement(string prefix, string localName, string ns) { this.WriteStartElement(prefix, localName, ns, string.Empty); } /// <summary> /// Build an element node and attach it to its parent, if one exists. Make the element the new parent node. /// </summary> public void WriteStartElement(string prefix, string localName, string ns, string baseUri) { int hash; Debug.Assert(prefix != null && localName != null && ns != null && localName.Length != 0 && baseUri != null); if (_atomizeNames) { prefix = _nameTable.Add(prefix); localName = _nameTable.Add(localName); ns = _nameTable.Add(ns); } AddSibling(XPathNodeType.Element, localName, ns, prefix, baseUri); _pageParent = _pageSibling; _idxParent = _idxSibling; _idxSibling = 0; // Link elements with the same name together hash = (_pageParent[_idxParent].LocalNameHashCode & (ElementIndexSize - 1)); _elemNameIndex[hash] = LinkSimilarElements(_elemNameIndex[hash].Page, _elemNameIndex[hash].Index, _pageParent, _idxParent); // If elements within this document might have IDs, then cache the name of the ID attribute, if one exists if (_elemIdMap != null) _idAttrName = (XmlQualifiedName)_elemIdMap[new XmlQualifiedName(localName, prefix)]; } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> public override void WriteEndElement() { WriteEndElement(true); } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> public override void WriteFullEndElement() { WriteEndElement(false); } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> internal override void WriteEndElement(string prefix, string localName, string namespaceName) { WriteEndElement(true); } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> internal override void WriteFullEndElement(string prefix, string localName, string namespaceName) { WriteEndElement(false); } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> public void WriteEndElement(bool allowShortcutTag) { XPathNodeRef nodeRef; Debug.Assert(_pageParent[_idxParent].NodeType == XPathNodeType.Element); // If element has no content-typed children except for the one about to be added, then // its value is the same as its only text child's. if (!_pageParent[_idxParent].HasContentChild) { switch (_textBldr.TextType) { case TextBlockType.Text: // Collapsed text node can be created if text line number information can be encoded efficiently in parent node if (_lineInfo != null) { // If collapsed text node is not on same line as parent, don't collapse text if (_textBldr.LineNumber != _pageParent[_idxParent].LineNumber) goto case TextBlockType.Whitespace; // If position is not within 256 of parent, don't collapse text int posDiff = _textBldr.LinePosition - _pageParent[_idxParent].LinePosition; if (posDiff < 0 || posDiff > XPathNode.MaxCollapsedPositionOffset) goto case TextBlockType.Whitespace; // Set collapsed node line position offset _pageParent[_idxParent].SetCollapsedLineInfoOffset(posDiff); } // Set collapsed node text _pageParent[_idxParent].SetCollapsedValue(_textBldr.ReadText()); break; case TextBlockType.SignificantWhitespace: case TextBlockType.Whitespace: // Create separate whitespace node CachedTextNode(); _pageParent[_idxParent].SetValue(_pageSibling[_idxSibling].Value); break; default: // Empty value, so don't create collapsed text node _pageParent[_idxParent].SetEmptyValue(allowShortcutTag); break; } } else { if (_textBldr.HasText) { // Element's last child (one of several) is a text or whitespace node CachedTextNode(); } } // If namespaces were added to this element, if (_pageParent[_idxParent].HasNamespaceDecls) { // Add it to the document's element --> namespace mapping _doc.AddNamespace(_pageParent, _idxParent, _pageNmsp, _idxNmsp); // Restore the previous namespace chain nodeRef = _stkNmsp.Pop(); _pageNmsp = nodeRef.Page; _idxNmsp = nodeRef.Index; } // Make parent of this element the current element _pageSibling = _pageParent; _idxSibling = _idxParent; _idxParent = _pageParent[_idxParent].GetParent(out _pageParent); } /// <summary> /// Shortcut for calling WriteStartAttribute with attrfType == null. /// </summary> public override void WriteStartAttribute(string prefix, string localName, string namespaceName) { Debug.Assert(!prefix.Equals("xmlns")); Debug.Assert(_idxParent == 0 || _pageParent[_idxParent].NodeType == XPathNodeType.Element); Debug.Assert(_idxSibling == 0 || _pageSibling[_idxSibling].NodeType == XPathNodeType.Attribute); if (_atomizeNames) { prefix = _nameTable.Add(prefix); localName = _nameTable.Add(localName); namespaceName = _nameTable.Add(namespaceName); } AddSibling(XPathNodeType.Attribute, localName, namespaceName, prefix, string.Empty); } /// <summary> /// Attach the attribute's text or typed value to the previously constructed attribute node. /// </summary> public override void WriteEndAttribute() { Debug.Assert(_pageSibling[_idxSibling].NodeType == XPathNodeType.Attribute); _pageSibling[_idxSibling].SetValue(_textBldr.ReadText()); if (_idAttrName != null) { // If this is an ID attribute, if (_pageSibling[_idxSibling].LocalName == _idAttrName.Name && _pageSibling[_idxSibling].Prefix == _idAttrName.Namespace) { // Then add its value to the idValueMap map Debug.Assert(_idxParent != 0, "ID attribute must have an element parent"); _doc.AddIdElement(_pageSibling[_idxSibling].Value, _pageParent, _idxParent); } } } /// <summary> /// Map CData text into regular text. /// </summary> public override void WriteCData(string text) { WriteString(text, TextBlockType.Text); } /// <summary> /// Construct comment node. /// </summary> public override void WriteComment(string text) { AddSibling(XPathNodeType.Comment, string.Empty, string.Empty, string.Empty, string.Empty); _pageSibling[_idxSibling].SetValue(text); } /// <summary> /// Shortcut for calling WriteProcessingInstruction with baseUri = string.Empty. /// </summary> public override void WriteProcessingInstruction(string name, string text) { this.WriteProcessingInstruction(name, text, string.Empty); } /// <summary> /// Construct pi node. /// </summary> public void WriteProcessingInstruction(string name, string text, string baseUri) { if (_atomizeNames) name = _nameTable.Add(name); AddSibling(XPathNodeType.ProcessingInstruction, name, string.Empty, string.Empty, baseUri); _pageSibling[_idxSibling].SetValue(text); } /// <summary> /// Write a whitespace text block. /// </summary> public override void WriteWhitespace(string ws) { WriteString(ws, TextBlockType.Whitespace); } /// <summary> /// Write an attribute or element text block. /// </summary> public override void WriteString(string text) { WriteString(text, TextBlockType.Text); } public override void WriteChars(char[] buffer, int index, int count) { WriteString(new string(buffer, index, count), TextBlockType.Text); } /// <summary> /// Map RawText to Text. This will lose entitization and won't roundtrip. /// </summary> public override void WriteRaw(string data) { WriteString(data, TextBlockType.Text); } public override void WriteRaw(char[] buffer, int index, int count) { WriteString(new string(buffer, index, count), TextBlockType.Text); } /// <summary> /// Write an element text block with the specified text type (whitespace, significant whitespace, or text). /// </summary> public void WriteString(string text, TextBlockType textType) { _textBldr.WriteTextBlock(text, textType); } /// <summary> /// Cache does not handle entity references. /// </summary> public override void WriteEntityRef(string name) { throw new NotImplementedException(); } /// <summary> /// Don't entitize, since the cache cannot represent character entities. /// </summary> public override void WriteCharEntity(char ch) { WriteString(char.ToString(ch), TextBlockType.Text); } /// <summary> /// Don't entitize, since the cache cannot represent character entities. /// </summary> public override void WriteSurrogateCharEntity(char lowChar, char highChar) { ReadOnlySpan<char> chars = stackalloc char[] { highChar, lowChar }; WriteString(new string(chars), TextBlockType.Text); } /// <summary> /// Signals the end of tree construction. /// </summary> public override void Close() { XPathNode[] page; int idx; // If cached text exists, then create a text node at the top-level if (_textBldr.HasText) CachedTextNode(); // If document does not yet contain nodes, then an empty text node must have been created idx = _doc.GetRootNode(out page); if (idx == _nodePageFact.NextNodeIndex && page == _nodePageFact.NextNodePage) { AddSibling(XPathNodeType.Text, string.Empty, string.Empty, string.Empty, string.Empty); _pageSibling[_idxSibling].SetValue(string.Empty); } } /// <summary> /// Since output is not forwarded to another object, this does nothing. /// </summary> public override void Flush() { } //----------------------------------------------- // XmlRawWriter interface //----------------------------------------------- /// <summary> /// Write the xml declaration. This must be the first call after Open. /// </summary> internal override void WriteXmlDeclaration(XmlStandalone standalone) { // Ignore the xml declaration when building the cache } internal override void WriteXmlDeclaration(string xmldecl) { // Ignore the xml declaration when building the cache } /// <summary> /// Called as element node's children are about to be enumerated. /// </summary> internal override void StartElementContent() { Debug.Assert(_pageParent[_idxParent].NodeType == XPathNodeType.Element); } /// <summary> /// Build a namespace declaration node. Attach it to an element parent, if one was previously constructed. /// All namespace declarations are linked together in an in-scope namespace tree. /// </summary> internal override void WriteNamespaceDeclaration(string prefix, string namespaceName) { XPathNode[] pageTemp, pageOverride, pageNew, pageOrig, pageCopy; int idxTemp, idxOverride, idxNew, idxOrig, idxCopy; Debug.Assert(_idxSibling == 0 || _pageSibling[_idxSibling].NodeType == XPathNodeType.Attribute); Debug.Assert(!prefix.Equals("xmlns") && !namespaceName.Equals(XmlReservedNs.NsXmlNs)); Debug.Assert(_idxParent == 0 || _idxNmsp != 0); Debug.Assert(_idxParent == 0 || _pageParent[_idxParent].NodeType == XPathNodeType.Element); if (_atomizeNames) prefix = _nameTable.Add(prefix); namespaceName = _nameTable.Add(namespaceName); // Does the new namespace override a previous namespace node? pageOverride = _pageNmsp; idxOverride = _idxNmsp; while (idxOverride != 0) { if ((object)pageOverride[idxOverride].LocalName == (object)prefix) { // Need to clone all namespaces up until the overridden node in order to bypass it break; } idxOverride = pageOverride[idxOverride].GetSibling(out pageOverride); } // Create new namespace node and add it to front of namespace list idxNew = NewNamespaceNode(out pageNew, prefix, namespaceName, _pageParent, _idxParent); if (idxOverride != 0) { // Bypass overridden node by cloning nodes in list leading to it pageOrig = _pageNmsp; idxOrig = _idxNmsp; pageCopy = pageNew; idxCopy = idxNew; while (idxOrig != idxOverride || pageOrig != pageOverride) { // Make a copy of the original namespace node idxTemp = pageOrig[idxOrig].GetParent(out pageTemp); idxTemp = NewNamespaceNode(out pageTemp, pageOrig[idxOrig].LocalName, pageOrig[idxOrig].Value, pageTemp, idxTemp); // Attach copy to chain of copied nodes pageCopy[idxCopy].SetSibling(_infoTable, pageTemp, idxTemp); // Position on the new copy pageCopy = pageTemp; idxCopy = idxTemp; // Get next original sibling idxOrig = pageOrig[idxOrig].GetSibling(out pageOrig); } // Link farther up in the original chain, just past the last overridden node idxOverride = pageOverride[idxOverride].GetSibling(out pageOverride); if (idxOverride != 0) pageCopy[idxCopy].SetSibling(_infoTable, pageOverride, idxOverride); else Debug.Assert(prefix.Equals("xml"), "xmlns:xml namespace declaration should always be present in the list."); } else if (_idxParent != 0) { // Link new node directly to last in-scope namespace. No overrides necessary. pageNew[idxNew].SetSibling(_infoTable, _pageNmsp, _idxNmsp); } else { // Floating namespace, so make this the root of the tree _doc.SetRootNode(pageNew, idxNew); } if (_idxParent != 0) { // If this is the first namespace on the current element, if (!_pageParent[_idxParent].HasNamespaceDecls) { // Then save the last in-scope namespace on a stack so that EndElementNode can restore it. _stkNmsp.Push(new XPathNodeRef(_pageNmsp, _idxNmsp)); // Mark element parent as having namespace nodes declared on it _pageParent[_idxParent].HasNamespaceDecls = true; } // New namespace is now last in-scope namespace _pageNmsp = pageNew; _idxNmsp = idxNew; } } //----------------------------------------------- // Custom Build Helper Methods //----------------------------------------------- /// <summary> /// Build ID lookup tables from the XSD schema or DTD. /// </summary> public void CreateIdTables(IDtdInfo dtdInfo) { // Extract the elements which has attribute defined as ID from the element declarations foreach (IDtdAttributeListInfo attrList in dtdInfo.GetAttributeLists()) { IDtdAttributeInfo idAttribute = attrList.LookupIdAttribute(); if (idAttribute != null) { if (_elemIdMap == null) _elemIdMap = new Hashtable(); // Id was defined in DTD and DTD doesn't have notion of namespace so we should // use prefix instead of namespace here. Schema already does this for us. _elemIdMap.Add(new XmlQualifiedName(attrList.LocalName, attrList.Prefix), new XmlQualifiedName(idAttribute.LocalName, idAttribute.Prefix)); } } } /// <summary> /// Link "prev" element with "next" element, which has a "similar" name. This increases the performance of searches by element name. /// </summary> private XPathNodeRef LinkSimilarElements(XPathNode[] pagePrev, int idxPrev, XPathNode[] pageNext, int idxNext) { // Set link on previous element if (pagePrev != null) pagePrev[idxPrev].SetSimilarElement(_infoTable, pageNext, idxNext); // Add next element to index return new XPathNodeRef(pageNext, idxNext); } /// <summary> /// Helper method that constructs a new Namespace XPathNode. /// </summary> private int NewNamespaceNode(out XPathNode[] page, string prefix, string namespaceUri, XPathNode[] pageElem, int idxElem) { XPathNode[] pageNode; int idxNode, lineNumOffset, linePosOffset; XPathNodeInfoAtom info; Debug.Assert(pageElem == null || pageElem[idxElem].NodeType == XPathNodeType.Element); // Allocate a page slot for the new XPathNode _nmspPageFact.AllocateSlot(out pageNode, out idxNode); // Compute node's line number information ComputeLineInfo(false, out lineNumOffset, out linePosOffset); // Obtain a XPathNodeInfoAtom object for this node info = _infoTable.Create(prefix, string.Empty, string.Empty, string.Empty, pageElem, pageNode, null, _doc, _lineNumBase, _linePosBase); // Initialize the new node pageNode[idxNode].Create(info, XPathNodeType.Namespace, idxElem); pageNode[idxNode].SetValue(namespaceUri); pageNode[idxNode].SetLineInfoOffsets(lineNumOffset, linePosOffset); page = pageNode; return idxNode; } /// <summary> /// Helper method that constructs a new XPathNode. /// </summary> private int NewNode(out XPathNode[] page, XPathNodeType xptyp, string localName, string namespaceUri, string prefix, string baseUri) { XPathNode[] pageNode; int idxNode, lineNumOffset, linePosOffset; XPathNodeInfoAtom info; Debug.Assert(xptyp != XPathNodeType.Namespace); // Allocate a page slot for the new XPathNode _nodePageFact.AllocateSlot(out pageNode, out idxNode); // Compute node's line number information ComputeLineInfo(XPathNavigator.IsText(xptyp), out lineNumOffset, out linePosOffset); // Obtain a XPathNodeInfoAtom object for this node info = _infoTable.Create(localName, namespaceUri, prefix, baseUri, _pageParent, pageNode, pageNode, _doc, _lineNumBase, _linePosBase); // Initialize the new node pageNode[idxNode].Create(info, xptyp, _idxParent); pageNode[idxNode].SetLineInfoOffsets(lineNumOffset, linePosOffset); page = pageNode; return idxNode; } /// <summary> /// Compute current node's line number information. /// </summary> private void ComputeLineInfo(bool isTextNode, out int lineNumOffset, out int linePosOffset) { int lineNum, linePos; if (_lineInfo == null) { lineNumOffset = 0; linePosOffset = 0; return; } // Get line number info from TextBlockBuilder if current node is a text node if (isTextNode) { lineNum = _textBldr.LineNumber; linePos = _textBldr.LinePosition; } else { Debug.Assert(_lineInfo.HasLineInfo(), "HasLineInfo should have been checked before this."); lineNum = _lineInfo.LineNumber; linePos = _lineInfo.LinePosition; } lineNumOffset = lineNum - _lineNumBase; if (lineNumOffset < 0 || lineNumOffset > XPathNode.MaxLineNumberOffset) { _lineNumBase = lineNum; lineNumOffset = 0; } linePosOffset = linePos - _linePosBase; if (linePosOffset < 0 || linePosOffset > XPathNode.MaxLinePositionOffset) { _linePosBase = linePos; linePosOffset = 0; } } /// <summary> /// Add a sibling node. If no previous sibling exists, add the node as the first child of the parent. /// If no parent exists, make this node the root of the document. /// </summary> private void AddSibling(XPathNodeType xptyp, string localName, string namespaceUri, string prefix, string baseUri) { XPathNode[] pageNew; int idxNew; Debug.Assert(xptyp != XPathNodeType.Root && xptyp != XPathNodeType.Namespace); if (_textBldr.HasText) CachedTextNode(); idxNew = NewNode(out pageNew, xptyp, localName, namespaceUri, prefix, baseUri); // this.idxParent is only 0 for the top-most node if (_idxParent != 0) { // Set properties on parent _pageParent[_idxParent].SetParentProperties(xptyp); if (_idxSibling == 0) { // This is the first child of the parent (so should be allocated immediately after parent) Debug.Assert(_idxParent + 1 == idxNew || idxNew == 1); } else { // There is already a previous sibling _pageSibling[_idxSibling].SetSibling(_infoTable, pageNew, idxNew); } } _pageSibling = pageNew; _idxSibling = idxNew; } /// <summary> /// Creates a text node from cached text parts. /// </summary> private void CachedTextNode() { TextBlockType textType; string text; Debug.Assert(_textBldr.HasText || (_idxSibling == 0 && _idxParent == 0), "Cannot create empty text node unless it's a top-level text node."); Debug.Assert(_idxSibling == 0 || !_pageSibling[_idxSibling].IsText, "Cannot create adjacent text nodes."); // Create a text node textType = _textBldr.TextType; text = _textBldr.ReadText(); AddSibling((XPathNodeType)textType, string.Empty, string.Empty, string.Empty, string.Empty); _pageSibling[_idxSibling].SetValue(text); } /// <summary> /// Allocates pages of nodes for the XPathDocumentBuilder. The initial pages and arrays are /// fairly small. As each page fills, a new page that is twice as big is allocated. /// The max size of a page is 65536 nodes, since XPathNode indexes are 16-bits. /// </summary> private struct NodePageFactory { private XPathNode[] _page; private XPathNodePageInfo _pageInfo; private int _pageSize; /// <summary> /// Allocates and returns the initial node page. /// </summary> public void Init(int initialPageSize) { // 0th slot: Index 0 is reserved to mean "null node". Only use 0th slot to store PageInfo. _pageSize = initialPageSize; _page = new XPathNode[_pageSize]; _pageInfo = new XPathNodePageInfo(null, 1); _page[0].Create(_pageInfo); } /// <summary> /// Return the page on which the next node will be allocated. /// </summary> public XPathNode[] NextNodePage { get { return _page; } } /// <summary> /// Return the page index that the next node will be given. /// </summary> public int NextNodeIndex { get { return _pageInfo.NodeCount; } } /// <summary> /// Allocate the next slot in the current node page. Return a reference to the page and the index /// of the allocated slot. /// </summary> public void AllocateSlot(out XPathNode[] page, out int idx) { page = _page; idx = _pageInfo.NodeCount; // Allocate new page if necessary if (++_pageInfo.NodeCount >= _page.Length) { if (_pageSize < (1 << 16)) { // New page shouldn't contain more slots than 16 bits can address _pageSize *= 2; } _page = new XPathNode[_pageSize]; _pageInfo.NextPage = _page; _pageInfo = new XPathNodePageInfo(page, _pageInfo.PageNumber + 1); _page[0].Create(_pageInfo); } } } /// <summary> /// This class concatenates adjacent text blocks and tracks TextBlockType and line number information. /// </summary> private struct TextBlockBuilder { private IXmlLineInfo _lineInfo; private TextBlockType _textType; private string _text; private int _lineNum, _linePos; /// <summary> /// Constructor. /// </summary> public void Initialize(IXmlLineInfo lineInfo) { _lineInfo = lineInfo; _textType = TextBlockType.None; } /// <summary> /// Return the type of the cached text block. /// </summary> public TextBlockType TextType { get { return _textType; } } /// <summary> /// Returns true if text has been cached. /// </summary> public bool HasText { get { return _textType != TextBlockType.None; } } /// <summary> /// Returns the line number of the last text block to be cached. /// </summary> public int LineNumber { get { return _lineNum; } } /// <summary> /// Returns the line position of the last text block to be cached. /// </summary> public int LinePosition { get { return _linePos; } } /// <summary> /// Append a text block with the specified type. /// </summary> public void WriteTextBlock(string text, TextBlockType textType) { Debug.Assert((int)XPathNodeType.Text < (int)XPathNodeType.SignificantWhitespace); Debug.Assert((int)XPathNodeType.SignificantWhitespace < (int)XPathNodeType.Whitespace); if (text.Length != 0) { if (_textType == TextBlockType.None) { _text = text; _textType = textType; if (_lineInfo != null) { _lineNum = _lineInfo.LineNumber; _linePos = _lineInfo.LinePosition; } } else { _text = string.Concat(_text, text); // Determine whether text is Text, Whitespace, or SignificantWhitespace if ((int)textType < (int)_textType) _textType = textType; } } } /// <summary> /// Read all cached text, or string.Empty if no text has been cached, and clear the text block type. /// </summary> public string ReadText() { if (_textType == TextBlockType.None) return string.Empty; _textType = TextBlockType.None; return _text; } } } }
using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using ProjectTracker.Library; using Csla.Security; namespace PTWin { public partial class MainForm : Form { public MainForm() { InitializeComponent(); _main = this; } private static MainForm _main; internal static MainForm Instance { get { return _main; } } private void MainForm_Load(object sender, EventArgs e) { if (Csla.ApplicationContext.AuthenticationType == "Windows") { AppDomain.CurrentDomain.SetPrincipalPolicy( System.Security.Principal.PrincipalPolicy.WindowsPrincipal); ApplyAuthorizationRules(); } else { DoLogin(); } if (DocumentCount == 0) this.DocumentsToolStripDropDownButton.Enabled = false; } #region Projects private void NewProjectToolStripMenuItem_Click( object sender, EventArgs e) { using (StatusBusy busy = new StatusBusy("Creating project...")) { AddWinPart(new ProjectEdit(ProjectTracker.Library.ProjectEdit.NewProject())); } } private void EditProjectToolStripMenuItem_Click( object sender, EventArgs e) { using (ProjectSelect dlg = new ProjectSelect()) { dlg.Text = "Edit Project"; if (dlg.ShowDialog() == DialogResult.OK) { ShowEditProject(dlg.ProjectId); } } } public void ShowEditProject(int projectId) { // see if this project is already loaded foreach (Control ctl in Panel1.Controls) { if (ctl is ProjectEdit) { ProjectEdit part = (ProjectEdit)ctl; if (part.Project.Id.Equals(projectId)) { // project already loaded so just // display the existing winpart ShowWinPart(part); return; } } } // the project wasn't already loaded // so load it and display the new winpart using (StatusBusy busy = new StatusBusy("Loading project...")) { try { AddWinPart(new ProjectEdit(ProjectTracker.Library.ProjectEdit.GetProject(projectId))); } catch (Csla.DataPortalException ex) { MessageBox.Show(ex.BusinessException.ToString(), "Error loading", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error loading", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } private void DeleteProjectToolStripMenuItem_Click(object sender, EventArgs e) { ProjectSelect dlg = new ProjectSelect(); dlg.Text = "Delete Project"; if (dlg.ShowDialog() == DialogResult.OK) { // get the project id var projectId = dlg.ProjectId; if (MessageBox.Show("Are you sure?", "Delete project", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) { using (StatusBusy busy = new StatusBusy("Deleting project...")) { try { ProjectTracker.Library.ProjectEdit.DeleteProject(projectId); } catch (Csla.DataPortalException ex) { MessageBox.Show(ex.BusinessException.ToString(), "Error deleting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error deleting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } } } #endregion #region Resources private void NewResourceToolStripMenuItem_Click(object sender, EventArgs e) { using (StatusBusy busy = new StatusBusy("Creating resource...")) { AddWinPart(new ResourceEdit(ProjectTracker.Library.ResourceEdit.NewResourceEdit())); } } private void EditResourceToolStripMenuItem_Click( object sender, EventArgs e) { ResourceSelect dlg = new ResourceSelect(); dlg.Text = "Edit Resource"; if (dlg.ShowDialog() == DialogResult.OK) { // get the resource id ShowEditResource(dlg.ResourceId); } } public void ShowEditResource(int resourceId) { // see if this resource is already loaded foreach (Control ctl in Panel1.Controls) { if (ctl is ResourceEdit) { ResourceEdit part = (ResourceEdit)ctl; if (part.Resource.Id.Equals(resourceId)) { // resource already loaded so just // display the existing winpart ShowWinPart(part); return; } } } // the resource wasn't already loaded // so load it and display the new winpart using (StatusBusy busy = new StatusBusy("Loading resource...")) { try { AddWinPart(new ResourceEdit(ProjectTracker.Library.ResourceEdit.GetResourceEdit(resourceId))); } catch (Csla.DataPortalException ex) { MessageBox.Show(ex.BusinessException.ToString(), "Error loading", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error loading", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } private void DeleteResourceToolStripMenuItem_Click( object sender, EventArgs e) { ResourceSelect dlg = new ResourceSelect(); dlg.Text = "Delete Resource"; if (dlg.ShowDialog() == DialogResult.OK) { // get the resource id int resourceId = dlg.ResourceId; if (MessageBox.Show("Are you sure?", "Delete resource", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) { using (StatusBusy busy = new StatusBusy("Deleting resource...")) { try { ProjectTracker.Library.ResourceEdit.DeleteResourceEdit(resourceId); } catch (Csla.DataPortalException ex) { MessageBox.Show(ex.BusinessException.ToString(), "Error deleting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error deleting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } } } #endregion #region Roles private void EditRolesToolStripMenuItem_Click( object sender, EventArgs e) { // see if this form is already loaded foreach (Control ctl in Panel1.Controls) { if (ctl is RolesEdit) { ShowWinPart((WinPart)ctl); return; } } // it wasn't already loaded, so show it. AddWinPart(new RolesEdit()); } #endregion #region ApplyAuthorizationRules private void ApplyAuthorizationRules() { // Project menu this.NewProjectToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectTracker.Library.ProjectEdit)); this.EditProjectToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(ProjectTracker.Library.ProjectEdit)); if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.ProjectEdit))) this.EditProjectToolStripMenuItem.Text = "Edit project"; else this.EditProjectToolStripMenuItem.Text = "View project"; this.DeleteProjectToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectTracker.Library.ProjectEdit)); // Resource menu this.NewResourceToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectTracker.Library.ResourceEdit)); this.EditResourceToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(ProjectTracker.Library.ResourceEdit)); if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.ResourceEdit))) this.EditResourceToolStripMenuItem.Text = "Edit resource"; else this.EditResourceToolStripMenuItem.Text = "View resource"; this.DeleteResourceToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectTracker.Library.ResourceEdit)); // Admin menu this.EditRolesToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.Admin.RoleEditList)); } #endregion #region Login/Logout private void LoginToolStripButton_Click( object sender, EventArgs e) { DoLogin(); } private void DoLogin() { ProjectTracker.Library.Security.PTPrincipal.Logout(); if (this.LoginToolStripButton.Text == "Login") { LoginForm loginForm = new LoginForm(); loginForm.ShowDialog(this); } System.Security.Principal.IPrincipal user = Csla.ApplicationContext.User; if (user.Identity.IsAuthenticated) { this.LoginToolStripLabel.Text = "Logged in as " + user.Identity.Name; this.LoginToolStripButton.Text = "Logout"; } else { this.LoginToolStripLabel.Text = "Not logged in"; this.LoginToolStripButton.Text = "Login"; } // reset menus, etc. ApplyAuthorizationRules(); // notify all documents List<object> tmpList = new List<object>(); foreach (var ctl in Panel1.Controls) tmpList.Add(ctl); foreach (var ctl in tmpList) if (ctl is WinPart) ((WinPart)ctl).OnCurrentPrincipalChanged(this, EventArgs.Empty); } #endregion #region WinPart handling /// <summary> /// Add a new WinPart control to the /// list of available documents and /// make it the active WinPart. /// </summary> /// <param name="part">The WinPart control to add and display.</param> private void AddWinPart(WinPart part) { part.CloseWinPart += new EventHandler(CloseWinPart); part.BackColor = toolStrip1.BackColor; Panel1.Controls.Add(part); this.DocumentsToolStripDropDownButton.Enabled = true; ShowWinPart(part); } /// <summary> /// Make the specified WinPart the /// active, displayed control. /// </summary> /// <param name="part">The WinPart control to display.</param> private void ShowWinPart(WinPart part) { part.Dock = DockStyle.Fill; part.Visible = true; part.BringToFront(); this.Text = "Project Tracker - " + part.ToString(); } /// <summary> /// Populate the Documents dropdown list. /// </summary> private void DocumentsToolStripDropDownButton_DropDownOpening( object sender, EventArgs e) { ToolStripItemCollection items = DocumentsToolStripDropDownButton.DropDownItems; foreach (ToolStripItem item in items) item.Click -= new EventHandler(DocumentClick); items.Clear(); foreach (Control ctl in Panel1.Controls) if (ctl is WinPart) { ToolStripItem item = new ToolStripMenuItem(); item.Text = ((WinPart)ctl).ToString(); item.Tag = ctl; item.Click += new EventHandler(DocumentClick); items.Add(item); } } /// <summary> /// Make selected WinPart the active control. /// </summary> private void DocumentClick(object sender, EventArgs e) { WinPart ctl = (WinPart)((ToolStripItem)sender).Tag; ShowWinPart(ctl); } /// <summary> /// Gets a count of the number of loaded /// documents. /// </summary> public int DocumentCount { get { int count = 0; foreach (Control ctl in Panel1.Controls) if (ctl is WinPart) count++; return count; } } /// <summary> /// Handles event from WinPart when that /// WinPart is closing. /// </summary> private void CloseWinPart(object sender, EventArgs e) { WinPart part = (WinPart)sender; part.CloseWinPart -= new EventHandler(CloseWinPart); part.Visible = false; Panel1.Controls.Remove(part); part.Dispose(); if (DocumentCount == 0) { this.DocumentsToolStripDropDownButton.Enabled = false; this.Text = "Project Tracker"; } else { // Find the first WinPart control and set // the main form's Text property accordingly. // This works because the first WinPart // is the active one. foreach (Control ctl in Panel1.Controls) { if (ctl is WinPart) { this.Text = "Project Tracker - " + ((WinPart)ctl).ToString(); break; } } } } #endregion } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace searchservice { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Indexes. /// </summary> public static partial class IndexesExtensions { /// <summary> /// Creates a new Azure Search index. /// <see href="https://msdn.microsoft.com/library/azure/dn798941.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='index'> /// The definition of the index to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Index Create(this IIndexes operations, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateAsync(index, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search index. /// <see href="https://msdn.microsoft.com/library/azure/dn798941.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='index'> /// The definition of the index to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Index> CreateAsync(this IIndexes operations, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(index, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all indexes available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn798923.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='select'> /// Selects which properties of the index definitions to retrieve. Specified as /// a comma-separated list of JSON property names, or '*' for all properties. /// The default is all properties. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexListResult List(this IIndexes operations, string select = default(string), SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.ListAsync(select, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Lists all indexes available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn798923.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='select'> /// Selects which properties of the index definitions to retrieve. Specified as /// a comma-separated list of JSON property names, or '*' for all properties. /// The default is all properties. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexListResult> ListAsync(this IIndexes operations, string select = default(string), SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(select, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new Azure Search index or updates an index if it already exists. /// <see href="https://msdn.microsoft.com/library/azure/dn800964.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The definition of the index to create or update. /// </param> /// <param name='index'> /// The definition of the index to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Index CreateOrUpdate(this IIndexes operations, string indexName, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateOrUpdateAsync(indexName, index, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search index or updates an index if it already exists. /// <see href="https://msdn.microsoft.com/library/azure/dn800964.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The definition of the index to create or update. /// </param> /// <param name='index'> /// The definition of the index to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Index> CreateOrUpdateAsync(this IIndexes operations, string indexName, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(indexName, index, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Azure Search index and all the documents it contains. /// <see href="https://msdn.microsoft.com/library/azure/dn798926.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static void Delete(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { operations.DeleteAsync(indexName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Azure Search index and all the documents it contains. /// <see href="https://msdn.microsoft.com/library/azure/dn798926.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(indexName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieves an index definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn798939.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Index Get(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.GetAsync(indexName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Retrieves an index definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn798939.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Index> GetAsync(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(indexName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns statistics for the given index, including a document count and /// storage usage. /// <see href="https://msdn.microsoft.com/library/azure/dn798942.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index for which to retrieve statistics. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexGetStatisticsResult GetStatistics(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.GetStatisticsAsync(indexName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Returns statistics for the given index, including a document count and /// storage usage. /// <see href="https://msdn.microsoft.com/library/azure/dn798942.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index for which to retrieve statistics. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexGetStatisticsResult> GetStatisticsAsync(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetStatisticsWithHttpMessagesAsync(indexName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
#region Using Directives using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; #endregion Using Directives namespace ScintillaNET { [TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))] public class Lexing : TopLevelHelper { #region Constants private const string DEFAULT_WHITECHARS = " \t\r\n\0"; private const string DEFAULT_WORDCHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; #endregion Constants #region Fields private KeywordCollection _keywords; private Dictionary<string, string> _lexerLanguageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private string _lexerName = "container"; private string _lineCommentPrefix = string.Empty; private string _streamCommentPrefix = string.Empty; private string _streamCommentSufix = string.Empty; private Dictionary<string, int> _styleNameMap = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); private string _whitespaceChars; private string _wordChars; internal char[] WhitespaceCharsArr; internal char[] WordCharsArr = null; #endregion Fields #region Methods public void Colorize() { Colorize(0, -1); } public void Colorize(int startPos, int endPos) { NativeScintilla.Colourise(startPos, endPos); } private int FindFirstNonWhitespaceChar(string s) { for (int i = 0; i < s.Length; i++) { if (s[i].ToString().IndexOfAny(WhitespaceCharsArr) == -1) return i; } return -1; } public string GetProperty(string name) { string s; NativeScintilla.GetProperty(name, out s); return s; } public string GetPropertyExpanded(string name) { string s; NativeScintilla.GetPropertyExpanded(name, out s); return s; } public int GetPropertyInt(string name) { return GetPropertyInt(name, 0); } public int GetPropertyInt(string name, int defaultValue) { return NativeScintilla.GetPropertyInt(name, defaultValue); } public void LineComment() { if (string.IsNullOrEmpty(_lineCommentPrefix)) return; // So the theory behind line commenting is that for every selected line // we look for the first non-whitespace character and insert the line // comment prefix. Lines without non-whitespace are skipped. NativeScintilla.BeginUndoAction(); Range selRange = Scintilla.Selection.Range; int start = selRange.StartingLine.Number; int end = selRange.EndingLine.Number; // We're tracking the new _end of the selection range including // the amount it expands because we're inserting new text. int offset = _lineCommentPrefix.Length; for (int i = start; i <= end; i++) { Line l = Scintilla.Lines[i]; int firstWordChar = FindFirstNonWhitespaceChar(l.Text); if (firstWordChar >= 0) { Scintilla.InsertText(l.StartPosition + firstWordChar, _lineCommentPrefix); selRange.End += offset; } } NativeScintilla.EndUndoAction(); // An odd side-effect of InsertText is that we lose the current // selection. This is undesirable. This is why we were tracking // the _end position offset. selRange.Select(); } public void LineUncomment() { if (string.IsNullOrEmpty(_lineCommentPrefix)) return; NativeScintilla.BeginUndoAction(); // Uncommenting is a lot like line commenting. However in addition // to looking for a non-whitespace character, the string that follows // it MUST be our line Comment Prefix. If this is the case the prefex // is removed from the line at its position. Range selRange = Scintilla.Selection.Range; int start = selRange.StartingLine.Number; int end = selRange.EndingLine.Number; int offset = _lineCommentPrefix.Length; for (int i = start; i <= end; i++) { Line l = Scintilla.Lines[i]; int firstWordChar = FindFirstNonWhitespaceChar(l.Text); if (firstWordChar >= 0) { int startPos = l.StartPosition + firstWordChar; Range commentRange = Scintilla.GetRange(startPos, startPos + offset); if (commentRange.Text == _lineCommentPrefix) commentRange.Text = string.Empty; } } NativeScintilla.EndUndoAction(); } public void LoadLexerLibrary(string path) { NativeScintilla.LoadLexerLibrary(path); } private void loadStyleMap() { if (Scintilla.IsDesignMode) return; _styleNameMap.Clear(); // These are global constants that always apply _styleNameMap.Add("BRACEBAD",Constants.STYLE_BRACEBAD); _styleNameMap.Add("BRACELIGHT",Constants.STYLE_BRACELIGHT); _styleNameMap.Add("CALLTIP",Constants.STYLE_CALLTIP); _styleNameMap.Add("CONTROLCHAR",Constants.STYLE_CONTROLCHAR); _styleNameMap.Add("DEFAULT",Constants.STYLE_DEFAULT); _styleNameMap.Add("LINENUMBER",Constants.STYLE_LINENUMBER); string lexname = this.Lexer.ToString().ToLower(); using (Stream s = GetType().Assembly.GetManifestResourceStream("ScintillaNET.Configuration.Builtin.LexerStyleNames." + lexname + ".txt")) { if (s == null) return; using (StreamReader sr = new StreamReader(s)) { while (!sr.EndOfStream) { string[] arr = sr.ReadLine().Split('='); if (arr.Length != 2) continue; string key = arr[0].Trim(); int value = int.Parse(arr[1].Trim()); _styleNameMap.Remove(key); _styleNameMap.Add(key, value); } } } } private void ResetLexer() { Lexer = Lexer.Container; } private void ResetLexerName() { LexerName = "container"; } private void ResetWhitespaceChars() { _whitespaceChars = DEFAULT_WHITECHARS; } private void ResetWordChars() { WordChars = DEFAULT_WORDCHARS; } public void SetKeywords(int keywordSet, string list) { NativeScintilla.SetKeywords(keywordSet, list); } public void SetProperty(string name, string value) { NativeScintilla.SetProperty(name, value); } internal bool ShouldSerialize() { return ShouldSerializeLexerName() || ShouldSerializeLexer() || ShouldSerializeWhitespaceChars() || ShouldSerializeWordChars(); } private bool ShouldSerializeLexer() { return Lexer != Lexer.Container; } private bool ShouldSerializeLexerName() { return LexerName != "container"; } private bool ShouldSerializeWhitespaceChars() { return _whitespaceChars != DEFAULT_WHITECHARS; } private bool ShouldSerializeWordChars() { return _wordChars != DEFAULT_WORDCHARS; } public void StreamComment() { if (string.IsNullOrEmpty(_streamCommentPrefix) || string.IsNullOrEmpty(_streamCommentSufix)) return; NativeScintilla.BeginUndoAction(); Range selRange = Scintilla.Selection.Range; Scintilla.InsertText(selRange.Start, _streamCommentPrefix); Scintilla.InsertText(selRange.End+ _streamCommentPrefix.Length, _streamCommentSufix); selRange.End += _streamCommentPrefix.Length + _streamCommentSufix.Length; selRange.Select(); NativeScintilla.EndUndoAction(); } public void ToggleLineComment() { if (string.IsNullOrEmpty(_lineCommentPrefix)) return; NativeScintilla.BeginUndoAction(); Range selRange = Scintilla.Selection.Range; int start = selRange.StartingLine.Number; int end = selRange.EndingLine.Number; int offset = _lineCommentPrefix.Length; for (int i = start; i <= end; i++) { Line l = Scintilla.Lines[i]; int firstWordChar = FindFirstNonWhitespaceChar(l.Text); if (firstWordChar >= 0) { int startPos = l.StartPosition + firstWordChar; Range commentRange = Scintilla.GetRange(startPos, startPos + offset); if (commentRange.Text == _lineCommentPrefix) { commentRange.Text = string.Empty; selRange.End -= offset; } else { Scintilla.InsertText(l.StartPosition + firstWordChar, _lineCommentPrefix); selRange.End += offset; } } } NativeScintilla.EndUndoAction(); selRange.Select(); } #endregion Methods #region Properties [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public KeywordCollection Keywords { get { return _keywords; } } public Lexer Lexer { get { return (Lexer)NativeScintilla.GetLexer(); } set { NativeScintilla.SetLexer((int)value); _lexerName = value.ToString().ToLower(); if (_lexerName == "null") _lexerName = ""; loadStyleMap(); } } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Dictionary<string, string> LexerLanguageMap { get { return _lexerLanguageMap; } } public string LexerName { get { return _lexerName; } set { if (string.IsNullOrEmpty(value)) value = "null"; NativeScintilla.SetLexerLanguage(value.ToLower()); _lexerName = value; loadStyleMap(); } } public string LineCommentPrefix { get { return _lineCommentPrefix; } set { if (value == null) value = string.Empty; _lineCommentPrefix = value; } } public string StreamCommentPrefix { get { return _streamCommentPrefix; } set { if (value == null) value = string.Empty; _streamCommentPrefix = value; } } public string StreamCommentSufix { get { return _streamCommentSufix; } set { if (value == null) value = string.Empty; _streamCommentSufix = value; } } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Dictionary<string, int> StyleNameMap { get { return _styleNameMap; } } [TypeConverter(typeof(ScintillaNET.WhitespaceStringConverter))] public string WhitespaceChars { get { return _whitespaceChars; } set { _whitespaceChars = value; WhitespaceCharsArr = _whitespaceChars.ToCharArray(); NativeScintilla.SetWhitespaceChars(value); } } public string WordChars { get { return _wordChars; } set { _wordChars = value; WordCharsArr = _wordChars.ToCharArray(); NativeScintilla.SetWordChars(value); } } #endregion Properties #region Constructors internal Lexing(Scintilla scintilla) : base(scintilla) { WhitespaceChars = DEFAULT_WHITECHARS; WordChars = DEFAULT_WORDCHARS; _keywords = new KeywordCollection(scintilla); // Language names are a superset lexer names. For instance the c and cs (c#) // langauges both use the cpp lexer (by default). Languages are kind of a // SCite concept, while Scintilla only cares about Lexers. However we don't // need to explicetly map a language to a lexer if they are the same name // like cpp. _lexerLanguageMap.Add("cs", "cpp"); _lexerLanguageMap.Add("html", "hypertext"); _lexerLanguageMap.Add("xml", "hypertext"); } #endregion Constructors } }
// NoteDataXML_Timeline.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using CoreUtilities; using CoreUtilities.Links; using System.Windows.Forms; using System.Xml.Serialization; using System.Collections.Generic; using Timeline; using System.ComponentModel; namespace Layout { public class NoteDataXML_Timeline : NoteDataXML { #region xml_variables ToolStripMenuItem RowFilterStrip; List<string> listoftableguids; /// <summary> /// Gets or sets the listoftableguids. /// /// These are the tables that are associated with this timeline /// /// NOTE: The first table is setup automatically when timeline created /// the others can only be hooked up via the Object Inspector. Advanced feature. /// </summary> /// <value> /// The listoftableguids. /// </value> [Editor(@"System.Windows.Forms.Design.StringCollectionEditor," + "System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))] [TypeConverter(typeof(Layout.StringListConverter))] public List<string> Listoftableguids { get { return listoftableguids; } set { listoftableguids = value; } } private int dayPanelWidth=100; // the size of each "day" in width public int DayPanelWidth { get { return dayPanelWidth; } set { dayPanelWidth = value; } } List<string> rowHistory = new List<string>(); [Editor(@"System.Windows.Forms.Design.StringCollectionEditor," + "System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))] [TypeConverter(typeof(Layout.StringListConverter))] public List<string> RowHistory { get { return rowHistory; } set { rowHistory = value; } } bool hideZoomOutPanel=false; [Description("Hides the 'month' panel.")] [DisplayName("Hide Zoomed Out Panel?")] public bool HideZoomOutPanel { get { return hideZoomOutPanel; } set { hideZoomOutPanel = value; } } private int iconsPerColumn=3; /// <summary> /// Gets or sets the icons per column. Indicates how many icons should appear in each column, in a day-box on the timeline." /// </summary> /// <value> /// The icons per column. /// </value> public int IconsPerColumn { get { return iconsPerColumn; } set { iconsPerColumn = value; } } private DateTime timelineStartDate; public DateTime TimelineStartDate { get { return timelineStartDate; } set { timelineStartDate = value; } } bool tableCreated = false; // internal only. Tracks whether the table has been made yet (basically only the VERY first call to CreateParent, creates the associated table) // I DO NOT know why I put this in place? It is important[XmlIgnore] public bool TableCreated { get { return tableCreated; } set { tableCreated = value; } } // we supply a default rowfilter so users understand this feature and how it works private string rowfilter = "icon>=0"; /// <summary> /// For Timelines, to filter the timeline /// </summary> [Description("Will filter the table(s) being used to populate the timeline.")] [DisplayName("Row Filter")] public string RowFilter { get { return rowfilter; } set { rowfilter = value; } } private Calendar.calendertype mCalendarType = Calendar.calendertype.Gregorian; /// <summary> /// Gets or sets the type of the Calendar. /// /// User can sets this. The TimeLinePanel itself 'does something' with it /// </summary> /// <value> /// The type of the M calendar. /// </value> public Calendar.calendertype MCalendarType { get { return mCalendarType; } set { mCalendarType = value; } } #endregion NotePanelTimeline Timeline = null; public NoteDataXML_Timeline () : base() { } public NoteDataXML_Timeline (int _height, int _width): base(_height, _width) { // This is the CREATIOn constructor and should only be caleld when a New Note is made // This is because we will create the TABLE that needs to be paired with this note Listoftableguids = new List<string>(); // the name for the default table string GuidOfTable = this.GuidForNote+"table"; Listoftableguids.Add (GuidOfTable); // Cannot actually create the table here becaue Layout is null } protected override string GetIcon () { return @"%*timeline_marker.png"; } protected override void CommonConstructorBehavior () { base.CommonConstructorBehavior (); Caption = Loc.Instance.Cat.GetString("Timeline"); } protected override void DoBuildChildren (LayoutPanelBase Layout) { base.DoBuildChildren (Layout); CaptionLabel.Dock = DockStyle.Top; if (TableCreated == false) { Width = 500; Height = 200; ParentNotePanel.Width = Width; ParentNotePanel.Height = Height; TimelineStartDate = DateTime.Today; // A. Create the Table NoteDataXML_Table myTable = new NoteDataXML_Table (100, 100, new ColumnDetails[7]{ new ColumnDetails ("Date", 50), new ColumnDetails ("Type", 50), new ColumnDetails ("Data", 50), new ColumnDetails ("Data2", 50), new ColumnDetails ("Data3", 50), new ColumnDetails ("Data4", 50), new ColumnDetails ("icon", 50)}); string GuidOfTable = this.GuidForNote + "table"; myTable.GuidForNote = GuidOfTable; myTable.Caption = Loc.Instance.GetStringFmt ("Table for Timeline"); Layout.AddNote (myTable); // we do not need to call CreateParent because AddNote does it for us //myTable.CreateParent (Layout); Save (); myTable.AddRow (new object[7]{DateTime.Today.ToString (), "100", "Example Description", "Example Title", "", "", 2}); TableCreated = true; Save (); // B. Populate it with example Row } Timeline = new NotePanelTimeline (this); Timeline.Dock = DockStyle.Fill; ParentNotePanel.Controls.Add (Timeline); Timeline.dayPanelWidth = DayPanelWidth; Timeline.BringToFront (); RowFilterStrip = LayoutDetails.BuildMenuPropertyEdit (Loc.Instance.GetString ("Row Filter: {0}"), RowFilter, Loc.Instance.GetString ("Filter via the columns on the table associated with this timeline."), HandleRowFilterChange); ToolStripSeparator sep = new ToolStripSeparator (); ToolStripComboBox dropper = new ToolStripComboBox (); dropper.ToolTipText = Loc.Instance.GetString ("Set the type of timeline you want by selecting an appropriate calendar."); dropper.DropDownStyle = ComboBoxStyle.DropDownList; foreach (Calendar.calendertype calendertype in Enum.GetValues (typeof(Calendar.calendertype))) { dropper.Items.Add (calendertype.ToString ()); } dropper.Text = MCalendarType.ToString (); dropper.SelectedIndexChanged += HandleSelectedIndexCalendarPickerChanged; // Icons Per Column. We had the edit to a ToolStrip Host and add the Host to the toolstrip NumericUpDown numbers = new NumericUpDown (); Panel numbersPanel = new Panel (); numbersPanel.BackColor = dropper.BackColor; Label numbersLabel = new Label (); numbersLabel.Left = 0; //numbersLabel.Dock = DockStyle.Left; numbersLabel.Text = Loc.Instance.GetString ("Icons/Column: "); numbersLabel.AutoSize = false; numbersLabel.Width = 85; numbers.Left = 90; numbers.Width = 45; //numbersLabel.AutoSize = true; //numbers.Dock = DockStyle.Right; numbersPanel.Controls.Add (numbersLabel); numbersPanel.Controls.Add (numbers); numbersLabel.BringToFront (); //numbersPanel.Dock = DockStyle.Fill; numbers.Value = IconsPerColumn; numbers.ValueChanged += HandleIconsPerColumnValueChanged; numbers.Minimum = 1; numbers.Maximum = 20; ToolStripControlHost iconsPerColumn = new ToolStripControlHost (numbersPanel); // Day Width ToolStripControlHost setDayWidth = BuildDayWidth(dropper.BackColor); DateTimePicker dates = new DateTimePicker (); dates.Width = 125; try { dates.Value = this.TimelineStartDate; } catch (Exception) { dates.Value = DateTime.Today; } dates.ValueChanged += HandleValueCurrentdateChanged; ToolStripControlHost dateToolStrip = new ToolStripControlHost (dates); dateToolStrip.ToolTipText = Loc.Instance.GetString ("Select a date to center the timeline on that date."); properties.DropDownItems.Add (sep); properties.DropDownItems.Add (dropper); properties.DropDownItems.Add (iconsPerColumn); properties.DropDownItems.Add (setDayWidth); properties.DropDownItems.Add (RowFilterStrip); properties.DropDownItems.Add (dateToolStrip); // add hjistory to RowFilterStrip foreach (string history in RowHistory) { ToolStripMenuItem test = new ToolStripMenuItem (history); test.Click += delegate(object sender, EventArgs e){ RowFilter = RowFilterStrip.Text = test.Text; Timeline.Refresh();}; RowFilterStrip.DropDownItems.Add (test); } // // // Hide ZOom Panel // // ToolStripButton HideMonths = new ToolStripButton(); HideMonths.Text = Loc.Instance.GetString("Hide Months Panel"); HideMonths.CheckOnClick = true; HideMonths.Checked = this.HideZoomOutPanel; HideMonths.Click+= HandleHideMonthsClick; properties.DropDownItems.Add (HideMonths); // Adjust panel as needed; also add this to the menu too Timeline.HideZoomPanel(this.HideZoomOutPanel); } ToolStripControlHost BuildDayWidth (System.Drawing.Color backColor) { NumericUpDown numbers = new NumericUpDown (); Panel numbersPanel = new Panel (); numbersPanel.Name = "numbers2"; numbersPanel.BackColor =backColor; Label numbersLabel = new Label (); numbersLabel.Left = 0; //numbersLabel.Dock = DockStyle.Left; numbersLabel.Text = Loc.Instance.GetString ("Day Width: "); numbersLabel.AutoSize = false; numbersLabel.Width = 85; numbers.Left = 90; numbers.Width = 45; //numbersLabel.AutoSize = true; //numbers.Dock = DockStyle.Right; numbersPanel.Controls.Add (numbersLabel); numbersPanel.Controls.Add (numbers); numbersLabel.BringToFront (); //numbersPanel.Dock = DockStyle.Fill; numbers.Minimum = 90; numbers.Maximum = 300; numbers.Value = DayPanelWidth; numbers.ValueChanged += HandleDayWidthValueChanged;; ToolStripControlHost daywidth = new ToolStripControlHost (numbersPanel); return daywidth; } void HandleDayWidthValueChanged (object sender, EventArgs e) { DayPanelWidth = (int)(sender as NumericUpDown).Value; Timeline.dayPanelWidth = DayPanelWidth; Timeline.Refresh(); SetSaveRequired(true); } void HandleHideMonthsClick (object sender, EventArgs e) { this.HideZoomOutPanel = (sender as ToolStripButton).Checked; Timeline.HideZoomPanel(this.HideZoomOutPanel); Timeline.Refresh(); } void HandleRowFilterChange (object sender, KeyEventArgs e) { if (e.KeyData == Keys.Enter) { string rowfilter = RowFilter; LayoutDetails.HandleMenuLabelEdit (sender, e, ref rowfilter, SetSaveRequired); RowFilter = rowfilter; // update based on filter setting Timeline.Refresh (); // add it to menu ToolStripMenuItem test = new ToolStripMenuItem (rowfilter); test.Click += delegate(object sender2, EventArgs e2) { RowFilter = RowFilterStrip.Text = test.Text; Timeline.Refresh();}; RowFilterStrip.DropDownItems.Add (test); // now add it to underlyin gdata if (RowHistory != null) { if (RowHistory.Count == 5) { RowHistory.Insert (0, rowfilter); // we know we have one at position 5 because count was 5 before (which meant position 4) and we added one RowHistory.RemoveAt(5); } else { RowHistory.Insert (0, rowfilter); } } } } void HandleValueCurrentdateChanged (object sender, EventArgs e) { this.TimelineStartDate = (sender as DateTimePicker).Value; Timeline.ResetTimeline(MCalendarType); Timeline.Refresh (); SetSaveRequired(true); } void HandleIconsPerColumnValueChanged (object sender, EventArgs e) { IconsPerColumn = (int)(sender as NumericUpDown).Value; Timeline.Refresh(); SetSaveRequired(true); } void HandleSelectedIndexCalendarPickerChanged (object sender, EventArgs e) { string value =(sender as ToolStripComboBox).Text; MCalendarType = (Calendar.calendertype)Enum.Parse (typeof(Calendar.calendertype), (value)); if (MCalendarType == Calendar.calendertype.Plot) { // we override the Start Date if we set this to a Plot Calendar TimelineStartDate = new DateTime(NotePanelTimeline.PLOT_DEFAULT_YEAR, 1, 1); } else { // we reset the timelinedate TimelineStartDate = DateTime.Today; } Timeline.ResetTimeline(this.MCalendarType); Timeline.Refresh (); SetSaveRequired(true); } public override void Save () { base.Save (); } public override string RegisterType () { return Loc.Instance.Cat.GetString("Timeline"); } private bool errorthrown=false; /// <summary> /// Gets the table for this timeline. /// </summary> /// <returns> /// The table for this timeline. /// </returns> /// <param name='TimelineTableGuid'> /// We pass in the GUID to allow other tables to be found (i.e., if you have made a list of tables to associate with this timeline) /// </param> public NoteDataXML_Table GetTableForThisTimeline (string TimelineTableGuid) { NoteDataXML_Table FoundTable = (NoteDataXML_Table)Layout.FindNoteByGuid (TimelineTableGuid); // April 1 2013 - this may make things TOO SLOW // but only way to guarantee al ive connection when the TIMELINE is not in the same panel as the TABLES FoundTable = (NoteDataXML_Table)Layout.GoToNote(FoundTable); if (null == FoundTable && false==errorthrown) { // just throw message once. NewMessage.Show (Loc.Instance.GetString ("The table for this Timeline was not found. Probably the guid of it needs to be set to its caption.")); errorthrown=true; //throw new Exception("The table for this Timeline was not found"); } return FoundTable; } /// <summary> /// Determines whether this instance is loaded. Passes the value from the layout /// </summary> /// <returns> /// <c>true</c> if this instance is loaded; otherwise, <c>false</c>. /// </returns> public bool IsLoaded() { if (Layout == null) return false; return Layout.IsLoaded; } public NoteDataXML_Timeline(NoteDataInterface Note) : base(Note) { } public override void CopyNote (NoteDataInterface Note) { base.CopyNote (Note); } protected override AppearanceClass UpdateAppearance () { AppearanceClass app = base.UpdateAppearance (); if (Timeline != null) { Timeline.GradientColor1 = app.captionBackground; Timeline.GradientColor2 = app.captionForeground; Timeline.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Horizontal; } return app; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Data { internal readonly struct DataKey { private const int maxColumns = 32; private readonly DataColumn[] _columns; internal DataKey(DataColumn[] columns, bool copyColumns) { if (columns == null) { throw ExceptionBuilder.ArgumentNull(nameof(columns)); } if (columns.Length == 0) { throw ExceptionBuilder.KeyNoColumns(); } if (columns.Length > maxColumns) { throw ExceptionBuilder.KeyTooManyColumns(maxColumns); } for (int i = 0; i < columns.Length; i++) { if (columns[i] == null) { throw ExceptionBuilder.ArgumentNull("column"); } } for (int i = 0; i < columns.Length; i++) { for (int j = 0; j < i; j++) { if (columns[i] == columns[j]) { throw ExceptionBuilder.KeyDuplicateColumns(columns[i].ColumnName); } } } if (copyColumns) { // Need to make a copy of all columns _columns = new DataColumn[columns.Length]; for (int i = 0; i < columns.Length; i++) { _columns[i] = columns[i]; } } else { // take ownership of the array passed in _columns = columns; } CheckState(); } internal DataColumn[] ColumnsReference => _columns; internal bool HasValue => null != _columns; internal DataTable Table => _columns[0].Table; internal void CheckState() { DataTable table = _columns[0].Table; if (table == null) { throw ExceptionBuilder.ColumnNotInAnyTable(); } for (int i = 1; i < _columns.Length; i++) { if (_columns[i].Table == null) { throw ExceptionBuilder.ColumnNotInAnyTable(); } if (_columns[i].Table != table) { throw ExceptionBuilder.KeyTableMismatch(); } } } //check to see if this.columns && key2's columns are equal regardless of order internal bool ColumnsEqual(DataKey key) => ColumnsEqual(_columns, key._columns); //check to see if columns1 && columns2 are equal regardless of order internal static bool ColumnsEqual(DataColumn[] column1, DataColumn[] column2) { if (column1 == column2) { return true; } else if (column1 == null || column2 == null) { return false; } else if (column1.Length != column2.Length) { return false; } else { int i, j; for (i = 0; i < column1.Length; i++) { bool check = false; for (j = 0; j < column2.Length; j++) { if (column1[i].Equals(column2[j])) { check = true; break; } } if (!check) { return false; } } } return true; } internal bool ContainsColumn(DataColumn column) { for (int i = 0; i < _columns.Length; i++) { if (column == _columns[i]) { return true; } } return false; } public override int GetHashCode() { Debug.Assert(false, "don't put DataKey into a Hashtable"); return base.GetHashCode(); } public override bool Equals(object value) { Debug.Assert(false, "need to directly call Equals(DataKey)"); return Equals((DataKey)value); } internal bool Equals(DataKey value) { //check to see if this.columns && key2's columns are equal... DataColumn[] column1 = _columns; DataColumn[] column2 = value._columns; if (column1 == column2) { return true; } else if (column1 == null || column2 == null) { return false; } else if (column1.Length != column2.Length) { return false; } else { for (int i = 0; i < column1.Length; i++) { if (!column1[i].Equals(column2[i])) { return false; } } return true; } } internal string[] GetColumnNames() { string[] values = new string[_columns.Length]; for (int i = 0; i < _columns.Length; ++i) { values[i] = _columns[i].ColumnName; } return values; } internal IndexField[] GetIndexDesc() { IndexField[] indexDesc = new IndexField[_columns.Length]; for (int i = 0; i < _columns.Length; i++) { indexDesc[i] = new IndexField(_columns[i], false); } return indexDesc; } internal object[] GetKeyValues(int record) { object[] values = new object[_columns.Length]; for (int i = 0; i < _columns.Length; i++) { values[i] = _columns[i][record]; } return values; } internal Index GetSortIndex() => GetSortIndex(DataViewRowState.CurrentRows); internal Index GetSortIndex(DataViewRowState recordStates) { IndexField[] indexDesc = GetIndexDesc(); return _columns[0].Table.GetIndex(indexDesc, recordStates, null); } internal bool RecordsEqual(int record1, int record2) { for (int i = 0; i < _columns.Length; i++) { if (_columns[i].Compare(record1, record2) != 0) { return false; } } return true; } internal DataColumn[] ToArray() { DataColumn[] values = new DataColumn[_columns.Length]; for (int i = 0; i < _columns.Length; ++i) { values[i] = _columns[i]; } return values; } } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 1.3.8 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IDefaultApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>string</returns> string AddDeed (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> ApiResponse<string> AddDeedWithHttpInfo (DeedApplication body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of string</returns> System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class DefaultApi : IDefaultApi { private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class. /// </summary> /// <returns></returns> public DefaultApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public DefaultApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Swagger.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>string</returns> public string AddDeed (DeedApplication body) { ApiResponse<string> localVarResponse = AddDeedWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> public ApiResponse< string > AddDeedWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling DefaultApi->AddDeed"); var localVarPath = "/deed/"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddDeed", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of string</returns> public async System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body) { ApiResponse<string> localVarResponse = await AddDeedAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> public async System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling DefaultApi->AddDeed"); var localVarPath = "/deed/"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddDeed", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="System.ServicesBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(SystemServicesServiceStatus))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(SystemServicesSSHAccess))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(SystemServicesSSHAccess_v2))] public partial class SystemServices : iControlInterface { public SystemServices() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // get_all_service_statuses //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SystemServicesServiceStatus [] get_all_service_statuses( ) { object [] results = this.Invoke("get_all_service_statuses", new object [0]); return ((SystemServicesServiceStatus [])(results[0])); } public System.IAsyncResult Beginget_all_service_statuses(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_service_statuses", new object[0], callback, asyncState); } public SystemServicesServiceStatus [] Endget_all_service_statuses(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SystemServicesServiceStatus [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SystemServicesServiceType [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((SystemServicesServiceType [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public SystemServicesServiceType [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SystemServicesServiceType [])(results[0])); } //----------------------------------------------------------------------- // get_service_status //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SystemServicesServiceStatus [] get_service_status( SystemServicesServiceType [] services ) { object [] results = this.Invoke("get_service_status", new object [] { services}); return ((SystemServicesServiceStatus [])(results[0])); } public System.IAsyncResult Beginget_service_status(SystemServicesServiceType [] services, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_service_status", new object[] { services}, callback, asyncState); } public SystemServicesServiceStatus [] Endget_service_status(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SystemServicesServiceStatus [])(results[0])); } //----------------------------------------------------------------------- // get_ssh_access //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SystemServicesSSHAccess get_ssh_access( ) { object [] results = this.Invoke("get_ssh_access", new object [0]); return ((SystemServicesSSHAccess)(results[0])); } public System.IAsyncResult Beginget_ssh_access(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ssh_access", new object[0], callback, asyncState); } public SystemServicesSSHAccess Endget_ssh_access(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SystemServicesSSHAccess)(results[0])); } //----------------------------------------------------------------------- // get_ssh_access_v2 //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SystemServicesSSHAccess_v2 get_ssh_access_v2( ) { object [] results = this.Invoke("get_ssh_access_v2", new object [0]); return ((SystemServicesSSHAccess_v2)(results[0])); } public System.IAsyncResult Beginget_ssh_access_v2(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ssh_access_v2", new object[0], callback, asyncState); } public SystemServicesSSHAccess_v2 Endget_ssh_access_v2(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SystemServicesSSHAccess_v2)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // reboot_system //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] public void reboot_system( long seconds_to_reboot ) { this.Invoke("reboot_system", new object [] { seconds_to_reboot}); } public System.IAsyncResult Beginreboot_system(long seconds_to_reboot, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reboot_system", new object[] { seconds_to_reboot}, callback, asyncState); } public void Endreboot_system(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_all_services //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] public void set_all_services( SystemServicesServiceAction service_action ) { this.Invoke("set_all_services", new object [] { service_action}); } public System.IAsyncResult Beginset_all_services(SystemServicesServiceAction service_action, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_all_services", new object[] { service_action}, callback, asyncState); } public void Endset_all_services(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_service //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] public void set_service( SystemServicesServiceType [] services, SystemServicesServiceAction service_action ) { this.Invoke("set_service", new object [] { services, service_action}); } public System.IAsyncResult Beginset_service(SystemServicesServiceType [] services,SystemServicesServiceAction service_action, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_service", new object[] { services, service_action}, callback, asyncState); } public void Endset_service(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ssh_access //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] public void set_ssh_access( SystemServicesSSHAccess access ) { this.Invoke("set_ssh_access", new object [] { access}); } public System.IAsyncResult Beginset_ssh_access(SystemServicesSSHAccess access, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ssh_access", new object[] { access}, callback, asyncState); } public void Endset_ssh_access(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ssh_access_v2 //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Services", RequestNamespace="urn:iControl:System/Services", ResponseNamespace="urn:iControl:System/Services")] public void set_ssh_access_v2( SystemServicesSSHAccess_v2 access ) { this.Invoke("set_ssh_access_v2", new object [] { access}); } public System.IAsyncResult Beginset_ssh_access_v2(SystemServicesSSHAccess_v2 access, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ssh_access_v2", new object[] { access}, callback, asyncState); } public void Endset_ssh_access_v2(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.Services.ServiceAction", Namespace = "urn:iControl")] public enum SystemServicesServiceAction { SERVICE_ACTION_START, SERVICE_ACTION_STOP, SERVICE_ACTION_REINIT, SERVICE_ACTION_RESTART, SERVICE_ACTION_ADD_TO_BOOT_LIST, SERVICE_ACTION_REMOVE_FROM_BOOT_LIST, SERVICE_ACTION_ADD_TO_DEFAULT_LIST, SERVICE_ACTION_REMOVE_FROM_DEFAULT_LIST, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.Services.ServiceStatusType", Namespace = "urn:iControl")] public enum SystemServicesServiceStatusType { SERVICE_STATUS_NOT_FOUND, SERVICE_STATUS_UP, SERVICE_STATUS_DOWN, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.Services.ServiceType", Namespace = "urn:iControl")] public enum SystemServicesServiceType { SERVICE_UNKNOWN, SERVICE_ALERTD, SERVICE_BCM56XXD, SERVICE_BIG3D, SERVICE_BIG3DSHIM, SERVICE_BIGD, SERVICE_BIGDBD, SERVICE_BIGSNMPD, SERVICE_CHMAND, SERVICE_CSSD, SERVICE_EVENTD, SERVICE_FPDD, SERVICE_HTTPD, SERVICE_LACPD, SERVICE_MCPD, SERVICE_NAMED, SERVICE_NOKIASNMPD, SERVICE_NTPD, SERVICE_OVERDOG, SERVICE_PVAD, SERVICE_RADVD, SERVICE_RMONSNMPD, SERVICE_SNMPD, SERVICE_SOD, SERVICE_SSHD, SERVICE_STATSD, SERVICE_STPD, SERVICE_SYSCALLD, SERVICE_SYSLOGD, SERVICE_TAMD, SERVICE_TMM, SERVICE_TMROUTED, SERVICE_TMSNMPD, SERVICE_TOMCAT4, SERVICE_ZEBOSD, SERVICE_GTMD, SERVICE_SUBSNMPD, SERVICE_ZRD, SERVICE_ASM, SERVICE_PVAC, SERVICE_COMM_SRV, SERVICE_HDS_PRUNE, SERVICE_TMZD, SERVICE_WAICD, SERVICE_CLUSTERD, SERVICE_CSYNCD, SERVICE_LIND, SERVICE_WAMD, SERVICE_DATASTOR, SERVICE_APD, SERVICE_APMD, SERVICE_ACED, SERVICE_DNSCACHED, SERVICE_REWRITE, SERVICE_WEBSSO, SERVICE_EAM, SERVICE_RBA, SERVICE_HTTPD_APM, SERVICE_MONPD, SERVICE_MYSQL, SERVICE_LOGSTATD, SERVICE_LOGD, SERVICE_WOCD, SERVICE_WCCPD, SERVICE_DEDUP_ADMIN, SERVICE_WOCPLUGIN, SERVICE_MD, SERVICE_DPID, SERVICE_VCMPD, SERVICE_ZXFRD, SERVICE_CBRD, SERVICE_ISTATSD, SERVICE_LLDPD, SERVICE_MERGED, SERVICE_NTLMCONNPOOL, SERVICE_SCRIPTD, SERVICE_DEVMGMTD, SERVICE_DISKEVENT, SERVICE_EMADMIND, SERVICE_EMALERTD, SERVICE_EMDEVICED, SERVICE_EMFILED, SERVICE_EMSTATSD, SERVICE_EMSNMPD, SERVICE_SWIMD, SERVICE_PKCS11D, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.Services.SSHAccess", Namespace = "urn:iControl")] public partial class SystemServicesSSHAccess { private CommonEnabledState stateField; public CommonEnabledState state { get { return this.stateField; } set { this.stateField = value; } } private string [] addressesField; public string [] addresses { get { return this.addressesField; } set { this.addressesField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.Services.SSHAccess_v2", Namespace = "urn:iControl")] public partial class SystemServicesSSHAccess_v2 { private CommonEnabledState stateField; public CommonEnabledState state { get { return this.stateField; } set { this.stateField = value; } } private string [] addressesField; public string [] addresses { get { return this.addressesField; } set { this.addressesField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.Services.ServiceStatus", Namespace = "urn:iControl")] public partial class SystemServicesServiceStatus { private SystemServicesServiceType serviceField; public SystemServicesServiceType service { get { return this.serviceField; } set { this.serviceField = value; } } private SystemServicesServiceStatusType statusField; public SystemServicesServiceStatusType status { get { return this.statusField; } set { this.statusField = value; } } }; }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.Linq; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Represents logging target. /// </summary> [NLogConfigurationItem] public abstract class Target : ISupportsInitialize, IDisposable { private readonly object _lockObject = new object(); private List<Layout> _allLayouts; /// <summary> Are all layouts in this target thread-agnostic, if so we don't precalculate the layouts </summary> private bool _allLayoutsAreThreadAgnostic; private bool _scannedForLayouts; private Exception _initializeException; /// <summary> /// The Max StackTraceUsage of all the <see cref="Layout"/> in this Target /// </summary> internal StackTraceUsage StackTraceUsage { get; private set; } /// <summary> /// Gets or sets the name of the target. /// </summary> /// <docgen category='General Options' order='10' /> public string Name { get; set; } /// <summary> /// Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers /// Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> public bool OptimizeBufferReuse { get; set; } /// <summary> /// Gets the object which can be used to synchronize asynchronous operations that must rely on the . /// </summary> protected object SyncRoot => _lockObject; /// <summary> /// Gets the logging configuration this target is part of. /// </summary> protected LoggingConfiguration LoggingConfiguration { get; private set; } /// <summary> /// Gets a value indicating whether the target has been initialized. /// </summary> protected bool IsInitialized { get { if (_isInitialized) return true; // Initialization has completed // Lets wait for initialization to complete, and then check again lock (SyncRoot) { return _isInitialized; } } } private volatile bool _isInitialized; /// <summary> /// Can be used if <see cref="OptimizeBufferReuse"/> has been enabled. /// </summary> internal readonly ReusableBuilderCreator ReusableLayoutBuilder = new ReusableBuilderCreator(); /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> void ISupportsInitialize.Initialize(LoggingConfiguration configuration) { lock (SyncRoot) { bool wasInitialized = _isInitialized; Initialize(configuration); if (wasInitialized && configuration != null) { FindAllLayouts(); } } } /// <summary> /// Closes this instance. /// </summary> void ISupportsInitialize.Close() { Close(); } /// <summary> /// Closes the target. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Flush(AsyncContinuation asyncContinuation) { if (asyncContinuation == null) { throw new ArgumentNullException("asyncContinuation"); } asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation); lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed asyncContinuation(null); return; } try { FlushAsync(asyncContinuation); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } asyncContinuation(exception); } } } /// <summary> /// Calls the <see cref="Layout.Precalculate"/> on each volatile layout /// used by this target. /// This method won't prerender if all layouts in this target are thread-agnostic. /// </summary> /// <param name="logEvent"> /// The log event. /// </param> public void PrecalculateVolatileLayouts(LogEventInfo logEvent) { if (_allLayoutsAreThreadAgnostic) return; // Not all Layouts support concurrent threads, so we have to protect them lock (SyncRoot) { if (!_isInitialized) return; if (_allLayouts != null) { if (OptimizeBufferReuse) { using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { foreach (Layout layout in _allLayouts) { targetBuilder.Result.ClearBuilder(); layout.PrecalculateBuilder(logEvent, targetBuilder.Result); } } } else { foreach (Layout layout in _allLayouts) { layout.Precalculate(logEvent); } } } } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { var targetAttribute = GetType().GetCustomAttribute<TargetAttribute>(); if (targetAttribute != null) { return $"{targetAttribute.Name} Target[{(Name ?? "(unnamed)")}]"; } return GetType().Name; } /// <summary> /// Writes the log to the target. /// </summary> /// <param name="logEvent">Log event to write.</param> public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent) { if (!IsInitialized) { lock (SyncRoot) { logEvent.Continuation(null); } return; } if (_initializeException != null) { lock (SyncRoot) { logEvent.Continuation(CreateInitException()); } return; } var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation); var wrappedLogEvent = logEvent.LogEvent.WithContinuation(wrappedContinuation); WriteAsyncThreadSafe(wrappedLogEvent); } /// <summary> /// Writes the array of log events. /// </summary> /// <param name="logEvents">The log events.</param> public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents) { if (logEvents == null || logEvents.Length == 0) { return; } WriteAsyncLogEvents((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes the array of log events. /// </summary> /// <param name="logEvents">The log events.</param> internal void WriteAsyncLogEvents(IList<AsyncLogEventInfo> logEvents) { if (logEvents == null || logEvents.Count == 0) { return; } if (!IsInitialized) { lock (SyncRoot) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(null); } } return; } if (_initializeException != null) { lock (SyncRoot) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(CreateInitException()); } } return; } IList<AsyncLogEventInfo> wrappedEvents; if (OptimizeBufferReuse) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation)); } wrappedEvents = logEvents; } else { var cloneLogEvents = new AsyncLogEventInfo[logEvents.Count]; for (int i = 0; i < logEvents.Count; ++i) { AsyncLogEventInfo ev = logEvents[i]; cloneLogEvents[i] = ev.LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(ev.Continuation)); } wrappedEvents = cloneLogEvents; } WriteAsyncThreadSafe(wrappedEvents); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> internal void Initialize(LoggingConfiguration configuration) { lock (SyncRoot) { LoggingConfiguration = configuration; if (!IsInitialized) { PropertyHelper.CheckRequiredParameters(this); try { InitializeTarget(); _initializeException = null; if (!_scannedForLayouts) { InternalLogger.Debug("InitializeTarget is done but not scanned For Layouts"); //this is critical, as we need the layouts. So if base.InitializeTarget() isn't called, we fix the layouts here. FindAllLayouts(); } } catch (Exception exception) { InternalLogger.Error(exception, "Error initializing target '{0}'.", this); _initializeException = exception; if (exception.MustBeRethrown()) { throw; } } finally { _isInitialized = true; } } } } /// <summary> /// Closes this instance. /// </summary> internal void Close() { lock (SyncRoot) { LoggingConfiguration = null; if (IsInitialized) { _isInitialized = false; try { if (_initializeException == null) { // if Init succeeded, call Close() InternalLogger.Debug("Closing target '{0}'.", this); CloseTarget(); InternalLogger.Debug("Closed target '{0}'.", this); } } catch (Exception exception) { InternalLogger.Error(exception, "Error closing target '{0}'.", this); if (exception.MustBeRethrown()) { throw; } } } } } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (_isInitialized) { _isInitialized = false; if (_initializeException == null) { CloseTarget(); } } } } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> protected virtual void InitializeTarget() { //rescan as amount layouts can be changed. FindAllLayouts(); } private void FindAllLayouts() { _allLayouts = ObjectGraphScanner.FindReachableObjects<Layout>(false, this); InternalLogger.Trace("{0} has {1} layouts", this, _allLayouts.Count); _allLayoutsAreThreadAgnostic = _allLayouts.All(layout => layout.ThreadAgnostic); StackTraceUsage = _allLayouts.DefaultIfEmpty().Max(layout => layout == null ? StackTraceUsage.None : layout.StackTraceUsage); _scannedForLayouts = true; } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected virtual void CloseTarget() { } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected virtual void FlushAsync(AsyncContinuation asyncContinuation) { asyncContinuation(null); } /// <summary> /// Writes logging event to the log target. Must be overridden in inheriting /// classes. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected virtual void Write(LogEventInfo logEvent) { // Override to perform the actual write-operation } /// <summary> /// Writes async log event to the log target. /// </summary> /// <param name="logEvent">Async Log event to be written out.</param> protected virtual void Write(AsyncLogEventInfo logEvent) { try { MergeEventProperties(logEvent.LogEvent); Write(logEvent.LogEvent); logEvent.Continuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } logEvent.Continuation(exception); } } /// <summary> /// Writes a log event to the log target, in a thread safe manner. /// </summary> /// <param name="logEvent">Log event to be written out.</param> protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed logEvent.Continuation(null); return; } try { Write(logEvent); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } logEvent.Continuation(exception); } } } /// <summary> /// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected virtual void Write(AsyncLogEventInfo[] logEvents) { Write((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected virtual void Write(IList<AsyncLogEventInfo> logEvents) { for (int i = 0; i < logEvents.Count; ++i) { Write(logEvents[i]); } } /// <summary> /// NOTE! Obsolete, instead override WriteAsyncThreadSafe(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target, in a thread safe manner. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo[] logEvents) { WriteAsyncThreadSafe((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes an array of logging events to the log target, in a thread safe manner. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected virtual void WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents) { lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(null); } return; } try { AsyncLogEventInfo[] logEventsArray = OptimizeBufferReuse ? null : logEvents as AsyncLogEventInfo[]; if (!OptimizeBufferReuse && logEventsArray != null) { // Backwards compatibility #pragma warning disable 612, 618 Write(logEventsArray); #pragma warning restore 612, 618 } else { Write(logEvents); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } // in case of synchronous failure, assume that nothing is running asynchronously for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(exception); } } } } private Exception CreateInitException() { return new NLogRuntimeException($"Target {this} failed to initialize.", _initializeException); } /// <summary> /// Merges (copies) the event context properties from any event info object stored in /// parameters of the given event info object. /// </summary> /// <param name="logEvent">The event info object to perform the merge to.</param> protected void MergeEventProperties(LogEventInfo logEvent) { if (logEvent.Parameters == null || logEvent.Parameters.Length == 0) { return; } //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < logEvent.Parameters.Length; ++i) { var logEventParameter = logEvent.Parameters[i] as LogEventInfo; if (logEventParameter != null && logEventParameter.HasProperties) { foreach (var key in logEventParameter.Properties.Keys) { logEvent.Properties.Add(key, logEventParameter.Properties[key]); } logEventParameter.Properties.Clear(); } } } /// <summary> /// Renders the event info in layout. /// </summary> /// <param name="layout">The layout.</param> /// <param name="logEvent">The event info.</param> /// <returns>String representing log event.</returns> protected string RenderLogEvent(Layout layout, LogEventInfo logEvent) { if (OptimizeBufferReuse) { SimpleLayout simpleLayout = layout as SimpleLayout; if (simpleLayout != null && simpleLayout.IsFixedText) return simpleLayout.Render(logEvent); using (var localTarget = ReusableLayoutBuilder.Allocate()) { return layout.RenderAllocateBuilder(logEvent, localTarget.Result, false); } } else { return layout.Render(logEvent); } } /// <summary> /// Register a custom Target. /// </summary> /// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks> /// <typeparam name="T"> Type of the Target.</typeparam> /// <param name="name"> Name of the Target.</param> public static void Register<T>(string name) where T : Target { var layoutRendererType = typeof(T); Register(name, layoutRendererType); } /// <summary> /// Register a custom Target. /// </summary> /// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks> /// <param name="targetType"> Type of the Target.</param> /// <param name="name"> Name of the Target.</param> public static void Register(string name, Type targetType) { ConfigurationItemFactory.Default.Targets .RegisterDefinition(name, targetType); } } }
/* * Copyright (c) 2007-2009, openmetaverse.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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Diagnostics; using System.Threading; using System.Text; namespace OpenMetaverse.Voice { public partial class VoiceGateway { public delegate void DaemonRunningCallback(); public delegate void DaemonExitedCallback(); public delegate void DaemonCouldntRunCallback(); public delegate void DaemonConnectedCallback(); public delegate void DaemonDisconnectedCallback(); public delegate void DaemonCouldntConnectCallback(); public event DaemonRunningCallback OnDaemonRunning; public event DaemonExitedCallback OnDaemonExited; public event DaemonCouldntRunCallback OnDaemonCouldntRun; public event DaemonConnectedCallback OnDaemonConnected; public event DaemonDisconnectedCallback OnDaemonDisconnected; public event DaemonCouldntConnectCallback OnDaemonCouldntConnect; public bool DaemonIsRunning { get { return daemonIsRunning; } } public bool DaemonIsConnected { get { return daemonIsConnected; } } public int RequestId { get { return requestId; } } protected Process daemonProcess; protected ManualResetEvent daemonLoopSignal = new ManualResetEvent(false); protected TCPPipe daemonPipe; protected bool daemonIsRunning = false; protected bool daemonIsConnected = false; protected int requestId = 0; #region Daemon Management /// <summary> /// Starts a thread that keeps the daemon running /// </summary> /// <param name="path"></param> /// <param name="args"></param> public void StartDaemon(string path, string args) { StopDaemon(); daemonLoopSignal.Set(); Thread thread = new Thread(new ThreadStart(delegate() { while (daemonLoopSignal.WaitOne(500, false)) { daemonProcess = new Process(); daemonProcess.StartInfo.FileName = path; daemonProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(path); daemonProcess.StartInfo.Arguments = args; daemonProcess.StartInfo.UseShellExecute = false; if (Environment.OSVersion.Platform == PlatformID.Unix) { string ldPath = string.Empty; try { ldPath = Environment.GetEnvironmentVariable("LD_LIBRARY_PATH"); } catch { } string newLdPath = daemonProcess.StartInfo.WorkingDirectory; if (!string.IsNullOrEmpty(ldPath)) newLdPath += ":" + ldPath; daemonProcess.StartInfo.EnvironmentVariables.Add("LD_LIBRARY_PATH", newLdPath); } Logger.DebugLog("Voice folder: " + daemonProcess.StartInfo.WorkingDirectory); Logger.DebugLog(path + " " + args); bool ok = true; if (!File.Exists(path)) ok = false; if (ok) { // Attempt to start the process if (!daemonProcess.Start()) ok = false; } if (!ok) { daemonIsRunning = false; daemonLoopSignal.Reset(); if (OnDaemonCouldntRun != null) { try { OnDaemonCouldntRun(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } return; } else { Thread.Sleep(2000); daemonIsRunning = true; if (OnDaemonRunning != null) { try { OnDaemonRunning(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } Logger.DebugLog("Started voice daemon, waiting for exit..."); daemonProcess.WaitForExit(); Logger.DebugLog("Voice daemon exited"); daemonIsRunning = false; if (OnDaemonExited != null) { try { OnDaemonExited(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } } } })); thread.Name = "VoiceDaemonController"; thread.IsBackground = true; thread.Start(); } /// <summary> /// Stops the daemon and the thread keeping it running /// </summary> public void StopDaemon() { daemonLoopSignal.Reset(); if (daemonProcess != null) { try { daemonProcess.Kill(); } catch (InvalidOperationException ex) { Logger.Log("Failed to stop the voice daemon", Helpers.LogLevel.Error, ex); } } } /// <summary> /// /// </summary> /// <param name="address"></param> /// <param name="port"></param> /// <returns></returns> public bool ConnectToDaemon(string address, int port) { daemonIsConnected = false; daemonPipe = new TCPPipe(); daemonPipe.OnDisconnected += delegate(SocketException e) { if (OnDaemonDisconnected != null) { try { OnDaemonDisconnected(); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, null, ex); } } }; daemonPipe.OnReceiveLine += new TCPPipe.OnReceiveLineCallback(daemonPipe_OnReceiveLine); SocketException se = daemonPipe.Connect(address, port); if (se == null) { daemonIsConnected = true; if (OnDaemonConnected != null) { try { OnDaemonConnected(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } return true; } else { daemonIsConnected = false; if (OnDaemonCouldntConnect != null) { try { OnDaemonCouldntConnect(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } Logger.Log("Voice daemon connection failed: " + se.Message, Helpers.LogLevel.Error); return false; } } #endregion Daemon Management public int Request(string action) { return Request(action, null); } public int Request(string action, string requestXML) { int returnId = requestId; if (daemonIsConnected) { StringBuilder sb = new StringBuilder(); sb.Append(String.Format("<Request requestId=\"{0}\" action=\"{1}\"", requestId++, action)); if (string.IsNullOrEmpty(requestXML)) { sb.Append(" />"); } else { sb.Append(">"); sb.Append(requestXML); sb.Append("</Request>"); } sb.Append("\n\n\n"); #if DEBUG Logger.Log("Request: " + sb.ToString(), Helpers.LogLevel.Debug); #endif try { daemonPipe.SendData(Encoding.ASCII.GetBytes(sb.ToString())); } catch { returnId = -1; } return returnId; } else { return -1; } } public static string MakeXML(string name, string text) { if (string.IsNullOrEmpty(text)) return string.Format("<{0} />", name); else return string.Format("<{0}>{1}</{0}>", name, text); } private void daemonPipe_OnReceiveLine(string line) { #if DEBUG Logger.Log(line, Helpers.LogLevel.Debug); #endif if (line.Substring(0, 10) == "<Response ") { VoiceResponse rsp = null; try { rsp = (VoiceResponse)ResponseSerializer.Deserialize(new StringReader(line)); } catch (Exception e) { Logger.Log("Failed to deserialize voice daemon response", Helpers.LogLevel.Error, e); return; } ResponseType genericResponse = ResponseType.None; switch (rsp.Action) { // These first responses carry useful information beyond simple status, // so they each have a specific Event. case "Connector.Create.1": if (OnConnectorCreateResponse != null) { OnConnectorCreateResponse( rsp.InputXml.Request, new VoiceConnectorEventArgs( int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.VersionID, rsp.Results.ConnectorHandle)); } break; case "Aux.GetCaptureDevices.1": inputDevices = new List<string>(); if (rsp.Results.CaptureDevices.Count == 0 || rsp.Results.CurrentCaptureDevice == null) break; foreach (CaptureDevice device in rsp.Results.CaptureDevices) inputDevices.Add(device.Device); currentCaptureDevice = rsp.Results.CurrentCaptureDevice.Device; if (OnAuxGetCaptureDevicesResponse != null && rsp.Results.CaptureDevices.Count > 0) { OnAuxGetCaptureDevicesResponse( rsp.InputXml.Request, new VoiceDevicesEventArgs( ResponseType.GetCaptureDevices, int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.CurrentCaptureDevice.Device, inputDevices)); } break; case "Aux.GetRenderDevices.1": outputDevices = new List<string>(); if (rsp.Results.RenderDevices.Count == 0 || rsp.Results.CurrentRenderDevice == null) break; foreach (RenderDevice device in rsp.Results.RenderDevices) outputDevices.Add(device.Device); currentPlaybackDevice = rsp.Results.CurrentRenderDevice.Device; if (OnAuxGetRenderDevicesResponse != null) { OnAuxGetRenderDevicesResponse( rsp.InputXml.Request, new VoiceDevicesEventArgs( ResponseType.GetCaptureDevices, int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.CurrentRenderDevice.Device, outputDevices)); } break; case "Account.Login.1": if (OnAccountLoginResponse != null) { OnAccountLoginResponse(rsp.InputXml.Request, new VoiceAccountEventArgs( int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.AccountHandle)); } break; case "Session.Create.1": if (OnSessionCreateResponse != null) { OnSessionCreateResponse( rsp.InputXml.Request, new VoiceSessionEventArgs( int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.SessionHandle)); } break; // All the remaining responses below this point just report status, // so they all share the same Event. Most are useful only for // detecting coding errors. case "Connector.InitiateShutdown.1": genericResponse = ResponseType.ConnectorInitiateShutdown; break; case "Aux.SetRenderDevice.1": genericResponse = ResponseType.SetRenderDevice; break; case "Connector.MuteLocalMic.1": genericResponse = ResponseType.MuteLocalMic; break; case "Connector.MuteLocalSpeaker.1": genericResponse = ResponseType.MuteLocalSpeaker; break; case "Connector.SetLocalMicVolume.1": genericResponse = ResponseType.SetLocalMicVolume; break; case "Connector.SetLocalSpeakerVolume.1": genericResponse = ResponseType.SetLocalSpeakerVolume; break; case "Aux.SetCaptureDevice.1": genericResponse = ResponseType.SetCaptureDevice; break; case "Session.RenderAudioStart.1": genericResponse = ResponseType.RenderAudioStart; break; case "Session.RenderAudioStop.1": genericResponse = ResponseType.RenderAudioStop; break; case "Aux.CaptureAudioStart.1": genericResponse = ResponseType.CaptureAudioStart; break; case "Aux.CaptureAudioStop.1": genericResponse = ResponseType.CaptureAudioStop; break; case "Aux.SetMicLevel.1": genericResponse = ResponseType.SetMicLevel; break; case "Aux.SetSpeakerLevel.1": genericResponse = ResponseType.SetSpeakerLevel; break; case "Account.Logout.1": genericResponse = ResponseType.AccountLogout; break; case "Session.Connect.1": genericResponse = ResponseType.SessionConnect; break; case "Session.Terminate.1": genericResponse = ResponseType.SessionTerminate; break; case "Session.SetParticipantVolumeForMe.1": genericResponse = ResponseType.SetParticipantVolumeForMe; break; case "Session.SetParticipantMuteForMe.1": genericResponse = ResponseType.SetParticipantMuteForMe; break; case "Session.Set3DPosition.1": genericResponse = ResponseType.Set3DPosition; break; default: Logger.Log("Unimplemented response from the voice daemon: " + line, Helpers.LogLevel.Error); break; } // Send the Response Event for all the simple cases. if (genericResponse != ResponseType.None && OnVoiceResponse != null) { OnVoiceResponse(rsp.InputXml.Request, new VoiceResponseEventArgs( genericResponse, int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString)); } } else if (line.Substring(0, 7) == "<Event ") { VoiceEvent evt = null; try { evt = (VoiceEvent)EventSerializer.Deserialize(new StringReader(line)); } catch (Exception e) { Logger.Log("Failed to deserialize voice daemon event", Helpers.LogLevel.Error, e); return; } switch (evt.Type) { case "LoginStateChangeEvent": case "AccountLoginStateChangeEvent": if (OnAccountLoginStateChangeEvent != null) { OnAccountLoginStateChangeEvent(this, new AccountLoginStateChangeEventArgs( evt.AccountHandle, int.Parse(evt.StatusCode), evt.StatusString, (LoginState)int.Parse(evt.State))); } break; case "SessionNewEvent": if (OnSessionNewEvent != null) { OnSessionNewEvent(this, new NewSessionEventArgs( evt.AccountHandle, evt.SessionHandle, evt.URI, bool.Parse(evt.IsChannel), evt.Name, evt.AudioMedia)); } break; case "SessionStateChangeEvent": if (OnSessionStateChangeEvent != null) { OnSessionStateChangeEvent(this, new SessionStateChangeEventArgs( evt.SessionHandle, int.Parse(evt.StatusCode), evt.StatusString, (SessionState)int.Parse(evt.State), evt.URI, bool.Parse(evt.IsChannel), evt.ChannelName)); } break; case "ParticipantAddedEvent": Logger.Log("Add participant " + evt.ParticipantUri, Helpers.LogLevel.Debug); if (OnSessionParticipantAddedEvent != null) { OnSessionParticipantAddedEvent(this, new ParticipantAddedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.ParticipantUri, evt.AccountName, evt.DisplayName, (ParticipantType)int.Parse(evt.ParticipantType), evt.Application)); } break; case "ParticipantRemovedEvent": if (OnSessionParticipantRemovedEvent != null) { OnSessionParticipantRemovedEvent(this, new ParticipantRemovedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.ParticipantUri, evt.AccountName, evt.Reason)); } break; case "ParticipantStateChangeEvent": // Useful in person-to-person calls if (OnSessionParticipantStateChangeEvent != null) { OnSessionParticipantStateChangeEvent(this, new ParticipantStateChangeEventArgs( evt.SessionHandle, int.Parse(evt.StatusCode), evt.StatusString, (ParticipantState)int.Parse(evt.State), // Ringing, Connected, etc evt.ParticipantUri, evt.AccountName, evt.DisplayName, (ParticipantType)int.Parse(evt.ParticipantType))); } break; case "ParticipantPropertiesEvent": if (OnSessionParticipantPropertiesEvent != null) { OnSessionParticipantPropertiesEvent(this, new ParticipantPropertiesEventArgs( evt.SessionHandle, evt.ParticipantUri, bool.Parse(evt.IsLocallyMuted), bool.Parse(evt.IsModeratorMuted), bool.Parse(evt.IsSpeaking), int.Parse(evt.Volume), float.Parse(evt.Energy))); } break; case "ParticipantUpdatedEvent": if (OnSessionParticipantUpdatedEvent != null) { OnSessionParticipantUpdatedEvent(this, new ParticipantUpdatedEventArgs( evt.SessionHandle, evt.ParticipantUri, bool.Parse(evt.IsModeratorMuted), bool.Parse(evt.IsSpeaking), int.Parse(evt.Volume), float.Parse(evt.Energy))); } break; case "SessionGroupAddedEvent": if (OnSessionGroupAddedEvent != null) { OnSessionGroupAddedEvent(this, new SessionGroupAddedEventArgs( evt.AccountHandle, evt.SessionGroupHandle, evt.Type)); } break; case "SessionAddedEvent": if (OnSessionAddedEvent != null) { OnSessionAddedEvent(this, new SessionAddedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.Uri, bool.Parse(evt.IsChannel), bool.Parse(evt.Incoming))); } break; case "SessionRemovedEvent": if (OnSessionRemovedEvent != null) { OnSessionRemovedEvent(this, new SessionRemovedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.Uri)); } break; case "SessionUpdatedEvent": if (OnSessionRemovedEvent != null) { OnSessionUpdatedEvent(this, new SessionUpdatedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.Uri, int.Parse(evt.IsMuted) != 0, int.Parse(evt.Volume), int.Parse(evt.TransmitEnabled) != 0, + int.Parse(evt.IsFocused) != 0)); } break; case "AuxAudioPropertiesEvent": if (OnAuxAudioPropertiesEvent != null) { OnAuxAudioPropertiesEvent(this, new AudioPropertiesEventArgs( bool.Parse(evt.MicIsActive), float.Parse(evt.MicEnergy), int.Parse(evt.MicVolume), int.Parse(evt.SpeakerVolume))); } break; case "SessionMediaEvent": if (OnSessionMediaEvent != null) { OnSessionMediaEvent(this, new SessionMediaEventArgs( evt.SessionHandle, bool.Parse(evt.HasText), bool.Parse(evt.HasAudio), bool.Parse(evt.HasVideo), bool.Parse(evt.Terminated))); } break; case "BuddyAndGroupListChangedEvent": // TODO * <AccountHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==</AccountHandle><Buddies /><Groups /> break; case "MediaStreamUpdatedEvent": // TODO <SessionGroupHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==_sg0</SessionGroupHandle> // <SessionHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==0</SessionHandle> //<StatusCode>0</StatusCode><StatusString /><State>1</State><Incoming>false</Incoming> break; default: Logger.Log("Unimplemented event from the voice daemon: " + line, Helpers.LogLevel.Error); break; } } else { Logger.Log("Unrecognized data from the voice daemon: " + line, Helpers.LogLevel.Error); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace CustomerInsights.Tests.Tests { using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Management.CustomerInsights; using Microsoft.Azure.Management.CustomerInsights.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; public class InteractionTypeScenarioTests { /// <summary> /// Constructor /// </summary> static InteractionTypeScenarioTests() { HubName = AppSettings.HubName; ResourceGroupName = AppSettings.ResourceGroupName; } /// <summary> /// Hub Name /// </summary> private static readonly string HubName; /// <summary> /// Reosurce Group Name /// </summary> private static readonly string ResourceGroupName; [Fact] public void CreateAndReadInteractionType() { using (var context = MockContext.Start(this.GetType())) { var aciClient = context.GetServiceClient<CustomerInsightsManagementClient>(); var interactionName = TestUtilities.GenerateName("TestInteractionType"); var interactionResourceFormat = Helpers.GetTestInteraction(interactionName, "profile1"); //Create interaction and verify var interactionResult = aciClient.Interactions.CreateOrUpdate( ResourceGroupName, HubName, interactionName, interactionResourceFormat); Assert.Equal(interactionName, interactionResult.TypeName); Assert.Equal(interactionResult.Name, HubName + "/" + interactionName); Assert.Equal("Microsoft.CustomerInsights/hubs/interactions", interactionResult.Type); //Get interaction and verify var interactionGetResult = aciClient.Interactions.Get( ResourceGroupName, HubName, interactionName, "en-us"); Assert.Equal(interactionName, interactionGetResult.TypeName); Assert.Equal( interactionGetResult.Name, HubName + "/" + interactionName, StringComparer.OrdinalIgnoreCase); Assert.Equal( "Microsoft.CustomerInsights/hubs/interactions", interactionGetResult.Type, StringComparer.OrdinalIgnoreCase); } } [Fact] public void ListInteractionTypesInHub() { using (var context = MockContext.Start(this.GetType())) { var aciClient = context.GetServiceClient<CustomerInsightsManagementClient>(); var interactionName1 = TestUtilities.GenerateName("TestInteractionType1"); var interactionResourceFormat1 = Helpers.GetTestInteraction(interactionName1, "profile1"); var interactionName2 = TestUtilities.GenerateName("TestInteractionType2"); var interactionResourceFormat2 = Helpers.GetTestInteraction(interactionName2, "profile2"); //Create interaction and verify aciClient.Interactions.CreateOrUpdate( ResourceGroupName, HubName, interactionName1, interactionResourceFormat1); aciClient.Interactions.CreateOrUpdate( ResourceGroupName, HubName, interactionName2, interactionResourceFormat2); var interactionList = aciClient.Interactions.ListByHub(ResourceGroupName, HubName); Assert.True(interactionList.ToList().Count >= 2); Assert.True( interactionList.ToList() .Any(interactionReturned => interactionName1 == interactionReturned.TypeName) && interactionList.ToList() .Any(interactionReturned => interactionName1 == interactionReturned.TypeName)); } } [Fact] public void SuggestRelationshipLinks() { using (var context = MockContext.Start(this.GetType())) { var aciClient = context.GetServiceClient<CustomerInsightsManagementClient>(); var profileName1 = TestUtilities.GenerateName("testProfile"); var profileName2 = TestUtilities.GenerateName("testProfile"); var interactionName1 = TestUtilities.GenerateName("testInteraction"); var profileResourceFormat1 = new ProfileResourceFormat { ApiEntitySetName = profileName1, Fields = new[] { new PropertyDefinition { FieldName = "ContactId", FieldType = "Edm.String", IsArray = false, IsRequired = true } }, StrongIds = new List<StrongId> { new StrongId { StrongIdName = "ContactId", KeyPropertyNames = new List<string> { "ContactId" } } } }; var profileResourceFormat2 = new ProfileResourceFormat { ApiEntitySetName = profileName2, Fields = new[] { new PropertyDefinition { FieldName = "BranchId", FieldType = "Edm.String", IsArray = false, IsRequired = true } }, StrongIds = new List<StrongId> { new StrongId { StrongIdName = "BranchId", KeyPropertyNames = new List<string> { "BranchId" } } } }; aciClient.Profiles.CreateOrUpdate(ResourceGroupName, HubName, profileName1, profileResourceFormat1); aciClient.Profiles.CreateOrUpdate(ResourceGroupName, HubName, profileName2, profileResourceFormat2); var interactionResourceFormat = new InteractionResourceFormat { ApiEntitySetName = interactionName1, Fields = new[] { new PropertyDefinition { FieldName = "ContactId", FieldType = "Edm.String" }, new PropertyDefinition { FieldName = "BranchId", FieldType = "Edm.String" } } }; aciClient.Interactions.CreateOrUpdate( ResourceGroupName, HubName, interactionName1, interactionResourceFormat); var linkName1 = TestUtilities.GenerateName("linkTest"); var linkName2 = TestUtilities.GenerateName("linkTest"); var linkResourceFormat1 = new LinkResourceFormat { TargetProfileType = profileName1, SourceInteractionType = interactionName1, ParticipantPropertyReferences = new[] { new ParticipantPropertyReference { ProfilePropertyName = "ContactId", InteractionPropertyName = "ContactId" } } }; var link1 = aciClient.Links.CreateOrUpdate(ResourceGroupName, HubName, linkName1, linkResourceFormat1); var linkResourceFormat2 = new LinkResourceFormat { TargetProfileType = profileName2, SourceInteractionType = interactionName1, ParticipantPropertyReferences = new[] { new ParticipantPropertyReference { ProfilePropertyName = "BranchId", InteractionPropertyName = "BranchId" } } }; var link2 = aciClient.Links.CreateOrUpdate(ResourceGroupName, HubName, linkName2, linkResourceFormat2); TestUtilities.Wait(5000); var suggestedRelationshipLinks = aciClient.Interactions.SuggestRelationshipLinks( ResourceGroupName, HubName, interactionName1); Assert.Equal(2, suggestedRelationshipLinks.SuggestedRelationships.Count); Assert.Equal(interactionName1, suggestedRelationshipLinks.InteractionName); Assert.True( ((suggestedRelationshipLinks.SuggestedRelationships[0].ProfileName == profileName1) && (suggestedRelationshipLinks.SuggestedRelationships[0].RelatedProfileName == profileName2)) || ((suggestedRelationshipLinks.SuggestedRelationships[0].ProfileName == profileName2) && (suggestedRelationshipLinks.SuggestedRelationships[0].RelatedProfileName == profileName1))); } } } }
using System.Security; using System; using System.Runtime.InteropServices; // For SafeHandle [SecurityCritical] public class MySafeValidHandle : SafeHandle { [SecurityCritical] public MySafeValidHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { [SecurityCritical] get { return false; } } [SecurityCritical] protected override bool ReleaseHandle() { return true; } } [SecurityCritical] public class MySafeInValidHandle : SafeHandle { [SecurityCritical] public MySafeInValidHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { [SecurityCritical] get { return true; } } [SecurityCritical] protected override bool ReleaseHandle() { return true; } } /// <summary> /// DangerousAddRef(System.Boolean@) /// </summary> public class SafeHandleDangerousAddRef { #region Public Methods [SecuritySafeCritical] public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; return retVal; } #region Positive Test Cases [SecuritySafeCritical] public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call DangerousAddRef on a valid handle"); try { SafeHandle handle = new MySafeValidHandle(); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef"); } } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call DangerousAddRef on an invalid handle"); try { SafeHandle handle = new MySafeInValidHandle(); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef"); } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call DangerousAddRef twice on a valid handle"); try { SafeHandle handle = new MySafeValidHandle(); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef"); } handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef"); } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Call DangerousAddRef twice on an invalid handle"); try { SafeHandle handle = new MySafeInValidHandle(); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef"); } handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef"); } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion [SecuritySafeCritical] public static int Main() { SafeHandleDangerousAddRef test = new SafeHandleDangerousAddRef(); TestLibrary.TestFramework.BeginTestCase("SafeHandleDangerousAddRef"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
namespace FakeItEasy.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FakeItEasy.Configuration; using FakeItEasy.Core; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xunit; public class OutAndRefParametersConfigurationExtensionsTests { public interface IInterface { void RequestOfOne(out int numberOut); void RequestOfOne(out string textOut); void RequestOfTwo(int number1, out int numberOut); void RequestOfTwo(string text1, out string textOut); void RequestOfThree(int number1, int number2, out int numberOut); void RequestOfThree(string text1, string text2, out string textOut); void RequestOfFour(int number1, int number2, int number3, out int numberOut); void RequestOfFour(string text1, string text2, string text3, out string textOut); } [Fact] public void AssignsOutAndRefParameters_should_return_configuration_returned_from_passed_in_configuration() { // Arrange var expectedConfig = A.Fake<IAfterCallConfiguredWithOutAndRefParametersConfiguration<IVoidConfiguration>>(); var config = A.Fake<IOutAndRefParametersConfiguration<IVoidConfiguration>>(); A.CallTo(() => config.AssignsOutAndRefParametersLazily( A<Func<IFakeObjectCall, ICollection<object?>>>.That.Matches(x => (string?)x.Invoke(A.Dummy<IFakeObjectCall>()).First() == "10"))) .Returns(expectedConfig); // Act var returned = config.AssignsOutAndRefParameters("10"); // Assert returned.Should().BeSameAs(expectedConfig); } [Fact] public void AssignsOutAndRefParameters_should_be_null_guarded() { // Arrange // Act // Assert Expression<Action> call = () => A.Fake<IOutAndRefParametersConfiguration<IVoidConfiguration>>().AssignsOutAndRefParameters("a string"); call.Should().BeNullGuarded(); } [Fact] public void AssignsOutAndRefParametersLazily_with_1_argument_should_use_ReturnsOutAndRefParameters_with_action_having_1_argument() { // Arrange const int OutValue = 5; int fakeOut; int result; var fake = A.Fake<IInterface>(); A.CallTo(() => fake.RequestOfOne(out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((int oi) => new object[] { OutValue }); // Act fake.RequestOfOne(out result); // Assert result.Should().Be(OutValue); } [Fact] public void AssignsOutAndRefParametersLazily_with_1_argument_should_support_overloads() { // Arrange const string OutValue = "Result"; string fakeOut; string result; var fake = A.Fake<IInterface>(); A.CallTo(() => fake.RequestOfOne(out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((string oi) => new object[] { OutValue }); // Act fake.RequestOfOne(out result); // Assert result.Should().Be(OutValue); } [Fact] public void AssignsOutAndRefParametersLazily_with_1_argument_should_throw_exception_when_argument_count_does_not_match() { // Arrange var fake = A.Fake<IInterface>(); int fakeOut; A.CallTo(() => fake.RequestOfTwo(5, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((int io) => { throw new InvalidOperationException( "assigns out and ref parameters lazily action should not be executed"); }); Action act = () => fake.RequestOfTwo(5, out fakeOut); // Act, Assert AssertThatSignatureMismatchExceptionIsThrown(act, "(System.Int32, System.Int32&)", "(System.Int32)"); } [Fact] public void AssignsOutAndRefParametersLazily_with_1_argument_should_throw_exception_when_type_does_not_match() { // Arrange var fake = A.Fake<IInterface>(); int fakeOut; A.CallTo(() => fake.RequestOfOne(out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((string s) => { throw new InvalidOperationException( "assigns out and ref parameters lazily action should not be executed"); }); Action act = () => fake.RequestOfOne(out fakeOut); // Act, Assert AssertThatSignatureMismatchExceptionIsThrown(act, "(System.Int32&)", "(System.String)"); } [Fact] public void AssignsOutAndRefParametersLazily_with_2_arguments_should_use_ReturnsOutAndRefParameters_with_action_having_2_arguments() { // Arrange const int Argument = 2; const int OutValue = 5; int? collectedArgument = null; int fakeOut; int result; var fake = A.Fake<IInterface>(); A.CallTo(() => fake.RequestOfTwo(Argument, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((int i, int oi) => { collectedArgument = i; return new object[] { OutValue }; }); // Act fake.RequestOfTwo(Argument, out result); // Assert result.Should().Be(OutValue); collectedArgument.Should().Be(Argument); } [Fact] public void AssignsOutAndRefParametersLazily_with_2_arguments_should_support_overloads() { // Arrange const string Argument = "argument"; const string OutValue = "Result"; string? collectedArgument = null; string fakeOut; string result; var fake = A.Fake<IInterface>(); A.CallTo(() => fake.RequestOfTwo(Argument, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((string s, string oi) => { collectedArgument = s; return new object[] { OutValue }; }); // Act fake.RequestOfTwo(Argument, out result); // Assert result.Should().Be(OutValue); collectedArgument.Should().Be(Argument); } [Fact] public void AssignsOutAndRefParametersLazily_with_2_arguments_should_throw_exception_when_argument_count_does_not_match() { // Arrange var fake = A.Fake<IInterface>(); int fakeOut; A.CallTo(() => fake.RequestOfThree(A<int>._, A<int>._, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((int i, int io) => { throw new InvalidOperationException( "assigns out and ref parameters lazily action should not be executed"); }); Action act = () => fake.RequestOfThree(5, 8, out fakeOut); // Act, Assert AssertThatSignatureMismatchExceptionIsThrown( act, "(System.Int32, System.Int32, System.Int32&)", "(System.Int32, System.Int32)"); } [Fact] public void AssignsOutAndRefParametersLazily_with_2_arguments_should_throw_exception_when_type_does_not_match() { // Arrange var fake = A.Fake<IInterface>(); int fakeOut; A.CallTo(() => fake.RequestOfTwo(A<int>._, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((string s, int io) => { throw new InvalidOperationException( "assigns out and ref parameters lazily action should not be executed"); }); Action act = () => fake.RequestOfTwo(5, out fakeOut); // Act, Assert AssertThatSignatureMismatchExceptionIsThrown( act, "(System.Int32, System.Int32&)", "(System.String, System.Int32)"); } [Fact] public void AssignsOutAndRefParametersLazily_with_3_arguments_should_use_ReturnsOutAndRefParameters_with_action_having_3_arguments() { // Arrange const int FirstArgument = 2; const int SecondArgument = 8; const int OutValue = 5; int? firstCollectedArgument = null; int? secondCollectedArgument = null; int fakeOut; int result; var fake = A.Fake<IInterface>(); A.CallTo(() => fake.RequestOfThree(FirstArgument, SecondArgument, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((int i1, int i2, int oi) => { firstCollectedArgument = i1; secondCollectedArgument = i2; return new object[] { OutValue }; }); // Act fake.RequestOfThree(FirstArgument, SecondArgument, out result); // Assert result.Should().Be(OutValue); firstCollectedArgument.Should().Be(FirstArgument); secondCollectedArgument.Should().Be(SecondArgument); } [Fact] public void AssignsOutAndRefParametersLazily_with_3_arguments_should_support_overloads() { // Arrange const string FirstArgument = "argument1"; const string SecondArgument = "argument2"; const string OutValue = "Result"; string? firstCollectedArgument = null; string? secondCollectedArgument = null; string fakeOut; string result; var fake = A.Fake<IInterface>(); A.CallTo(() => fake.RequestOfThree(FirstArgument, SecondArgument, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((string s1, string s2, string oi) => { firstCollectedArgument = s1; secondCollectedArgument = s2; return new object[] { OutValue }; }); // Act fake.RequestOfThree(FirstArgument, SecondArgument, out result); // Assert result.Should().Be(OutValue); firstCollectedArgument.Should().Be(FirstArgument); secondCollectedArgument.Should().Be(SecondArgument); } [Fact] public void AssignsOutAndRefParametersLazily_with_3_arguments_should_throw_exception_when_argument_count_does_not_match() { // Arrange var fake = A.Fake<IInterface>(); int fakeOut; A.CallTo(() => fake.RequestOfFour(A<int>._, A<int>._, A<int>._, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((int i1, int i2, int io) => { throw new InvalidOperationException( "assigns out and ref parameters lazily action should not be executed"); }); Action act = () => fake.RequestOfFour(5, 8, 9, out fakeOut); // Act, Assert AssertThatSignatureMismatchExceptionIsThrown( act, "(System.Int32, System.Int32, System.Int32, System.Int32&)", "(System.Int32, System.Int32, System.Int32)"); } [Fact] public void AssignsOutAndRefParametersLazily_with_3_arguments_should_throw_exception_when_type_does_not_match() { // Arrange var fake = A.Fake<IInterface>(); int fakeOut; A.CallTo(() => fake.RequestOfThree(A<int>._, A<int>._, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((string s1, string s2, int io) => { throw new InvalidOperationException( "assigns out and ref parameters lazily action should not be executed"); }); Action act = () => fake.RequestOfThree(5, 8, out fakeOut); // Act, Assert AssertThatSignatureMismatchExceptionIsThrown( act, "(System.Int32, System.Int32, System.Int32&)", "(System.String, System.String, System.Int32)"); } [Fact] public void AssignsOutAndRefParametersLazily_with_4_arguments_should_use_ReturnsOutAndRefParameters_with_action_having_4_arguments() { // Arrange const int FirstArgument = 2; const int SecondArgument = 8; const int ThirdArgument = 4; const int OutValue = 5; int? firstCollectedArgument = null; int? secondCollectedArgument = null; int? thirdCollectedArgument = null; int fakeOut; int result; var fake = A.Fake<IInterface>(); A.CallTo(() => fake.RequestOfFour(FirstArgument, SecondArgument, ThirdArgument, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((int i1, int i2, int i3, int oi) => { firstCollectedArgument = i1; secondCollectedArgument = i2; thirdCollectedArgument = i3; return new object[] { OutValue }; }); // Act fake.RequestOfFour(FirstArgument, SecondArgument, ThirdArgument, out result); // Assert result.Should().Be(OutValue); firstCollectedArgument.Should().Be(FirstArgument); secondCollectedArgument.Should().Be(SecondArgument); thirdCollectedArgument.Should().Be(ThirdArgument); } [Fact] public void AssignsOutAndRefParametersLazily_with_4_arguments_should_support_overloads() { // Arrange const string FirstArgument = "argument1"; const string SecondArgument = "argument2"; const string ThirdArgument = "argument3"; const string OutValue = "Result"; string? firstCollectedArgument = null; string? secondCollectedArgument = null; string? thirdCollectedArgument = null; string fakeOut; string result; var fake = A.Fake<IInterface>(); A.CallTo(() => fake.RequestOfFour(FirstArgument, SecondArgument, ThirdArgument, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((string s1, string s2, string s3, string oi) => { firstCollectedArgument = s1; secondCollectedArgument = s2; thirdCollectedArgument = s3; return new object[] { OutValue }; }); // Act fake.RequestOfFour(FirstArgument, SecondArgument, ThirdArgument, out result); // Assert result.Should().Be(OutValue); firstCollectedArgument.Should().Be(FirstArgument); secondCollectedArgument.Should().Be(SecondArgument); thirdCollectedArgument.Should().Be(ThirdArgument); } [Fact] public void AssignsOutAndRefParametersLazily_with_4_arguments_should_throw_exception_when_argument_count_does_not_match() { // Arrange var fake = A.Fake<IInterface>(); int fakeOut; A.CallTo(() => fake.RequestOfTwo(A<int>._, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((int i1, int i2, int i3, int io) => { throw new InvalidOperationException( "assigns out and ref parameters lazily action should not be executed"); }); Action act = () => fake.RequestOfTwo(5, out fakeOut); // Act, Assert AssertThatSignatureMismatchExceptionIsThrown( act, "(System.Int32, System.Int32&)", "(System.Int32, System.Int32, System.Int32, System.Int32)"); } [Fact] public void AssignsOutAndRefParametersLazily_with_4_arguments_should_throw_exception_when_type_does_not_match() { // Arrange var fake = A.Fake<IInterface>(); int fakeOut; A.CallTo(() => fake.RequestOfFour(A<int>._, A<int>._, A<int>._, out fakeOut)) .WithAnyArguments() .AssignsOutAndRefParametersLazily((string s1, string s2, string s3, int io) => { throw new InvalidOperationException( "assigns out and ref parameters lazily action should not be executed"); }); Action act = () => fake.RequestOfFour(5, 8, 4, out fakeOut); // Act, Assert AssertThatSignatureMismatchExceptionIsThrown( act, "(System.Int32, System.Int32, System.Int32, System.Int32&)", "(System.String, System.String, System.String, System.Int32)"); } private static void AssertThatSignatureMismatchExceptionIsThrown( Action act, string fakeSignature, string outAndRefSignature) { // Arrange var expectedMessage = "The faked method has the signature " + fakeSignature + ", but assigns out and ref parameters lazily was used with " + outAndRefSignature + "."; // Act var exception = Record.Exception(act); // Assert exception.Should().BeAnExceptionOfType<FakeConfigurationException>() .And.Message.Should().Be(expectedMessage); } } }
using System; using System.Collections.Generic; using GitVersion; using NUnit.Framework; using Shouldly; [TestFixture] public class ArgumentParserTests { [Test] public void Empty_means_use_current_directory() { var arguments = ArgumentParser.ParseArguments(""); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void Single_means_use_as_target_directory() { var arguments = ArgumentParser.ParseArguments("path"); arguments.TargetPath.ShouldBe("path"); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void No_path_and_logfile_should_use_current_directory_TargetDirectory() { var arguments = ArgumentParser.ParseArguments("-l logFilePath"); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void h_means_IsHelp() { var arguments = ArgumentParser.ParseArguments("-h"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsHelp.ShouldBe(true); } [Test] public void exec() { var arguments = ArgumentParser.ParseArguments("-exec rake"); arguments.Exec.ShouldBe("rake"); } [Test] public void exec_with_args() { var arguments = ArgumentParser.ParseArguments(new List<string> { "-exec", "rake", "-execargs", "clean build" }); arguments.Exec.ShouldBe("rake"); arguments.ExecArgs.ShouldBe("clean build"); } [Test] public void msbuild() { var arguments = ArgumentParser.ParseArguments("-proj msbuild.proj"); arguments.Proj.ShouldBe("msbuild.proj"); } [Test] public void msbuild_with_args() { var arguments = ArgumentParser.ParseArguments(new List<string> { "-proj", "msbuild.proj", "-projargs", "/p:Configuration=Debug /p:Platform=AnyCPU" }); arguments.Proj.ShouldBe("msbuild.proj"); arguments.ProjArgs.ShouldBe("/p:Configuration=Debug /p:Platform=AnyCPU"); } [Test] public void execwith_targetdirectory() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -exec rake"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Exec.ShouldBe("rake"); } [Test] public void TargetDirectory_and_LogFilePath_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void Username_and_Password_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Authentication.Username.ShouldBe("[username]"); arguments.Authentication.Password.ShouldBe("[password]"); arguments.IsHelp.ShouldBe(false); } [Test] public void Unknown_output_should_throw() { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); exception.Message.ShouldBe("Value 'invalid_value' cannot be parsed as output type, please use 'json' or 'buildserver'"); } [Test] public void Output_defaults_to_json() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath"); arguments.Output.ShouldBe(OutputType.Json); } [Test] public void Output_json_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output json"); arguments.Output.ShouldBe(OutputType.Json); } [Test] public void Output_buildserver_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver"); arguments.Output.ShouldBe(OutputType.BuildServer); } [Test] public void MultipleArgsAndFlag() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); arguments.Output.ShouldBe(OutputType.BuildServer); } [Test] public void Url_and_BranchName_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.TargetUrl.ShouldBe("http://github.com/Particular/GitVersion.git"); arguments.TargetBranch.ShouldBe("somebranch"); arguments.IsHelp.ShouldBe(false); } [Test] public void Wrong_number_of_arguments_should_throw() { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'."); } [Test] public void Unknown_argument_should_throw() { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -x logFilePath")); exception.Message.ShouldBe("Could not parse command line parameter '-x'."); } [TestCase("-updateAssemblyInfo true")] [TestCase("-updateAssemblyInfo 1")] [TestCase("-updateAssemblyInfo")] [TestCase("-updateAssemblyInfo -proj foo.sln")] public void update_assembly_info_true(string command) { var arguments = ArgumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(true); } [TestCase("-updateAssemblyInfo false")] [TestCase("-updateAssemblyInfo 0")] public void update_assembly_info_false(string command) { var arguments = ArgumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(false); } [Test] public void update_assembly_info_with_filename() { var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.ShouldBe("CommonAssemblyInfo.cs"); } [Test] public void update_assembly_info_with_relative_filename() { var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.ShouldBe("..\\..\\CommonAssemblyInfo.cs"); } [Test] public void dynamicRepoLocation() { var arguments = ArgumentParser.ParseArguments("-dynamicRepoLocation c:\\foo\\"); arguments.DynamicRepositoryLocation.ShouldBe("c:\\foo\\"); } [Test] public void can_log_to_console() { var arguments = ArgumentParser.ParseArguments("-l console -proj foo.sln"); arguments.LogFilePath.ShouldBe("console"); } [Test] public void nofetch_true_when_defined() { var arguments = ArgumentParser.ParseArguments("-nofetch"); arguments.NoFetch = true; } [Test] public void other_arguments_can_be_parsed_before_nofetch() { var arguments = ArgumentParser.ParseArguments("targetpath -nofetch "); arguments.TargetPath = "targetpath"; arguments.NoFetch = true; } [Test] public void other_arguments_can_be_parsed_after_nofetch() { var arguments = ArgumentParser.ParseArguments("-nofetch -proj foo.sln"); arguments.NoFetch = true; arguments.Proj = "foo.sln"; } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnSuspensione class. /// </summary> [Serializable] public partial class PnSuspensioneCollection : ActiveList<PnSuspensione, PnSuspensioneCollection> { public PnSuspensioneCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnSuspensioneCollection</returns> public PnSuspensioneCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnSuspensione o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_suspensiones table. /// </summary> [Serializable] public partial class PnSuspensione : ActiveRecord<PnSuspensione>, IActiveRecord { #region .ctors and Default Settings public PnSuspensione() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnSuspensione(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnSuspensione(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnSuspensione(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_suspensiones", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdSuspension = new TableSchema.TableColumn(schema); colvarIdSuspension.ColumnName = "id_suspension"; colvarIdSuspension.DataType = DbType.Int32; colvarIdSuspension.MaxLength = 0; colvarIdSuspension.AutoIncrement = true; colvarIdSuspension.IsNullable = false; colvarIdSuspension.IsPrimaryKey = true; colvarIdSuspension.IsForeignKey = false; colvarIdSuspension.IsReadOnly = false; colvarIdSuspension.DefaultSetting = @""; colvarIdSuspension.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdSuspension); TableSchema.TableColumn colvarIdLegajo = new TableSchema.TableColumn(schema); colvarIdLegajo.ColumnName = "id_legajo"; colvarIdLegajo.DataType = DbType.Int32; colvarIdLegajo.MaxLength = 0; colvarIdLegajo.AutoIncrement = false; colvarIdLegajo.IsNullable = false; colvarIdLegajo.IsPrimaryKey = false; colvarIdLegajo.IsForeignKey = false; colvarIdLegajo.IsReadOnly = false; colvarIdLegajo.DefaultSetting = @""; colvarIdLegajo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdLegajo); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "fecha"; colvarFecha.DataType = DbType.DateTime; colvarFecha.MaxLength = 0; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = false; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; colvarFecha.DefaultSetting = @""; colvarFecha.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha); TableSchema.TableColumn colvarMotivo = new TableSchema.TableColumn(schema); colvarMotivo.ColumnName = "motivo"; colvarMotivo.DataType = DbType.AnsiString; colvarMotivo.MaxLength = -1; colvarMotivo.AutoIncrement = false; colvarMotivo.IsNullable = false; colvarMotivo.IsPrimaryKey = false; colvarMotivo.IsForeignKey = false; colvarMotivo.IsReadOnly = false; colvarMotivo.DefaultSetting = @""; colvarMotivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarMotivo); TableSchema.TableColumn colvarDias = new TableSchema.TableColumn(schema); colvarDias.ColumnName = "dias"; colvarDias.DataType = DbType.Int16; colvarDias.MaxLength = 0; colvarDias.AutoIncrement = false; colvarDias.IsNullable = false; colvarDias.IsPrimaryKey = false; colvarDias.IsForeignKey = false; colvarDias.IsReadOnly = false; colvarDias.DefaultSetting = @""; colvarDias.ForeignKeyTableName = ""; schema.Columns.Add(colvarDias); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_suspensiones",schema); } } #endregion #region Props [XmlAttribute("IdSuspension")] [Bindable(true)] public int IdSuspension { get { return GetColumnValue<int>(Columns.IdSuspension); } set { SetColumnValue(Columns.IdSuspension, value); } } [XmlAttribute("IdLegajo")] [Bindable(true)] public int IdLegajo { get { return GetColumnValue<int>(Columns.IdLegajo); } set { SetColumnValue(Columns.IdLegajo, value); } } [XmlAttribute("Fecha")] [Bindable(true)] public DateTime Fecha { get { return GetColumnValue<DateTime>(Columns.Fecha); } set { SetColumnValue(Columns.Fecha, value); } } [XmlAttribute("Motivo")] [Bindable(true)] public string Motivo { get { return GetColumnValue<string>(Columns.Motivo); } set { SetColumnValue(Columns.Motivo, value); } } [XmlAttribute("Dias")] [Bindable(true)] public short Dias { get { return GetColumnValue<short>(Columns.Dias); } set { SetColumnValue(Columns.Dias, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdLegajo,DateTime varFecha,string varMotivo,short varDias) { PnSuspensione item = new PnSuspensione(); item.IdLegajo = varIdLegajo; item.Fecha = varFecha; item.Motivo = varMotivo; item.Dias = varDias; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdSuspension,int varIdLegajo,DateTime varFecha,string varMotivo,short varDias) { PnSuspensione item = new PnSuspensione(); item.IdSuspension = varIdSuspension; item.IdLegajo = varIdLegajo; item.Fecha = varFecha; item.Motivo = varMotivo; item.Dias = varDias; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdSuspensionColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdLegajoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn FechaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn MotivoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn DiasColumn { get { return Schema.Columns[4]; } } #endregion #region Columns Struct public struct Columns { public static string IdSuspension = @"id_suspension"; public static string IdLegajo = @"id_legajo"; public static string Fecha = @"fecha"; public static string Motivo = @"motivo"; public static string Dias = @"dias"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DynamicTests : ExpressionCompilerTestBase { [Fact] public void Local_Simple() { var source = @"class C { static void M() { dynamic d = 1; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); } [Fact] public void Local_Array() { var source = @"class C { static void M() { dynamic[] d = new dynamic[1]; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic[] V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); } [Fact] public void Local_Generic() { var source = @"class C { static void M() { System.Collections.Generic.List<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Collections.Generic.List<dynamic> V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); } [Fact] public void LocalConstant_Simple() { var source = @"class C { static void M() { const dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, new SymReader(pdbBytes, exeBytes)); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } [Fact] public void LocalConstant_Array() { var source = @"class C { static void M() { const dynamic[] d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, new SymReader(pdbBytes, exeBytes)); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } [Fact] public void LocalConstant_Generic() { var source = @"class C { static void M() { const Generic<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } } class Generic<T> { } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, new SymReader(pdbBytes, exeBytes)); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); } [Fact] public void Parameter_Simple() { var source = @"class C { static void M(dynamic d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void Parameter_Array() { var source = @"class C { static void M(dynamic[] d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void Parameter_Generic() { var source = @"class C { static void M(System.Collections.Generic.List<dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [WorkItem(1087216, "DevDiv")] [Fact] public void ComplexDynamicType() { var source = @"class C { static void M(Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } } public class Outer<T, U> { public class Inner<V, W> { public enum E { A } } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); VerifyCustomTypeInfo(locals[0], 0x04, 0x03); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); string error; var result = context.CompileExpression("d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, 0x04, 0x03); // Note that the method produced by CompileAssignment returns void // so there is never custom type info. result = context.CompileAssignment("d", "d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, null); } [Fact] public void DynamicAttribute_NotAvailable() { var source = @"class C { static void M() { dynamic d = 1; } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasNoDynamicAttribute(method); } private static void AssertHasDynamicAttribute(IMethodSymbol method) { Assert.Contains( "System.Runtime.CompilerServices.DynamicAttribute", method.GetSynthesizedAttributes(forReturnType: true).Select(a => a.AttributeClass.ToTestDisplayString())); } private static void AssertHasNoDynamicAttribute(IMethodSymbol method) { Assert.DoesNotContain( "System.Runtime.CompilerServices.DynamicAttribute", method.GetSynthesizedAttributes(forReturnType: true).Select(a => a.AttributeClass.ToTestDisplayString())); } [Fact] public void DynamicCall() { var source = @" class C { void M() { dynamic d = this; d.M(); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("d.M()", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(TypeKind.Dynamic, methodData.Method.ReturnType.TypeKind); methodData.VerifyIL(@" { // Code size 77 (0x4d) .maxstack 9 .locals init (dynamic V_0) //d IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""M"" IL_000d: ldnull IL_000e: ldtoken ""<>x"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldloc.0 IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: ret } "); } [WorkItem(1072296)] [Fact] public void InvokeStaticMemberInLambda() { var source = @" class C { static dynamic x; static void Foo(dynamic y) { System.Action a = () => Foo(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.Foo"); var testData = new CompilationTestData(); string error; var result = context.CompileAssignment("a", "() => Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); testData.GetMethodData("<>x.<>c.<<>m0>b__0_0").VerifyIL(@" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Foo"" IL_0011: ldnull IL_0012: ldtoken ""<>x"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0055: ldtoken ""<>x"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.x"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0069: ret }"); context = CreateMethodContext(runtime, "C.<>c.<Foo>b__1_0"); testData = new CompilationTestData(); result = context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Foo"" IL_000d: ldnull IL_000e: ldtoken ""<>x"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldsfld ""dynamic C.x"" IL_0060: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0065: ret }"); } [WorkItem(1095613)] [Fact(Skip = "1095613")] public void HoistedLocalsLoseDynamicAttribute() { var source = @" class C { static void M(dynamic x) { dynamic y = 3; System.Func<dynamic> a = () => x + y; } static void Foo(int x) { M(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>c.<>m0()").VerifyIL(@" { // Code size 166 (0xa6) .maxstack 11 .locals init (System.Func<dynamic> V_0) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Func<dynamic>"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""<>c"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_003f: brtrue.s IL_007c IL_0041: ldc.i4.0 IL_0042: ldstr ""Foo"" IL_0047: ldnull IL_0048: ldtoken ""<>c"" IL_004d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0052: ldc.i4.2 IL_0053: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0058: dup IL_0059: ldc.i4.0 IL_005a: ldc.i4.s 33 IL_005c: ldnull IL_005d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.1 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_008b: ldtoken ""<>c"" IL_0090: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0095: ldsfld ""dynamic C.x"" IL_009a: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_009f: callvirt ""System.Func<dynamic> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a4: stloc.0 IL_00a5: ret }"); result = context.CompileExpression("Foo(y)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>c.<>m0()").VerifyIL(@" { // Code size 166 (0xa6) .maxstack 11 .locals init (System.Func<dynamic> V_0) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Func<dynamic>"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""<>c"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>> <>c.<<>m0>o__SiteContainer0.<>p__Site2"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_003f: brtrue.s IL_007c IL_0041: ldc.i4.0 IL_0042: ldstr ""Foo"" IL_0047: ldnull IL_0048: ldtoken ""<>c"" IL_004d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0052: ldc.i4.2 IL_0053: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0058: dup IL_0059: ldc.i4.0 IL_005a: ldc.i4.s 33 IL_005c: ldnull IL_005d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.1 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>c.<<>m0>o__SiteContainer0.<>p__Site1"" IL_008b: ldtoken ""<>c"" IL_0090: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0095: ldsfld ""dynamic C.x"" IL_009a: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_009f: callvirt ""System.Func<dynamic> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Func<dynamic>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a4: stloc.0 IL_00a5: ret }"); } private static void VerifyCustomTypeInfo(LocalAndMethod localAndMethod, params byte[] expectedBytes) { VerifyCustomTypeInfo(localAndMethod.GetCustomTypeInfo(), expectedBytes); } private static void VerifyCustomTypeInfo(CompileResult compileResult, params byte[] expectedBytes) { VerifyCustomTypeInfo(compileResult.GetCustomTypeInfo(), expectedBytes); } private static void VerifyCustomTypeInfo(CustomTypeInfo customTypeInfo, byte[] expectedBytes) { Assert.Equal(DynamicFlagsCustomTypeInfo.PayloadTypeId, customTypeInfo.PayloadTypeId); Assert.Equal(expectedBytes, customTypeInfo.Payload); } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace NAudio.Wave.Compression { /// <summary> /// AcmStream encapsulates an Audio Compression Manager Stream /// used to convert audio from one format to another /// </summary> public class AcmStream : IDisposable { private readonly WaveFormat sourceFormat; private IntPtr driverHandle; private IntPtr streamHandle; private AcmStreamHeader streamHeader; /// <summary> /// Creates a new ACM stream to convert one format to another. Note that /// not all conversions can be done in one step /// </summary> /// <param name="sourceFormat">The source audio format</param> /// <param name="destFormat">The destination audio format</param> public AcmStream(WaveFormat sourceFormat, WaveFormat destFormat) { try { streamHandle = IntPtr.Zero; this.sourceFormat = sourceFormat; int sourceBufferSize = Math.Max(65536, sourceFormat.AverageBytesPerSecond); sourceBufferSize -= (sourceBufferSize%sourceFormat.BlockAlign); MmException.Try( AcmInterop.acmStreamOpen(out streamHandle, IntPtr.Zero, sourceFormat, destFormat, null, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen"); int destBufferSize = SourceToDest(sourceBufferSize); streamHeader = new AcmStreamHeader(streamHandle, sourceBufferSize, destBufferSize); driverHandle = IntPtr.Zero; } catch { // suppress the finalise and clean up resources Dispose(); throw; } } /// <summary> /// Creates a new ACM stream to convert one format to another, using a /// specified driver identified and wave filter /// </summary> /// <param name="driverId">the driver identifier</param> /// <param name="sourceFormat">the source format</param> /// <param name="waveFilter">the wave filter</param> public AcmStream(IntPtr driverId, WaveFormat sourceFormat, WaveFilter waveFilter) { int sourceBufferSize = Math.Max(16384, sourceFormat.AverageBytesPerSecond); this.sourceFormat = sourceFormat; sourceBufferSize -= (sourceBufferSize%sourceFormat.BlockAlign); MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, driverId, 0), "acmDriverOpen"); MmException.Try(AcmInterop.acmStreamOpen(out streamHandle, driverHandle, sourceFormat, sourceFormat, waveFilter, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen"); streamHeader = new AcmStreamHeader(streamHandle, sourceBufferSize, SourceToDest(sourceBufferSize)); } /// <summary> /// Returns the Source Buffer. Fill this with data prior to calling convert /// </summary> public byte[] SourceBuffer { get { return streamHeader.SourceBuffer; } } /// <summary> /// Returns the Destination buffer. This will contain the converted data /// after a successful call to Convert /// </summary> public byte[] DestBuffer { get { return streamHeader.DestBuffer; } } /// <summary> /// Returns the number of output bytes for a given number of input bytes /// </summary> /// <param name="source">Number of input bytes</param> /// <returns>Number of output bytes</returns> public int SourceToDest(int source) { if (source == 0) // zero is an invalid parameter to acmStreamSize return 0; int convertedBytes; MmResult mmResult = AcmInterop.acmStreamSize(streamHandle, source, out convertedBytes, AcmStreamSizeFlags.Source); MmException.Try(mmResult, "acmStreamSize"); return convertedBytes; } /// <summary> /// Returns the number of source bytes for a given number of destination bytes /// </summary> /// <param name="dest">Number of destination bytes</param> /// <returns>Number of source bytes</returns> public int DestToSource(int dest) { if (dest == 0) // zero is an invalid parameter to acmStreamSize return 0; int convertedBytes; MmException.Try( AcmInterop.acmStreamSize(streamHandle, dest, out convertedBytes, AcmStreamSizeFlags.Destination), "acmStreamSize"); return convertedBytes; } /// <summary> /// Suggests an appropriate PCM format that the compressed format can be converted /// to in one step /// </summary> /// <param name="compressedFormat">The compressed format</param> /// <returns>The PCM format</returns> public static WaveFormat SuggestPcmFormat(WaveFormat compressedFormat) { // create a PCM format var suggestedFormat = new WaveFormat(compressedFormat.SampleRate, 16, compressedFormat.Channels); MmException.Try( AcmInterop.acmFormatSuggest(IntPtr.Zero, compressedFormat, suggestedFormat, Marshal.SizeOf(suggestedFormat), AcmFormatSuggestFlags.FormatTag), "acmFormatSuggest"); /*IntPtr suggestedFormatPointer = WaveFormat.MarshalToPtr(suggestedFormat); IntPtr compressedFormatPointer = WaveFormat.MarshalToPtr(compressedFormat); MmResult result = AcmInterop.acmFormatSuggest2(IntPtr.Zero, compressedFormatPointer, suggestedFormatPointer, Marshal.SizeOf(suggestedFormat), AcmFormatSuggestFlags.FormatTag); suggestedFormat = WaveFormat.MarshalFromPtr(suggestedFormatPointer); Marshal.FreeHGlobal(suggestedFormatPointer); Marshal.FreeHGlobal(compressedFormatPointer); MmException.Try(result, "acmFormatSuggest");*/ return suggestedFormat; } /// <summary> /// Report that we have repositioned in the source stream /// </summary> public void Reposition() { streamHeader.Reposition(); } /// <summary> /// Converts the contents of the SourceBuffer into the DestinationBuffer /// </summary> /// <param name="bytesToConvert"> /// The number of bytes in the SourceBuffer /// that need to be converted /// </param> /// <param name="sourceBytesConverted">The number of source bytes actually converted</param> /// <returns>The number of converted bytes in the DestinationBuffer</returns> public int Convert(int bytesToConvert, out int sourceBytesConverted) { if (bytesToConvert%sourceFormat.BlockAlign != 0) { Debug.WriteLine(String.Format("Not a whole number of blocks: {0} ({1})", bytesToConvert, sourceFormat.BlockAlign)); bytesToConvert -= (bytesToConvert%sourceFormat.BlockAlign); } return streamHeader.Convert(bytesToConvert, out sourceBytesConverted); } /// <summary> /// Converts the contents of the SourceBuffer into the DestinationBuffer /// </summary> /// <param name="bytesToConvert"> /// The number of bytes in the SourceBuffer /// that need to be converted /// </param> /// <returns>The number of converted bytes in the DestinationBuffer</returns> public int Convert(int bytesToConvert) { int sourceBytesConverted; int destBytes = Convert(bytesToConvert, out sourceBytesConverted); if (sourceBytesConverted != bytesToConvert) { throw new MmException(MmResult.NotSupported, "AcmStreamHeader.Convert didn't convert everything"); } return destBytes; } #region IDisposable Members /// <summary> /// Frees resources associated with this ACM Stream /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Frees resources associated with this ACM Stream /// </summary> protected virtual void Dispose(bool disposing) { if (disposing) { // Free other state (managed objects). if (streamHeader != null) { streamHeader.Dispose(); streamHeader = null; } } // Free your own state (unmanaged objects). if (streamHandle != IntPtr.Zero) { MmResult result = AcmInterop.acmStreamClose(streamHandle, 0); streamHandle = IntPtr.Zero; if (result != MmResult.NoError) { throw new MmException(result, "acmStreamClose"); } } // Set large fields to null. if (driverHandle != IntPtr.Zero) { AcmInterop.acmDriverClose(driverHandle, 0); driverHandle = IntPtr.Zero; } } /// <summary> /// Frees resources associated with this ACM Stream /// </summary> ~AcmStream() { // Simply call Dispose(false). Debug.Assert(false, "AcmStream Dispose was not called"); Dispose(false); } #endregion /* Relevant only for async conversion streams public void Reset() { MmException.Try(AcmInterop.acmStreamReset(streamHandle,0),"acmStreamReset"); } */ } }
using System.Collections; using System.ComponentModel; using System.Reflection; using System.Globalization; namespace System.ComponentModel { /// <summary> /// TypeDescriptorEvaluator /// </summary> //+ copied from DataSourceHelper:DataBinder public class TypeDescriptorEvaluator { private static readonly char[] s_expressionPartSeparator = new char[] { '.' }; private static readonly char[] s_indexExpressionEndChars = new char[] { ']', ')' }; private static readonly char[] s_indexExpressionStartChars = new char[] { '[', '(' }; /// <summary> /// Gets the resolved data source. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="dataMember">The data member.</param> /// <returns></returns> public static IEnumerable GetResolvedDataSource(object dataSource, string dataMember) { if (dataSource != null) { var source = (dataSource as IListSource); if (source != null) { var list = source.GetList(); if (!source.ContainsListCollection) return list; if ((list != null) && (list is ITypedList)) { var itemProperties = ((ITypedList)list).GetItemProperties(new PropertyDescriptor[0]); if ((itemProperties == null) || (itemProperties.Count == 0)) throw new Exception("ListSource_Without_DataMembers"); var descriptor = (string.IsNullOrEmpty(dataMember) ? itemProperties[0] : itemProperties.Find(dataMember, true)); if (descriptor != null) { object component = list[0]; object obj3 = descriptor.GetValue(component); if ((obj3 != null) && (obj3 is IEnumerable)) return (IEnumerable)obj3; } throw new Exception(string.Format("ListSource_Missing_DataMemberA[{0}]", dataMember)); } } if (dataSource is IEnumerable) return (IEnumerable)dataSource; } return null; } /// <summary> /// Evals the specified container. /// </summary> /// <param name="container">The container.</param> /// <param name="expression">The expression.</param> /// <returns></returns> public static object Eval(object container, string expression) { if (expression == null) throw new ArgumentNullException("expression"); if ((expression = expression.Trim()).Length == 0) throw new ArgumentNullException("expression"); if (container == null) return null; string[] expressionParts = expression.Split(s_expressionPartSeparator); return Eval(container, expressionParts); } /// <summary> /// Evals the specified container. /// </summary> /// <param name="container">The container.</param> /// <param name="expressionParts">The expression parts.</param> /// <returns></returns> private static object Eval(object container, string[] expressionParts) { object expressionValue = container; for (int expressionPartIndex = 0; (expressionPartIndex < expressionParts.Length) && (expressionValue != null); expressionPartIndex++) { string expressionPart = expressionParts[expressionPartIndex]; expressionValue = (expressionPart.IndexOfAny(s_indexExpressionStartChars) < 0 ? GetPropertyValue(expressionValue, expressionPart) : GetIndexedPropertyValue(expressionValue, expressionPart)); } return expressionValue; } /// <summary> /// Evals the specified container. /// </summary> /// <param name="container">The container.</param> /// <param name="expression">The expression.</param> /// <param name="format">The format.</param> /// <returns></returns> public static string Eval(object container, string expression, string format) { object expressionValue = Eval(container, expression); if ((expressionValue == null) || (expressionValue == DBNull.Value)) return string.Empty; return (string.IsNullOrEmpty(format) ? expressionValue.ToString() : string.Format(format, expressionValue)); } //public static object GetDataItem(object container) //{ // bool flag; // return GetDataItem(container, out flag); //} //public static object GetDataItem(object container, out bool foundDataItem) //{ // if (container == null) // { // foundDataItem = false; // return null; // } // var container2 = (container as IDataItemContainer); // if (container2 != null) // { // foundDataItem = true; // return container2.DataItem; // } // string name = "DataItem"; // var property = container.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); // if (property == null) // { // foundDataItem = false; // return null; // } // foundDataItem = true; // return property.GetValue(container, null); //} /// <summary> /// Gets the indexed property value. /// </summary> /// <param name="container">The container.</param> /// <param name="propertyName">The expr.</param> /// <returns></returns> public static object GetIndexedPropertyValue(object container, string propertyName) { if (container == null) throw new ArgumentNullException("container"); if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName"); object obj2 = null; bool flag = false; int length = propertyName.IndexOfAny(s_indexExpressionStartChars); int num2 = propertyName.IndexOfAny(s_indexExpressionEndChars, length + 1); if (((length < 0) || (num2 < 0)) || (num2 == (length + 1))) throw new ArgumentException(string.Format("DataBinder_Invalid_Indexed_ExprA[{0}]", propertyName)); string actualPropertyName = null; object obj3 = null; string s = propertyName.Substring(length + 1, (num2 - length) - 1).Trim(); if (length != 0) actualPropertyName = propertyName.Substring(0, length); if (s.Length != 0) { if (((s[0] == '"') && (s[s.Length - 1] == '"')) || ((s[0] == '\'') && (s[s.Length - 1] == '\''))) obj3 = s.Substring(1, s.Length - 2); else if (char.IsDigit(s[0])) { int num3; flag = int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out num3); if (flag) obj3 = num3; else obj3 = s; } else obj3 = s; } if (obj3 == null) throw new ArgumentException(string.Format("DataBinder_Invalid_Indexed_ExprA[{0}]", propertyName)); object propertyValue = (!string.IsNullOrEmpty(actualPropertyName) ? GetPropertyValue(container, actualPropertyName) : container); if (propertyValue == null) return obj2; var array = (propertyValue as System.Array); if ((array != null) && (flag)) return array.GetValue((int)obj3); if ((propertyValue is IList) && (flag)) return ((IList)propertyValue)[(int)obj3]; var info = propertyValue.GetType().GetProperty("Item", BindingFlags.Public | BindingFlags.Instance, null, null, new Type[] { obj3.GetType() }, null); if (info == null) throw new ArgumentException(string.Format("DataBinder_No_Indexed_AccessorA[{0}]", propertyValue.GetType().FullName)); return info.GetValue(propertyValue, new object[] { obj3 }); } /// <summary> /// Gets the indexed property value. /// </summary> /// <param name="container">The container.</param> /// <param name="propertyName">Name of the prop.</param> /// <param name="format">The format.</param> /// <returns></returns> public static string GetIndexedPropertyValue(object container, string propertyName, string format) { object propertyValue = GetIndexedPropertyValue(container, propertyName); if ((propertyValue == null) || (propertyValue == DBNull.Value)) return string.Empty; return (string.IsNullOrEmpty(format) ? propertyValue.ToString() : string.Format(format, propertyValue)); } /// <summary> /// Gets the property value. /// </summary> /// <param name="container">The container.</param> /// <param name="propertyName">Name of the prop.</param> /// <returns></returns> public static object GetPropertyValue(object container, string propertyName) { if (container == null) throw new ArgumentNullException("container"); if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName"); var descriptor = TypeDescriptor.GetProperties(container).Find(propertyName, true); if (descriptor == null) throw new Exception(string.Format("DataBinder_Prop_Not_FoundAB[{0},{1}]", container.GetType().FullName, propertyName)); return descriptor.GetValue(container); } /// <summary> /// Gets the property value. /// </summary> /// <param name="container">The container.</param> /// <param name="propertyName">Name of the prop.</param> /// <param name="format">The format.</param> /// <returns></returns> public static string GetPropertyValue(object container, string propertyName, string format) { object propertyValue = GetPropertyValue(container, propertyName); if ((propertyValue == null) || (propertyValue == DBNull.Value)) return string.Empty; return (string.IsNullOrEmpty(format) ? propertyValue.ToString() : string.Format(format, propertyValue)); } private static bool IsNull(object value) { return (!((value != null) && (!Convert.IsDBNull(value)))); } } }
//Copyright (c) 2007-2010, Adolfo Marinucci //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 Adolfo Marinucci nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. //IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, //EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; using System.Xml; using System.Windows.Forms.Integration; using System.Diagnostics; using System.Windows.Threading; using System.Threading; using System.Reflection; using System.Net.Cache; namespace AvalonDock { public abstract class ManagedContent : ContentControl, INotifyPropertyChanged { static ManagedContent() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(typeof(ManagedContent))); WidthProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(double.NaN, null, new CoerceValueCallback( (s, v) => { if (!DesignerProperties.GetIsInDesignMode(s as DependencyObject)) return double.NaN; return v; }))); HeightProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(double.NaN, null, new CoerceValueCallback( (s, v) => { if (!DesignerProperties.GetIsInDesignMode(s as DependencyObject)) return double.NaN; return v; }))); FocusableProperty.OverrideMetadata(typeof(ManagedContent), new FrameworkPropertyMetadata(true)); } public ManagedContent() { this.Loaded += new RoutedEventHandler(ManagedContent_Loaded); this.Unloaded += new RoutedEventHandler(ManagedContent_Unloaded); } //WindowsFormsHost GetWinFormsHost() //{ // WindowsFormsHost contentHost = null; // if (this.Content is UserControl) // { // UserControl usTemp = this.Content as UserControl; // if (usTemp.Content is WindowsFormsHost) // contentHost = usTemp.Content as WindowsFormsHost; // } // else if (this.Content is WindowsFormsHost) // { // contentHost = this.Content as WindowsFormsHost; // } // return contentHost; //} //void ManagedContent_SizeChanged(object sender, SizeChangedEventArgs e) //{ //WindowsFormsHost contentHost = GetWinFormsHost(); //if (contentHost != null) //{ // object childCtrl = contentHost.GetType().GetProperty("Child").GetValue(contentHost, null); // if (childCtrl != null) // { // this.Dispatcher.Invoke(new Action<object>((o) => o.CallMethod("Refresh", null)), DispatcherPriority.Render, childCtrl); // } //} //} protected virtual void OnContentLoaded() { RaisePropertyChanged("ContainerPane"); } protected virtual void OnContentUnloaded() { RaisePropertyChanged("ContainerPane"); } void ManagedContent_Loaded(object sender, RoutedEventArgs e) { OnContentLoaded(); //WindowsFormsHost contentHost = GetWinFormsHost(); //if (contentHost != null) //{ // contentHost.SizeChanged += new SizeChangedEventHandler(ManagedContent_SizeChanged); //} } void ManagedContent_Unloaded(object sender, RoutedEventArgs e) { OnContentUnloaded(); //WindowsFormsHost contentHost = GetWinFormsHost(); //if (contentHost != null) //{ // contentHost.SizeChanged -= new SizeChangedEventHandler(ManagedContent_SizeChanged); //} } #region Title /// <summary> /// Gets or set the title of the content /// </summary> public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } // Using a DependencyProperty as the backing store for Title. This enables animation, styling, binding, etc... public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ManagedContent)); #endregion #region Icon /// <summary> /// Access to <see cref="IconProperty"/> dependency property /// </summary> public ImageSource Icon { get { return (ImageSource)GetValue(IconProperty); } set { SetValue(IconProperty, value); } } /// <summary> /// Select an icon object for the content /// </summary> public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(ManagedContent), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerce_Icon))); private static object OnCoerce_Icon(DependencyObject o, object value) { //if (value is string) //{ // Uri iconUri; // //// try to resolve given value as an absolute URI // if (Uri.TryCreate(value as String, UriKind.Relative, out iconUri)) // { // ImageSource img = new BitmapImage(iconUri); // if (img != null) // return img;//new Image() { Source = img }; // //GreyableImage seems to be not compatible with .net 4 // //if (null != img) // //{ // // GreyableImage icon = (o as ManagedContent).Icon as GreyableImage; // // if (null == icon) // // icon = new GreyableImage(); // // icon.Source = img; // // //icon.Stretch = Stretch.None; // // //icon.SnapsToDevicePixels = true; // // return icon; // //} // } //} return value; } #endregion #region DefaultElement /// <summary> /// Access to <see cref="DefaultFocusedElementProperty"/> /// </summary> public IInputElement DefaultElement { get { return (IInputElement)GetValue(DefaultFocusedElementProperty); } set { SetValue(DefaultFocusedElementProperty, value); } } /// <summary> /// Gets or sets an element which is focused by default when content is activated /// </summary> public static readonly DependencyProperty DefaultFocusedElementProperty = DependencyProperty.Register("DefaultElement", typeof(IInputElement), typeof(ManagedContent)); #endregion FrameworkElement _dragEnabledArea; /// <summary> /// Gets the draggable area of the document /// </summary> protected FrameworkElement DragEnabledArea { get { return _dragEnabledArea; } } public override void OnApplyTemplate() { base.OnApplyTemplate(); _dragEnabledArea = GetTemplateChild("PART_DragArea") as FrameworkElement; if (_dragEnabledArea != null) { _dragEnabledArea.MouseDown += new MouseButtonEventHandler(OnDragMouseDown); _dragEnabledArea.MouseMove += new MouseEventHandler(OnDragMouseMove); _dragEnabledArea.MouseUp += new MouseButtonEventHandler(OnDragMouseUp); _dragEnabledArea.MouseLeave += new MouseEventHandler(OnDragMouseLeave); } if (_dragEnabledArea != null) _dragEnabledArea.InputBindings.Add(new InputBinding(ManagedContentCommands.Close, new MouseGesture(MouseAction.MiddleClick))); if (_dragEnabledArea != null && _dragEnabledArea.ContextMenu == null) { _dragEnabledArea.MouseRightButtonDown += (s, e) => { if (!e.Handled) { Activate(); if (_dragEnabledArea.ContextMenu == null) { Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(delegate { ContainerPane.OpenOptionsMenu(null); })); } e.Handled = true; } }; } } #region Mouse management protected virtual void OnDragStart(Point ptMouse, Point ptrelativeMouse) { } Point ptStartDrag; bool isMouseDown = false; protected Point StartDragPoint { get { return ptStartDrag; } } protected bool IsMouseDown { get { return isMouseDown; } } protected void ResetIsMouseDownFlag() { isMouseDown = false; } protected virtual void OnDragMouseDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("OnDragMouseDown" + e.ClickCount); if (!e.Handled && Manager != null)// && State != DockableContentState.AutoHide) { isMouseDown = true; ptStartDrag = e.GetPosition((IInputElement)System.Windows.Media.VisualTreeHelper.GetParent(this)); } } protected virtual void OnDragMouseMove(object sender, MouseEventArgs e) { } protected virtual void OnDragMouseUp(object sender, MouseButtonEventArgs e) { isMouseDown = false; Debug.WriteLine("OnDragMouseUp" + e.ClickCount); } Point ptRelativePosition; protected virtual void OnDragMouseLeave(object sender, MouseEventArgs e) { if (!e.Handled && isMouseDown && e.LeftButton == MouseButtonState.Pressed && Manager != null) { if (!IsMouseCaptured) { Point ptMouseMove = e.GetPosition((IInputElement)System.Windows.Media.VisualTreeHelper.GetParent(this)); ManagedContent contentToSwap = null; if (ContainerPane != null) { foreach (ManagedContent content in ContainerPane.Items) { if (content == this) continue; HitTestResult res = VisualTreeHelper.HitTest(content, e.GetPosition(content)); if (res != null) { contentToSwap = content; break; } } } if (contentToSwap != null && contentToSwap != this) { Pane containerPane = ContainerPane; int myIndex = containerPane.Items.IndexOf(this); ContainerPane.Items.RemoveAt(myIndex); int otherIndex = containerPane.Items.IndexOf(contentToSwap); containerPane.Items.RemoveAt(otherIndex); containerPane.Items.Insert(otherIndex, this); containerPane.Items.Insert(myIndex, contentToSwap); containerPane.SelectedItem = this; e.Handled = false; //avoid ismouseDown = false call return; } else if (Math.Abs(ptMouseMove.X - StartDragPoint.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(ptMouseMove.Y - StartDragPoint.Y) > SystemParameters.MinimumVerticalDragDistance) { ptRelativePosition = e.GetPosition(DragEnabledArea); ResetIsMouseDownFlag(); OnDragStart(StartDragPoint, ptRelativePosition); e.Handled = true; } } } ResetIsMouseDownFlag(); } #endregion protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); if (!e.Handled) { Activate(); //FocusManager.SetFocusedElement(Content as DependencyObject, DefaultElement); //IInputElement focusedElement = e.Source as IInputElement; //if (focusedElement != null) Keyboard.Focus(focusedElement); } } protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Enter) { if (ContainerPane != null) ContainerPane.SelectedItem = this; } base.OnKeyDown(e); } /// <summary> /// Gets container pane currently hosting the content /// </summary> /// <remarks>Please note that this value could change as user move the content around the <see cref="DockingManager"/>.</remarks> public Pane ContainerPane { get { Pane containerPane = Parent as Pane; if (containerPane != null) return containerPane; return this.FindVisualAncestor<Pane>(false); } } /// <summary> /// Remove this content from its parent container pane /// </summary> /// <returns></returns> internal virtual ManagedContent DetachFromContainerPane() { if (ContainerPane != null) { int indexOfContent = ContainerPane.Items.IndexOf(this); return ContainerPane.RemoveContent(indexOfContent) as ManagedContent; } return null; } protected override void OnVisualParentChanged(DependencyObject oldParent) { RaisePropertyChanged("ContainerPane"); base.OnVisualParentChanged(oldParent); } #region Manager private DockingManager _manager = null; /// <summary> /// Get current hosting docking manager (<see cref="DockingManager"/>) /// </summary> public DockingManager Manager { get { return _manager; } internal set { if (_manager != value) { DockingManager oldValue = _manager; _manager = value; OnManagerChanged(oldValue, value); RaisePropertyChanged("Manager"); } } } /// <summary> /// Provides derived classes an opportunity to handle changes to the Manager property. /// </summary> protected virtual void OnManagerChanged(DockingManager oldValue, DockingManager newValue) { } #endregion protected DockingManager GetParentManager(Pane containerPane) { if (containerPane == null) containerPane = ContainerPane; if (containerPane != null) return ContainerPane.GetManager(); return null; } protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnGotKeyboardFocus(e); Debug.WriteLine(string.Format("[{0}].OnGotKeyboardFocus() Source={1} NewFocus={2} OldFocus={3}", this.Name, e.Source.GetType().ToString(), e.NewFocus.GetType().ToString(), e.OldFocus == null ? "<null>" : e.OldFocus.GetType().ToString())); if (Manager != null && this.IsKeyboardFocusWithin) { Manager.ActiveContent = this; } } protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e) { Debug.WriteLine(string.Format("[{0}].OnLostKeyboardFocus() Source={1} NewFocus={2} OldFocus={3}", this.Name, e.Source.GetType().ToString(), e.NewFocus == null ? "<null>" : e.NewFocus.GetType().ToString(), e.OldFocus == null ? "<null>" : e.OldFocus.GetType().ToString())); base.OnLostKeyboardFocus(e); } #region IsActiveContent /// <summary> /// IsActiveContent Read-Only Dependency Property /// </summary> private static readonly DependencyPropertyKey IsActiveContentPropertyKey = DependencyProperty.RegisterReadOnly("IsActiveContent", typeof(bool), typeof(ManagedContent), new FrameworkPropertyMetadata((bool)false, new PropertyChangedCallback(OnIsActiveContentChanged))); public static readonly DependencyProperty IsActiveContentProperty = IsActiveContentPropertyKey.DependencyProperty; /// <summary> /// Gets the IsActiveContent property. This dependency property /// indicates the active (selected) content between all contents of the docking manager /// </summary> public bool IsActiveContent { get { return (bool)GetValue(IsActiveContentProperty); } } /// <summary> /// Provides a secure method for setting the IsActiveContent property. /// This dependency property indicates the current content is the active content between all docking manager contents /// </summary> /// <param name="value">The new value for the property.</param> internal void SetIsActiveContent(bool value) { SetValue(IsActiveContentPropertyKey, value); } /// <summary> /// Handles changes to the IsActiveContent property. /// </summary> private static void OnIsActiveContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((ManagedContent)d).OnIsActiveContentChanged(e); } DateTime _lastActivation = DateTime.MinValue; internal DateTime LastActivation { get { return _lastActivation; } } /// <summary> /// Provides derived classes an opportunity to handle changes to the IsActiveContent property. /// </summary> protected virtual void OnIsActiveContentChanged(DependencyPropertyChangedEventArgs e) { if (IsActiveContent) _lastActivation = DateTime.Now; FocusContent(); Pane parentPane = ContainerPane as Pane; if (parentPane != null) { parentPane.RefreshContainsActiveContentProperty(); if (IsActiveContent) parentPane.SelectedItem = this; } //for backward compatibility RaisePropertyChanged("IsActiveContent"); if (IsActiveContentChanged != null) IsActiveContentChanged(this, EventArgs.Empty); } /// <summary> /// Provides derived classes an opportunity to manage custom focus strategy. /// </summary> /// <remarks> /// Derived classes should not call base class if don't want AvalonDock to set focus on <see cref="DefaultElement"/> object /// </remarks> protected virtual void FocusContent() { if (IsActiveContent && !IsKeyboardFocused) { #region Focus on winforms content if (this.Content is WindowsFormsHost) { //Use reflection in order to remove WinForms assembly reference //WindowsFormsHost contentHost = this.Content as WindowsFormsHost; //object childCtrl = contentHost.GetType().GetProperty("Child").GetValue(contentHost, null); //if (childCtrl != null) //{ // if (!childCtrl.GetPropertyValue<bool>("Focused")) // { // childCtrl.CallMethod("Focus", null); // } //} //Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(delegate // { // if (IsActiveContent && !IsKeyboardFocused) // { // if (this.Content is WindowsFormsHost) // { // //Use reflection in order to remove WinForms assembly reference // WindowsFormsHost contentHost = this.Content as WindowsFormsHost; // object childCtrl = contentHost.GetType().GetProperty("Child").GetValue(contentHost, null); // if (childCtrl != null) // { // if (!childCtrl.GetPropertyValue<bool>("Focused")) // { // childCtrl.CallMethod("Focus", null); // } // } // } // } // })); } #endregion Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(delegate { if (IsActiveContent && !IsKeyboardFocused) { if (DefaultElement != null) { Debug.WriteLine("Try to set kb focus to " + DefaultElement); IInputElement kbFocused = Keyboard.Focus(DefaultElement); if (kbFocused != null) Debug.WriteLine("Focused element " + kbFocused); else Debug.WriteLine("No focused element"); } else if (Content is UIElement && Content is DependencyObject) { Debug.WriteLine("Try to set kb focus to " + this.Content.ToString()); (Content as UIElement).Focus(); IInputElement kbFocused = Keyboard.Focus(this.Content as IInputElement); if (kbFocused != null) Debug.WriteLine("Focused element " + kbFocused); else Debug.WriteLine("No focused element"); } } })); } } /// <summary> /// Event fired when the <see cref="IsActiveContent"/> property changes /// </summary> public event EventHandler IsActiveContentChanged; #endregion #region IsActiveDocument /// <summary> /// IsActiveDocument Read-Only Dependency Property /// </summary> private static readonly DependencyPropertyKey IsActiveDocumentPropertyKey = DependencyProperty.RegisterReadOnly("IsActiveDocument", typeof(bool), typeof(ManagedContent), new FrameworkPropertyMetadata((bool)false, new PropertyChangedCallback(OnIsActiveDocumentChanged))); public static readonly DependencyProperty IsActiveDocumentProperty = IsActiveDocumentPropertyKey.DependencyProperty; /// <summary> /// Gets the IsActiveDocument property. This dependency property /// indicates is content is the active document. /// </summary> public bool IsActiveDocument { get { return (bool)GetValue(IsActiveDocumentProperty); } } /// <summary> /// Provides a secure method for setting the IsActiveDocument property. /// This dependency property indicates is content is the active document. /// </summary> /// <param name="value">The new value for the property.</param> internal void SetIsActiveDocument(bool value) { SetValue(IsActiveDocumentPropertyKey, value); } /// <summary> /// Handles changes to the IsActiveDocument property. /// </summary> private static void OnIsActiveDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((ManagedContent)d).OnIsActiveDocumentChanged(e); } /// <summary> /// Provides derived classes an opportunity to handle changes to the IsActiveDocument property. /// </summary> protected virtual void OnIsActiveDocumentChanged(DependencyPropertyChangedEventArgs e) { if ((bool)e.NewValue) { if (ContainerPane != null) ContainerPane.SelectedItem = this; } DocumentPane parentDocumentPane = ContainerPane as DocumentPane; if (parentDocumentPane != null) { parentDocumentPane.RefreshContainsActiveDocumentProperty(); } //Debug.WriteLine("{0}-{1}-{2}", IsFocused, IsKeyboardFocused, IsKeyboardFocusWithin); //for backward compatibility RaisePropertyChanged("IsActiveDocumentChanged"); if (IsActiveDocumentChanged != null) IsActiveDocumentChanged(this, EventArgs.Empty); } /// <summary> /// Event fired when the <see cref="IsActiveContent"/> property changes /// </summary> public event EventHandler IsActiveDocumentChanged; #endregion #region IsLocked /// <summary> /// IsLocked Dependency Property /// </summary> public static readonly DependencyProperty IsLockedProperty = DependencyProperty.Register("IsLocked", typeof(bool), typeof(ManagedContent), new FrameworkPropertyMetadata((bool)false)); /// <summary> /// Gets or sets the IsLocked property. This dependency property /// indicates if this content is locked (for <see cref="DocumentContent"/> objects this often means that it's readonly). /// </summary> public bool IsLocked { get { return (bool)GetValue(IsLockedProperty); } set { SetValue(IsLockedProperty, value); } } #endregion #region FloatingWindowSize /// <summary> /// FloatingWindowSize Dependency Property /// </summary> public static readonly DependencyProperty FloatingWindowSizeProperty = DependencyProperty.Register("FloatingWindowSize", typeof(Size), typeof(ManagedContent), new FrameworkPropertyMetadata(new Size(250,400), new PropertyChangedCallback(OnFloatingWindowSizeChanged))); /// <summary> /// Gets or sets the FloatingWindowSize property. This dependency property /// indicates the size of the floating window hosting the content when it's floating. /// </summary> public Size FloatingWindowSize { get { return (Size)GetValue(FloatingWindowSizeProperty); } set { SetValue(FloatingWindowSizeProperty, value); } } /// <summary> /// Handles changes to the FloatingWindowSize property. /// </summary> private static void OnFloatingWindowSizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((ManagedContent)d).OnFloatingWindowSizeChanged(e); } /// <summary> /// Provides derived classes an opportunity to handle changes to the FloatingWindowSize property. /// </summary> protected virtual void OnFloatingWindowSizeChanged(DependencyPropertyChangedEventArgs e) { } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region IsCloseable /// <summary> /// Get or set a value indicating if this content can be closed or hidden /// </summary> public bool IsCloseable { get { return (bool)GetValue(IsCloseableProperty); } set { SetValue(IsCloseableProperty, value); } } // Using a DependencyProperty as the backing store for IsCloseable. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsCloseableProperty = DependencyProperty.Register("IsCloseable", typeof(bool), typeof(ManagedContent), new UIPropertyMetadata(true)); internal virtual bool CanClose() { if (!IsCloseable) return false; return true; } #endregion #region Commands protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.CommandBindings.Add( new CommandBinding(ManagedContentCommands.Hide, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(ManagedContentCommands.Close, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(ManagedContentCommands.Show, this.OnExecuteCommand, this.OnCanExecuteCommand)); this.CommandBindings.Add( new CommandBinding(ManagedContentCommands.Activate, this.OnExecuteCommand, this.OnCanExecuteCommand)); } void OnExecuteCommand(object sender, ExecutedRoutedEventArgs e) { if (e.Command == ManagedContentCommands.Show) { Show(); e.Handled = true; } else if (e.Command == ManagedContentCommands.Hide) { e.Handled = Hide(); } else if (e.Command == ManagedContentCommands.Close) { e.Handled = Close(); } else if (e.Command == ManagedContentCommands.Activate) { Activate(); e.Handled = true; } //else if (e.Command == ShowOptionsCommand) //{ // OpenOptionsContextMenu(); // e.Handled = true; //} } void OnCanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = CanExecuteCommand(e.Command); //Debug.WriteLine("ManagedContent.OnCanExecuteCommand({0}) = {1} (ContinueRouting={2})", (e.Command as RoutedUICommand).Name, e.CanExecute, e.ContinueRouting); } /// <summary> /// Retrive a value indicating if the command passed can be executed based to the content state /// </summary> /// <param name="command">Command to execute</param> /// <returns>True if the command can be execute, false otherwise.</returns> protected virtual bool CanExecuteCommand(ICommand command) { if (Manager == null) return false; return true; } /// <summary> /// Shows the content /// </summary> /// <remarks>How content is shows depends from the type of the content.</remarks> public abstract void Show(); /// <summary> /// Shows the content inside a <see cref="DockingManager"/> object /// </summary> /// <remarks>How content is shows depends from the type of the content.</remarks> public abstract void Show(DockingManager manager); /// <summary> /// Event fired when the content is about to be closed /// </summary> public event EventHandler<CancelEventArgs> Closing; /// <summary> /// Event fired when the content has been closed /// </summary> /// <remarks>Note that when a document is closed property like <see cref="ManagedContent.ContainerPane"/> or <see cref="ManagedContent.Manager"/> returns null.</remarks> public event EventHandler Closed; /// <summary> /// Ovveride this method to handle <see cref="DocumentContent.OnClosing"/> event. /// </summary> protected virtual void OnClosing(CancelEventArgs e) { if (Closing != null && !e.Cancel) { Closing(this, e); } } /// <summary> /// Ovveride this method to handle <see cref="DocumentContent.OnClose"/> event. /// </summary> protected virtual void OnClosed() { if (Closed != null) Closed(this, EventArgs.Empty); } /// <summary> /// Close the content /// </summary> /// <returns>Returns true if the content was succesfully closed, false otherwise.</returns> public abstract bool Close(); /// <summary> /// Hide the content /// </summary> public abstract bool Hide(); /// <summary> /// Set the content as the active content /// </summary> /// <remarks>After this method returns property <see cref="IsActiveContent"/> returns true.</remarks> public virtual void Activate() { if (ContainerPane != null && Manager != null)// && Manager.ActiveContent != this) { ContainerPane.SelectedItem = this; FocusContent(); if (Manager != null) Manager.ActiveContent = this; } } #endregion #region Save/Restore Content Layout /// <summary> /// Save content specific layout settings /// </summary> /// <param name="storeWriter">Backend store writer</param> /// <remarks>Custom derived class can overloads this method to handle custom layout persistence.</remarks> public virtual void SaveLayout(XmlWriter storeWriter) { } /// <summary> /// Restore content specific layout settings /// </summary> /// <param name="storeReader">Saved xml element containg content layout settings</param> /// <remarks>Custom derived class must overload this method to restore custom layout settings previously saved trought <see cref="SaveLayout"/>.</remarks> public virtual void RestoreLayout(XmlElement contentElement) { } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.Contracts; namespace Microsoft.Research.CodeAnalysis { public static partial class AnalysisWrapper { /// <summary> /// This class is just for binding types for the internal clases /// </summary> public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable> where Variable : IEquatable<Variable> where Expression : IEquatable<Expression> where Type : IEquatable<Type> { internal class EnumObligations : ProofObligations<Local, Parameter, Method, Field, Property, Event, Type, Variable, Attribute, Assembly, BoxedExpression, ProofObligationBase<BoxedExpression, Variable>> { readonly private IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> methodDriver; public EnumObligations( IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver, bool noProofObligations) { Contract.Requires(mdriver != null); this.methodDriver = mdriver; if (noProofObligations) { return; } this.Run(mdriver.ValueLayer); } public override string Name { get { return "Enum"; } } public override bool Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Variable dest, ArgList args, bool data) { var mdDecoder = this.MetaDataDecoder; var formalParameters = this.MetaDataDecoder.Parameters(method); var isStaticCall = mdDecoder.IsStatic(method); Contract.Assume(isStaticCall? formalParameters.Count == args.Count : formalParameters.Count + 1 == args.Count, "sanity check, just for debugging"); for (var i = 0; i < formalParameters.Count; i++) { var formalType = mdDecoder.ParameterType(formalParameters[i]); if (mdDecoder.IsEnumWithoutFlagAttribute(formalType)) { var argIndex = isStaticCall ? i : i + 1; this.Add(new EnumIsDefinedProofObligation(EnumIsDefinedProofObligation.Kind.Parameter, pc, this.methodDriver.CurrentMethodName(), formalType, args[argIndex])); } } return data; } public override bool Starg(APC pc, Parameter argument, Variable source, bool data) { // TODO: wire it to the MetaDataDecoder return false; } public override bool Stelem(APC pc, Type arraytype, Variable array, Variable index, Variable value, bool data) { var type = this.Context.ValueContext.GetType(pc, array); if(type.IsNormal && this.MetaDataDecoder.IsEnumWithoutFlagAttribute(this.MetaDataDecoder.ElementType(type.Value))) { this.Add(new EnumIsDefinedProofObligation(EnumIsDefinedProofObligation.Kind.Assignment, pc, this.methodDriver.CurrentMethodName(), this.MetaDataDecoder.ElementType(type.Value), value)); } return data; } public override bool Stfld(APC pc, Field field, bool @volatile, Variable obj, Variable value, bool data) { var type = this.MetaDataDecoder.FieldType(field); if (this.MetaDataDecoder.IsEnumWithoutFlagAttribute(type)) { this.Add(new EnumIsDefinedProofObligation(EnumIsDefinedProofObligation.Kind.Assignment, pc, this.methodDriver.CurrentMethodName(), type, value)); } return data; } public override bool Stind(APC pc, Type type, bool @volatile, Variable ptr, Variable value, bool data) { if (this.MetaDataDecoder.IsEnumWithoutFlagAttribute(type)) { this.Add(new EnumIsDefinedProofObligation(EnumIsDefinedProofObligation.Kind.Assignment, pc, this.methodDriver.CurrentMethodName(), type, value)); } return data; } public override bool Stloc(APC pc, Local local, Variable source, bool data) { var type = this.MetaDataDecoder.LocalType(local); if (this.MetaDataDecoder.IsEnumWithoutFlagAttribute(type)) { this.Add(new EnumIsDefinedProofObligation(EnumIsDefinedProofObligation.Kind.Assignment, pc, this.methodDriver.CurrentMethodName(), type, source)); } return data; } public override bool Stsfld(APC pc, Field field, bool @volatile, Variable value, bool data) { var type = this.MetaDataDecoder.FieldType(field); if (this.MetaDataDecoder.IsEnumWithoutFlagAttribute(type)) { this.Add(new EnumIsDefinedProofObligation(EnumIsDefinedProofObligation.Kind.Assignment, pc, this.methodDriver.CurrentMethodName(), type, value)); } return data; } public override bool Return(APC pc, Variable source, bool data) { var mdDecoder = this.MetaDataDecoder; var type = mdDecoder.ReturnType(this.methodDriver.CurrentMethod); if (mdDecoder.IsEnumWithoutFlagAttribute(type)) { var pcForObligation = this.methodDriver.ContractFreeCFG.NormalExit; this.Add(new EnumIsDefinedProofObligation(EnumIsDefinedProofObligation.Kind.ReturnValue, pcForObligation, this.methodDriver.CurrentMethodName(), type, source)); } return data; } #region ProofObligation for Enum class EnumIsDefinedProofObligation : ProofObligationBase<BoxedExpression, Variable> { #region public enum Kind { Assignment, ReturnValue, Parameter} #endregion #region Messages public static readonly string[,] fixedMessages; static EnumIsDefinedProofObligation() { fixedMessages = new string[,] {{"The assigned value may not be in the range defined for this enum value", "This assignment is unreached", "Assignment to an enum value ok", "The assigned value is not one of those defined for this enum. Forgotten [Flag] in the enum definition?" }, {"The returned value may not be in the range defined for this enum value", "This return point is unreached", "Returned value is in the enum range", "The returned value is not one of those defined for this enum. Forgotten [Flag] in the enum definition?" }, {"The actual value may not be in the range defined for this enum value", "This method call is unreached", "Actual parameter is in the enum range", "The actual value is not one of those defined for this enum. Forgotten [Flag] in the enum definition?" }}; } #endregion #region Private state private readonly Type type; private readonly Variable value; private readonly Kind kind; #endregion /// <summary> /// The proof obligation roughly standing for Enum.IsDefined(type, value) /// </summary> public EnumIsDefinedProofObligation(Kind kind, APC pc, string definingMethod, Type type, Variable value) : base(pc, definingMethod, null) { this.type = type; this.value = value; this.kind = kind; } public override void EmitOutcome(ProofOutcome outcome, IOutputResults output) { var witness = GetWitness(outcome); output.EmitOutcome(witness, AddHintsForTheUser(outcome, "{0}"), fixedMessages[(int)this.kind, (int)outcome]); } public override Witness GetWitness(ProofOutcome outcome) { return new Witness(this.ID, WarningType.EnumRange, outcome, this.PC, this.AdditionalInformationOnTheWarning); } protected override void PopulateWarningContextInternal(ProofOutcome outcome) { // do nothing } public override BoxedExpression Condition { get { return null; } } protected override ProofOutcome ValidateInternal(IFactQuery<BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output) { ProofOutcome outcome; if ((outcome = query.IsVariableDefinedForType(this.PC, this.value, this.type)) != ProofOutcome.Top) { return outcome; } return ProofOutcome.Top; } public override string ObligationName { get { return "EnumIsDefinedProofObligation"; } } } #endregion } } } }