context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; namespace PythonToolsTests { [TestClass] public class WorkspaceInterpreterFactoryTests { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); } [TestMethod, Priority(0)] public void WatchWorkspaceFolderChanged() { var workspaceFolder1 = TestData.GetTempPath(); Directory.CreateDirectory(workspaceFolder1); File.WriteAllText(Path.Combine(workspaceFolder1, "app1.py"), string.Empty); var workspaceFolder2 = TestData.GetTempPath(); Directory.CreateDirectory(workspaceFolder2); File.WriteAllText(Path.Combine(workspaceFolder2, "app2.py"), string.Empty); var workspace1 = new WorkspaceTestHelper.MockWorkspace(workspaceFolder1); var workspace2 = new WorkspaceTestHelper.MockWorkspace(workspaceFolder2); var workspaceContext1 = new WorkspaceTestHelper.MockWorkspaceContext(workspace1); var workspaceContext2 = new WorkspaceTestHelper.MockWorkspaceContext(workspace2); var workspaceContextProvider = new WorkspaceTestHelper.MockWorkspaceContextProvider(workspaceContext1); using (var factoryProvider = new WorkspaceInterpreterFactoryProvider(workspaceContextProvider)) { // Load a different workspace Action triggerDiscovery = () => { workspaceContextProvider.SimulateChangeWorkspace(workspaceContext2); }; TestTriggerDiscovery(workspaceContext1, triggerDiscovery, workspaceContextProvider, true); } } [TestMethod, Priority(0)] public void WatchWorkspaceSettingsChanged() { var workspaceFolder = TestData.GetTempPath(); Directory.CreateDirectory(workspaceFolder); File.WriteAllText(Path.Combine(workspaceFolder, "app.py"), string.Empty); var workspace = new WorkspaceTestHelper.MockWorkspace(workspaceFolder); var workspaceContext = new WorkspaceTestHelper.MockWorkspaceContext(workspace); // Modify settings Action triggerDiscovery = () => { workspaceContext.SimulateChangeInterpreterSetting("Global|PythonCore|3.7"); }; TestTriggerDiscovery(workspaceContext, triggerDiscovery, null, true); } [TestMethod, Priority(0)] public void WatchWorkspaceVirtualEnvCreated() { var python = PythonPaths.Python37_x64 ?? PythonPaths.Python37; var workspaceFolder = TestData.GetTempPath(); Directory.CreateDirectory(workspaceFolder); File.WriteAllText(Path.Combine(workspaceFolder, "app.py"), string.Empty); string envFolder = Path.Combine(workspaceFolder, "env"); var workspace = new WorkspaceTestHelper.MockWorkspace(workspaceFolder); var workspaceContext = new WorkspaceTestHelper.MockWorkspaceContext(workspace); // Create virtual env inside the workspace folder (one level from root) var configs = TestTriggerDiscovery( workspaceContext, () => python.CreatePythonVirtualEnv(Path.Combine(workspaceFolder, "env")) ).ToArray(); Assert.AreEqual(1, configs.Length); Assert.IsTrue(PathUtils.IsSamePath( Path.Combine(envFolder, "scripts", "python.exe"), configs[0].InterpreterPath )); Assert.AreEqual("Workspace|Workspace|env", configs[0].Id); } [TestMethod, Priority(0)] public void DetectLocalEnvOutsideWorkspace() { var python = PythonPaths.Python37_x64 ?? PythonPaths.Python37; var tempFolder = TestData.GetTempPath(); var workspaceFolder = Path.Combine(tempFolder, "workspace"); var envFolder = Path.Combine(tempFolder, "outside"); Directory.CreateDirectory(workspaceFolder); File.WriteAllText(Path.Combine(workspaceFolder, "app.py"), string.Empty); // Create virtual env outside the workspace folder using (var p = ProcessOutput.RunHiddenAndCapture(python.InterpreterPath, "-m", "venv", envFolder)) { Console.WriteLine(p.Arguments); p.Wait(); Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines))); Assert.AreEqual(0, p.ExitCode); } // Normally a local virtual environment outside the workspace // wouldn't be detected, but it is when it's referenced from // the workspace python settings. var workspace = new WorkspaceTestHelper.MockWorkspace(workspaceFolder); var workspaceContext = new WorkspaceTestHelper.MockWorkspaceContext(workspace, @"..\outside\scripts\python.exe"); var workspaceContextProvider = new WorkspaceTestHelper.MockWorkspaceContextProvider(workspaceContext); using (var factoryProvider = new WorkspaceInterpreterFactoryProvider(workspaceContextProvider)) { workspaceContextProvider.SimulateChangeWorkspace(workspaceContext); var configs = factoryProvider.GetInterpreterConfigurations().ToArray(); Assert.AreEqual(1, configs.Length); Assert.IsTrue(PathUtils.IsSamePath( Path.Combine(envFolder, "scripts", "python.exe"), configs[0].InterpreterPath )); Assert.AreEqual("Workspace|Workspace|outside", configs[0].Id); } } [TestMethod, Priority(0)] public void WatchWorkspaceVirtualEnvRenamed() { const string ENV_NAME = "env"; var workspaceContext = CreateEnvAndGetWorkspaceService(ENV_NAME); string envPath = Path.Combine(workspaceContext.Location, ENV_NAME); string renamedEnvPath = Path.Combine(workspaceContext.Location, string.Concat(ENV_NAME, "1")); var configs = TestTriggerDiscovery(workspaceContext, () => Directory.Move(envPath, renamedEnvPath)).ToArray(); Assert.AreEqual(1, configs.Length); Assert.IsTrue(PathUtils.IsSamePath(Path.Combine(renamedEnvPath, "scripts", "python.exe"), configs[0].InterpreterPath)); Assert.AreEqual("Workspace|Workspace|env1", configs[0].Id); } [TestMethod, Priority(0)] public void WatchWorkspaceVirtualEnvDeleted() { const string ENV_NAME = "env"; var workspaceContext = CreateEnvAndGetWorkspaceService(ENV_NAME); string envPath = Path.Combine(workspaceContext.Location, ENV_NAME); var configs = TestTriggerDiscovery(workspaceContext, () => Directory.Delete(envPath, true)).ToArray(); Assert.AreEqual(0, configs.Length); } private static IEnumerable<InterpreterConfiguration> TestTriggerDiscovery( IPythonWorkspaceContext workspaceContext, Action triggerDiscovery, IPythonWorkspaceContextProvider workspaceContextProvider = null, bool useDiscoveryStartedEvent = false ) { workspaceContextProvider = workspaceContextProvider ?? new WorkspaceTestHelper.MockWorkspaceContextProvider(workspaceContext); using (var provider = new WorkspaceInterpreterFactoryProvider(workspaceContextProvider)) using (var evt = new AutoResetEvent(false)) { // This initializes the provider, discovers the initial set // of factories and starts watching the filesystem. provider.GetInterpreterFactories(); if (useDiscoveryStartedEvent) { provider.DiscoveryStarted += (sender, e) => { evt.Set(); }; } else { provider.InterpreterFactoriesChanged += (sender, e) => { evt.Set(); }; } triggerDiscovery(); Assert.IsTrue(evt.WaitOne(5000), "Failed to trigger discovery."); return provider.GetInterpreterConfigurations(); } } private WorkspaceTestHelper.MockWorkspaceContext CreateEnvAndGetWorkspaceService(string envName) { var python = PythonPaths.Python37_x64 ?? PythonPaths.Python37; var workspacePath = TestData.GetTempPath(); Directory.CreateDirectory(workspacePath); File.WriteAllText(Path.Combine(workspacePath, "app.py"), string.Empty); python.CreatePythonVirtualEnv(Path.Combine(workspacePath, envName)); return new WorkspaceTestHelper.MockWorkspaceContext(new WorkspaceTestHelper.MockWorkspace(workspacePath)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Unmanaged { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Unmanaged utility classes. /// </summary> internal static unsafe class UnmanagedUtils { /** Interop factory ID for .Net. */ private const int InteropFactoryId = 1; #region PROCEDURE NAMES private const string ProcReallocate = "IgniteReallocate"; private const string ProcIgnitionStart = "IgniteIgnitionStart"; private const string ProcIgnitionStop = "IgniteIgnitionStop"; private const string ProcIgnitionStopAll = "IgniteIgnitionStopAll"; private const string ProcProcessorReleaseStart = "IgniteProcessorReleaseStart"; private const string ProcProcessorProjection = "IgniteProcessorProjection"; private const string ProcProcessorCache = "IgniteProcessorCache"; private const string ProcProcessorGetOrCreateCache = "IgniteProcessorGetOrCreateCache"; private const string ProcProcessorCreateCache = "IgniteProcessorCreateCache"; private const string ProcProcessorAffinity = "IgniteProcessorAffinity"; private const string ProcProcessorDataStreamer = "IgniteProcessorDataStreamer"; private const string ProcProcessorTransactions = "IgniteProcessorTransactions"; private const string ProcProcessorCompute = "IgniteProcessorCompute"; private const string ProcProcessorMessage = "IgniteProcessorMessage"; private const string ProcProcessorEvents = "IgniteProcessorEvents"; private const string ProcProcessorServices = "IgniteProcessorServices"; private const string ProcProcessorExtensions = "IgniteProcessorExtensions"; private const string ProcProcessorAtomicLong = "IgniteProcessorAtomicLong"; private const string ProcTargetInStreamOutLong = "IgniteTargetInStreamOutLong"; private const string ProcTargetInStreamOutStream = "IgniteTargetInStreamOutStream"; private const string ProcTargetInStreamOutObject = "IgniteTargetInStreamOutObject"; private const string ProcTargetInObjectStreamOutStream = "IgniteTargetInObjectStreamOutStream"; private const string ProcTargetOutLong = "IgniteTargetOutLong"; private const string ProcTargetOutStream = "IgniteTargetOutStream"; private const string ProcTargetOutObject = "IgniteTargetOutObject"; private const string ProcTargetListenFut = "IgniteTargetListenFuture"; private const string ProcTargetListenFutForOp = "IgniteTargetListenFutureForOperation"; private const string ProcAffinityParts = "IgniteAffinityPartitions"; private const string ProcCacheWithSkipStore = "IgniteCacheWithSkipStore"; private const string ProcCacheWithNoRetries = "IgniteCacheWithNoRetries"; private const string ProcCacheWithExpiryPolicy = "IgniteCacheWithExpiryPolicy"; private const string ProcCacheWithAsync = "IgniteCacheWithAsync"; private const string ProcCacheWithKeepBinary = "IgniteCacheWithKeepPortable"; private const string ProcCacheClear = "IgniteCacheClear"; private const string ProcCacheRemoveAll = "IgniteCacheRemoveAll"; private const string ProcCacheOutOpQueryCursor = "IgniteCacheOutOpQueryCursor"; private const string ProcCacheOutOpContinuousQuery = "IgniteCacheOutOpContinuousQuery"; private const string ProcCacheIterator = "IgniteCacheIterator"; private const string ProcCacheLocalIterator = "IgniteCacheLocalIterator"; private const string ProcCacheEnterLock = "IgniteCacheEnterLock"; private const string ProcCacheExitLock = "IgniteCacheExitLock"; private const string ProcCacheTryEnterLock = "IgniteCacheTryEnterLock"; private const string ProcCacheCloseLock = "IgniteCacheCloseLock"; private const string ProcCacheRebalance = "IgniteCacheRebalance"; private const string ProcCacheSize = "IgniteCacheSize"; private const string ProcCacheStoreCallbackInvoke = "IgniteCacheStoreCallbackInvoke"; private const string ProcComputeWithNoFailover = "IgniteComputeWithNoFailover"; private const string ProcComputeWithTimeout = "IgniteComputeWithTimeout"; private const string ProcComputeExecuteNative = "IgniteComputeExecuteNative"; private const string ProcContinuousQryClose = "IgniteContinuousQueryClose"; private const string ProcContinuousQryGetInitialQueryCursor = "IgniteContinuousQueryGetInitialQueryCursor"; private const string ProcDataStreamerListenTop = "IgniteDataStreamerListenTopology"; private const string ProcDataStreamerAllowOverwriteGet = "IgniteDataStreamerAllowOverwriteGet"; private const string ProcDataStreamerAllowOverwriteSet = "IgniteDataStreamerAllowOverwriteSet"; private const string ProcDataStreamerSkipStoreGet = "IgniteDataStreamerSkipStoreGet"; private const string ProcDataStreamerSkipStoreSet = "IgniteDataStreamerSkipStoreSet"; private const string ProcDataStreamerPerNodeBufferSizeGet = "IgniteDataStreamerPerNodeBufferSizeGet"; private const string ProcDataStreamerPerNodeBufferSizeSet = "IgniteDataStreamerPerNodeBufferSizeSet"; private const string ProcDataStreamerPerNodeParallelOpsGet = "IgniteDataStreamerPerNodeParallelOperationsGet"; private const string ProcDataStreamerPerNodeParallelOpsSet = "IgniteDataStreamerPerNodeParallelOperationsSet"; private const string ProcMessagingWithAsync = "IgniteMessagingWithAsync"; private const string ProcQryCursorIterator = "IgniteQueryCursorIterator"; private const string ProcQryCursorClose = "IgniteQueryCursorClose"; private const string ProcProjectionForOthers = "IgniteProjectionForOthers"; private const string ProcProjectionForRemotes = "IgniteProjectionForRemotes"; private const string ProcProjectionForDaemons = "IgniteProjectionForDaemons"; private const string ProcProjectionForRandom = "IgniteProjectionForRandom"; private const string ProcProjectionForOldest = "IgniteProjectionForOldest"; private const string ProcProjectionForYoungest = "IgniteProjectionForYoungest"; private const string ProcProjectionResetMetrics = "IgniteProjectionResetMetrics"; private const string ProcProjectionOutOpRet = "IgniteProjectionOutOpRet"; private const string ProcAcquire = "IgniteAcquire"; private const string ProcRelease = "IgniteRelease"; private const string ProcTxStart = "IgniteTransactionsStart"; private const string ProcTxCommit = "IgniteTransactionsCommit"; private const string ProcTxCommitAsync = "IgniteTransactionsCommitAsync"; private const string ProcTxRollback = "IgniteTransactionsRollback"; private const string ProcTxRollbackAsync = "IgniteTransactionsRollbackAsync"; private const string ProcTxClose = "IgniteTransactionsClose"; private const string ProcTxState = "IgniteTransactionsState"; private const string ProcTxSetRollbackOnly = "IgniteTransactionsSetRollbackOnly"; private const string ProcTxResetMetrics = "IgniteTransactionsResetMetrics"; private const string ProcThrowToJava = "IgniteThrowToJava"; private const string ProcDestroyJvm = "IgniteDestroyJvm"; private const string ProcHandlersSize = "IgniteHandlersSize"; private const string ProcCreateContext = "IgniteCreateContext"; private const string ProcEventsWithAsync = "IgniteEventsWithAsync"; private const string ProcEventsStopLocalListen = "IgniteEventsStopLocalListen"; private const string ProcEventsLocalListen = "IgniteEventsLocalListen"; private const string ProcEventsIsEnabled = "IgniteEventsIsEnabled"; private const string ProcDeleteContext = "IgniteDeleteContext"; private const string ProcServicesWithAsync = "IgniteServicesWithAsync"; private const string ProcServicesWithServerKeepBinary = "IgniteServicesWithServerKeepPortable"; private const string ProcServicesCancel = "IgniteServicesCancel"; private const string ProcServicesCancelAll = "IgniteServicesCancelAll"; private const string ProcServicesGetServiceProxy = "IgniteServicesGetServiceProxy"; private const string ProcAtomicLongGet = "IgniteAtomicLongGet"; private const string ProcAtomicLongIncrementAndGet = "IgniteAtomicLongIncrementAndGet"; private const string ProcAtomicLongAddAndGet = "IgniteAtomicLongAddAndGet"; private const string ProcAtomicLongDecrementAndGet = "IgniteAtomicLongDecrementAndGet"; private const string ProcAtomicLongGetAndSet = "IgniteAtomicLongGetAndSet"; private const string ProcAtomicLongCompareAndSetAndGet = "IgniteAtomicLongCompareAndSetAndGet"; private const string ProcAtomicLongIsClosed = "IgniteAtomicLongIsClosed"; private const string ProcAtomicLongClose = "IgniteAtomicLongClose"; #endregion #region DELEGATE DEFINITIONS private delegate int ReallocateDelegate(long memPtr, int cap); private delegate void* IgnitionStartDelegate(void* ctx, sbyte* cfgPath, sbyte* gridName, int factoryId, long dataPtr); private delegate bool IgnitionStopDelegate(void* ctx, sbyte* gridName, bool cancel); private delegate void IgnitionStopAllDelegate(void* ctx, bool cancel); private delegate void ProcessorReleaseStartDelegate(void* ctx, void* obj); private delegate void* ProcessorProjectionDelegate(void* ctx, void* obj); private delegate void* ProcessorCacheDelegate(void* ctx, void* obj, sbyte* name); private delegate void* ProcessorCreateCacheDelegate(void* ctx, void* obj, sbyte* name); private delegate void* ProcessorGetOrCreateCacheDelegate(void* ctx, void* obj, sbyte* name); private delegate void* ProcessorAffinityDelegate(void* ctx, void* obj, sbyte* name); private delegate void* ProcessorDataStreamerDelegate(void* ctx, void* obj, sbyte* name, bool keepBinary); private delegate void* ProcessorTransactionsDelegate(void* ctx, void* obj); private delegate void* ProcessorComputeDelegate(void* ctx, void* obj, void* prj); private delegate void* ProcessorMessageDelegate(void* ctx, void* obj, void* prj); private delegate void* ProcessorEventsDelegate(void* ctx, void* obj, void* prj); private delegate void* ProcessorServicesDelegate(void* ctx, void* obj, void* prj); private delegate void* ProcessorExtensionsDelegate(void* ctx, void* obj); private delegate void* ProcessorAtomicLongDelegate(void* ctx, void* obj, sbyte* name, long initVal, bool create); private delegate long TargetInStreamOutLongDelegate(void* ctx, void* target, int opType, long memPtr); private delegate void TargetInStreamOutStreamDelegate(void* ctx, void* target, int opType, long inMemPtr, long outMemPtr); private delegate void* TargetInStreamOutObjectDelegate(void* ctx, void* target, int opType, long memPtr); private delegate void TargetInObjectStreamOutStreamDelegate(void* ctx, void* target, int opType, void* arg, long inMemPtr, long outMemPtr); private delegate long TargetOutLongDelegate(void* ctx, void* target, int opType); private delegate void TargetOutStreamDelegate(void* ctx, void* target, int opType, long memPtr); private delegate void* TargetOutObjectDelegate(void* ctx, void* target, int opType); private delegate void TargetListenFutureDelegate(void* ctx, void* target, long futId, int typ); private delegate void TargetListenFutureForOpDelegate(void* ctx, void* target, long futId, int typ, int opId); private delegate int AffinityPartitionsDelegate(void* ctx, void* target); private delegate void* CacheWithSkipStoreDelegate(void* ctx, void* obj); private delegate void* CacheNoRetriesDelegate(void* ctx, void* obj); private delegate void* CacheWithExpiryPolicyDelegate(void* ctx, void* obj, long create, long update, long access); private delegate void* CacheWithAsyncDelegate(void* ctx, void* obj); private delegate void* CacheWithKeepBinaryDelegate(void* ctx, void* obj); private delegate void CacheClearDelegate(void* ctx, void* obj); private delegate void CacheRemoveAllDelegate(void* ctx, void* obj); private delegate void* CacheOutOpQueryCursorDelegate(void* ctx, void* obj, int type, long memPtr); private delegate void* CacheOutOpContinuousQueryDelegate(void* ctx, void* obj, int type, long memPtr); private delegate void* CacheIteratorDelegate(void* ctx, void* obj); private delegate void* CacheLocalIteratorDelegate(void* ctx, void* obj, int peekModes); private delegate void CacheEnterLockDelegate(void* ctx, void* obj, long id); private delegate void CacheExitLockDelegate(void* ctx, void* obj, long id); private delegate bool CacheTryEnterLockDelegate(void* ctx, void* obj, long id, long timeout); private delegate void CacheCloseLockDelegate(void* ctx, void* obj, long id); private delegate void CacheRebalanceDelegate(void* ctx, void* obj, long futId); private delegate int CacheSizeDelegate(void* ctx, void* obj, int peekModes, bool loc); private delegate void CacheStoreCallbackInvokeDelegate(void* ctx, void* obj, long memPtr); private delegate void ComputeWithNoFailoverDelegate(void* ctx, void* target); private delegate void ComputeWithTimeoutDelegate(void* ctx, void* target, long timeout); private delegate void ComputeExecuteNativeDelegate(void* ctx, void* target, long taskPtr, long topVer); private delegate void ContinuousQueryCloseDelegate(void* ctx, void* target); private delegate void* ContinuousQueryGetInitialQueryCursorDelegate(void* ctx, void* target); private delegate void DataStreamerListenTopologyDelegate(void* ctx, void* obj, long ptr); private delegate bool DataStreamerAllowOverwriteGetDelegate(void* ctx, void* obj); private delegate void DataStreamerAllowOverwriteSetDelegate(void* ctx, void* obj, bool val); private delegate bool DataStreamerSkipStoreGetDelegate(void* ctx, void* obj); private delegate void DataStreamerSkipStoreSetDelegate(void* ctx, void* obj, bool val); private delegate int DataStreamerPerNodeBufferSizeGetDelegate(void* ctx, void* obj); private delegate void DataStreamerPerNodeBufferSizeSetDelegate(void* ctx, void* obj, int val); private delegate int DataStreamerPerNodeParallelOperationsGetDelegate(void* ctx, void* obj); private delegate void DataStreamerPerNodeParallelOperationsSetDelegate(void* ctx, void* obj, int val); private delegate void* MessagingWithAsyncDelegate(void* ctx, void* target); private delegate void* ProjectionForOthersDelegate(void* ctx, void* obj, void* prj); private delegate void* ProjectionForRemotesDelegate(void* ctx, void* obj); private delegate void* ProjectionForDaemonsDelegate(void* ctx, void* obj); private delegate void* ProjectionForRandomDelegate(void* ctx, void* obj); private delegate void* ProjectionForOldestDelegate(void* ctx, void* obj); private delegate void* ProjectionForYoungestDelegate(void* ctx, void* obj); private delegate void ProjectionResetMetricsDelegate(void* ctx, void* obj); private delegate void* ProjectionOutOpRetDelegate(void* ctx, void* obj, int type, long memPtr); private delegate void QueryCursorIteratorDelegate(void* ctx, void* target); private delegate void QueryCursorCloseDelegate(void* ctx, void* target); private delegate void* AcquireDelegate(void* ctx, void* target); private delegate void ReleaseDelegate(void* target); private delegate long TransactionsStartDelegate(void* ctx, void* target, int concurrency, int isolation, long timeout, int txSize); private delegate int TransactionsCommitDelegate(void* ctx, void* target, long id); private delegate void TransactionsCommitAsyncDelegate(void* ctx, void* target, long id, long futId); private delegate int TransactionsRollbackDelegate(void* ctx, void* target, long id); private delegate void TransactionsRollbackAsyncDelegate(void* ctx, void* target, long id, long futId); private delegate int TransactionsCloseDelegate(void* ctx, void* target, long id); private delegate int TransactionsStateDelegate(void* ctx, void* target, long id); private delegate bool TransactionsSetRollbackOnlyDelegate(void* ctx, void* target, long id); private delegate void TransactionsResetMetricsDelegate(void* ctx, void* target); private delegate void ThrowToJavaDelegate(void* ctx, char* msg); private delegate void DestroyJvmDelegate(void* ctx); private delegate int HandlersSizeDelegate(); private delegate void* CreateContextDelegate(void* opts, int optsLen, void* cbs); private delegate void* EventsWithAsyncDelegate(void* ctx, void* obj); private delegate bool EventsStopLocalListenDelegate(void* ctx, void* obj, long hnd); private delegate void EventsLocalListenDelegate(void* ctx, void* obj, long hnd, int type); private delegate bool EventsIsEnabledDelegate(void* ctx, void* obj, int type); private delegate void DeleteContextDelegate(void* ptr); private delegate void* ServicesWithAsyncDelegate(void* ctx, void* target); private delegate void* ServicesWithServerKeepBinaryDelegate(void* ctx, void* target); private delegate long ServicesCancelDelegate(void* ctx, void* target, char* name); private delegate long ServicesCancelAllDelegate(void* ctx, void* target); private delegate void* ServicesGetServiceProxyDelegate(void* ctx, void* target, char* name, bool sticky); private delegate long AtomicLongGetDelegate(void* ctx, void* target); private delegate long AtomicLongIncrementAndGetDelegate(void* ctx, void* target); private delegate long AtomicLongAddAndGetDelegate(void* ctx, void* target, long value); private delegate long AtomicLongDecrementAndGetDelegate(void* ctx, void* target); private delegate long AtomicLongGetAndSetDelegate(void* ctx, void* target, long value); private delegate long AtomicLongCompareAndSetAndGetDelegate(void* ctx, void* target, long expVal, long newVal); private delegate bool AtomicLongIsClosedDelegate(void* ctx, void* target); private delegate void AtomicLongCloseDelegate(void* ctx, void* target); #endregion #region DELEGATE MEMBERS // ReSharper disable InconsistentNaming private static readonly ReallocateDelegate REALLOCATE; private static readonly IgnitionStartDelegate IGNITION_START; private static readonly IgnitionStopDelegate IGNITION_STOP; private static readonly IgnitionStopAllDelegate IGNITION_STOP_ALL; private static readonly ProcessorReleaseStartDelegate PROCESSOR_RELEASE_START; private static readonly ProcessorProjectionDelegate PROCESSOR_PROJECTION; private static readonly ProcessorCacheDelegate PROCESSOR_CACHE; private static readonly ProcessorCreateCacheDelegate PROCESSOR_CREATE_CACHE; private static readonly ProcessorGetOrCreateCacheDelegate PROCESSOR_GET_OR_CREATE_CACHE; private static readonly ProcessorAffinityDelegate PROCESSOR_AFFINITY; private static readonly ProcessorDataStreamerDelegate PROCESSOR_DATA_STREAMER; private static readonly ProcessorTransactionsDelegate PROCESSOR_TRANSACTIONS; private static readonly ProcessorComputeDelegate PROCESSOR_COMPUTE; private static readonly ProcessorMessageDelegate PROCESSOR_MESSAGE; private static readonly ProcessorEventsDelegate PROCESSOR_EVENTS; private static readonly ProcessorServicesDelegate PROCESSOR_SERVICES; private static readonly ProcessorExtensionsDelegate PROCESSOR_EXTENSIONS; private static readonly ProcessorAtomicLongDelegate PROCESSOR_ATOMIC_LONG; private static readonly TargetInStreamOutLongDelegate TARGET_IN_STREAM_OUT_LONG; private static readonly TargetInStreamOutStreamDelegate TARGET_IN_STREAM_OUT_STREAM; private static readonly TargetInStreamOutObjectDelegate TARGET_IN_STREAM_OUT_OBJECT; private static readonly TargetInObjectStreamOutStreamDelegate TARGET_IN_OBJECT_STREAM_OUT_STREAM; private static readonly TargetOutLongDelegate TARGET_OUT_LONG; private static readonly TargetOutStreamDelegate TARGET_OUT_STREAM; private static readonly TargetOutObjectDelegate TARGET_OUT_OBJECT; private static readonly TargetListenFutureDelegate TargetListenFut; private static readonly TargetListenFutureForOpDelegate TargetListenFutForOp; private static readonly AffinityPartitionsDelegate AffinityParts; private static readonly CacheWithSkipStoreDelegate CACHE_WITH_SKIP_STORE; private static readonly CacheNoRetriesDelegate CACHE_WITH_NO_RETRIES; private static readonly CacheWithExpiryPolicyDelegate CACHE_WITH_EXPIRY_POLICY; private static readonly CacheWithAsyncDelegate CACHE_WITH_ASYNC; private static readonly CacheWithKeepBinaryDelegate CACHE_WITH_KEEP_BINARY; private static readonly CacheClearDelegate CACHE_CLEAR; private static readonly CacheRemoveAllDelegate CACHE_REMOVE_ALL; private static readonly CacheOutOpQueryCursorDelegate CACHE_OUT_OP_QUERY_CURSOR; private static readonly CacheOutOpContinuousQueryDelegate CACHE_OUT_OP_CONTINUOUS_QUERY; private static readonly CacheIteratorDelegate CACHE_ITERATOR; private static readonly CacheLocalIteratorDelegate CACHE_LOCAL_ITERATOR; private static readonly CacheEnterLockDelegate CACHE_ENTER_LOCK; private static readonly CacheExitLockDelegate CACHE_EXIT_LOCK; private static readonly CacheTryEnterLockDelegate CACHE_TRY_ENTER_LOCK; private static readonly CacheCloseLockDelegate CACHE_CLOSE_LOCK; private static readonly CacheRebalanceDelegate CACHE_REBALANCE; private static readonly CacheSizeDelegate CACHE_SIZE; private static readonly CacheStoreCallbackInvokeDelegate CACHE_STORE_CALLBACK_INVOKE; private static readonly ComputeWithNoFailoverDelegate COMPUTE_WITH_NO_FAILOVER; private static readonly ComputeWithTimeoutDelegate COMPUTE_WITH_TIMEOUT; private static readonly ComputeExecuteNativeDelegate COMPUTE_EXECUTE_NATIVE; private static readonly ContinuousQueryCloseDelegate ContinuousQryClose; private static readonly ContinuousQueryGetInitialQueryCursorDelegate ContinuousQryGetInitialQueryCursor; private static readonly DataStreamerListenTopologyDelegate DataStreamerListenTop; private static readonly DataStreamerAllowOverwriteGetDelegate DATA_STREAMER_ALLOW_OVERWRITE_GET; private static readonly DataStreamerAllowOverwriteSetDelegate DATA_STREAMER_ALLOW_OVERWRITE_SET; private static readonly DataStreamerSkipStoreGetDelegate DATA_STREAMER_SKIP_STORE_GET; private static readonly DataStreamerSkipStoreSetDelegate DATA_STREAMER_SKIP_STORE_SET; private static readonly DataStreamerPerNodeBufferSizeGetDelegate DATA_STREAMER_PER_NODE_BUFFER_SIZE_GET; private static readonly DataStreamerPerNodeBufferSizeSetDelegate DATA_STREAMER_PER_NODE_BUFFER_SIZE_SET; private static readonly DataStreamerPerNodeParallelOperationsGetDelegate DataStreamerPerNodeParallelOpsGet; private static readonly DataStreamerPerNodeParallelOperationsSetDelegate DataStreamerPerNodeParallelOpsSet; private static readonly MessagingWithAsyncDelegate MessagingWithAsync; private static readonly ProjectionForOthersDelegate PROJECTION_FOR_OTHERS; private static readonly ProjectionForRemotesDelegate PROJECTION_FOR_REMOTES; private static readonly ProjectionForDaemonsDelegate PROJECTION_FOR_DAEMONS; private static readonly ProjectionForRandomDelegate PROJECTION_FOR_RANDOM; private static readonly ProjectionForOldestDelegate PROJECTION_FOR_OLDEST; private static readonly ProjectionForYoungestDelegate PROJECTION_FOR_YOUNGEST; private static readonly ProjectionResetMetricsDelegate PROJECTION_RESET_METRICS; private static readonly ProjectionOutOpRetDelegate PROJECTION_OUT_OP_RET; private static readonly QueryCursorIteratorDelegate QryCursorIterator; private static readonly QueryCursorCloseDelegate QryCursorClose; private static readonly AcquireDelegate ACQUIRE; private static readonly ReleaseDelegate RELEASE; private static readonly TransactionsStartDelegate TxStart; private static readonly TransactionsCommitDelegate TxCommit; private static readonly TransactionsCommitAsyncDelegate TxCommitAsync; private static readonly TransactionsRollbackDelegate TxRollback; private static readonly TransactionsRollbackAsyncDelegate TxRollbackAsync; private static readonly TransactionsCloseDelegate TxClose; private static readonly TransactionsStateDelegate TxState; private static readonly TransactionsSetRollbackOnlyDelegate TxSetRollbackOnly; private static readonly TransactionsResetMetricsDelegate TxResetMetrics; private static readonly ThrowToJavaDelegate THROW_TO_JAVA; private static readonly DestroyJvmDelegate DESTROY_JVM; private static readonly HandlersSizeDelegate HANDLERS_SIZE; private static readonly CreateContextDelegate CREATE_CONTEXT; private static readonly EventsWithAsyncDelegate EVENTS_WITH_ASYNC; private static readonly EventsStopLocalListenDelegate EVENTS_STOP_LOCAL_LISTEN; private static readonly EventsLocalListenDelegate EVENTS_LOCAL_LISTEN; private static readonly EventsIsEnabledDelegate EVENTS_IS_ENABLED; private static readonly DeleteContextDelegate DELETE_CONTEXT; private static readonly ServicesWithAsyncDelegate SERVICES_WITH_ASYNC; private static readonly ServicesWithServerKeepBinaryDelegate SERVICES_WITH_SERVER_KEEP_BINARY; private static readonly ServicesCancelDelegate SERVICES_CANCEL; private static readonly ServicesCancelAllDelegate SERVICES_CANCEL_ALL; private static readonly ServicesGetServiceProxyDelegate SERVICES_GET_SERVICE_PROXY; private static readonly AtomicLongGetDelegate ATOMIC_LONG_GET; private static readonly AtomicLongIncrementAndGetDelegate ATOMIC_LONG_INCREMENT_AND_GET; private static readonly AtomicLongAddAndGetDelegate ATOMIC_LONG_ADD_AND_GET; private static readonly AtomicLongDecrementAndGetDelegate ATOMIC_LONG_DECREMENT_AND_GET; private static readonly AtomicLongGetAndSetDelegate ATOMIC_LONG_GET_AND_SET; private static readonly AtomicLongCompareAndSetAndGetDelegate ATOMIC_LONG_COMPARE_AND_SET_AND_GET; private static readonly AtomicLongIsClosedDelegate ATOMIC_LONG_IS_CLOSED; private static readonly AtomicLongCloseDelegate ATOMIC_LONG_CLOSE; // ReSharper restore InconsistentNaming #endregion /** Library pointer. */ private static readonly IntPtr Ptr; /// <summary> /// Initializer. /// </summary> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static UnmanagedUtils() { var path = IgniteUtils.UnpackEmbeddedResource(IgniteUtils.FileIgniteJniDll); Ptr = NativeMethods.LoadLibrary(path); if (Ptr == IntPtr.Zero) throw new IgniteException("Failed to load " + IgniteUtils.FileIgniteJniDll + ": " + Marshal.GetLastWin32Error()); REALLOCATE = CreateDelegate<ReallocateDelegate>(ProcReallocate); IGNITION_START = CreateDelegate<IgnitionStartDelegate>(ProcIgnitionStart); IGNITION_STOP = CreateDelegate<IgnitionStopDelegate>(ProcIgnitionStop); IGNITION_STOP_ALL = CreateDelegate<IgnitionStopAllDelegate>(ProcIgnitionStopAll); PROCESSOR_RELEASE_START = CreateDelegate<ProcessorReleaseStartDelegate>(ProcProcessorReleaseStart); PROCESSOR_PROJECTION = CreateDelegate<ProcessorProjectionDelegate>(ProcProcessorProjection); PROCESSOR_CACHE = CreateDelegate<ProcessorCacheDelegate>(ProcProcessorCache); PROCESSOR_CREATE_CACHE = CreateDelegate<ProcessorCreateCacheDelegate>(ProcProcessorCreateCache); PROCESSOR_GET_OR_CREATE_CACHE = CreateDelegate<ProcessorGetOrCreateCacheDelegate>(ProcProcessorGetOrCreateCache); PROCESSOR_AFFINITY = CreateDelegate<ProcessorAffinityDelegate>(ProcProcessorAffinity); PROCESSOR_DATA_STREAMER = CreateDelegate<ProcessorDataStreamerDelegate>(ProcProcessorDataStreamer); PROCESSOR_TRANSACTIONS = CreateDelegate<ProcessorTransactionsDelegate>(ProcProcessorTransactions); PROCESSOR_COMPUTE = CreateDelegate<ProcessorComputeDelegate>(ProcProcessorCompute); PROCESSOR_MESSAGE = CreateDelegate<ProcessorMessageDelegate>(ProcProcessorMessage); PROCESSOR_EVENTS = CreateDelegate<ProcessorEventsDelegate>(ProcProcessorEvents); PROCESSOR_SERVICES = CreateDelegate<ProcessorServicesDelegate>(ProcProcessorServices); PROCESSOR_EXTENSIONS = CreateDelegate<ProcessorExtensionsDelegate>(ProcProcessorExtensions); PROCESSOR_ATOMIC_LONG = CreateDelegate<ProcessorAtomicLongDelegate>(ProcProcessorAtomicLong); TARGET_IN_STREAM_OUT_LONG = CreateDelegate<TargetInStreamOutLongDelegate>(ProcTargetInStreamOutLong); TARGET_IN_STREAM_OUT_STREAM = CreateDelegate<TargetInStreamOutStreamDelegate>(ProcTargetInStreamOutStream); TARGET_IN_STREAM_OUT_OBJECT = CreateDelegate<TargetInStreamOutObjectDelegate>(ProcTargetInStreamOutObject); TARGET_IN_OBJECT_STREAM_OUT_STREAM = CreateDelegate<TargetInObjectStreamOutStreamDelegate>(ProcTargetInObjectStreamOutStream); TARGET_OUT_LONG = CreateDelegate<TargetOutLongDelegate>(ProcTargetOutLong); TARGET_OUT_STREAM = CreateDelegate<TargetOutStreamDelegate>(ProcTargetOutStream); TARGET_OUT_OBJECT = CreateDelegate<TargetOutObjectDelegate>(ProcTargetOutObject); TargetListenFut = CreateDelegate<TargetListenFutureDelegate>(ProcTargetListenFut); TargetListenFutForOp = CreateDelegate<TargetListenFutureForOpDelegate>(ProcTargetListenFutForOp); AffinityParts = CreateDelegate<AffinityPartitionsDelegate>(ProcAffinityParts); CACHE_WITH_SKIP_STORE = CreateDelegate<CacheWithSkipStoreDelegate>(ProcCacheWithSkipStore); CACHE_WITH_NO_RETRIES = CreateDelegate<CacheNoRetriesDelegate>(ProcCacheWithNoRetries); CACHE_WITH_EXPIRY_POLICY = CreateDelegate<CacheWithExpiryPolicyDelegate>(ProcCacheWithExpiryPolicy); CACHE_WITH_ASYNC = CreateDelegate<CacheWithAsyncDelegate>(ProcCacheWithAsync); CACHE_WITH_KEEP_BINARY = CreateDelegate<CacheWithKeepBinaryDelegate>(ProcCacheWithKeepBinary); CACHE_CLEAR = CreateDelegate<CacheClearDelegate>(ProcCacheClear); CACHE_REMOVE_ALL = CreateDelegate<CacheRemoveAllDelegate>(ProcCacheRemoveAll); CACHE_OUT_OP_QUERY_CURSOR = CreateDelegate<CacheOutOpQueryCursorDelegate>(ProcCacheOutOpQueryCursor); CACHE_OUT_OP_CONTINUOUS_QUERY = CreateDelegate<CacheOutOpContinuousQueryDelegate>(ProcCacheOutOpContinuousQuery); CACHE_ITERATOR = CreateDelegate<CacheIteratorDelegate>(ProcCacheIterator); CACHE_LOCAL_ITERATOR = CreateDelegate<CacheLocalIteratorDelegate>(ProcCacheLocalIterator); CACHE_ENTER_LOCK = CreateDelegate<CacheEnterLockDelegate>(ProcCacheEnterLock); CACHE_EXIT_LOCK = CreateDelegate<CacheExitLockDelegate>(ProcCacheExitLock); CACHE_TRY_ENTER_LOCK = CreateDelegate<CacheTryEnterLockDelegate>(ProcCacheTryEnterLock); CACHE_CLOSE_LOCK = CreateDelegate<CacheCloseLockDelegate>(ProcCacheCloseLock); CACHE_REBALANCE = CreateDelegate<CacheRebalanceDelegate>(ProcCacheRebalance); CACHE_SIZE = CreateDelegate<CacheSizeDelegate>(ProcCacheSize); CACHE_STORE_CALLBACK_INVOKE = CreateDelegate<CacheStoreCallbackInvokeDelegate>(ProcCacheStoreCallbackInvoke); COMPUTE_WITH_NO_FAILOVER = CreateDelegate<ComputeWithNoFailoverDelegate>(ProcComputeWithNoFailover); COMPUTE_WITH_TIMEOUT = CreateDelegate<ComputeWithTimeoutDelegate>(ProcComputeWithTimeout); COMPUTE_EXECUTE_NATIVE = CreateDelegate<ComputeExecuteNativeDelegate>(ProcComputeExecuteNative); ContinuousQryClose = CreateDelegate<ContinuousQueryCloseDelegate>(ProcContinuousQryClose); ContinuousQryGetInitialQueryCursor = CreateDelegate<ContinuousQueryGetInitialQueryCursorDelegate>(ProcContinuousQryGetInitialQueryCursor); DataStreamerListenTop = CreateDelegate<DataStreamerListenTopologyDelegate>(ProcDataStreamerListenTop); DATA_STREAMER_ALLOW_OVERWRITE_GET = CreateDelegate<DataStreamerAllowOverwriteGetDelegate>(ProcDataStreamerAllowOverwriteGet); DATA_STREAMER_ALLOW_OVERWRITE_SET = CreateDelegate<DataStreamerAllowOverwriteSetDelegate>(ProcDataStreamerAllowOverwriteSet); DATA_STREAMER_SKIP_STORE_GET = CreateDelegate<DataStreamerSkipStoreGetDelegate>(ProcDataStreamerSkipStoreGet); DATA_STREAMER_SKIP_STORE_SET = CreateDelegate<DataStreamerSkipStoreSetDelegate>(ProcDataStreamerSkipStoreSet); DATA_STREAMER_PER_NODE_BUFFER_SIZE_GET = CreateDelegate<DataStreamerPerNodeBufferSizeGetDelegate>(ProcDataStreamerPerNodeBufferSizeGet); DATA_STREAMER_PER_NODE_BUFFER_SIZE_SET = CreateDelegate<DataStreamerPerNodeBufferSizeSetDelegate>(ProcDataStreamerPerNodeBufferSizeSet); DataStreamerPerNodeParallelOpsGet = CreateDelegate<DataStreamerPerNodeParallelOperationsGetDelegate>(ProcDataStreamerPerNodeParallelOpsGet); DataStreamerPerNodeParallelOpsSet = CreateDelegate<DataStreamerPerNodeParallelOperationsSetDelegate>(ProcDataStreamerPerNodeParallelOpsSet); MessagingWithAsync = CreateDelegate<MessagingWithAsyncDelegate>(ProcMessagingWithAsync); PROJECTION_FOR_OTHERS = CreateDelegate<ProjectionForOthersDelegate>(ProcProjectionForOthers); PROJECTION_FOR_REMOTES = CreateDelegate<ProjectionForRemotesDelegate>(ProcProjectionForRemotes); PROJECTION_FOR_DAEMONS = CreateDelegate<ProjectionForDaemonsDelegate>(ProcProjectionForDaemons); PROJECTION_FOR_RANDOM = CreateDelegate<ProjectionForRandomDelegate>(ProcProjectionForRandom); PROJECTION_FOR_OLDEST = CreateDelegate<ProjectionForOldestDelegate>(ProcProjectionForOldest); PROJECTION_FOR_YOUNGEST = CreateDelegate<ProjectionForYoungestDelegate>(ProcProjectionForYoungest); PROJECTION_RESET_METRICS = CreateDelegate<ProjectionResetMetricsDelegate>(ProcProjectionResetMetrics); PROJECTION_OUT_OP_RET = CreateDelegate<ProjectionOutOpRetDelegate>(ProcProjectionOutOpRet); QryCursorIterator = CreateDelegate<QueryCursorIteratorDelegate>(ProcQryCursorIterator); QryCursorClose = CreateDelegate<QueryCursorCloseDelegate>(ProcQryCursorClose); ACQUIRE = CreateDelegate<AcquireDelegate>(ProcAcquire); RELEASE = CreateDelegate<ReleaseDelegate>(ProcRelease); TxStart = CreateDelegate<TransactionsStartDelegate>(ProcTxStart); TxCommit = CreateDelegate<TransactionsCommitDelegate>(ProcTxCommit); TxCommitAsync = CreateDelegate<TransactionsCommitAsyncDelegate>(ProcTxCommitAsync); TxRollback = CreateDelegate<TransactionsRollbackDelegate>(ProcTxRollback); TxRollbackAsync = CreateDelegate<TransactionsRollbackAsyncDelegate>(ProcTxRollbackAsync); TxClose = CreateDelegate<TransactionsCloseDelegate>(ProcTxClose); TxState = CreateDelegate<TransactionsStateDelegate>(ProcTxState); TxSetRollbackOnly = CreateDelegate<TransactionsSetRollbackOnlyDelegate>(ProcTxSetRollbackOnly); TxResetMetrics = CreateDelegate<TransactionsResetMetricsDelegate>(ProcTxResetMetrics); THROW_TO_JAVA = CreateDelegate<ThrowToJavaDelegate>(ProcThrowToJava); HANDLERS_SIZE = CreateDelegate<HandlersSizeDelegate>(ProcHandlersSize); CREATE_CONTEXT = CreateDelegate<CreateContextDelegate>(ProcCreateContext); DELETE_CONTEXT = CreateDelegate<DeleteContextDelegate>(ProcDeleteContext); DESTROY_JVM = CreateDelegate<DestroyJvmDelegate>(ProcDestroyJvm); EVENTS_WITH_ASYNC = CreateDelegate<EventsWithAsyncDelegate>(ProcEventsWithAsync); EVENTS_STOP_LOCAL_LISTEN = CreateDelegate<EventsStopLocalListenDelegate>(ProcEventsStopLocalListen); EVENTS_LOCAL_LISTEN = CreateDelegate<EventsLocalListenDelegate>(ProcEventsLocalListen); EVENTS_IS_ENABLED = CreateDelegate<EventsIsEnabledDelegate>(ProcEventsIsEnabled); SERVICES_WITH_ASYNC = CreateDelegate<ServicesWithAsyncDelegate>(ProcServicesWithAsync); SERVICES_WITH_SERVER_KEEP_BINARY = CreateDelegate<ServicesWithServerKeepBinaryDelegate>(ProcServicesWithServerKeepBinary); SERVICES_CANCEL = CreateDelegate<ServicesCancelDelegate>(ProcServicesCancel); SERVICES_CANCEL_ALL = CreateDelegate<ServicesCancelAllDelegate>(ProcServicesCancelAll); SERVICES_GET_SERVICE_PROXY = CreateDelegate<ServicesGetServiceProxyDelegate>(ProcServicesGetServiceProxy); ATOMIC_LONG_GET = CreateDelegate<AtomicLongGetDelegate>(ProcAtomicLongGet); ATOMIC_LONG_INCREMENT_AND_GET = CreateDelegate<AtomicLongIncrementAndGetDelegate>(ProcAtomicLongIncrementAndGet); ATOMIC_LONG_ADD_AND_GET = CreateDelegate<AtomicLongAddAndGetDelegate>(ProcAtomicLongAddAndGet); ATOMIC_LONG_DECREMENT_AND_GET = CreateDelegate<AtomicLongDecrementAndGetDelegate>(ProcAtomicLongDecrementAndGet); ATOMIC_LONG_GET_AND_SET = CreateDelegate<AtomicLongGetAndSetDelegate>(ProcAtomicLongGetAndSet); ATOMIC_LONG_COMPARE_AND_SET_AND_GET = CreateDelegate<AtomicLongCompareAndSetAndGetDelegate>(ProcAtomicLongCompareAndSetAndGet); ATOMIC_LONG_IS_CLOSED = CreateDelegate<AtomicLongIsClosedDelegate>(ProcAtomicLongIsClosed); ATOMIC_LONG_CLOSE = CreateDelegate<AtomicLongCloseDelegate>(ProcAtomicLongClose); } #region NATIVE METHODS: PROCESSOR internal static IUnmanagedTarget IgnitionStart(UnmanagedContext ctx, string cfgPath, string gridName, bool clientMode) { using (var mem = IgniteManager.Memory.Allocate().GetStream()) { mem.WriteBool(clientMode); sbyte* cfgPath0 = IgniteUtils.StringToUtf8Unmanaged(cfgPath); sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName); try { void* res = IGNITION_START(ctx.NativeContext, cfgPath0, gridName0, InteropFactoryId, mem.SynchronizeOutput()); return new UnmanagedTarget(ctx, res); } finally { Marshal.FreeHGlobal(new IntPtr(cfgPath0)); Marshal.FreeHGlobal(new IntPtr(gridName0)); } } } internal static bool IgnitionStop(void* ctx, string gridName, bool cancel) { sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName); try { return IGNITION_STOP(ctx, gridName0, cancel); } finally { Marshal.FreeHGlobal(new IntPtr(gridName0)); } } internal static void IgnitionStopAll(void* ctx, bool cancel) { IGNITION_STOP_ALL(ctx, cancel); } internal static void ProcessorReleaseStart(IUnmanagedTarget target) { PROCESSOR_RELEASE_START(target.Context, target.Target); } internal static IUnmanagedTarget ProcessorProjection(IUnmanagedTarget target) { void* res = PROCESSOR_PROJECTION(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_CACHE(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_CREATE_CACHE(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_GET_OR_CREATE_CACHE(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorAffinity(IUnmanagedTarget target, string name) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_AFFINITY(target.Context, target.Target, name0); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorDataStreamer(IUnmanagedTarget target, string name, bool keepBinary) { sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { void* res = PROCESSOR_DATA_STREAMER(target.Context, target.Target, name0, keepBinary); return target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } internal static IUnmanagedTarget ProcessorTransactions(IUnmanagedTarget target) { void* res = PROCESSOR_TRANSACTIONS(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorCompute(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROCESSOR_COMPUTE(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorMessage(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROCESSOR_MESSAGE(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorEvents(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROCESSOR_EVENTS(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorServices(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROCESSOR_SERVICES(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorExtensions(IUnmanagedTarget target) { void* res = PROCESSOR_EXTENSIONS(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProcessorAtomicLong(IUnmanagedTarget target, string name, long initialValue, bool create) { var name0 = IgniteUtils.StringToUtf8Unmanaged(name); try { var res = PROCESSOR_ATOMIC_LONG(target.Context, target.Target, name0, initialValue, create); return res == null ? null : target.ChangeTarget(res); } finally { Marshal.FreeHGlobal(new IntPtr(name0)); } } #endregion #region NATIVE METHODS: TARGET internal static long TargetInStreamOutLong(IUnmanagedTarget target, int opType, long memPtr) { return TARGET_IN_STREAM_OUT_LONG(target.Context, target.Target, opType, memPtr); } internal static void TargetInStreamOutStream(IUnmanagedTarget target, int opType, long inMemPtr, long outMemPtr) { TARGET_IN_STREAM_OUT_STREAM(target.Context, target.Target, opType, inMemPtr, outMemPtr); } internal static IUnmanagedTarget TargetInStreamOutObject(IUnmanagedTarget target, int opType, long inMemPtr) { void* res = TARGET_IN_STREAM_OUT_OBJECT(target.Context, target.Target, opType, inMemPtr); return target.ChangeTarget(res); } internal static void TargetInObjectStreamOutStream(IUnmanagedTarget target, int opType, void* arg, long inMemPtr, long outMemPtr) { TARGET_IN_OBJECT_STREAM_OUT_STREAM(target.Context, target.Target, opType, arg, inMemPtr, outMemPtr); } internal static long TargetOutLong(IUnmanagedTarget target, int opType) { return TARGET_OUT_LONG(target.Context, target.Target, opType); } internal static void TargetOutStream(IUnmanagedTarget target, int opType, long memPtr) { TARGET_OUT_STREAM(target.Context, target.Target, opType, memPtr); } internal static IUnmanagedTarget TargetOutObject(IUnmanagedTarget target, int opType) { void* res = TARGET_OUT_OBJECT(target.Context, target.Target, opType); return target.ChangeTarget(res); } internal static void TargetListenFuture(IUnmanagedTarget target, long futId, int typ) { TargetListenFut(target.Context, target.Target, futId, typ); } internal static void TargetListenFutureForOperation(IUnmanagedTarget target, long futId, int typ, int opId) { TargetListenFutForOp(target.Context, target.Target, futId, typ, opId); } #endregion #region NATIVE METHODS: AFFINITY internal static int AffinityPartitions(IUnmanagedTarget target) { return AffinityParts(target.Context, target.Target); } #endregion #region NATIVE METHODS: CACHE internal static IUnmanagedTarget CacheWithSkipStore(IUnmanagedTarget target) { void* res = CACHE_WITH_SKIP_STORE(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheWithNoRetries(IUnmanagedTarget target) { void* res = CACHE_WITH_NO_RETRIES(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheWithExpiryPolicy(IUnmanagedTarget target, long create, long update, long access) { void* res = CACHE_WITH_EXPIRY_POLICY(target.Context, target.Target, create, update, access); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheWithAsync(IUnmanagedTarget target) { void* res = CACHE_WITH_ASYNC(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheWithKeepBinary(IUnmanagedTarget target) { void* res = CACHE_WITH_KEEP_BINARY(target.Context, target.Target); return target.ChangeTarget(res); } internal static void CacheClear(IUnmanagedTarget target) { CACHE_CLEAR(target.Context, target.Target); } internal static void CacheRemoveAll(IUnmanagedTarget target) { CACHE_REMOVE_ALL(target.Context, target.Target); } internal static IUnmanagedTarget CacheOutOpQueryCursor(IUnmanagedTarget target, int type, long memPtr) { void* res = CACHE_OUT_OP_QUERY_CURSOR(target.Context, target.Target, type, memPtr); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheOutOpContinuousQuery(IUnmanagedTarget target, int type, long memPtr) { void* res = CACHE_OUT_OP_CONTINUOUS_QUERY(target.Context, target.Target, type, memPtr); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheIterator(IUnmanagedTarget target) { void* res = CACHE_ITERATOR(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget CacheLocalIterator(IUnmanagedTarget target, int peekModes) { void* res = CACHE_LOCAL_ITERATOR(target.Context, target.Target, peekModes); return target.ChangeTarget(res); } internal static void CacheEnterLock(IUnmanagedTarget target, long id) { CACHE_ENTER_LOCK(target.Context, target.Target, id); } internal static void CacheExitLock(IUnmanagedTarget target, long id) { CACHE_EXIT_LOCK(target.Context, target.Target, id); } internal static bool CacheTryEnterLock(IUnmanagedTarget target, long id, long timeout) { return CACHE_TRY_ENTER_LOCK(target.Context, target.Target, id, timeout); } internal static void CacheCloseLock(IUnmanagedTarget target, long id) { CACHE_CLOSE_LOCK(target.Context, target.Target, id); } internal static void CacheRebalance(IUnmanagedTarget target, long futId) { CACHE_REBALANCE(target.Context, target.Target, futId); } internal static void CacheStoreCallbackInvoke(IUnmanagedTarget target, long memPtr) { CACHE_STORE_CALLBACK_INVOKE(target.Context, target.Target, memPtr); } internal static int CacheSize(IUnmanagedTarget target, int modes, bool loc) { return CACHE_SIZE(target.Context, target.Target, modes, loc); } #endregion #region NATIVE METHODS: COMPUTE internal static void ComputeWithNoFailover(IUnmanagedTarget target) { COMPUTE_WITH_NO_FAILOVER(target.Context, target.Target); } internal static void ComputeWithTimeout(IUnmanagedTarget target, long timeout) { COMPUTE_WITH_TIMEOUT(target.Context, target.Target, timeout); } internal static void ComputeExecuteNative(IUnmanagedTarget target, long taskPtr, long topVer) { COMPUTE_EXECUTE_NATIVE(target.Context, target.Target, taskPtr, topVer); } #endregion #region NATIVE METHODS: CONTINUOUS QUERY internal static void ContinuousQueryClose(IUnmanagedTarget target) { ContinuousQryClose(target.Context, target.Target); } internal static IUnmanagedTarget ContinuousQueryGetInitialQueryCursor(IUnmanagedTarget target) { void* res = ContinuousQryGetInitialQueryCursor(target.Context, target.Target); return res == null ? null : target.ChangeTarget(res); } #endregion #region NATIVE METHODS: DATA STREAMER internal static void DataStreamerListenTopology(IUnmanagedTarget target, long ptr) { DataStreamerListenTop(target.Context, target.Target, ptr); } internal static bool DataStreamerAllowOverwriteGet(IUnmanagedTarget target) { return DATA_STREAMER_ALLOW_OVERWRITE_GET(target.Context, target.Target); } internal static void DataStreamerAllowOverwriteSet(IUnmanagedTarget target, bool val) { DATA_STREAMER_ALLOW_OVERWRITE_SET(target.Context, target.Target, val); } internal static bool DataStreamerSkipStoreGet(IUnmanagedTarget target) { return DATA_STREAMER_SKIP_STORE_GET(target.Context, target.Target); } internal static void DataStreamerSkipStoreSet(IUnmanagedTarget target, bool val) { DATA_STREAMER_SKIP_STORE_SET(target.Context, target.Target, val); } internal static int DataStreamerPerNodeBufferSizeGet(IUnmanagedTarget target) { return DATA_STREAMER_PER_NODE_BUFFER_SIZE_GET(target.Context, target.Target); } internal static void DataStreamerPerNodeBufferSizeSet(IUnmanagedTarget target, int val) { DATA_STREAMER_PER_NODE_BUFFER_SIZE_SET(target.Context, target.Target, val); } internal static int DataStreamerPerNodeParallelOperationsGet(IUnmanagedTarget target) { return DataStreamerPerNodeParallelOpsGet(target.Context, target.Target); } internal static void DataStreamerPerNodeParallelOperationsSet(IUnmanagedTarget target, int val) { DataStreamerPerNodeParallelOpsSet(target.Context, target.Target, val); } #endregion #region NATIVE METHODS: MESSAGING internal static IUnmanagedTarget MessagingWithASync(IUnmanagedTarget target) { void* res = MessagingWithAsync(target.Context, target.Target); return target.ChangeTarget(res); } #endregion #region NATIVE METHODS: PROJECTION internal static IUnmanagedTarget ProjectionForOthers(IUnmanagedTarget target, IUnmanagedTarget prj) { void* res = PROJECTION_FOR_OTHERS(target.Context, target.Target, prj.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForRemotes(IUnmanagedTarget target) { void* res = PROJECTION_FOR_REMOTES(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForDaemons(IUnmanagedTarget target) { void* res = PROJECTION_FOR_DAEMONS(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForRandom(IUnmanagedTarget target) { void* res = PROJECTION_FOR_RANDOM(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForOldest(IUnmanagedTarget target) { void* res = PROJECTION_FOR_OLDEST(target.Context, target.Target); return target.ChangeTarget(res); } internal static IUnmanagedTarget ProjectionForYoungest(IUnmanagedTarget target) { void* res = PROJECTION_FOR_YOUNGEST(target.Context, target.Target); return target.ChangeTarget(res); } internal static void ProjectionResetMetrics(IUnmanagedTarget target) { PROJECTION_RESET_METRICS(target.Context, target.Target); } internal static IUnmanagedTarget ProjectionOutOpRet(IUnmanagedTarget target, int type, long memPtr) { void* res = PROJECTION_OUT_OP_RET(target.Context, target.Target, type, memPtr); return target.ChangeTarget(res); } #endregion #region NATIVE METHODS: QUERY CURSOR internal static void QueryCursorIterator(IUnmanagedTarget target) { QryCursorIterator(target.Context, target.Target); } internal static void QueryCursorClose(IUnmanagedTarget target) { QryCursorClose(target.Context, target.Target); } #endregion #region NATIVE METHODS: TRANSACTIONS internal static long TransactionsStart(IUnmanagedTarget target, int concurrency, int isolation, long timeout, int txSize) { return TxStart(target.Context, target.Target, concurrency, isolation, timeout, txSize); } internal static int TransactionsCommit(IUnmanagedTarget target, long id) { return TxCommit(target.Context, target.Target, id); } internal static void TransactionsCommitAsync(IUnmanagedTarget target, long id, long futId) { TxCommitAsync(target.Context, target.Target, id, futId); } internal static int TransactionsRollback(IUnmanagedTarget target, long id) { return TxRollback(target.Context, target.Target, id); } internal static void TransactionsRollbackAsync(IUnmanagedTarget target, long id, long futId) { TxRollbackAsync(target.Context, target.Target, id, futId); } internal static int TransactionsClose(IUnmanagedTarget target, long id) { return TxClose(target.Context, target.Target, id); } internal static int TransactionsState(IUnmanagedTarget target, long id) { return TxState(target.Context, target.Target, id); } internal static bool TransactionsSetRollbackOnly(IUnmanagedTarget target, long id) { return TxSetRollbackOnly(target.Context, target.Target, id); } internal static void TransactionsResetMetrics(IUnmanagedTarget target) { TxResetMetrics(target.Context, target.Target); } #endregion #region NATIVE METHODS: MISCELANNEOUS internal static void Reallocate(long memPtr, int cap) { int res = REALLOCATE(memPtr, cap); if (res != 0) throw new IgniteException("Failed to reallocate external memory [ptr=" + memPtr + ", capacity=" + cap + ']'); } internal static IUnmanagedTarget Acquire(UnmanagedContext ctx, void* target) { void* target0 = ACQUIRE(ctx.NativeContext, target); return new UnmanagedTarget(ctx, target0); } internal static void Release(IUnmanagedTarget target) { RELEASE(target.Target); } internal static void ThrowToJava(void* ctx, Exception e) { char* msgChars = (char*)IgniteUtils.StringToUtf8Unmanaged(e.Message); try { THROW_TO_JAVA(ctx, msgChars); } finally { Marshal.FreeHGlobal(new IntPtr(msgChars)); } } internal static int HandlersSize() { return HANDLERS_SIZE(); } internal static void* CreateContext(void* opts, int optsLen, void* cbs) { return CREATE_CONTEXT(opts, optsLen, cbs); } internal static void DeleteContext(void* ctx) { DELETE_CONTEXT(ctx); } internal static void DestroyJvm(void* ctx) { DESTROY_JVM(ctx); } #endregion #region NATIVE METHODS: EVENTS internal static IUnmanagedTarget EventsWithAsync(IUnmanagedTarget target) { return target.ChangeTarget(EVENTS_WITH_ASYNC(target.Context, target.Target)); } internal static bool EventsStopLocalListen(IUnmanagedTarget target, long handle) { return EVENTS_STOP_LOCAL_LISTEN(target.Context, target.Target, handle); } internal static bool EventsIsEnabled(IUnmanagedTarget target, int type) { return EVENTS_IS_ENABLED(target.Context, target.Target, type); } internal static void EventsLocalListen(IUnmanagedTarget target, long handle, int type) { EVENTS_LOCAL_LISTEN(target.Context, target.Target, handle, type); } #endregion #region NATIVE METHODS: SERVICES internal static IUnmanagedTarget ServicesWithAsync(IUnmanagedTarget target) { return target.ChangeTarget(SERVICES_WITH_ASYNC(target.Context, target.Target)); } internal static IUnmanagedTarget ServicesWithServerKeepBinary(IUnmanagedTarget target) { return target.ChangeTarget(SERVICES_WITH_SERVER_KEEP_BINARY(target.Context, target.Target)); } internal static void ServicesCancel(IUnmanagedTarget target, string name) { var nameChars = (char*)IgniteUtils.StringToUtf8Unmanaged(name); try { SERVICES_CANCEL(target.Context, target.Target, nameChars); } finally { Marshal.FreeHGlobal(new IntPtr(nameChars)); } } internal static void ServicesCancelAll(IUnmanagedTarget target) { SERVICES_CANCEL_ALL(target.Context, target.Target); } internal static IUnmanagedTarget ServicesGetServiceProxy(IUnmanagedTarget target, string name, bool sticky) { var nameChars = (char*)IgniteUtils.StringToUtf8Unmanaged(name); try { return target.ChangeTarget( SERVICES_GET_SERVICE_PROXY(target.Context, target.Target, nameChars, sticky)); } finally { Marshal.FreeHGlobal(new IntPtr(nameChars)); } } #endregion #region NATIVE METHODS: DATA STRUCTURES internal static long AtomicLongGet(IUnmanagedTarget target) { return ATOMIC_LONG_GET(target.Context, target.Target); } internal static long AtomicLongIncrementAndGet(IUnmanagedTarget target) { return ATOMIC_LONG_INCREMENT_AND_GET(target.Context, target.Target); } internal static long AtomicLongAddAndGet(IUnmanagedTarget target, long value) { return ATOMIC_LONG_ADD_AND_GET(target.Context, target.Target, value); } internal static long AtomicLongDecrementAndGet(IUnmanagedTarget target) { return ATOMIC_LONG_DECREMENT_AND_GET(target.Context, target.Target); } internal static long AtomicLongGetAndSet(IUnmanagedTarget target, long value) { return ATOMIC_LONG_GET_AND_SET(target.Context, target.Target, value); } internal static long AtomicLongCompareAndSetAndGet(IUnmanagedTarget target, long expVal, long newVal) { return ATOMIC_LONG_COMPARE_AND_SET_AND_GET(target.Context, target.Target, expVal, newVal); } internal static bool AtomicLongIsClosed(IUnmanagedTarget target) { return ATOMIC_LONG_IS_CLOSED(target.Context, target.Target); } internal static void AtomicLongClose(IUnmanagedTarget target) { ATOMIC_LONG_CLOSE(target.Context, target.Target); } #endregion /// <summary> /// No-op initializer used to force type loading and static constructor call. /// </summary> internal static void Initialize() { // No-op. } /// <summary> /// Create delegate for the given procedure. /// </summary> /// <typeparam name="T">Delegate type.</typeparam> /// <param name="procName">Procedure name.</param> /// <returns></returns> private static T CreateDelegate<T>(string procName) { var procPtr = NativeMethods.GetProcAddress(Ptr, procName); if (procPtr == IntPtr.Zero) { var error = Marshal.GetLastWin32Error(); throw new IgniteException(string.Format(CultureInfo.InvariantCulture, "Unable to find native function: {0} (Error code: {1}). Make sure that module.def is up to date", procName, error)); } return TypeCaster<T>.Cast(Marshal.GetDelegateForFunctionPointer(procPtr, typeof (T))); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Mime; using System.Text; using System.Text.RegularExpressions; using iTextSharp.text.pdf; using Memorandum.Core; using Memorandum.Core.Domain; using Memorandum.Web.Framework; using Memorandum.Web.Views.Drops; namespace Memorandum.Web.Utitlities { internal static class Utilities { public static List<LinkDrop> GetLinkDrops(UnitOfWork unit, Node node) { var links = unit.Links.Where(l => l.StartNode == node.NodeId.Id && l.StartNodeProvider == node.NodeId.Provider) .ToList(); var linkDrops = links.Select(link => new LinkDrop(link, unit.Nodes.FindById(link.GetEndIdentifier()))).ToList(); var dir = node as DirectoryNode; if (dir != null) { linkDrops.AddRange(dir.GetChild().Select(ch => new LinkDrop(new Link(node, ch) { Comment = ch.IsDirectory ? "Folder" : "File" }, ch))); } return linkDrops; } public static List<RenderedLinkDrop> GetRenderedLinkDrops(UnitOfWork unit, Node node) { var links = unit.Links.Where(l => l.StartNode == node.NodeId.Id && l.StartNodeProvider == node.NodeId.Provider) .ToList(); var linkDrops = links.Select(link => new RenderedLinkDrop(link, unit.Nodes.FindById(link.GetEndIdentifier()))).ToList(); var dir = node as DirectoryNode; if (dir != null) { linkDrops.AddRange(dir.GetChild().Select(ch => new RenderedLinkDrop(new Link(node, ch) { Comment = ch.IsDirectory ? "Folder" : "File" }, ch))); } return linkDrops; } public static IEnumerable<LinksGroupDrop> GetGroupedLinks(UnitOfWork unit, Node node) { var gId = 0; var linkDrops = GetLinkDrops(unit, node); if (linkDrops.Count == 0) return new List<LinksGroupDrop> {new LinksGroupDrop(gId) }; var groups = new List<LinksGroupDrop>(); var unnamedGroup = new LinksGroupDrop(gId++); groups.Add(unnamedGroup); foreach (var link in linkDrops) { if (!string.IsNullOrWhiteSpace(link.Comment)) { var sameRealtionLink = unnamedGroup.Items.FirstOrDefault( l => l.Comment != null && l.Comment.Equals(link.Comment, StringComparison.CurrentCultureIgnoreCase)); if (sameRealtionLink != null) { unnamedGroup.Items.Remove(sameRealtionLink); var group = new LinksGroupDrop(gId++, new List<LinkDrop> {link, sameRealtionLink}); groups.Add(group); continue; } var groupWithSameRelation = groups.FirstOrDefault( g => g.Name.Equals(link.Comment, StringComparison.CurrentCultureIgnoreCase)); if (groupWithSameRelation != null) { groupWithSameRelation.Items.Add(link); continue; } } unnamedGroup.Items.Add(link); } return groups; } public static void DeleteLinks(UnitOfWork unit, Node node) { var outLinks = unit.Links.Where( l => l.StartNodeProvider == node.NodeId.Provider && l.StartNode == node.NodeId.Id); var inLinks = unit.Links.Where( l => l.EndNodeProvider == node.NodeId.Provider && l.EndNode == node.NodeId.Id); foreach (var inLink in inLinks) unit.Links.Delete(inLink); foreach (var outLink in outLinks) unit.Links.Delete(outLink); } public static string GetWebPageTitle(string url) { // Create a request to the url var request = WebRequest.Create(url) as HttpWebRequest; if (request == null) return null; // Use the user's credentials request.UseDefaultCredentials = true; // Obtain a response from the server, if there was an error, return nothing HttpWebResponse response; try { response = request.GetResponse() as HttpWebResponse; } catch (WebException) { return Path.GetFileName(new Uri(url).LocalPath); } if (response == null) return Path.GetFileName(new Uri(url).LocalPath); // Regular expression for an HTML title const string regex = @"(?<=<title.*>)([\s\S]*)(?=</title>)"; // If the correct HTML header exists for HTML text, continue var headers = new List<string>(response.Headers.AllKeys); // Try to get title from text html if (response.ContentType.StartsWith("text/html")) { var encoding = Encoding.GetEncoding(response.CharacterSet); var page = encoding.GetString(FromResponseStream(response.GetResponseStream())); var ex = new Regex(regex, RegexOptions.IgnoreCase); response.Close(); return ex.Match(page).Value.Trim(); } // Try to get title from pdf meta if (response.ContentType.Contains("pdf") || Path.GetExtension(response.ResponseUri.LocalPath).Equals("pdf")) { var pdf = new PdfReader(FromResponseStream(response.GetResponseStream())); if (pdf.Info.ContainsKey("Title")) { var title = pdf.Info["Title"]; if (!string.IsNullOrWhiteSpace(title) && !title.Trim().ToLower().Equals("untitled")) return title; } } response.Close(); // Try to get title from content disposition if (headers.Contains("Content-Disposition")) { var cd = response.Headers["content-disposition"]; if (!string.IsNullOrEmpty(cd)) { var filename = new ContentDisposition(cd).FileName; if (!string.IsNullOrEmpty(filename)) return filename; } } // Get from URI finally return Path.GetFileName(response.ResponseUri.LocalPath); } public static Link CreateLinkForNode(IRequest request, Node parentNode, Node newNode) { var link = new Link(parentNode, newNode) { Comment = request.PostArgs["comment"], DateAdded = DateTime.Now, User = request.User }; request.UnitOfWork.Links.Save(link); return link; } public static Link CreateLinkForNode(IRequest request, Node parentNode, Node newNode, string comment) { var link = new Link(parentNode, newNode) { Comment = comment, DateAdded = DateTime.Now, User = request.User }; request.UnitOfWork.Links.Save(link); return link; } public static byte[] FromResponseStream(Stream stream) { var buffer = new byte[16 * 1024]; using (var ms = new MemoryStream()) { int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) ms.Write(buffer, 0, read); return ms.ToArray(); } } } }
#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.Generic; #if !PORTABLE40 using System.Collections.Specialized; #endif using System.Threading; using Newtonsoft.Json.Utilities; using System.Collections; using System.Globalization; using System.ComponentModel; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a token that can contain other tokens. /// </summary> public abstract class JContainer : JToken, IList<JToken> #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40) , ITypedList, IBindingList #elif PORTABLE , INotifyCollectionChanged #endif , IList #if !(SILVERLIGHT || NET20 || NET35 || NETFX_CORE || PORTABLE40 || PORTABLE) , INotifyCollectionChanged #endif { #if !(SILVERLIGHT || NETFX_CORE || PORTABLE40 || PORTABLE) internal ListChangedEventHandler _listChanged; internal AddingNewEventHandler _addingNew; /// <summary> /// Occurs when the list changes or an item in the list changes. /// </summary> public event ListChangedEventHandler ListChanged { add { _listChanged += value; } remove { _listChanged -= value; } } /// <summary> /// Occurs before an item is added to the collection. /// </summary> public event AddingNewEventHandler AddingNew { add { _addingNew += value; } remove { _addingNew -= value; } } #endif #if SILVERLIGHT || !(NET20 || NET35 || PORTABLE40) internal NotifyCollectionChangedEventHandler _collectionChanged; /// <summary> /// Occurs when the items list of the collection has changed, or the collection is reset. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged { add { _collectionChanged += value; } remove { _collectionChanged -= value; } } #endif /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected abstract IList<JToken> ChildrenTokens { get; } private object _syncRoot; #if !(PORTABLE40) private bool _busy; #endif internal JContainer() { } internal JContainer(JContainer other) : this() { ValidationUtils.ArgumentNotNull(other, "c"); foreach (JToken child in other) { Add(child); } } internal void CheckReentrancy() { #if !(PORTABLE40) if (_busy) throw new InvalidOperationException("Cannot change {0} during a collection change event.".FormatWith(CultureInfo.InvariantCulture, GetType())); #endif } internal virtual IList<JToken> CreateChildrenCollection() { return new List<JToken>(); } #if !(SILVERLIGHT || NETFX_CORE || PORTABLE40 || PORTABLE) /// <summary> /// Raises the <see cref="AddingNew"/> event. /// </summary> /// <param name="e">The <see cref="AddingNewEventArgs"/> instance containing the event data.</param> protected virtual void OnAddingNew(AddingNewEventArgs e) { AddingNewEventHandler handler = _addingNew; if (handler != null) handler(this, e); } /// <summary> /// Raises the <see cref="ListChanged"/> event. /// </summary> /// <param name="e">The <see cref="ListChangedEventArgs"/> instance containing the event data.</param> protected virtual void OnListChanged(ListChangedEventArgs e) { ListChangedEventHandler handler = _listChanged; if (handler != null) { _busy = true; try { handler(this, e); } finally { _busy = false; } } } #endif #if SILVERLIGHT || !(NET20 || NET35 || PORTABLE40) /// <summary> /// Raises the <see cref="CollectionChanged"/> event. /// </summary> /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param> protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { NotifyCollectionChangedEventHandler handler = _collectionChanged; if (handler != null) { _busy = true; try { handler(this, e); } finally { _busy = false; } } } #endif /// <summary> /// Gets a value indicating whether this token has childen tokens. /// </summary> /// <value> /// <c>true</c> if this token has child values; otherwise, <c>false</c>. /// </value> public override bool HasValues { get { return ChildrenTokens.Count > 0; } } internal bool ContentsEqual(JContainer container) { if (container == this) return true; IList<JToken> t1 = ChildrenTokens; IList<JToken> t2 = container.ChildrenTokens; if (t1.Count != t2.Count) return false; for (int i = 0; i < t1.Count; i++) { if (!t1[i].DeepEquals(t2[i])) return false; } return true; } /// <summary> /// Get the first child token of this token. /// </summary> /// <value> /// A <see cref="JToken"/> containing the first child token of the <see cref="JToken"/>. /// </value> public override JToken First { get { return ChildrenTokens.FirstOrDefault(); } } /// <summary> /// Get the last child token of this token. /// </summary> /// <value> /// A <see cref="JToken"/> containing the last child token of the <see cref="JToken"/>. /// </value> public override JToken Last { get { return ChildrenTokens.LastOrDefault(); } } /// <summary> /// Returns a collection of the child tokens of this token, in document order. /// </summary> /// <returns> /// An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> containing the child tokens of this <see cref="JToken"/>, in document order. /// </returns> public override JEnumerable<JToken> Children() { return new JEnumerable<JToken>(ChildrenTokens); } /// <summary> /// Returns a collection of the child values of this token, in document order. /// </summary> /// <typeparam name="T">The type to convert the values to.</typeparam> /// <returns> /// A <see cref="IEnumerable{T}"/> containing the child values of this <see cref="JToken"/>, in document order. /// </returns> public override IEnumerable<T> Values<T>() { return ChildrenTokens.Convert<JToken, T>(); } /// <summary> /// Returns a collection of the descendant tokens for this token in document order. /// </summary> /// <returns>An <see cref="IEnumerable{JToken}"/> containing the descendant tokens of the <see cref="JToken"/>.</returns> public IEnumerable<JToken> Descendants() { foreach (JToken o in ChildrenTokens) { yield return o; JContainer c = o as JContainer; if (c != null) { foreach (JToken d in c.Descendants()) { yield return d; } } } } internal bool IsMultiContent(object content) { return (content is IEnumerable && !(content is string) && !(content is JToken) && !(content is byte[])); } internal JToken EnsureParentToken(JToken item, bool skipParentCheck) { if (item == null) return new JValue((object) null); if (skipParentCheck) return item; // to avoid a token having multiple parents or creating a recursive loop, create a copy if... // the item already has a parent // the item is being added to itself // the item is being added to the root parent of itself if (item.Parent != null || item == this || (item.HasValues && Root == item)) item = item.CloneToken(); return item; } private class JTokenReferenceEqualityComparer : IEqualityComparer<JToken> { public static readonly JTokenReferenceEqualityComparer Instance = new JTokenReferenceEqualityComparer(); public bool Equals(JToken x, JToken y) { return ReferenceEquals(x, y); } public int GetHashCode(JToken obj) { if (obj == null) return 0; return obj.GetHashCode(); } } internal int IndexOfItem(JToken item) { return ChildrenTokens.IndexOf(item, JTokenReferenceEqualityComparer.Instance); } internal virtual void InsertItem(int index, JToken item, bool skipParentCheck) { if (index > ChildrenTokens.Count) throw new ArgumentOutOfRangeException("index", "Index must be within the bounds of the List."); CheckReentrancy(); item = EnsureParentToken(item, skipParentCheck); JToken previous = (index == 0) ? null : ChildrenTokens[index - 1]; // haven't inserted new token yet so next token is still at the inserting index JToken next = (index == ChildrenTokens.Count) ? null : ChildrenTokens[index]; ValidateToken(item, null); item.Parent = this; item.Previous = previous; if (previous != null) previous.Next = item; item.Next = next; if (next != null) next.Previous = item; ChildrenTokens.Insert(index, item); #if !(SILVERLIGHT || NETFX_CORE || PORTABLE40 || PORTABLE) if (_listChanged != null) OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index)); #endif #if SILVERLIGHT || !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); #endif } internal virtual void RemoveItemAt(int index) { if (index < 0) throw new ArgumentOutOfRangeException("index", "Index is less than 0."); if (index >= ChildrenTokens.Count) throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count."); CheckReentrancy(); JToken item = ChildrenTokens[index]; JToken previous = (index == 0) ? null : ChildrenTokens[index - 1]; JToken next = (index == ChildrenTokens.Count - 1) ? null : ChildrenTokens[index + 1]; if (previous != null) previous.Next = next; if (next != null) next.Previous = previous; item.Parent = null; item.Previous = null; item.Next = null; ChildrenTokens.RemoveAt(index); #if !(SILVERLIGHT || NETFX_CORE || PORTABLE40 || PORTABLE) if (_listChanged != null) OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index)); #endif #if SILVERLIGHT || !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); #endif } internal virtual bool RemoveItem(JToken item) { int index = IndexOfItem(item); if (index >= 0) { RemoveItemAt(index); return true; } return false; } internal virtual JToken GetItem(int index) { return ChildrenTokens[index]; } internal virtual void SetItem(int index, JToken item) { if (index < 0) throw new ArgumentOutOfRangeException("index", "Index is less than 0."); if (index >= ChildrenTokens.Count) throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count."); JToken existing = ChildrenTokens[index]; if (IsTokenUnchanged(existing, item)) return; CheckReentrancy(); item = EnsureParentToken(item, false); ValidateToken(item, existing); JToken previous = (index == 0) ? null : ChildrenTokens[index - 1]; JToken next = (index == ChildrenTokens.Count - 1) ? null : ChildrenTokens[index + 1]; item.Parent = this; item.Previous = previous; if (previous != null) previous.Next = item; item.Next = next; if (next != null) next.Previous = item; ChildrenTokens[index] = item; existing.Parent = null; existing.Previous = null; existing.Next = null; #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40) if (_listChanged != null) OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index)); #endif #if SILVERLIGHT || !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item, existing, index)); #endif } internal virtual void ClearItems() { CheckReentrancy(); foreach (JToken item in ChildrenTokens) { item.Parent = null; item.Previous = null; item.Next = null; } ChildrenTokens.Clear(); #if !(SILVERLIGHT || NETFX_CORE || PORTABLE40 || PORTABLE) if (_listChanged != null) OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1)); #endif #if SILVERLIGHT || !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); #endif } internal virtual void ReplaceItem(JToken existing, JToken replacement) { if (existing == null || existing.Parent != this) return; int index = IndexOfItem(existing); SetItem(index, replacement); } internal virtual bool ContainsItem(JToken item) { return (IndexOfItem(item) != -1); } internal virtual void CopyItemsTo(Array array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0."); if (arrayIndex >= array.Length && arrayIndex != 0) throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); if (Count > array.Length - arrayIndex) throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); int index = 0; foreach (JToken token in ChildrenTokens) { array.SetValue(token, arrayIndex + index); index++; } } internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue) { JValue v1 = currentValue as JValue; if (v1 != null) { // null will get turned into a JValue of type null if (v1.Type == JTokenType.Null && newValue == null) return true; return v1.Equals(newValue); } return false; } internal virtual void ValidateToken(JToken o, JToken existing) { ValidationUtils.ArgumentNotNull(o, "o"); if (o.Type == JTokenType.Property) throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); } /// <summary> /// Adds the specified content as children of this <see cref="JToken"/>. /// </summary> /// <param name="content">The content to be added.</param> public virtual void Add(object content) { AddInternal(ChildrenTokens.Count, content, false); } internal void AddAndSkipParentCheck(JToken token) { AddInternal(ChildrenTokens.Count, token, true); } /// <summary> /// Adds the specified content as the first children of this <see cref="JToken"/>. /// </summary> /// <param name="content">The content to be added.</param> public void AddFirst(object content) { AddInternal(0, content, false); } internal void AddInternal(int index, object content, bool skipParentCheck) { if (IsMultiContent(content)) { IEnumerable enumerable = (IEnumerable)content; int multiIndex = index; foreach (object c in enumerable) { AddInternal(multiIndex, c, skipParentCheck); multiIndex++; } } else { JToken item = CreateFromContent(content); InsertItem(index, item, skipParentCheck); } } internal JToken CreateFromContent(object content) { if (content is JToken) return (JToken)content; return new JValue(content); } /// <summary> /// Creates an <see cref="JsonWriter"/> that can be used to add tokens to the <see cref="JToken"/>. /// </summary> /// <returns>An <see cref="JsonWriter"/> that is ready to have content written to it.</returns> public JsonWriter CreateWriter() { return new JTokenWriter(this); } /// <summary> /// Replaces the children nodes of this token with the specified content. /// </summary> /// <param name="content">The content.</param> public void ReplaceAll(object content) { ClearItems(); Add(content); } /// <summary> /// Removes the child nodes from this token. /// </summary> public void RemoveAll() { ClearItems(); } internal void ReadTokenFrom(JsonReader reader) { int startDepth = reader.Depth; if (!reader.Read()) throw JsonReaderException.Create(reader, "Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); ReadContentFrom(reader); int endDepth = reader.Depth; if (endDepth > startDepth) throw JsonReaderException.Create(reader, "Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); } internal void ReadContentFrom(JsonReader r) { ValidationUtils.ArgumentNotNull(r, "r"); IJsonLineInfo lineInfo = r as IJsonLineInfo; JContainer parent = this; do { if (parent is JProperty && ((JProperty)parent).Value != null) { if (parent == this) return; parent = parent.Parent; } switch (r.TokenType) { case JsonToken.None: // new reader. move to actual content break; case JsonToken.StartArray: JArray a = new JArray(); a.SetLineInfo(lineInfo); parent.Add(a); parent = a; break; case JsonToken.EndArray: if (parent == this) return; parent = parent.Parent; break; case JsonToken.StartObject: JObject o = new JObject(); o.SetLineInfo(lineInfo); parent.Add(o); parent = o; break; case JsonToken.EndObject: if (parent == this) return; parent = parent.Parent; break; case JsonToken.StartConstructor: JConstructor constructor = new JConstructor(r.Value.ToString()); constructor.SetLineInfo(constructor); parent.Add(constructor); parent = constructor; break; case JsonToken.EndConstructor: if (parent == this) return; parent = parent.Parent; break; case JsonToken.String: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Date: case JsonToken.Boolean: case JsonToken.Bytes: JValue v = new JValue(r.Value); v.SetLineInfo(lineInfo); parent.Add(v); break; case JsonToken.Comment: v = JValue.CreateComment(r.Value.ToString()); v.SetLineInfo(lineInfo); parent.Add(v); break; case JsonToken.Null: v = new JValue(null, JTokenType.Null); v.SetLineInfo(lineInfo); parent.Add(v); break; case JsonToken.Undefined: v = new JValue(null, JTokenType.Undefined); v.SetLineInfo(lineInfo); parent.Add(v); break; case JsonToken.PropertyName: string propertyName = r.Value.ToString(); JProperty property = new JProperty(propertyName); property.SetLineInfo(lineInfo); JObject parentObject = (JObject) parent; // handle multiple properties with the same name in JSON JProperty existingPropertyWithName = parentObject.Property(propertyName); if (existingPropertyWithName == null) parent.Add(property); else existingPropertyWithName.Replace(property); parent = property; break; default: throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, r.TokenType)); } } while (r.Read()); } internal int ContentsHashCode() { int hashCode = 0; foreach (JToken item in ChildrenTokens) { hashCode ^= item.GetDeepHashCode(); } return hashCode; } #if !(SILVERLIGHT || NETFX_CORE || PORTABLE40 || PORTABLE) string ITypedList.GetListName(PropertyDescriptor[] listAccessors) { return string.Empty; } PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { ICustomTypeDescriptor d = First as ICustomTypeDescriptor; if (d != null) return d.GetProperties(); return null; } #endif #region IList<JToken> Members int IList<JToken>.IndexOf(JToken item) { return IndexOfItem(item); } void IList<JToken>.Insert(int index, JToken item) { InsertItem(index, item, false); } void IList<JToken>.RemoveAt(int index) { RemoveItemAt(index); } JToken IList<JToken>.this[int index] { get { return GetItem(index); } set { SetItem(index, value); } } #endregion #region ICollection<JToken> Members void ICollection<JToken>.Add(JToken item) { Add(item); } void ICollection<JToken>.Clear() { ClearItems(); } bool ICollection<JToken>.Contains(JToken item) { return ContainsItem(item); } void ICollection<JToken>.CopyTo(JToken[] array, int arrayIndex) { CopyItemsTo(array, arrayIndex); } bool ICollection<JToken>.IsReadOnly { get { return false; } } bool ICollection<JToken>.Remove(JToken item) { return RemoveItem(item); } #endregion private JToken EnsureValue(object value) { if (value == null) return null; if (value is JToken) return (JToken) value; throw new ArgumentException("Argument is not a JToken."); } #region IList Members int IList.Add(object value) { Add(EnsureValue(value)); return Count - 1; } void IList.Clear() { ClearItems(); } bool IList.Contains(object value) { return ContainsItem(EnsureValue(value)); } int IList.IndexOf(object value) { return IndexOfItem(EnsureValue(value)); } void IList.Insert(int index, object value) { InsertItem(index, EnsureValue(value), false); } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } void IList.Remove(object value) { RemoveItem(EnsureValue(value)); } void IList.RemoveAt(int index) { RemoveItemAt(index); } object IList.this[int index] { get { return GetItem(index); } set { SetItem(index, EnsureValue(value)); } } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { CopyItemsTo(array, index); } /// <summary> /// Gets the count of child JSON tokens. /// </summary> /// <value>The count of child JSON tokens</value> public int Count { get { return ChildrenTokens.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) Interlocked.CompareExchange(ref _syncRoot, new object(), null); return _syncRoot; } } #endregion #region IBindingList Members #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40) void IBindingList.AddIndex(PropertyDescriptor property) { } object IBindingList.AddNew() { AddingNewEventArgs args = new AddingNewEventArgs(); OnAddingNew(args); if (args.NewObject == null) throw new JsonException("Could not determine new value to add to '{0}'.".FormatWith(CultureInfo.InvariantCulture, GetType())); if (!(args.NewObject is JToken)) throw new JsonException("New item to be added to collection must be compatible with {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JToken))); JToken newItem = (JToken)args.NewObject; Add(newItem); return newItem; } bool IBindingList.AllowEdit { get { return true; } } bool IBindingList.AllowNew { get { return true; } } bool IBindingList.AllowRemove { get { return true; } } void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction) { throw new NotSupportedException(); } int IBindingList.Find(PropertyDescriptor property, object key) { throw new NotSupportedException(); } bool IBindingList.IsSorted { get { return false; } } void IBindingList.RemoveIndex(PropertyDescriptor property) { } void IBindingList.RemoveSort() { throw new NotSupportedException(); } ListSortDirection IBindingList.SortDirection { get { return ListSortDirection.Ascending; } } PropertyDescriptor IBindingList.SortProperty { get { return null; } } bool IBindingList.SupportsChangeNotification { get { return true; } } bool IBindingList.SupportsSearching { get { return false; } } bool IBindingList.SupportsSorting { get { return false; } } #endif #endregion } }
using System; using System.Text; using System.Collections; using System.Collections.Generic; namespace Com.Aspose.Tasks.Model { public class Resource { public string Name { get; set; } public int? Uid { get; set; } public int? Id { get; set; } public string Type { get; set; } public bool? IsNull { get; set; } public string Initials { get; set; } public string Phonetics { get; set; } public string NtAccount { get; set; } public string MaterialLabel { get; set; } public string Code { get; set; } public string Group { get; set; } public string EMailAddress { get; set; } public string EmailAddress { get; set; } public string Hyperlink { get; set; } public string HyperlinkAddress { get; set; } public string HyperlinkSubAddress { get; set; } public double? MaxUnits { get; set; } public double? PeakUnits { get; set; } public bool? Overallocated { get; set; } public bool? OverAllocated { get; set; } public DateTime AvailableFrom { get; set; } public DateTime AvailableTo { get; set; } public DateTime Start { get; set; } public DateTime Finish { get; set; } public bool? CanLevel { get; set; } public string AccrueAt { get; set; } public string Work { get; set; } public string WorkString { get; set; } public string RegularWork { get; set; } public string RegularWorkString { get; set; } public string OvertimeWork { get; set; } public string OvertimeWorkString { get; set; } public string ActualWork { get; set; } public string ActualWorkString { get; set; } public string RemainingWork { get; set; } public string RemainingWorkString { get; set; } public string ActualOvertimeWork { get; set; } public string ActualOvertimeWorkString { get; set; } public string RemainingOvertimeWork { get; set; } public string RemainingOvertimeWorkString { get; set; } public int? PercentWorkComplete { get; set; } public double? StandardRate { get; set; } public string StandardRateFormat { get; set; } public double? Cost { get; set; } public string OvertimeRateFormat { get; set; } public double? OvertimeCost { get; set; } public double? CostPerUse { get; set; } public double? ActualCost { get; set; } public double? ActualOvertimeCost { get; set; } public double? RemainingCost { get; set; } public double? RemainingOvertimeCost { get; set; } public double? WorkVariance { get; set; } public double? CostVariance { get; set; } public double? Sv { get; set; } public double? SV { get; set; } public double? Cv { get; set; } public double? CV { get; set; } public double? Acwp { get; set; } public double? ACWP { get; set; } public int? CalendarUid { get; set; } public string NotesText { get; set; } public double? Bcws { get; set; } public double? BCWS { get; set; } public double? Bcwp { get; set; } public double? BCWP { get; set; } public bool? IsGeneric { get; set; } public bool? IsInactive { get; set; } public bool? IsEnterprise { get; set; } public string BookingType { get; set; } public string ActualWorkProtected { get; set; } public string ActualWorkProtectedString { get; set; } public string ActualOvertimeWorkProtected { get; set; } public string ActualOvertimeWorkProtectedString { get; set; } public string ActiveDirectoryGuid { get; set; } public DateTime CreationDate { get; set; } public DateTime Created { get; set; } public string CostCenter { get; set; } public bool? IsCostResource { get; set; } public bool? TeamAssignmentPool { get; set; } public bool? IsTeamAssignmentPool { get; set; } public string AssignmentOwner { get; set; } public string AssignmentOwnerGuid { get; set; } public bool? IsBudget { get; set; } public string BudgetWork { get; set; } public string BudgetWorkString { get; set; } public double? BudgetCost { get; set; } public double? OvertimeRate { get; set; } public string BaselineWork { get; set; } public string BaselineWorkString { get; set; } public double? BaselineCost { get; set; } public double? BaselineBcws { get; set; } public double? BaselineBcwp { get; set; } public string Baseline1Work { get; set; } public string Baseline1WorkString { get; set; } public double? Baseline1Cost { get; set; } public double? Baseline1Bcws { get; set; } public double? Baseline1Bcwp { get; set; } public string Baseline2Work { get; set; } public string Baseline2WorkString { get; set; } public double? Baseline2Cost { get; set; } public double? Baseline2Bcws { get; set; } public double? Baseline2Bcwp { get; set; } public string Baseline3Work { get; set; } public string Baseline3WorkString { get; set; } public double? Baseline3Cost { get; set; } public double? Baseline3Bcws { get; set; } public double? Baseline3Bcwp { get; set; } public string Baseline4Work { get; set; } public string Baseline4WorkString { get; set; } public double? Baseline4Cost { get; set; } public double? Baseline4Bcws { get; set; } public double? Baseline4Bcwp { get; set; } public string Baseline5Work { get; set; } public string Baseline5WorkString { get; set; } public double? Baseline5Cost { get; set; } public double? Baseline5Bcws { get; set; } public double? Baseline5Bcwp { get; set; } public string Baseline6Work { get; set; } public string Baseline6WorkString { get; set; } public double? Baseline6Cost { get; set; } public double? Baseline6Bcws { get; set; } public double? Baseline6Bcwp { get; set; } public string Baseline7Work { get; set; } public string Baseline7WorkString { get; set; } public double? Baseline7Cost { get; set; } public double? Baseline7Bcws { get; set; } public double? Baseline7Bcwp { get; set; } public string Baseline8Work { get; set; } public string Baseline8WorkString { get; set; } public double? Baseline8Cost { get; set; } public double? Baseline8Bcws { get; set; } public double? Baseline8Bcwp { get; set; } public string Baseline9Work { get; set; } public string Baseline9WorkString { get; set; } public double? Baseline9Cost { get; set; } public double? Baseline9Bcws { get; set; } public double? Baseline9Bcwp { get; set; } public string Baseline10Work { get; set; } public string Baseline10WorkString { get; set; } public double? Baseline10Cost { get; set; } public double? Baseline10Bcws { get; set; } public double? Baseline10Bcwp { get; set; } public List<ExtendedAttribute> ExtendedAttributes { get; set; } public List<OutlineCode> OutlineCodes { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.Append("class Resource {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Uid: ").Append(Uid).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" IsNull: ").Append(IsNull).Append("\n"); sb.Append(" Initials: ").Append(Initials).Append("\n"); sb.Append(" Phonetics: ").Append(Phonetics).Append("\n"); sb.Append(" NtAccount: ").Append(NtAccount).Append("\n"); sb.Append(" MaterialLabel: ").Append(MaterialLabel).Append("\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" Group: ").Append(Group).Append("\n"); sb.Append(" EMailAddress: ").Append(EMailAddress).Append("\n"); sb.Append(" EmailAddress: ").Append(EmailAddress).Append("\n"); sb.Append(" Hyperlink: ").Append(Hyperlink).Append("\n"); sb.Append(" HyperlinkAddress: ").Append(HyperlinkAddress).Append("\n"); sb.Append(" HyperlinkSubAddress: ").Append(HyperlinkSubAddress).Append("\n"); sb.Append(" MaxUnits: ").Append(MaxUnits).Append("\n"); sb.Append(" PeakUnits: ").Append(PeakUnits).Append("\n"); sb.Append(" Overallocated: ").Append(Overallocated).Append("\n"); sb.Append(" OverAllocated: ").Append(OverAllocated).Append("\n"); sb.Append(" AvailableFrom: ").Append(AvailableFrom).Append("\n"); sb.Append(" AvailableTo: ").Append(AvailableTo).Append("\n"); sb.Append(" Start: ").Append(Start).Append("\n"); sb.Append(" Finish: ").Append(Finish).Append("\n"); sb.Append(" CanLevel: ").Append(CanLevel).Append("\n"); sb.Append(" AccrueAt: ").Append(AccrueAt).Append("\n"); sb.Append(" Work: ").Append(Work).Append("\n"); sb.Append(" WorkString: ").Append(WorkString).Append("\n"); sb.Append(" RegularWork: ").Append(RegularWork).Append("\n"); sb.Append(" RegularWorkString: ").Append(RegularWorkString).Append("\n"); sb.Append(" OvertimeWork: ").Append(OvertimeWork).Append("\n"); sb.Append(" OvertimeWorkString: ").Append(OvertimeWorkString).Append("\n"); sb.Append(" ActualWork: ").Append(ActualWork).Append("\n"); sb.Append(" ActualWorkString: ").Append(ActualWorkString).Append("\n"); sb.Append(" RemainingWork: ").Append(RemainingWork).Append("\n"); sb.Append(" RemainingWorkString: ").Append(RemainingWorkString).Append("\n"); sb.Append(" ActualOvertimeWork: ").Append(ActualOvertimeWork).Append("\n"); sb.Append(" ActualOvertimeWorkString: ").Append(ActualOvertimeWorkString).Append("\n"); sb.Append(" RemainingOvertimeWork: ").Append(RemainingOvertimeWork).Append("\n"); sb.Append(" RemainingOvertimeWorkString: ").Append(RemainingOvertimeWorkString).Append("\n"); sb.Append(" PercentWorkComplete: ").Append(PercentWorkComplete).Append("\n"); sb.Append(" StandardRate: ").Append(StandardRate).Append("\n"); sb.Append(" StandardRateFormat: ").Append(StandardRateFormat).Append("\n"); sb.Append(" Cost: ").Append(Cost).Append("\n"); sb.Append(" OvertimeRateFormat: ").Append(OvertimeRateFormat).Append("\n"); sb.Append(" OvertimeCost: ").Append(OvertimeCost).Append("\n"); sb.Append(" CostPerUse: ").Append(CostPerUse).Append("\n"); sb.Append(" ActualCost: ").Append(ActualCost).Append("\n"); sb.Append(" ActualOvertimeCost: ").Append(ActualOvertimeCost).Append("\n"); sb.Append(" RemainingCost: ").Append(RemainingCost).Append("\n"); sb.Append(" RemainingOvertimeCost: ").Append(RemainingOvertimeCost).Append("\n"); sb.Append(" WorkVariance: ").Append(WorkVariance).Append("\n"); sb.Append(" CostVariance: ").Append(CostVariance).Append("\n"); sb.Append(" Sv: ").Append(Sv).Append("\n"); sb.Append(" SV: ").Append(SV).Append("\n"); sb.Append(" Cv: ").Append(Cv).Append("\n"); sb.Append(" CV: ").Append(CV).Append("\n"); sb.Append(" Acwp: ").Append(Acwp).Append("\n"); sb.Append(" ACWP: ").Append(ACWP).Append("\n"); sb.Append(" CalendarUid: ").Append(CalendarUid).Append("\n"); sb.Append(" NotesText: ").Append(NotesText).Append("\n"); sb.Append(" Bcws: ").Append(Bcws).Append("\n"); sb.Append(" BCWS: ").Append(BCWS).Append("\n"); sb.Append(" Bcwp: ").Append(Bcwp).Append("\n"); sb.Append(" BCWP: ").Append(BCWP).Append("\n"); sb.Append(" IsGeneric: ").Append(IsGeneric).Append("\n"); sb.Append(" IsInactive: ").Append(IsInactive).Append("\n"); sb.Append(" IsEnterprise: ").Append(IsEnterprise).Append("\n"); sb.Append(" BookingType: ").Append(BookingType).Append("\n"); sb.Append(" ActualWorkProtected: ").Append(ActualWorkProtected).Append("\n"); sb.Append(" ActualWorkProtectedString: ").Append(ActualWorkProtectedString).Append("\n"); sb.Append(" ActualOvertimeWorkProtected: ").Append(ActualOvertimeWorkProtected).Append("\n"); sb.Append(" ActualOvertimeWorkProtectedString: ").Append(ActualOvertimeWorkProtectedString).Append("\n"); sb.Append(" ActiveDirectoryGuid: ").Append(ActiveDirectoryGuid).Append("\n"); sb.Append(" CreationDate: ").Append(CreationDate).Append("\n"); sb.Append(" Created: ").Append(Created).Append("\n"); sb.Append(" CostCenter: ").Append(CostCenter).Append("\n"); sb.Append(" IsCostResource: ").Append(IsCostResource).Append("\n"); sb.Append(" TeamAssignmentPool: ").Append(TeamAssignmentPool).Append("\n"); sb.Append(" IsTeamAssignmentPool: ").Append(IsTeamAssignmentPool).Append("\n"); sb.Append(" AssignmentOwner: ").Append(AssignmentOwner).Append("\n"); sb.Append(" AssignmentOwnerGuid: ").Append(AssignmentOwnerGuid).Append("\n"); sb.Append(" IsBudget: ").Append(IsBudget).Append("\n"); sb.Append(" BudgetWork: ").Append(BudgetWork).Append("\n"); sb.Append(" BudgetWorkString: ").Append(BudgetWorkString).Append("\n"); sb.Append(" BudgetCost: ").Append(BudgetCost).Append("\n"); sb.Append(" OvertimeRate: ").Append(OvertimeRate).Append("\n"); sb.Append(" BaselineWork: ").Append(BaselineWork).Append("\n"); sb.Append(" BaselineWorkString: ").Append(BaselineWorkString).Append("\n"); sb.Append(" BaselineCost: ").Append(BaselineCost).Append("\n"); sb.Append(" BaselineBcws: ").Append(BaselineBcws).Append("\n"); sb.Append(" BaselineBcwp: ").Append(BaselineBcwp).Append("\n"); sb.Append(" Baseline1Work: ").Append(Baseline1Work).Append("\n"); sb.Append(" Baseline1WorkString: ").Append(Baseline1WorkString).Append("\n"); sb.Append(" Baseline1Cost: ").Append(Baseline1Cost).Append("\n"); sb.Append(" Baseline1Bcws: ").Append(Baseline1Bcws).Append("\n"); sb.Append(" Baseline1Bcwp: ").Append(Baseline1Bcwp).Append("\n"); sb.Append(" Baseline2Work: ").Append(Baseline2Work).Append("\n"); sb.Append(" Baseline2WorkString: ").Append(Baseline2WorkString).Append("\n"); sb.Append(" Baseline2Cost: ").Append(Baseline2Cost).Append("\n"); sb.Append(" Baseline2Bcws: ").Append(Baseline2Bcws).Append("\n"); sb.Append(" Baseline2Bcwp: ").Append(Baseline2Bcwp).Append("\n"); sb.Append(" Baseline3Work: ").Append(Baseline3Work).Append("\n"); sb.Append(" Baseline3WorkString: ").Append(Baseline3WorkString).Append("\n"); sb.Append(" Baseline3Cost: ").Append(Baseline3Cost).Append("\n"); sb.Append(" Baseline3Bcws: ").Append(Baseline3Bcws).Append("\n"); sb.Append(" Baseline3Bcwp: ").Append(Baseline3Bcwp).Append("\n"); sb.Append(" Baseline4Work: ").Append(Baseline4Work).Append("\n"); sb.Append(" Baseline4WorkString: ").Append(Baseline4WorkString).Append("\n"); sb.Append(" Baseline4Cost: ").Append(Baseline4Cost).Append("\n"); sb.Append(" Baseline4Bcws: ").Append(Baseline4Bcws).Append("\n"); sb.Append(" Baseline4Bcwp: ").Append(Baseline4Bcwp).Append("\n"); sb.Append(" Baseline5Work: ").Append(Baseline5Work).Append("\n"); sb.Append(" Baseline5WorkString: ").Append(Baseline5WorkString).Append("\n"); sb.Append(" Baseline5Cost: ").Append(Baseline5Cost).Append("\n"); sb.Append(" Baseline5Bcws: ").Append(Baseline5Bcws).Append("\n"); sb.Append(" Baseline5Bcwp: ").Append(Baseline5Bcwp).Append("\n"); sb.Append(" Baseline6Work: ").Append(Baseline6Work).Append("\n"); sb.Append(" Baseline6WorkString: ").Append(Baseline6WorkString).Append("\n"); sb.Append(" Baseline6Cost: ").Append(Baseline6Cost).Append("\n"); sb.Append(" Baseline6Bcws: ").Append(Baseline6Bcws).Append("\n"); sb.Append(" Baseline6Bcwp: ").Append(Baseline6Bcwp).Append("\n"); sb.Append(" Baseline7Work: ").Append(Baseline7Work).Append("\n"); sb.Append(" Baseline7WorkString: ").Append(Baseline7WorkString).Append("\n"); sb.Append(" Baseline7Cost: ").Append(Baseline7Cost).Append("\n"); sb.Append(" Baseline7Bcws: ").Append(Baseline7Bcws).Append("\n"); sb.Append(" Baseline7Bcwp: ").Append(Baseline7Bcwp).Append("\n"); sb.Append(" Baseline8Work: ").Append(Baseline8Work).Append("\n"); sb.Append(" Baseline8WorkString: ").Append(Baseline8WorkString).Append("\n"); sb.Append(" Baseline8Cost: ").Append(Baseline8Cost).Append("\n"); sb.Append(" Baseline8Bcws: ").Append(Baseline8Bcws).Append("\n"); sb.Append(" Baseline8Bcwp: ").Append(Baseline8Bcwp).Append("\n"); sb.Append(" Baseline9Work: ").Append(Baseline9Work).Append("\n"); sb.Append(" Baseline9WorkString: ").Append(Baseline9WorkString).Append("\n"); sb.Append(" Baseline9Cost: ").Append(Baseline9Cost).Append("\n"); sb.Append(" Baseline9Bcws: ").Append(Baseline9Bcws).Append("\n"); sb.Append(" Baseline9Bcwp: ").Append(Baseline9Bcwp).Append("\n"); sb.Append(" Baseline10Work: ").Append(Baseline10Work).Append("\n"); sb.Append(" Baseline10WorkString: ").Append(Baseline10WorkString).Append("\n"); sb.Append(" Baseline10Cost: ").Append(Baseline10Cost).Append("\n"); sb.Append(" Baseline10Bcws: ").Append(Baseline10Bcws).Append("\n"); sb.Append(" Baseline10Bcwp: ").Append(Baseline10Bcwp).Append("\n"); sb.Append(" ExtendedAttributes: ").Append(ExtendedAttributes).Append("\n"); sb.Append(" OutlineCodes: ").Append(OutlineCodes).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
// 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.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="ConversionValueRuleServiceClient"/> instances.</summary> public sealed partial class ConversionValueRuleServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ConversionValueRuleServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ConversionValueRuleServiceSettings"/>.</returns> public static ConversionValueRuleServiceSettings GetDefault() => new ConversionValueRuleServiceSettings(); /// <summary> /// Constructs a new <see cref="ConversionValueRuleServiceSettings"/> object with default settings. /// </summary> public ConversionValueRuleServiceSettings() { } private ConversionValueRuleServiceSettings(ConversionValueRuleServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetConversionValueRuleSettings = existing.GetConversionValueRuleSettings; MutateConversionValueRulesSettings = existing.MutateConversionValueRulesSettings; OnCopy(existing); } partial void OnCopy(ConversionValueRuleServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ConversionValueRuleServiceClient.GetConversionValueRule</c> and /// <c>ConversionValueRuleServiceClient.GetConversionValueRuleAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetConversionValueRuleSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ConversionValueRuleServiceClient.MutateConversionValueRules</c> and /// <c>ConversionValueRuleServiceClient.MutateConversionValueRulesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateConversionValueRulesSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ConversionValueRuleServiceSettings"/> object.</returns> public ConversionValueRuleServiceSettings Clone() => new ConversionValueRuleServiceSettings(this); } /// <summary> /// Builder class for <see cref="ConversionValueRuleServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class ConversionValueRuleServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionValueRuleServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ConversionValueRuleServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ConversionValueRuleServiceClientBuilder() { UseJwtAccessWithScopes = ConversionValueRuleServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ConversionValueRuleServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionValueRuleServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ConversionValueRuleServiceClient Build() { ConversionValueRuleServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ConversionValueRuleServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ConversionValueRuleServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ConversionValueRuleServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ConversionValueRuleServiceClient.Create(callInvoker, Settings); } private async stt::Task<ConversionValueRuleServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ConversionValueRuleServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ConversionValueRuleServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ConversionValueRuleServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionValueRuleServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ConversionValueRuleService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage conversion value rules. /// </remarks> public abstract partial class ConversionValueRuleServiceClient { /// <summary> /// The default endpoint for the ConversionValueRuleService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ConversionValueRuleService scopes.</summary> /// <remarks> /// The default ConversionValueRuleService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ConversionValueRuleServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ConversionValueRuleServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ConversionValueRuleServiceClient"/>.</returns> public static stt::Task<ConversionValueRuleServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ConversionValueRuleServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ConversionValueRuleServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ConversionValueRuleServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ConversionValueRuleServiceClient"/>.</returns> public static ConversionValueRuleServiceClient Create() => new ConversionValueRuleServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ConversionValueRuleServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ConversionValueRuleServiceSettings"/>.</param> /// <returns>The created <see cref="ConversionValueRuleServiceClient"/>.</returns> internal static ConversionValueRuleServiceClient Create(grpccore::CallInvoker callInvoker, ConversionValueRuleServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ConversionValueRuleService.ConversionValueRuleServiceClient grpcClient = new ConversionValueRuleService.ConversionValueRuleServiceClient(callInvoker); return new ConversionValueRuleServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ConversionValueRuleService client</summary> public virtual ConversionValueRuleService.ConversionValueRuleServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ConversionValueRule GetConversionValueRule(GetConversionValueRuleRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(GetConversionValueRuleRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(GetConversionValueRuleRequest request, st::CancellationToken cancellationToken) => GetConversionValueRuleAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ConversionValueRule GetConversionValueRule(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionValueRule(new GetConversionValueRuleRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionValueRuleAsync(new GetConversionValueRuleRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(string resourceName, st::CancellationToken cancellationToken) => GetConversionValueRuleAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ConversionValueRule GetConversionValueRule(gagvr::ConversionValueRuleName resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionValueRule(new GetConversionValueRuleRequest { ResourceNameAsConversionValueRuleName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(gagvr::ConversionValueRuleName resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionValueRuleAsync(new GetConversionValueRuleRequest { ResourceNameAsConversionValueRuleName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(gagvr::ConversionValueRuleName resourceName, st::CancellationToken cancellationToken) => GetConversionValueRuleAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes conversion value rules. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateConversionValueRulesResponse MutateConversionValueRules(MutateConversionValueRulesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes conversion value rules. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(MutateConversionValueRulesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes conversion value rules. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(MutateConversionValueRulesRequest request, st::CancellationToken cancellationToken) => MutateConversionValueRulesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes conversion value rules. Operation statuses are /// returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion value rules are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion value rules. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateConversionValueRulesResponse MutateConversionValueRules(string customerId, scg::IEnumerable<ConversionValueRuleOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionValueRules(new MutateConversionValueRulesRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes conversion value rules. Operation statuses are /// returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion value rules are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion value rules. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(string customerId, scg::IEnumerable<ConversionValueRuleOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionValueRulesAsync(new MutateConversionValueRulesRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes conversion value rules. Operation statuses are /// returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion value rules are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion value rules. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(string customerId, scg::IEnumerable<ConversionValueRuleOperation> operations, st::CancellationToken cancellationToken) => MutateConversionValueRulesAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ConversionValueRuleService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage conversion value rules. /// </remarks> public sealed partial class ConversionValueRuleServiceClientImpl : ConversionValueRuleServiceClient { private readonly gaxgrpc::ApiCall<GetConversionValueRuleRequest, gagvr::ConversionValueRule> _callGetConversionValueRule; private readonly gaxgrpc::ApiCall<MutateConversionValueRulesRequest, MutateConversionValueRulesResponse> _callMutateConversionValueRules; /// <summary> /// Constructs a client wrapper for the ConversionValueRuleService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ConversionValueRuleServiceSettings"/> used within this client. /// </param> public ConversionValueRuleServiceClientImpl(ConversionValueRuleService.ConversionValueRuleServiceClient grpcClient, ConversionValueRuleServiceSettings settings) { GrpcClient = grpcClient; ConversionValueRuleServiceSettings effectiveSettings = settings ?? ConversionValueRuleServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetConversionValueRule = clientHelper.BuildApiCall<GetConversionValueRuleRequest, gagvr::ConversionValueRule>(grpcClient.GetConversionValueRuleAsync, grpcClient.GetConversionValueRule, effectiveSettings.GetConversionValueRuleSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetConversionValueRule); Modify_GetConversionValueRuleApiCall(ref _callGetConversionValueRule); _callMutateConversionValueRules = clientHelper.BuildApiCall<MutateConversionValueRulesRequest, MutateConversionValueRulesResponse>(grpcClient.MutateConversionValueRulesAsync, grpcClient.MutateConversionValueRules, effectiveSettings.MutateConversionValueRulesSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateConversionValueRules); Modify_MutateConversionValueRulesApiCall(ref _callMutateConversionValueRules); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetConversionValueRuleApiCall(ref gaxgrpc::ApiCall<GetConversionValueRuleRequest, gagvr::ConversionValueRule> call); partial void Modify_MutateConversionValueRulesApiCall(ref gaxgrpc::ApiCall<MutateConversionValueRulesRequest, MutateConversionValueRulesResponse> call); partial void OnConstruction(ConversionValueRuleService.ConversionValueRuleServiceClient grpcClient, ConversionValueRuleServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ConversionValueRuleService client</summary> public override ConversionValueRuleService.ConversionValueRuleServiceClient GrpcClient { get; } partial void Modify_GetConversionValueRuleRequest(ref GetConversionValueRuleRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateConversionValueRulesRequest(ref MutateConversionValueRulesRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::ConversionValueRule GetConversionValueRule(GetConversionValueRuleRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetConversionValueRuleRequest(ref request, ref callSettings); return _callGetConversionValueRule.Sync(request, callSettings); } /// <summary> /// Returns the requested conversion value rule. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(GetConversionValueRuleRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetConversionValueRuleRequest(ref request, ref callSettings); return _callGetConversionValueRule.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes conversion value rules. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateConversionValueRulesResponse MutateConversionValueRules(MutateConversionValueRulesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionValueRulesRequest(ref request, ref callSettings); return _callMutateConversionValueRules.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes conversion value rules. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(MutateConversionValueRulesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionValueRulesRequest(ref request, ref callSettings); return _callMutateConversionValueRules.Async(request, callSettings); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; namespace System.Collections.Immutable { /// <summary> /// An immutable queue. /// </summary> /// <typeparam name="T">The type of elements stored in the queue.</typeparam> [DebuggerDisplay("IsEmpty = {IsEmpty}")] [DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableQueue<T> : IImmutableQueue<T> { /// <summary> /// The singleton empty queue. /// </summary> /// <remarks> /// Additional instances representing the empty queue may exist on deserialized instances. /// Actually since this queue is a struct, instances don't even apply and there are no singletons. /// </remarks> private static readonly ImmutableQueue<T> s_EmptyField = new ImmutableQueue<T>(ImmutableStack<T>.Empty, ImmutableStack<T>.Empty); /// <summary> /// The end of the queue that enqueued elements are pushed onto. /// </summary> private readonly ImmutableStack<T> _backwards; /// <summary> /// The end of the queue from which elements are dequeued. /// </summary> private readonly ImmutableStack<T> _forwards; /// <summary> /// Backing field for the <see cref="BackwardsReversed"/> property. /// </summary> private ImmutableStack<T> _backwardsReversed; /// <summary> /// Initializes a new instance of the <see cref="ImmutableQueue{T}"/> class. /// </summary> /// <param name="forwards">The forwards stack.</param> /// <param name="backwards">The backwards stack.</param> internal ImmutableQueue(ImmutableStack<T> forwards, ImmutableStack<T> backwards) { Debug.Assert(forwards != null); Debug.Assert(backwards != null); _forwards = forwards; _backwards = backwards; } /// <summary> /// Gets the empty queue. /// </summary> public ImmutableQueue<T> Clear() { Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty); Contract.Assume(s_EmptyField.IsEmpty); return Empty; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { Debug.Assert(!_forwards.IsEmpty || _backwards.IsEmpty); return _forwards.IsEmpty; } } /// <summary> /// Gets the empty queue. /// </summary> public static ImmutableQueue<T> Empty { get { Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty); Contract.Assume(s_EmptyField.IsEmpty); return s_EmptyField; } } /// <summary> /// Gets an empty queue. /// </summary> IImmutableQueue<T> IImmutableQueue<T>.Clear() { Contract.Assume(s_EmptyField.IsEmpty); return this.Clear(); } /// <summary> /// Gets the reversed <see cref="_backwards"/> stack. /// </summary> private ImmutableStack<T> BackwardsReversed { get { Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null); // Although this is a lazy-init pattern, no lock is required because // this instance is immutable otherwise, and a double-assignment from multiple // threads is harmless. if (_backwardsReversed == null) { _backwardsReversed = _backwards.Reverse(); } return _backwardsReversed; } } /// <summary> /// Gets the element at the front of the queue. /// </summary> /// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception> [Pure] public T Peek() { if (this.IsEmpty) { throw new InvalidOperationException(SR.InvalidEmptyOperation); } return _forwards.Peek(); } /// <summary> /// Adds an element to the back of the queue. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The new queue. /// </returns> [Pure] public ImmutableQueue<T> Enqueue(T value) { Contract.Ensures(!Contract.Result<ImmutableQueue<T>>().IsEmpty); if (this.IsEmpty) { return new ImmutableQueue<T>(ImmutableStack.Create(value), ImmutableStack<T>.Empty); } else { return new ImmutableQueue<T>(_forwards, _backwards.Push(value)); } } /// <summary> /// Adds an element to the back of the queue. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The new queue. /// </returns> [Pure] IImmutableQueue<T> IImmutableQueue<T>.Enqueue(T value) { return this.Enqueue(value); } /// <summary> /// Returns a queue that is missing the front element. /// </summary> /// <returns>A queue; never <c>null</c>.</returns> /// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception> [Pure] public ImmutableQueue<T> Dequeue() { if (this.IsEmpty) { throw new InvalidOperationException(SR.InvalidEmptyOperation); } ImmutableStack<T> f = _forwards.Pop(); if (!f.IsEmpty) { return new ImmutableQueue<T>(f, _backwards); } else if (_backwards.IsEmpty) { return ImmutableQueue<T>.Empty; } else { return new ImmutableQueue<T>(this.BackwardsReversed, ImmutableStack<T>.Empty); } } /// <summary> /// Retrieves the item at the head of the queue, and returns a queue with the head element removed. /// </summary> /// <param name="value">Receives the value from the head of the queue.</param> /// <returns>The new queue with the head element removed.</returns> /// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")] [Pure] public ImmutableQueue<T> Dequeue(out T value) { value = this.Peek(); return this.Dequeue(); } /// <summary> /// Returns a queue that is missing the front element. /// </summary> /// <returns>A queue; never <c>null</c>.</returns> /// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception> [Pure] IImmutableQueue<T> IImmutableQueue<T>.Dequeue() { return this.Dequeue(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// An <see cref="Enumerator"/> that can be used to iterate through the collection. /// </returns> [Pure] public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [Pure] IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.IsEmpty ? Enumerable.Empty<T>().GetEnumerator() : new EnumeratorObject(this); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [Pure] IEnumerator IEnumerable.GetEnumerator() { return new EnumeratorObject(this); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>CustomerClientLink</c> resource.</summary> public sealed partial class CustomerClientLinkName : gax::IResourceName, sys::IEquatable<CustomerClientLinkName> { /// <summary>The possible contents of <see cref="CustomerClientLinkName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </summary> CustomerClientCustomerManagerLink = 1, } private static gax::PathTemplate s_customerClientCustomerManagerLink = new gax::PathTemplate("customers/{customer_id}/customerClientLinks/{client_customer_id_manager_link_id}"); /// <summary>Creates a <see cref="CustomerClientLinkName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CustomerClientLinkName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomerClientLinkName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomerClientLinkName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomerClientLinkName"/> with the pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clientCustomerId">The <c>ClientCustomer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CustomerClientLinkName"/> constructed from the provided ids.</returns> public static CustomerClientLinkName FromCustomerClientCustomerManagerLink(string customerId, string clientCustomerId, string managerLinkId) => new CustomerClientLinkName(ResourceNameType.CustomerClientCustomerManagerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), clientCustomerId: gax::GaxPreconditions.CheckNotNullOrEmpty(clientCustomerId, nameof(clientCustomerId)), managerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(managerLinkId, nameof(managerLinkId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerClientLinkName"/> with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clientCustomerId">The <c>ClientCustomer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerClientLinkName"/> with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </returns> public static string Format(string customerId, string clientCustomerId, string managerLinkId) => FormatCustomerClientCustomerManagerLink(customerId, clientCustomerId, managerLinkId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerClientLinkName"/> with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clientCustomerId">The <c>ClientCustomer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerClientLinkName"/> with pattern /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c>. /// </returns> public static string FormatCustomerClientCustomerManagerLink(string customerId, string clientCustomerId, string managerLinkId) => s_customerClientCustomerManagerLink.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(clientCustomerId, nameof(clientCustomerId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(managerLinkId, nameof(managerLinkId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerClientLinkName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="customerClientLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomerClientLinkName"/> if successful.</returns> public static CustomerClientLinkName Parse(string customerClientLinkName) => Parse(customerClientLinkName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerClientLinkName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerClientLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CustomerClientLinkName"/> if successful.</returns> public static CustomerClientLinkName Parse(string customerClientLinkName, bool allowUnparsed) => TryParse(customerClientLinkName, allowUnparsed, out CustomerClientLinkName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerClientLinkName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="customerClientLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerClientLinkName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerClientLinkName, out CustomerClientLinkName result) => TryParse(customerClientLinkName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerClientLinkName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerClientLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerClientLinkName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerClientLinkName, bool allowUnparsed, out CustomerClientLinkName result) { gax::GaxPreconditions.CheckNotNull(customerClientLinkName, nameof(customerClientLinkName)); gax::TemplatedResourceName resourceName; if (s_customerClientCustomerManagerLink.TryParseName(customerClientLinkName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerClientCustomerManagerLink(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customerClientLinkName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private CustomerClientLinkName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string clientCustomerId = null, string customerId = null, string managerLinkId = null) { Type = type; UnparsedResource = unparsedResourceName; ClientCustomerId = clientCustomerId; CustomerId = customerId; ManagerLinkId = managerLinkId; } /// <summary> /// Constructs a new instance of a <see cref="CustomerClientLinkName"/> class from the component parts of /// pattern <c>customers/{customer_id}/customerClientLinks/{client_customer_id}~{manager_link_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clientCustomerId">The <c>ClientCustomer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param> public CustomerClientLinkName(string customerId, string clientCustomerId, string managerLinkId) : this(ResourceNameType.CustomerClientCustomerManagerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), clientCustomerId: gax::GaxPreconditions.CheckNotNullOrEmpty(clientCustomerId, nameof(clientCustomerId)), managerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(managerLinkId, nameof(managerLinkId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>ClientCustomer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string ClientCustomerId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>ManagerLink</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ManagerLinkId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerClientCustomerManagerLink: return s_customerClientCustomerManagerLink.Expand(CustomerId, $"{ClientCustomerId}~{ManagerLinkId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CustomerClientLinkName); /// <inheritdoc/> public bool Equals(CustomerClientLinkName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomerClientLinkName a, CustomerClientLinkName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomerClientLinkName a, CustomerClientLinkName b) => !(a == b); } public partial class CustomerClientLink { /// <summary> /// <see cref="CustomerClientLinkName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CustomerClientLinkName ResourceNameAsCustomerClientLinkName { get => string.IsNullOrEmpty(ResourceName) ? null : CustomerClientLinkName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CustomerName"/>-typed view over the <see cref="ClientCustomer"/> resource name property. /// </summary> internal CustomerName ClientCustomerAsCustomerName { get => string.IsNullOrEmpty(ClientCustomer) ? null : CustomerName.Parse(ClientCustomer, allowUnparsed: true); set => ClientCustomer = value?.ToString() ?? ""; } } }
using System; using System.Collections; using System.Configuration; using NUnit.Framework; using IBatisNet.DataMapper.Exceptions; using IBatisNet.DataMapper.Test; using IBatisNet.DataMapper.Test.Domain; namespace IBatisNet.DataMapper.Test.NUnit.SqlMapTests { /// <summary> /// Summary description for TransactionTest. /// </summary> [TestFixture] public class TransactionTest: BaseTest { #region SetUp & TearDown /// <summary> /// SetUp /// </summary> [SetUp] public void Init() { InitScript( sqlMap.DataSource, ScriptDirectory + "account-init.sql" ); } /// <summary> /// TearDown /// </summary> [TearDown] public void Dispose() { /* ... */ } #endregion #region Transaction tests /// <summary> /// Test IsTransactionStart /// </summary> [Test] public void TestIsTransactionStartProperty() { Account account = NewAccount6(); sqlMap.BeginTransaction(); sqlMap.Insert("InsertAccountViaParameterMap", account); InsertNewAccount(); sqlMap.CommitTransaction(); } public void InsertNewAccount() { Account account = NewAccount6(); account.Id = 7; bool existingTransaction = (sqlMap.LocalSession != null && !sqlMap.LocalSession.IsTransactionStart); if (existingTransaction) { sqlMap.BeginTransaction(); } sqlMap.Insert("InsertAccountViaParameterMap", account); if (existingTransaction) { sqlMap.CommitTransaction(); } } /// <summary> /// Test BeginTransaction, CommitTransaction /// </summary> [Test] public void TestBeginCommitTransaction() { Account account = NewAccount6(); try { sqlMap.BeginTransaction(); sqlMap.Insert("InsertAccountViaParameterMap", account); sqlMap.CommitTransaction(); } finally { } // This will use autocommit... account = (Account) sqlMap.QueryForObject("GetAccountNullableEmail", 6); AssertAccount6(account); } /// <summary> /// Test that nested BeginTransaction throw an exception /// </summary> [Test] public void TestTransactionAlreadyStarted() { Account account = NewAccount6(); bool exceptionThrownAsExpected = false; try { sqlMap.BeginTransaction(); sqlMap.Insert("InsertAccountViaParameterMap", account); try { sqlMap.BeginTransaction(); // transaction already started } catch (DataMapperException e) { exceptionThrownAsExpected = true; Console.WriteLine ( "Test TransactionAlreadyStarted " + e.Message ); } sqlMap.CommitTransaction(); } finally { } // This will use autocommit... account = (Account) sqlMap.QueryForObject("GetAccountNullableEmail", 6); AssertAccount6(account); Assert.IsTrue(exceptionThrownAsExpected); } /// <summary> /// Test that CommitTransaction without BeginTransaction trow an exception /// </summary> [Test] public void TestNoTransactionStarted() { Account account = NewAccount6(); bool exceptionThrownAsExpected = false; sqlMap.Insert("InsertAccountViaParameterMap", account); try { sqlMap.CommitTransaction(); // No transaction started } catch (DataMapperException e) { exceptionThrownAsExpected = true; Console.WriteLine ( "Test NoTransactionStarted " + e.Message ); } // This will use autocommit... Assert.IsTrue(exceptionThrownAsExpected); account = (Account) sqlMap.QueryForObject("GetAccountNullableEmail", 6); AssertAccount6(account); } /// <summary> /// Test a RollBack Transaction. /// </summary> [Test] public void TestBeginRollbackTransaction() { Account account = NewAccount6(); try { sqlMap.BeginTransaction(); sqlMap.Insert("InsertAccountViaParameterMap", account); } finally { sqlMap.RollBackTransaction(); } // This will use autocommit... account = (Account) sqlMap.QueryForObject("GetAccountNullableEmail", 6); Assert.IsNull(account); } #endregion #region AutoCommit tests /// <summary> /// Test usage of auto commit for an insert /// </summary> [Test] public void TestAutoCommitInsert() { Account account = NewAccount6(); sqlMap.Insert("InsertAccountViaParameterMap", account); account = (Account) sqlMap.QueryForObject("GetAccountNullableEmail", 6); AssertAccount6(account); } /// <summary> /// Test usage of auto commit for a query /// </summary> [Test] public void TestAutoCommitQuery() { Account account = (Account) sqlMap.QueryForObject("GetAccountNullableEmail", 1); AssertAccount1(account); } #endregion } }
using UnityEditor; using UnityEngine; using System.IO; using System.Collections.Generic; [CustomEditor(typeof(MegaShape))] public class MegaShapeEditor : Editor { public bool showcommon = true; public float outline = 0.0f; int selected = -1; Vector3 pm = new Vector3(); Vector3 delta = new Vector3(); bool showsplines = false; bool showknots = false; bool showlabels = true; float ImportScale = 1.0f; bool hidewire = false; bool addingknot = false; Vector3 addpos; int knum; int snum; Bounds bounds; string lastpath = ""; MegaKnotAnim ma; public bool showfuncs = false; public bool export = false; public MegaAxis xaxis = MegaAxis.X; public MegaAxis yaxis = MegaAxis.Z; public float strokewidth = 1.0f; public Color strokecol = Color.black; static public Vector3 CursorPos = Vector3.zero; static public Vector3 CursorSpline = Vector3.zero; static public Vector3 CursorTangent = Vector3.zero; static public int CursorKnot = 0; public delegate bool ParseBinCallbackType(BinaryReader br, string id); public delegate void ParseClassCallbackType(string classname, BinaryReader br); public virtual bool Params() { MegaShape shape = (MegaShape)target; bool rebuild = false; float radius = EditorGUILayout.FloatField("Radius", shape.defRadius); if ( radius != shape.defRadius ) { if ( radius < 0.001f ) radius = 0.001f; shape.defRadius = radius; rebuild = true; } return rebuild; } public override void OnInspectorGUI() { //undoManager.CheckUndo(); bool buildmesh = false; bool recalc = false; MegaShape shape = (MegaShape)target; EditorGUILayout.BeginHorizontal(); int curve = shape.selcurve; if ( GUILayout.Button("Add Knot") ) { if ( shape.splines == null || shape.splines.Count == 0 ) { MegaSpline spline = new MegaSpline(); // Have methods for these shape.splines.Add(spline); } MegaKnot knot = new MegaKnot(); float per = shape.CursorPercent * 0.01f; CursorTangent = shape.splines[curve].Interpolate(per + 0.01f, true, ref CursorKnot); //this.GetPositionOnSpline(i) - p; CursorPos = shape.splines[curve].Interpolate(per, true, ref CursorKnot); //this.GetPositionOnSpline(i) - p; knot.p = CursorPos; knot.outvec = (CursorTangent - knot.p); knot.outvec.Normalize(); knot.outvec *= shape.splines[curve].knots[CursorKnot].seglength * 0.25f; knot.invec = -knot.outvec; knot.invec += knot.p; knot.outvec += knot.p; knot.twist = shape.splines[curve].knots[CursorKnot].twist; knot.id = shape.splines[curve].knots[CursorKnot].id; shape.splines[curve].knots.Insert(CursorKnot + 1, knot); shape.CalcLength(); //10); EditorUtility.SetDirty(target); buildmesh = true; } if ( GUILayout.Button("Delete Knot") ) { if ( selected != -1 ) { shape.splines[curve].knots.RemoveAt(selected); selected--; shape.CalcLength(); //10); } EditorUtility.SetDirty(target); buildmesh = true; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if ( GUILayout.Button("Match Handles") ) { if ( selected != -1 ) { Vector3 p = shape.splines[curve].knots[selected].p; Vector3 d = shape.splines[curve].knots[selected].outvec - p; shape.splines[curve].knots[selected].invec = p - d; shape.CalcLength(); //10); } EditorUtility.SetDirty(target); buildmesh = true; } if ( GUILayout.Button("Load") ) { LoadShape(ImportScale); buildmesh = true; } if ( GUILayout.Button("Load SXL") ) { LoadSXL(ImportScale); buildmesh = true; } if ( GUILayout.Button("Load KML") ) { LoadKML(ImportScale); buildmesh = true; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if ( GUILayout.Button("AutoCurve") ) { shape.AutoCurve(); EditorUtility.SetDirty(target); buildmesh = true; } if ( GUILayout.Button("Reverse") ) { shape.Reverse(curve); //shape.CalcLength(); EditorUtility.SetDirty(target); buildmesh = true; } EditorGUILayout.EndHorizontal(); if ( GUILayout.Button("Centre Shape") ) { shape.Centre(1.0f, Vector3.one); } if ( GUILayout.Button("Apply Scaling") ) { shape.Scale(shape.transform.localScale); EditorUtility.SetDirty(target); shape.transform.localScale = Vector3.one; buildmesh = true; } if ( GUILayout.Button("Import SVG") ) { LoadSVG(ImportScale); buildmesh = true; } showcommon = EditorGUILayout.Foldout(showcommon, "Common Params"); bool rebuild = false; //Params(); if ( showcommon ) { shape.CursorPercent = EditorGUILayout.FloatField("Cursor", shape.CursorPercent); shape.CursorPercent = Mathf.Repeat(shape.CursorPercent, 100.0f); ImportScale = EditorGUILayout.FloatField("Import Scale", ImportScale); MegaAxis av = (MegaAxis)EditorGUILayout.EnumPopup("Axis", shape.axis); if ( av != shape.axis ) { shape.axis = av; rebuild = true; } if ( shape.splines.Count > 1 ) shape.selcurve = EditorGUILayout.IntSlider("Curve", shape.selcurve, 0, shape.splines.Count - 1); if ( shape.selcurve < 0 ) shape.selcurve = 0; if ( shape.selcurve > shape.splines.Count - 1 ) shape.selcurve = shape.splines.Count - 1; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Colors"); shape.col1 = EditorGUILayout.ColorField(shape.col1); shape.col2 = EditorGUILayout.ColorField(shape.col2); EditorGUILayout.EndHorizontal(); shape.VecCol = EditorGUILayout.ColorField("Vec Col", shape.VecCol); shape.KnotSize = EditorGUILayout.FloatField("Knot Size", shape.KnotSize); shape.stepdist = EditorGUILayout.FloatField("Step Dist", shape.stepdist); MegaSpline spline = shape.splines[shape.selcurve]; if ( shape.stepdist < 0.01f ) shape.stepdist = 0.01f; shape.dolateupdate = EditorGUILayout.Toggle("Do Late Update", shape.dolateupdate); shape.normalizedInterp = EditorGUILayout.Toggle("Normalized Interp", shape.normalizedInterp); spline.constantSpeed = EditorGUILayout.Toggle("Constant Speed", spline.constantSpeed); int subdivs = EditorGUILayout.IntField("Calc Subdivs", spline.subdivs); if ( subdivs < 2 ) subdivs = 2; if ( subdivs != spline.subdivs ) spline.CalcLength(subdivs); shape.drawHandles = EditorGUILayout.Toggle("Draw Handles", shape.drawHandles); shape.drawKnots = EditorGUILayout.Toggle("Draw Knots", shape.drawKnots); shape.drawTwist = EditorGUILayout.Toggle("Draw Twist", shape.drawTwist); shape.drawspline = EditorGUILayout.Toggle("Draw Spline", shape.drawspline); shape.showorigin = EditorGUILayout.Toggle("Origin Handle", shape.showorigin); shape.lockhandles = EditorGUILayout.Toggle("Lock Handles", shape.lockhandles); shape.updateondrag = EditorGUILayout.Toggle("Update On Drag", shape.updateondrag); shape.usesnap = EditorGUILayout.BeginToggleGroup("Use Snap", shape.usesnap); shape.usesnaphandles = EditorGUILayout.Toggle("Snap Handles", shape.usesnaphandles); shape.snap = EditorGUILayout.Vector3Field("Snap", shape.snap); if ( shape.snap.x < 0.0f ) shape.snap.x = 0.0f; if ( shape.snap.y < 0.0f ) shape.snap.y = 0.0f; if ( shape.snap.z < 0.0f ) shape.snap.z = 0.0f; EditorGUILayout.EndToggleGroup(); //shape.autosmooth = EditorGUILayout.Toggle("Auto Smooth", shape.autosmooth); //shape.smoothness = EditorGUILayout.FloatField("Smoothness", shape.smoothness); float smoothness = EditorGUILayout.Slider("Smoothness", shape.smoothness, 0.0f, 1.5f); if ( smoothness != shape.smoothness ) { shape.smoothness = smoothness; shape.AutoCurve(); recalc = true; } shape.handleType = (MegaHandleType)EditorGUILayout.EnumPopup("Handle Type", shape.handleType); showlabels = EditorGUILayout.Toggle("Labels", showlabels); bool hidewire1 = EditorGUILayout.Toggle("Hide Wire", hidewire); if ( hidewire1 != hidewire ) { hidewire = hidewire1; EditorUtility.SetSelectedWireframeHidden(shape.GetComponent<Renderer>(), hidewire); } shape.animate = EditorGUILayout.Toggle("Animate", shape.animate); if ( shape.animate ) { shape.time = EditorGUILayout.FloatField("Time", shape.time); shape.MaxTime = EditorGUILayout.FloatField("Loop Time", shape.MaxTime); shape.speed = EditorGUILayout.FloatField("Speed", shape.speed); shape.LoopMode = (MegaRepeatMode)EditorGUILayout.EnumPopup("Loop Mode", shape.LoopMode); } AnimationKeyFrames(shape); if ( shape.splines.Count > 0 ) { if ( spline.outlineSpline != -1 ) { int outlineSpline = EditorGUILayout.IntSlider("Outline Spl", spline.outlineSpline, 0, shape.splines.Count - 1); float outline = EditorGUILayout.FloatField("Outline", spline.outline); if ( outline != spline.outline || outlineSpline != spline.outlineSpline ) { spline.outlineSpline = outlineSpline; spline.outline = outline; if ( outlineSpline != shape.selcurve ) { shape.OutlineSpline(shape.splines[spline.outlineSpline], spline, spline.outline, true); spline.CalcLength(); //10); EditorUtility.SetDirty(target); buildmesh = true; } } } else { outline = EditorGUILayout.FloatField("Outline", outline); if ( GUILayout.Button("Outline") ) { shape.OutlineSpline(shape, shape.selcurve, outline, true); shape.splines[shape.splines.Count - 1].outline = outline; shape.splines[shape.splines.Count - 1].outlineSpline = shape.selcurve; shape.selcurve = shape.splines.Count - 1; EditorUtility.SetDirty(target); buildmesh = true; } } } // Mesher shape.makeMesh = EditorGUILayout.Toggle("Make Mesh", shape.makeMesh); if ( shape.makeMesh ) { shape.meshType = (MeshShapeType)EditorGUILayout.EnumPopup("Mesh Type", shape.meshType); shape.Pivot = EditorGUILayout.Vector3Field("Pivot", shape.Pivot); shape.CalcTangents = EditorGUILayout.Toggle("Calc Tangents", shape.CalcTangents); shape.GenUV = EditorGUILayout.Toggle("Gen UV", shape.GenUV); if ( GUILayout.Button("Build LightMap") ) { MegaShapeLightMapWindow.Init(); } EditorGUILayout.BeginVertical("Box"); switch ( shape.meshType ) { case MeshShapeType.Fill: shape.DoubleSided = EditorGUILayout.Toggle("Double Sided", shape.DoubleSided); shape.Height = EditorGUILayout.FloatField("Height", shape.Height); shape.UseHeightCurve = EditorGUILayout.Toggle("Use Height Crv", shape.UseHeightCurve); if ( shape.UseHeightCurve ) { shape.heightCrv = EditorGUILayout.CurveField("Height Curve", shape.heightCrv); shape.heightOff = EditorGUILayout.Slider("Height Off", shape.heightOff, -1.0f, 1.0f); } shape.mat1 = (Material)EditorGUILayout.ObjectField("Top Mat", shape.mat1, typeof(Material), true); shape.mat2 = (Material)EditorGUILayout.ObjectField("Bot Mat", shape.mat2, typeof(Material), true); shape.mat3 = (Material)EditorGUILayout.ObjectField("Side Mat", shape.mat3, typeof(Material), true); shape.PhysUV = EditorGUILayout.Toggle("Physical UV", shape.PhysUV); shape.UVOffset = EditorGUILayout.Vector2Field("UV Offset", shape.UVOffset); shape.UVRotate = EditorGUILayout.Vector2Field("UV Rotate", shape.UVRotate); shape.UVScale = EditorGUILayout.Vector2Field("UV Scale", shape.UVScale); shape.UVOffset1 = EditorGUILayout.Vector2Field("UV Offset1", shape.UVOffset1); shape.UVRotate1 = EditorGUILayout.Vector2Field("UV Rotate1", shape.UVRotate1); shape.UVScale1 = EditorGUILayout.Vector2Field("UV Scale1", shape.UVScale1); break; case MeshShapeType.Tube: shape.TubeStart = EditorGUILayout.Slider("Start", shape.TubeStart, -1.0f, 2.0f); shape.TubeLength = EditorGUILayout.Slider("Length", shape.TubeLength, 0.0f, 1.0f); shape.rotate = EditorGUILayout.FloatField("Rotate", shape.rotate); shape.tsides = EditorGUILayout.IntField("Sides", shape.tsides); shape.tradius = EditorGUILayout.FloatField("Radius", shape.tradius); shape.offset = EditorGUILayout.FloatField("Offset", shape.offset); shape.scaleX = EditorGUILayout.CurveField("Scale X", shape.scaleX); shape.unlinkScale = EditorGUILayout.BeginToggleGroup("unlink Scale", shape.unlinkScale); shape.scaleY = EditorGUILayout.CurveField("Scale Y", shape.scaleY); EditorGUILayout.EndToggleGroup(); shape.strands = EditorGUILayout.IntField("Strands", shape.strands); if ( shape.strands > 1 ) { shape.strandRadius = EditorGUILayout.FloatField("Strand Radius", shape.strandRadius); shape.TwistPerUnit = EditorGUILayout.FloatField("Twist", shape.TwistPerUnit); shape.startAng = EditorGUILayout.FloatField("Start Twist", shape.startAng); } shape.UVOffset = EditorGUILayout.Vector2Field("UV Offset", shape.UVOffset); shape.uvtilex = EditorGUILayout.FloatField("UV Tile X", shape.uvtilex); shape.uvtiley = EditorGUILayout.FloatField("UV Tile Y", shape.uvtiley); shape.cap = EditorGUILayout.Toggle("Cap", shape.cap); shape.RopeUp = (MegaAxis)EditorGUILayout.EnumPopup("Up", shape.RopeUp); shape.mat1 = (Material)EditorGUILayout.ObjectField("Mat", shape.mat1, typeof(Material), true); shape.flipNormals = EditorGUILayout.Toggle("Flip Normals", shape.flipNormals); break; case MeshShapeType.Ribbon: shape.TubeStart = EditorGUILayout.Slider("Start", shape.TubeStart, -1.0f, 2.0f); shape.TubeLength = EditorGUILayout.Slider("Length", shape.TubeLength, 0.0f, 1.0f); shape.boxwidth = EditorGUILayout.FloatField("Width", shape.boxwidth); shape.raxis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", shape.raxis); shape.rotate = EditorGUILayout.FloatField("Rotate", shape.rotate); shape.ribsegs = EditorGUILayout.IntField("Segs", shape.ribsegs); if ( shape.ribsegs < 1 ) shape.ribsegs = 1; shape.offset = EditorGUILayout.FloatField("Offset", shape.offset); shape.scaleX = EditorGUILayout.CurveField("Scale X", shape.scaleX); shape.strands = EditorGUILayout.IntField("Strands", shape.strands); if ( shape.strands > 1 ) { shape.strandRadius = EditorGUILayout.FloatField("Strand Radius", shape.strandRadius); shape.TwistPerUnit = EditorGUILayout.FloatField("Twist", shape.TwistPerUnit); shape.startAng = EditorGUILayout.FloatField("Start Twist", shape.startAng); } shape.UVOffset = EditorGUILayout.Vector2Field("UV Offset", shape.UVOffset); shape.uvtilex = EditorGUILayout.FloatField("UV Tile X", shape.uvtilex); shape.uvtiley = EditorGUILayout.FloatField("UV Tile Y", shape.uvtiley); shape.RopeUp = (MegaAxis)EditorGUILayout.EnumPopup("Up", shape.RopeUp); shape.mat1 = (Material)EditorGUILayout.ObjectField("Mat", shape.mat1, typeof(Material), true); shape.flipNormals = EditorGUILayout.Toggle("Flip Normals", shape.flipNormals); break; case MeshShapeType.Box: shape.TubeStart = EditorGUILayout.Slider("Start", shape.TubeStart, -1.0f, 2.0f); shape.TubeLength = EditorGUILayout.Slider("Length", shape.TubeLength, 0.0f, 1.0f); shape.rotate = EditorGUILayout.FloatField("Rotate", shape.rotate); shape.boxwidth = EditorGUILayout.FloatField("Box Width", shape.boxwidth); shape.boxheight = EditorGUILayout.FloatField("Box Height", shape.boxheight); shape.offset = EditorGUILayout.FloatField("Offset", shape.offset); shape.scaleX = EditorGUILayout.CurveField("Scale X", shape.scaleX); shape.unlinkScale = EditorGUILayout.BeginToggleGroup("unlink Scale", shape.unlinkScale); shape.scaleY = EditorGUILayout.CurveField("Scale Y", shape.scaleY); EditorGUILayout.EndToggleGroup(); shape.strands = EditorGUILayout.IntField("Strands", shape.strands); if ( shape.strands > 1 ) { shape.tradius = EditorGUILayout.FloatField("Radius", shape.tradius); shape.TwistPerUnit = EditorGUILayout.FloatField("Twist", shape.TwistPerUnit); shape.startAng = EditorGUILayout.FloatField("Start Twist", shape.startAng); } shape.UVOffset = EditorGUILayout.Vector2Field("UV Offset", shape.UVOffset); shape.uvtilex = EditorGUILayout.FloatField("UV Tile X", shape.uvtilex); shape.uvtiley = EditorGUILayout.FloatField("UV Tile Y", shape.uvtiley); shape.cap = EditorGUILayout.Toggle("Cap", shape.cap); shape.RopeUp = (MegaAxis)EditorGUILayout.EnumPopup("Up", shape.RopeUp); shape.mat1 = (Material)EditorGUILayout.ObjectField("Mat", shape.mat1, typeof(Material), true); shape.flipNormals = EditorGUILayout.Toggle("Flip Normals", shape.flipNormals); break; } if ( shape.strands < 1 ) shape.strands = 1; EditorGUILayout.EndVertical(); // Conform shape.conform = EditorGUILayout.BeginToggleGroup("Conform", shape.conform); GameObject contarget = (GameObject)EditorGUILayout.ObjectField("Target", shape.target, typeof(GameObject), true); if ( contarget != shape.target ) shape.SetTarget(contarget); shape.conformAmount = EditorGUILayout.Slider("Amount", shape.conformAmount, 0.0f, 1.0f); shape.raystartoff = EditorGUILayout.FloatField("Ray Start Off", shape.raystartoff); shape.conformOffset = EditorGUILayout.FloatField("Conform Offset", shape.conformOffset); shape.raydist = EditorGUILayout.FloatField("Ray Dist", shape.raydist); EditorGUILayout.EndToggleGroup(); } else { shape.ClearMesh(); } showsplines = EditorGUILayout.Foldout(showsplines, "Spline Data"); if ( showsplines ) { EditorGUILayout.BeginVertical("Box"); if ( shape.splines != null && shape.splines.Count > 0 ) DisplaySpline(shape, shape.splines[shape.selcurve]); EditorGUILayout.EndVertical(); } EditorGUILayout.BeginHorizontal(); Color col = GUI.backgroundColor; GUI.backgroundColor = Color.green; if ( GUILayout.Button("Add") ) { // Create a new spline in the shape MegaSpline spl = MegaSpline.Copy(shape.splines[shape.selcurve]); shape.splines.Add(spl); shape.selcurve = shape.splines.Count - 1; EditorUtility.SetDirty(shape); buildmesh = true; } if ( shape.splines.Count > 1 ) { GUI.backgroundColor = Color.red; if ( GUILayout.Button("Delete") ) { // Delete current spline shape.splines.RemoveAt(shape.selcurve); for ( int i = 0; i < shape.splines.Count; i++ ) { if ( shape.splines[i].outlineSpline == shape.selcurve ) shape.splines[i].outlineSpline = -1; if ( shape.splines[i].outlineSpline > shape.selcurve ) shape.splines[i].outlineSpline--; } shape.selcurve--; if ( shape.selcurve < 0 ) shape.selcurve = 0; EditorUtility.SetDirty(shape); buildmesh = true; } } GUI.backgroundColor = col; EditorGUILayout.EndHorizontal(); } if ( !shape.imported ) { if ( Params() ) { rebuild = true; } } showfuncs = EditorGUILayout.Foldout(showfuncs, "Extra Functions"); if ( showfuncs ) { if ( GUILayout.Button("Flatten") ) { shape.SetHeight(shape.selcurve, 0.0f); shape.CalcLength(); EditorUtility.SetDirty(target); } if ( GUILayout.Button("Remove Twist") ) { shape.SetTwist(shape.selcurve, 0.0f); EditorUtility.SetDirty(target); } if ( GUILayout.Button("Copy IDS") ) { shape.CopyIDS(shape.selcurve); EditorUtility.SetDirty(target); } } export = EditorGUILayout.Foldout(export, "Export Options"); if ( export ) { xaxis = (MegaAxis)EditorGUILayout.EnumPopup("X Axis", xaxis); yaxis = (MegaAxis)EditorGUILayout.EnumPopup("Y Axis", yaxis); strokewidth = EditorGUILayout.FloatField("Stroke Width", strokewidth); strokecol = EditorGUILayout.ColorField("Stroke Color", strokecol); if ( GUILayout.Button("Export") ) { Export(shape); } } if ( recalc ) { shape.CalcLength(); //10); shape.BuildMesh(); MegaLoftLayerSimple[] layers = (MegaLoftLayerSimple[])FindObjectsOfType(typeof(MegaLoftLayerSimple)); for ( int i = 0; i < layers.Length; i++ ) { layers[i].Notify(shape.splines[shape.selcurve], 0); } EditorUtility.SetDirty(shape); } if ( GUI.changed ) { EditorUtility.SetDirty(target); buildmesh = true; } if ( rebuild ) { shape.MakeShape(); EditorUtility.SetDirty(target); buildmesh = true; } if ( buildmesh ) { if ( shape.makeMesh ) { shape.SetMats(); shape.BuildMesh(); } } //undoManager.CheckDirty(); } void DisplayKnot(MegaShape shape, MegaSpline spline, MegaKnot knot, int i) { bool recalc = false; Vector3 p = EditorGUILayout.Vector3Field("Knot [" + i + "] Pos", knot.p); delta = p - knot.p; knot.invec += delta; knot.outvec += delta; if ( knot.p != p ) { recalc = true; knot.p = p; } if ( recalc ) { shape.CalcLength(); //10); } knot.twist = EditorGUILayout.FloatField("Twist", knot.twist); knot.id = EditorGUILayout.IntField("ID", knot.id); } void DisplaySpline(MegaShape shape, MegaSpline spline) { bool closed = EditorGUILayout.Toggle("Closed", spline.closed); if ( closed != spline.closed ) { spline.closed = closed; shape.CalcLength(); //10); EditorUtility.SetDirty(target); //shape.BuildMesh(); } spline.reverse = EditorGUILayout.Toggle("Reverse", spline.reverse); EditorGUILayout.LabelField("Length ", spline.length.ToString("0.000")); spline.twistmode = (MegaShapeEase)EditorGUILayout.EnumPopup("Twist Mode", spline.twistmode); showknots = EditorGUILayout.Foldout(showknots, "Knots"); if ( showknots ) { for ( int i = 0; i < spline.knots.Count; i++ ) { DisplayKnot(shape, spline, spline.knots[i], i); //EditorGUILayout.Separator(); } } } public void OnSceneGUI() { MegaShape shape = (MegaShape)target; bool mouseup = false; bool recalc = false; if ( Event.current.type == EventType.mouseUp ) { mouseup = true; recalc = true; if ( addingknot ) { addingknot = false; MegaKnot knot = new MegaKnot(); knot.p = addpos; knot.id = shape.splines[snum].knots[knum].id; knot.twist = shape.splines[snum].knots[knum].twist; shape.splines[snum].knots.Insert(knum + 1, knot); shape.AutoCurve(shape.splines[snum]); //, knum, knum + 2); shape.CalcLength(); //10); EditorUtility.SetDirty(target); if ( shape.makeMesh ) { shape.SetMats(); shape.BuildMesh(); } } } Handles.matrix = shape.transform.localToWorldMatrix; if ( shape.selcurve > shape.splines.Count - 1 ) shape.selcurve = 0; Vector3 dragplane = Vector3.one; Color nocol = new Color(0, 0, 0, 0); bounds.size = Vector3.zero; Color twistcol = new Color(0.5f, 0.5f, 1.0f, 0.25f); for ( int s = 0; s < shape.splines.Count; s++ ) { for ( int p = 0; p < shape.splines[s].knots.Count; p++ ) { if ( s == shape.selcurve ) { bounds.Encapsulate(shape.splines[s].knots[p].p); } if ( shape.drawKnots && s == shape.selcurve ) { pm = shape.splines[s].knots[p].p; if ( showlabels ) { if ( p == selected && s == shape.selcurve ) { Handles.color = Color.white; Handles.Label(pm, " Selected\n" + pm.ToString("0.000")); } else { Handles.color = shape.KnotCol; Handles.Label(pm, " " + p); } } Handles.color = nocol; Vector3 newp = Vector3.zero; if ( shape.usesnap ) newp = PosHandlesSnap(shape, pm, Quaternion.identity); else newp = PosHandles(shape, pm, Quaternion.identity); if ( newp != pm ) { MegaUndo.SetSnapshotTarget(shape, "Knot Move"); } Vector3 dl = Vector3.Scale(newp - pm, dragplane); shape.splines[s].knots[p].p += dl; //Vector3.Scale(newp - pm, dragplane); shape.splines[s].knots[p].invec += dl; //delta; shape.splines[s].knots[p].outvec += dl; //delta; if ( newp != pm ) { selected = p; recalc = true; } } if ( shape.drawHandles && s == shape.selcurve ) { Handles.color = shape.VecCol; pm = shape.splines[s].knots[p].p; Vector3 ip = shape.splines[s].knots[p].invec; Vector3 op = shape.splines[s].knots[p].outvec; Handles.DrawLine(pm, ip); Handles.DrawLine(pm, op); Handles.color = shape.HandleCol; Vector3 invec = shape.splines[s].knots[p].invec; Handles.color = nocol; Vector3 newinvec = Vector3.zero; if ( shape.usesnaphandles ) newinvec = PosHandlesSnap(shape, invec, Quaternion.identity); else newinvec = PosHandles(shape, invec, Quaternion.identity); if ( newinvec != invec ) //shape.splines[s].knots[p].invec ) { MegaUndo.SetSnapshotTarget(shape, "Handle Move"); } Vector3 dl = Vector3.Scale(newinvec - invec, dragplane); shape.splines[s].knots[p].invec += dl; //Vector3.Scale(newinvec - invec, dragplane); if ( invec != newinvec ) //shape.splines[s].knots[p].invec ) { if ( shape.lockhandles ) { shape.splines[s].knots[p].outvec -= dl; } selected = p; recalc = true; } Vector3 outvec = shape.splines[s].knots[p].outvec; Vector3 newoutvec = Vector3.zero; if ( shape.usesnaphandles ) newoutvec = PosHandlesSnap(shape, outvec, Quaternion.identity); else newoutvec = PosHandles(shape, outvec, Quaternion.identity); if ( newoutvec != outvec ) //shape.splines[s].knots[p].outvec ) { MegaUndo.SetSnapshotTarget(shape, "Handle Move"); } dl = Vector3.Scale(newoutvec - outvec, dragplane); shape.splines[s].knots[p].outvec += dl; if ( outvec != newoutvec ) //shape.splines[s].knots[p].outvec ) { if ( shape.lockhandles ) { shape.splines[s].knots[p].invec -= dl; } selected = p; recalc = true; } Vector3 hp = shape.splines[s].knots[p].invec; if ( selected == p ) Handles.Label(hp, " " + p); hp = shape.splines[s].knots[p].outvec; if ( selected == p ) Handles.Label(hp, " " + p); } // TODO: Draw a wedge to show the twist angle // Twist handles if ( shape.drawTwist && s == shape.selcurve ) { Vector3 np = Vector3.zero; if ( p == 0 || p < shape.splines[s].knots.Count - 2 ) { np = shape.splines[s].knots[p].Interpolate(0.002f, shape.splines[s].knots[p + 1]); np = np - shape.splines[s].knots[p].p; //np = shape.splines[s].knots[p].outvec; //(0.0f, shape.splines[s].knots[p + 1]); //Debug.Log("np " + np); } else { if ( shape.splines[s].closed ) { np = shape.splines[s].knots[p].Interpolate(0.002f, shape.splines[s].knots[0]); np = np - shape.splines[s].knots[p].p; //np = shape.splines[s].knots[p].outvec; //Tangent(0.0f, shape.splines[s].knots[0]); //Debug.Log("np " + np); } else { np = shape.splines[s].knots[p - 1].Interpolate(0.998f, shape.splines[s].knots[p]); np = shape.splines[s].knots[p].p - np; //np = shape.splines[s].knots[p - 1].outvec; //Tangent(0.9999f, shape.splines[s].knots[p]); //Debug.Log("np " + np); } } if ( np == Vector3.zero ) np = Vector3.forward; np = np.normalized; // np holds the tangent so we can align the arc Quaternion fwd = Quaternion.LookRotation(np); Vector3 rg = Vector3.Cross(np, Vector3.up); //Vector3 up = Vector3.Cross(np, rg); Handles.color = twistcol; float twist = shape.splines[s].knots[p].twist; Handles.DrawSolidArc(shape.splines[s].knots[p].p, np, rg, twist, shape.KnotSize * 0.1f); Vector3 tang = new Vector3(0.0f, 0.0f, shape.splines[s].knots[p].twist); Quaternion inrot = fwd * Quaternion.Euler(tang); //Quaternion rot = Handles.RotationHandle(inrot, shape.splines[s].knots[p].p); Handles.color = Color.white; Quaternion rot = Handles.Disc(inrot, shape.splines[s].knots[p].p, np, shape.KnotSize * 0.1f, false, 0.0f); if ( rot != inrot ) { tang = rot.eulerAngles; float diff = (tang.z - shape.splines[s].knots[p].twist); if ( Mathf.Abs(diff) > 0.0001f ) { while ( diff > 180.0f ) diff -= 360.0f; while ( diff < -180.0f ) diff += 360.0f; shape.splines[s].knots[p].twist += diff; recalc = true; } } } // Midpoint add knot code if ( s == shape.selcurve ) { if ( p < shape.splines[s].knots.Count - 1 ) { Handles.color = Color.white; Vector3 mp = shape.splines[s].knots[p].InterpolateCS(0.5f, shape.splines[s].knots[p + 1]); Vector3 mp1 = Handles.FreeMoveHandle(mp, Quaternion.identity, shape.KnotSize * 0.01f, Vector3.zero, Handles.CircleCap); if ( mp1 != mp ) { if ( !addingknot ) { addingknot = true; addpos = mp; knum = p; snum = s; } } } } } } // Draw nearest point (use for adding knot) Vector3 wcp = CursorPos; Vector3 newCursorPos = PosHandles(shape, wcp, Quaternion.identity); if ( newCursorPos != wcp ) { Vector3 cd = newCursorPos - wcp; CursorPos += cd; float calpha = 0.0f; CursorPos = shape.FindNearestPoint(CursorPos, 5, ref CursorKnot, ref CursorTangent, ref calpha); shape.CursorPercent = calpha * 100.0f; } Handles.Label(CursorPos, "Cursor " + shape.CursorPercent.ToString("0.00") + "% - " + CursorPos); // Move whole spline handle if ( shape.showorigin ) { Handles.Label(bounds.min, "Origin"); Vector3 spos = Handles.PositionHandle(bounds.min, Quaternion.identity); if ( spos != bounds.min ) { if ( shape.usesnap ) { if ( shape.snap.x != 0.0f ) spos.x = (int)(spos.x / shape.snap.x) * shape.snap.x; if ( shape.snap.y != 0.0f ) spos.y = (int)(spos.y / shape.snap.y) * shape.snap.y; if ( shape.snap.z != 0.0f ) spos.z = (int)(spos.z / shape.snap.z) * shape.snap.z; } // Move the spline shape.MoveSpline(spos - bounds.min, shape.selcurve, false); recalc = true; } } if ( recalc ) { shape.CalcLength(); //10); if ( shape.updateondrag || (!shape.updateondrag && mouseup) ) { shape.BuildMesh(); MegaLoftLayerSimple[] layers = (MegaLoftLayerSimple[])FindObjectsOfType(typeof(MegaLoftLayerSimple)); for ( int i = 0; i < layers.Length; i++ ) { layers[i].Notify(shape.splines[shape.selcurve], 0); } EditorUtility.SetDirty(shape); } } Handles.matrix = Matrix4x4.identity; //undoManager.CheckDirty(target); // This is wrong gui not changing here if ( GUI.changed ) { MegaUndo.CreateSnapshot(); MegaUndo.RegisterSnapshot(); } MegaUndo.ClearSnapshotTarget(); } Vector3 PosHandlesSnap(MegaShape shape, Vector3 pos, Quaternion q) { switch ( shape.handleType ) { case MegaHandleType.Position: pos = Handles.PositionHandle(pos, q); break; case MegaHandleType.Free: pos = Handles.FreeMoveHandle(pos, q, shape.KnotSize * 0.01f, Vector3.zero, Handles.CircleCap); break; } if ( shape.usesnap ) { if ( shape.snap.x != 0.0f ) pos.x = (int)(pos.x / shape.snap.x) * shape.snap.x; if ( shape.snap.y != 0.0f ) pos.y = (int)(pos.y / shape.snap.y) * shape.snap.y; if ( shape.snap.z != 0.0f ) pos.z = (int)(pos.z / shape.snap.z) * shape.snap.z; } return pos; } Vector3 PosHandles(MegaShape shape, Vector3 pos, Quaternion q) { switch ( shape.handleType ) { case MegaHandleType.Position: pos = Handles.PositionHandle(pos, q); break; case MegaHandleType.Free: pos = Handles.FreeMoveHandle(pos, q, shape.KnotSize * 0.01f, Vector3.zero, Handles.CircleCap); break; } return pos; } #if UNITY_5_1 || UNITY_5_2 [DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.Pickable | GizmoType.InSelectionHierarchy)] #else [DrawGizmo(GizmoType.NotSelected | GizmoType.Pickable | GizmoType.SelectedOrChild)] #endif static void RenderGizmo(MegaShape shape, GizmoType gizmoType) { if ( (gizmoType & GizmoType.Active) != 0 && Selection.activeObject == shape.gameObject ) { if ( shape.splines == null || shape.splines.Count == 0 ) return; DrawGizmos(shape, new Color(1.0f, 1.0f, 1.0f, 1.0f)); Color col = Color.yellow; col.a = 0.5f; Gizmos.color = col; //Color.yellow; CursorPos = shape.InterpCurve3D(shape.selcurve, shape.CursorPercent * 0.01f, true); Gizmos.DrawSphere(shape.transform.TransformPoint(CursorPos), shape.KnotSize * 0.01f); Handles.color = Color.white; if ( shape.handleType == MegaHandleType.Free ) { int s = shape.selcurve; { for ( int p = 0; p < shape.splines[s].knots.Count; p++ ) { if ( shape.drawKnots ) //&& s == shape.selcurve ) { Gizmos.color = Color.green; Gizmos.DrawSphere(shape.transform.TransformPoint(shape.splines[s].knots[p].p), shape.KnotSize * 0.01f); } if ( shape.drawHandles ) { Gizmos.color = Color.red; Gizmos.DrawSphere(shape.transform.TransformPoint(shape.splines[s].knots[p].invec), shape.KnotSize * 0.01f); Gizmos.DrawSphere(shape.transform.TransformPoint(shape.splines[s].knots[p].outvec), shape.KnotSize * 0.01f); } } } } } else DrawGizmos(shape, new Color(1.0f, 1.0f, 1.0f, 0.25f)); if ( Camera.current ) { Vector3 vis = Camera.current.WorldToScreenPoint(shape.transform.position); if ( vis.z > 0.0f ) { Gizmos.DrawIcon(shape.transform.position, "MegaSpherify icon.png", false); Handles.Label(shape.transform.position, " " + shape.name); } } } // Dont want this in here, want in editor // If we go over a knot then should draw to the knot static void DrawGizmos(MegaShape shape, Color modcol1) { if ( ((1 << shape.gameObject.layer) & Camera.current.cullingMask) == 0 ) return; if ( !shape.drawspline ) return; Matrix4x4 tm = shape.transform.localToWorldMatrix; for ( int s = 0; s < shape.splines.Count; s++ ) { float ldist = shape.stepdist * 0.1f; if ( ldist < 0.01f ) ldist = 0.01f; Color modcol = modcol1; if ( s != shape.selcurve && modcol1.a == 1.0f ) modcol.a *= 0.5f; if ( shape.splines[s].length / ldist > 500.0f ) ldist = shape.splines[s].length / 500.0f; float ds = shape.splines[s].length / (shape.splines[s].length / ldist); if ( ds > shape.splines[s].length ) ds = shape.splines[s].length; int c = 0; int k = -1; int lk = -1; Vector3 first = shape.splines[s].Interpolate(0.0f, shape.normalizedInterp, ref lk); for ( float dist = ds; dist < shape.splines[s].length; dist += ds ) { float alpha = dist / shape.splines[s].length; Vector3 pos = shape.splines[s].Interpolate(alpha, shape.normalizedInterp, ref k); if ( (c & 1) == 1 ) Gizmos.color = shape.col1 * modcol; else Gizmos.color = shape.col2 * modcol; if ( k != lk ) { for ( lk = lk + 1; lk <= k; lk++ ) { Gizmos.DrawLine(tm.MultiplyPoint(first), tm.MultiplyPoint(shape.splines[s].knots[lk].p)); first = shape.splines[s].knots[lk].p; } } lk = k; Gizmos.DrawLine(tm.MultiplyPoint(first), tm.MultiplyPoint(pos)); c++; first = pos; } if ( (c & 1) == 1 ) Gizmos.color = shape.col1 * modcol; else Gizmos.color = shape.col2 * modcol; Vector3 lastpos; if ( shape.splines[s].closed ) lastpos = shape.splines[s].Interpolate(0.0f, shape.normalizedInterp, ref k); else lastpos = shape.splines[s].Interpolate(1.0f, shape.normalizedInterp, ref k); Gizmos.DrawLine(tm.MultiplyPoint(first), tm.MultiplyPoint(lastpos)); } } void LoadSVG(float scale) { MegaShape ms = (MegaShape)target; string filename = EditorUtility.OpenFilePanel("SVG File", lastpath, "svg"); if ( filename == null || filename.Length < 1 ) return; lastpath = filename; bool opt = true; if ( ms.splines != null && ms.splines.Count > 0 ) opt = EditorUtility.DisplayDialog("Spline Import Option", "Splines already present, do you want to 'Add' or 'Replace' splines with this file?", "Add", "Replace"); int startspline = 0; if ( opt ) startspline = ms.splines.Count; StreamReader streamReader = new StreamReader(filename); string text = streamReader.ReadToEnd(); streamReader.Close(); MegaShapeSVG svg = new MegaShapeSVG(); svg.importData(text, ms, scale, opt, startspline); //.splines[0]); ms.imported = true; } void LoadSXL(float scale) { MegaShape ms = (MegaShape)target; string filename = EditorUtility.OpenFilePanel("SXL File", lastpath, "sxl"); if ( filename == null || filename.Length < 1 ) return; lastpath = filename; bool opt = true; if ( ms.splines != null && ms.splines.Count > 0 ) opt = EditorUtility.DisplayDialog("Spline Import Option", "Splines already present, do you want to 'Add' or 'Replace' splines with this file?", "Add", "Replace"); int startspline = 0; if ( opt ) startspline = ms.splines.Count; StreamReader streamReader = new StreamReader(filename); string text = streamReader.ReadToEnd(); streamReader.Close(); MegaShapeSXL sxl = new MegaShapeSXL(); sxl.importData(text, ms, scale, opt, startspline); //.splines[0]); ms.imported = true; } void LoadKML(float scale) { MegaShape ms = (MegaShape)target; string filename = EditorUtility.OpenFilePanel("KML File", lastpath, "kml"); if ( filename == null || filename.Length < 1 ) return; lastpath = filename; //bool opt = true; //if ( ms.splines != null && ms.splines.Count > 0 ) // opt = EditorUtility.DisplayDialog("Spline Import Option", "Splines already present, do you want to 'Add' or 'Replace' splines with this file?", "Add", "Replace"); //int startspline = 0; //if ( opt ) // startspline = ms.splines.Count; MegaKML kml = new MegaKML(); kml.KMLDecode(filename); Vector3[] points = kml.GetPoints(ImportScale); ms.BuildSpline(ms.selcurve, points, true); } void LoadShape(float scale) { MegaShape ms = (MegaShape)target; string filename = EditorUtility.OpenFilePanel("Shape File", lastpath, "spl"); if ( filename == null || filename.Length < 1 ) return; lastpath = filename; // Clear what we have bool opt = true; if ( ms.splines != null && ms.splines.Count > 0 ) opt = EditorUtility.DisplayDialog("Spline Import Option", "Splines already present, do you want to 'Add' or 'Replace' splines with this file?", "Add", "Replace"); int startspline = 0; if ( opt ) startspline = ms.splines.Count; else ms.splines.Clear(); ParseFile(filename, ShapeCallback); ms.Scale(scale, startspline); ms.MaxTime = 0.0f; for ( int s = 0; s < ms.splines.Count; s++ ) { if ( ms.splines[s].animations != null ) { for ( int a = 0; a < ms.splines[s].animations.Count; a++ ) { MegaControl con = ms.splines[s].animations[a].con; if ( con != null ) { float t = con.Times[con.Times.Length - 1]; if ( t > ms.MaxTime ) ms.MaxTime = t; } } } } ms.imported = true; } public void ShapeCallback(string classname, BinaryReader br) { switch ( classname ) { case "Shape": LoadShape(br); break; } } public void LoadShape(BinaryReader br) { MegaParse.Parse(br, ParseShape); } public void ParseFile(string assetpath, ParseClassCallbackType cb) { FileStream fs = new FileStream(assetpath, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read); BinaryReader br = new BinaryReader(fs); bool processing = true; while ( processing ) { string classname = MegaParse.ReadString(br); if ( classname == "Done" ) break; int chunkoff = br.ReadInt32(); long fpos = fs.Position; cb(classname, br); fs.Position = fpos + chunkoff; } br.Close(); } static public Vector3 ReadP3(BinaryReader br) { Vector3 p = Vector3.zero; p.x = br.ReadSingle(); p.y = br.ReadSingle(); p.z = br.ReadSingle(); return p; } bool SplineParse(BinaryReader br, string cid) { MegaShape ms = (MegaShape)target; MegaSpline ps = ms.splines[ms.splines.Count - 1]; switch ( cid ) { case "Transform": Vector3 pos = ReadP3(br); Vector3 rot = ReadP3(br); Vector3 scl = ReadP3(br); rot.y = -rot.y; ms.transform.position = pos; ms.transform.rotation = Quaternion.Euler(rot * Mathf.Rad2Deg); ms.transform.localScale = scl; break; case "Flags": int count = br.ReadInt32(); ps.closed = (br.ReadInt32() == 1); count = br.ReadInt32(); ps.knots = new List<MegaKnot>(count); ps.length = 0.0f; break; case "Knots": for ( int i = 0; i < ps.knots.Capacity; i++ ) { MegaKnot pk = new MegaKnot(); pk.p = ReadP3(br); pk.invec = ReadP3(br); pk.outvec = ReadP3(br); pk.seglength = br.ReadSingle(); ps.length += pk.seglength; pk.length = ps.length; ps.knots.Add(pk); } break; } return true; } bool AnimParse(BinaryReader br, string cid) { MegaShape ms = (MegaShape)target; switch ( cid ) { case "V": int v = br.ReadInt32(); ma = new MegaKnotAnim(); int s = ms.GetSpline(v, ref ma); //.s, ref ma.p, ref ma.t); if ( ms.splines[s].animations == null ) ms.splines[s].animations = new List<MegaKnotAnim>(); ms.splines[s].animations.Add(ma); break; case "Anim": ma.con = MegaParseBezVector3Control.LoadBezVector3KeyControl(br); break; } return true; } bool ParseShape(BinaryReader br, string cid) { MegaShape ms = (MegaShape)target; switch ( cid ) { case "Num": int count = br.ReadInt32(); ms.splines = new List<MegaSpline>(count); break; case "Spline": MegaSpline spl = new MegaSpline(); ms.splines.Add(spl); MegaParse.Parse(br, SplineParse); break; case "Anim": MegaParse.Parse(br, AnimParse); break; } return true; } [MenuItem("GameObject/Create MegaShape Prefab")] static void DoCreateSimplePrefabNew() { if ( Selection.activeGameObject != null ) { if ( !Directory.Exists("Assets/MegaPrefabs") ) { AssetDatabase.CreateFolder("Assets", "MegaPrefabs"); //string newFolderPath = AssetDatabase.GUIDToAssetPath(guid); //Debug.Log("folder path " + newFolderPath); } GameObject obj = Selection.activeGameObject; GameObject prefab = PrefabUtility.CreatePrefab("Assets/MegaPrefabs/" + Selection.activeGameObject.name + ".prefab", Selection.activeGameObject); MeshFilter mf = obj.GetComponent<MeshFilter>(); if ( mf ) { MeshFilter newmf = prefab.GetComponent<MeshFilter>(); Mesh mesh = CloneMesh(mf.sharedMesh); mesh.name = obj.name + " copy"; AssetDatabase.AddObjectToAsset(mesh, prefab); //AssetDatabase.CreateAsset(mesh, "Assets/MegaPrefabs/" + Selection.activeGameObject.name + ".asset"); newmf.sharedMesh = mesh; MeshCollider mc = prefab.GetComponent<MeshCollider>(); if ( mc ) { mc.sharedMesh = null; mc.sharedMesh = mesh; } } MegaShapeLoft oldloft = obj.GetComponent<MegaShapeLoft>(); MegaShapeLoft loft = prefab.GetComponent<MegaShapeLoft>(); if ( loft ) { for ( int i = 0; i < loft.Layers.Length; i++ ) loft.Layers[i].CopyLayer(oldloft.Layers[i]); } //PrefabUtility.DisconnectPrefabInstance(prefab); } } static Mesh CloneMesh(Mesh mesh) { Mesh clonemesh = new Mesh(); clonemesh.vertices = mesh.vertices; #if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 clonemesh.uv2 = mesh.uv2; #else clonemesh.uv1 = mesh.uv1; clonemesh.uv2 = mesh.uv2; #endif clonemesh.uv = mesh.uv; clonemesh.normals = mesh.normals; clonemesh.tangents = mesh.tangents; clonemesh.colors = mesh.colors; clonemesh.subMeshCount = mesh.subMeshCount; for ( int s = 0; s < mesh.subMeshCount; s++ ) clonemesh.SetTriangles(mesh.GetTriangles(s), s); clonemesh.boneWeights = mesh.boneWeights; clonemesh.bindposes = mesh.bindposes; clonemesh.name = mesh.name + "_copy"; clonemesh.RecalculateBounds(); return clonemesh; } // Animation keyframe stuff // Need system to grab state of curve void AnimationKeyFrames(MegaShape shape) { MegaSpline spline = shape.splines[shape.selcurve]; shape.showanimations = EditorGUILayout.Foldout(shape.showanimations, "Animations"); if ( shape.showanimations ) { shape.keytime = EditorGUILayout.FloatField("Key Time", shape.keytime); if ( shape.keytime < 0.0f ) shape.keytime = 0.0f; spline.splineanim.Enabled = EditorGUILayout.BeginToggleGroup("Enabled", spline.splineanim.Enabled); EditorGUILayout.BeginHorizontal(); //if ( spline.splineanim == null ) //{ //} //else { //if ( GUILayout.Button("Create") ) //{ //spline.splineanim = new MegaSplineAnim(); //spline.splineanim.Init(spline); //} if ( GUILayout.Button("Add Key") ) { AddKeyFrame(shape, shape.keytime); } if ( GUILayout.Button("Clear") ) { ClearAnim(shape); } //if ( GUILayout.Button("Delete") ) //{ // spline.splineanim = null; //} } EditorGUILayout.EndHorizontal(); //if ( spline.splineanim == null ) // return; // Need to show each keyframe if ( spline.splineanim != null ) { //EditorGUILayout.LabelField("Frames " + spline.splineanim.knots[0].) int nk = spline.splineanim.NumKeys(); float mt = 0.0f; for ( int i = 0; i < nk; i++ ) { EditorGUILayout.BeginHorizontal(); mt = spline.splineanim.GetKeyTime(i); EditorGUILayout.LabelField("" + i, GUILayout.MaxWidth(20)); //" + " Time: " + mt); float t = EditorGUILayout.FloatField("", mt, GUILayout.MaxWidth(100)); if ( t != mt ) spline.splineanim.SetKeyTime(spline, i, t); if ( GUILayout.Button("Delete", GUILayout.MaxWidth(50)) ) spline.splineanim.RemoveKey(i); if ( GUILayout.Button("Update", GUILayout.MaxWidth(50)) ) spline.splineanim.UpdateKey(spline, i); if ( GUILayout.Button("Get", GUILayout.MaxWidth(50)) ) { spline.splineanim.GetKey(spline, i); EditorUtility.SetDirty(target); } EditorGUILayout.EndHorizontal(); } shape.MaxTime = mt; float at = EditorGUILayout.Slider("T", shape.testtime, 0.0f, mt); if ( at != shape.testtime ) { shape.testtime = at; if ( !shape.animate ) { for ( int s = 0; s < shape.splines.Count; s++ ) { if ( shape.splines[s].splineanim != null && shape.splines[s].splineanim.Enabled ) { shape.splines[s].splineanim.GetState1(shape.splines[s], at); shape.splines[s].CalcLength(); //(10); // could use less here } } } } } EditorGUILayout.EndToggleGroup(); } } void ClearAnim(MegaShape shape) { MegaSpline spline = shape.splines[shape.selcurve]; if ( spline.splineanim != null ) { spline.splineanim.Init(spline); } } void AddKeyFrame(MegaShape shape, float t) { MegaSpline spline = shape.splines[shape.selcurve]; //if ( spline.splineanim == null ) //{ //Debug.Log("1"); //MegaSplineAnim sa = new MegaSplineAnim(); //sa.Init(spline); //spline.splineanim = sa; //} //else //{ spline.splineanim.AddState(spline, t); //} } void Export(MegaShape shape) { string filename = EditorUtility.SaveFilePanel("Export Shape to SVG", "", shape.name, ".svg"); if ( filename.Length > 0 ) { string data = MegaShapeSVG.Export(shape, (int)xaxis, (int)yaxis, strokewidth, strokecol); System.IO.File.WriteAllText(filename, data); } } }
/* * 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; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A physical CPU /// First published in XenServer 4.0. /// </summary> public partial class Host_cpu : XenObject<Host_cpu> { #region Constructors public Host_cpu() { } public Host_cpu(string uuid, XenRef<Host> host, long number, string vendor, long speed, string modelname, long family, long model, string stepping, string flags, string features, double utilisation, Dictionary<string, string> other_config) { this.uuid = uuid; this.host = host; this.number = number; this.vendor = vendor; this.speed = speed; this.modelname = modelname; this.family = family; this.model = model; this.stepping = stepping; this.flags = flags; this.features = features; this.utilisation = utilisation; this.other_config = other_config; } /// <summary> /// Creates a new Host_cpu from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Host_cpu(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Host_cpu from a Proxy_Host_cpu. /// </summary> /// <param name="proxy"></param> public Host_cpu(Proxy_Host_cpu proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Host_cpu. /// </summary> public override void UpdateFrom(Host_cpu record) { uuid = record.uuid; host = record.host; number = record.number; vendor = record.vendor; speed = record.speed; modelname = record.modelname; family = record.family; model = record.model; stepping = record.stepping; flags = record.flags; features = record.features; utilisation = record.utilisation; other_config = record.other_config; } internal void UpdateFrom(Proxy_Host_cpu proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); number = proxy.number == null ? 0 : long.Parse(proxy.number); vendor = proxy.vendor == null ? null : proxy.vendor; speed = proxy.speed == null ? 0 : long.Parse(proxy.speed); modelname = proxy.modelname == null ? null : proxy.modelname; family = proxy.family == null ? 0 : long.Parse(proxy.family); model = proxy.model == null ? 0 : long.Parse(proxy.model); stepping = proxy.stepping == null ? null : proxy.stepping; flags = proxy.flags == null ? null : proxy.flags; features = proxy.features == null ? null : proxy.features; utilisation = Convert.ToDouble(proxy.utilisation); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Host_cpu /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("host")) host = Marshalling.ParseRef<Host>(table, "host"); if (table.ContainsKey("number")) number = Marshalling.ParseLong(table, "number"); if (table.ContainsKey("vendor")) vendor = Marshalling.ParseString(table, "vendor"); if (table.ContainsKey("speed")) speed = Marshalling.ParseLong(table, "speed"); if (table.ContainsKey("modelname")) modelname = Marshalling.ParseString(table, "modelname"); if (table.ContainsKey("family")) family = Marshalling.ParseLong(table, "family"); if (table.ContainsKey("model")) model = Marshalling.ParseLong(table, "model"); if (table.ContainsKey("stepping")) stepping = Marshalling.ParseString(table, "stepping"); if (table.ContainsKey("flags")) flags = Marshalling.ParseString(table, "flags"); if (table.ContainsKey("features")) features = Marshalling.ParseString(table, "features"); if (table.ContainsKey("utilisation")) utilisation = Marshalling.ParseDouble(table, "utilisation"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public Proxy_Host_cpu ToProxy() { Proxy_Host_cpu result_ = new Proxy_Host_cpu(); result_.uuid = uuid ?? ""; result_.host = host ?? ""; result_.number = number.ToString(); result_.vendor = vendor ?? ""; result_.speed = speed.ToString(); result_.modelname = modelname ?? ""; result_.family = family.ToString(); result_.model = model.ToString(); result_.stepping = stepping ?? ""; result_.flags = flags ?? ""; result_.features = features ?? ""; result_.utilisation = utilisation; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } public bool DeepEquals(Host_cpu other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._host, other._host) && Helper.AreEqual2(this._number, other._number) && Helper.AreEqual2(this._vendor, other._vendor) && Helper.AreEqual2(this._speed, other._speed) && Helper.AreEqual2(this._modelname, other._modelname) && Helper.AreEqual2(this._family, other._family) && Helper.AreEqual2(this._model, other._model) && Helper.AreEqual2(this._stepping, other._stepping) && Helper.AreEqual2(this._flags, other._flags) && Helper.AreEqual2(this._features, other._features) && Helper.AreEqual2(this._utilisation, other._utilisation) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Host_cpu server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Host_cpu.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given host_cpu. /// First published in XenServer 4.0. /// Deprecated since XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> [Deprecated("XenServer 5.6")] public static Host_cpu get_record(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_record(session.opaque_ref, _host_cpu); else return new Host_cpu(session.XmlRpcProxy.host_cpu_get_record(session.opaque_ref, _host_cpu ?? "").parse()); } /// <summary> /// Get a reference to the host_cpu instance with the specified UUID. /// First published in XenServer 4.0. /// Deprecated since XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> [Deprecated("XenServer 5.6")] public static XenRef<Host_cpu> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Host_cpu>.Create(session.XmlRpcProxy.host_cpu_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static string get_uuid(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_uuid(session.opaque_ref, _host_cpu); else return session.XmlRpcProxy.host_cpu_get_uuid(session.opaque_ref, _host_cpu ?? "").parse(); } /// <summary> /// Get the host field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static XenRef<Host> get_host(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_host(session.opaque_ref, _host_cpu); else return XenRef<Host>.Create(session.XmlRpcProxy.host_cpu_get_host(session.opaque_ref, _host_cpu ?? "").parse()); } /// <summary> /// Get the number field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static long get_number(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_number(session.opaque_ref, _host_cpu); else return long.Parse(session.XmlRpcProxy.host_cpu_get_number(session.opaque_ref, _host_cpu ?? "").parse()); } /// <summary> /// Get the vendor field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static string get_vendor(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_vendor(session.opaque_ref, _host_cpu); else return session.XmlRpcProxy.host_cpu_get_vendor(session.opaque_ref, _host_cpu ?? "").parse(); } /// <summary> /// Get the speed field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static long get_speed(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_speed(session.opaque_ref, _host_cpu); else return long.Parse(session.XmlRpcProxy.host_cpu_get_speed(session.opaque_ref, _host_cpu ?? "").parse()); } /// <summary> /// Get the modelname field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static string get_modelname(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_modelname(session.opaque_ref, _host_cpu); else return session.XmlRpcProxy.host_cpu_get_modelname(session.opaque_ref, _host_cpu ?? "").parse(); } /// <summary> /// Get the family field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static long get_family(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_family(session.opaque_ref, _host_cpu); else return long.Parse(session.XmlRpcProxy.host_cpu_get_family(session.opaque_ref, _host_cpu ?? "").parse()); } /// <summary> /// Get the model field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static long get_model(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_model(session.opaque_ref, _host_cpu); else return long.Parse(session.XmlRpcProxy.host_cpu_get_model(session.opaque_ref, _host_cpu ?? "").parse()); } /// <summary> /// Get the stepping field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static string get_stepping(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_stepping(session.opaque_ref, _host_cpu); else return session.XmlRpcProxy.host_cpu_get_stepping(session.opaque_ref, _host_cpu ?? "").parse(); } /// <summary> /// Get the flags field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static string get_flags(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_flags(session.opaque_ref, _host_cpu); else return session.XmlRpcProxy.host_cpu_get_flags(session.opaque_ref, _host_cpu ?? "").parse(); } /// <summary> /// Get the features field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static string get_features(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_features(session.opaque_ref, _host_cpu); else return session.XmlRpcProxy.host_cpu_get_features(session.opaque_ref, _host_cpu ?? "").parse(); } /// <summary> /// Get the utilisation field of the given host_cpu. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static double get_utilisation(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_utilisation(session.opaque_ref, _host_cpu); else return Convert.ToDouble(session.XmlRpcProxy.host_cpu_get_utilisation(session.opaque_ref, _host_cpu ?? "").parse()); } /// <summary> /// Get the other_config field of the given host_cpu. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> public static Dictionary<string, string> get_other_config(Session session, string _host_cpu) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_other_config(session.opaque_ref, _host_cpu); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.host_cpu_get_other_config(session.opaque_ref, _host_cpu ?? "").parse()); } /// <summary> /// Set the other_config field of the given host_cpu. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _host_cpu, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.host_cpu_set_other_config(session.opaque_ref, _host_cpu, _other_config); else session.XmlRpcProxy.host_cpu_set_other_config(session.opaque_ref, _host_cpu ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given host_cpu. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _host_cpu, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.host_cpu_add_to_other_config(session.opaque_ref, _host_cpu, _key, _value); else session.XmlRpcProxy.host_cpu_add_to_other_config(session.opaque_ref, _host_cpu ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given host_cpu. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_cpu">The opaque_ref of the given host_cpu</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _host_cpu, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.host_cpu_remove_from_other_config(session.opaque_ref, _host_cpu, _key); else session.XmlRpcProxy.host_cpu_remove_from_other_config(session.opaque_ref, _host_cpu ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the host_cpus known to the system. /// First published in XenServer 4.0. /// Deprecated since XenServer 5.6. /// </summary> /// <param name="session">The session</param> [Deprecated("XenServer 5.6")] public static List<XenRef<Host_cpu>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_all(session.opaque_ref); else return XenRef<Host_cpu>.Create(session.XmlRpcProxy.host_cpu_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the host_cpu Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Host_cpu>, Host_cpu> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_cpu_get_all_records(session.opaque_ref); else return XenRef<Host_cpu>.Create<Proxy_Host_cpu>(session.XmlRpcProxy.host_cpu_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// the host the CPU is in /// </summary> [JsonConverter(typeof(XenRefConverter<Host>))] public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host = new XenRef<Host>(Helper.NullOpaqueRef); /// <summary> /// the number of the physical CPU within the host /// </summary> public virtual long number { get { return _number; } set { if (!Helper.AreEqual(value, _number)) { _number = value; NotifyPropertyChanged("number"); } } } private long _number; /// <summary> /// the vendor of the physical CPU /// </summary> public virtual string vendor { get { return _vendor; } set { if (!Helper.AreEqual(value, _vendor)) { _vendor = value; NotifyPropertyChanged("vendor"); } } } private string _vendor = ""; /// <summary> /// the speed of the physical CPU /// </summary> public virtual long speed { get { return _speed; } set { if (!Helper.AreEqual(value, _speed)) { _speed = value; NotifyPropertyChanged("speed"); } } } private long _speed; /// <summary> /// the model name of the physical CPU /// </summary> public virtual string modelname { get { return _modelname; } set { if (!Helper.AreEqual(value, _modelname)) { _modelname = value; NotifyPropertyChanged("modelname"); } } } private string _modelname = ""; /// <summary> /// the family (number) of the physical CPU /// </summary> public virtual long family { get { return _family; } set { if (!Helper.AreEqual(value, _family)) { _family = value; NotifyPropertyChanged("family"); } } } private long _family; /// <summary> /// the model number of the physical CPU /// </summary> public virtual long model { get { return _model; } set { if (!Helper.AreEqual(value, _model)) { _model = value; NotifyPropertyChanged("model"); } } } private long _model; /// <summary> /// the stepping of the physical CPU /// </summary> public virtual string stepping { get { return _stepping; } set { if (!Helper.AreEqual(value, _stepping)) { _stepping = value; NotifyPropertyChanged("stepping"); } } } private string _stepping = ""; /// <summary> /// the flags of the physical CPU (a decoded version of the features field) /// </summary> public virtual string flags { get { return _flags; } set { if (!Helper.AreEqual(value, _flags)) { _flags = value; NotifyPropertyChanged("flags"); } } } private string _flags = ""; /// <summary> /// the physical CPU feature bitmap /// </summary> public virtual string features { get { return _features; } set { if (!Helper.AreEqual(value, _features)) { _features = value; NotifyPropertyChanged("features"); } } } private string _features = ""; /// <summary> /// the current CPU utilisation /// </summary> public virtual double utilisation { get { return _utilisation; } set { if (!Helper.AreEqual(value, _utilisation)) { _utilisation = value; NotifyPropertyChanged("utilisation"); } } } private double _utilisation; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Collections.Generic; using NDesk.Options; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Core.TfsInterop; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("branch")] [Description("branch\n\n" + " * Display inited remote TFS branches:\n git tfs branch\n\n" + " * Display remote TFS branches:\n git tfs branch -r\n git tfs branch -r -all\n\n" + " * Create a TFS branch from current commit:\n git tfs branch $/Repository/ProjectBranchToCreate <myWishedRemoteName> --comment=\"Creation of my branch\"\n\n" + " * Rename a remote branch:\n git tfs branch --move oldTfsRemoteName newTfsRemoteName\n\n" + " * Delete a remote branche:\n git tfs branch --delete tfsRemoteName\n\n" + " * Initialise an existing remote TFS branch:\n git tfs branch --init $/Repository/ProjectBranch\n git tfs branch --init $/Repository/ProjectBranch myNewBranch\n git tfs branch --init --all\n git tfs branch --init --tfs-parent-branch=$/Repository/ProjectParentBranch $/Repository/ProjectBranch\n")] [RequiresValidGitRepository] public class Branch : GitTfsCommand { private Globals globals; private TextWriter stdout; private readonly Help helper; private readonly Cleanup cleanup; private readonly InitBranch initBranch; public bool DisplayRemotes { get; set; } public bool ManageAll { get; set; } public bool ShouldRenameRemote { get; set; } public bool ShouldDeleteRemote { get; set; } public bool ShouldInitBranch { get; set; } public string IgnoreRegex { get; set; } public string ExceptRegex { get; set; } public bool NoFetch { get; set; } public string Comment { get; set; } public string TfsUsername { get; set; } public string TfsPassword { get; set; } public string AuthorsFilePath { get; set; } public string ParentBranch { get; set; } public OptionSet OptionSet { get { return new OptionSet { { "r|remotes", "Display the TFS branches of the current TFS root branch existing on the TFS server", v => DisplayRemotes = (v != null) }, { "all", "Display (used with option --remotes) the TFS branches of all the root branches existing on the TFS server\n or Initialize (used with option --init) all existing TFS branches (For TFS 2010 and later)", v => ManageAll = (v != null) }, { "comment=", "Comment used for the creation of the TFS branch ", v => Comment = v }, { "m|move", "Rename a TFS remote", v => ShouldRenameRemote = (v != null) }, { "delete", "Delete a TFS remote", v => ShouldDeleteRemote = (v != null) }, { "init", "Initialize an existing TFS branch", v => ShouldInitBranch = (v != null) }, { "ignore-regex=", "a regex of files to ignore", v => IgnoreRegex = v }, { "except-regex=", "a regex of exceptions to ignore-regex", v => ExceptRegex = v}, { "no-fetch", "Don't fetch changeset for inited branch(es)", v => NoFetch = (v != null) }, { "b|tfs-parent-branch=", "TFS Parent branch of the TFS branch to clone (TFS 2008 only! And required!!) ex: $/Repository/ProjectParentBranch", v => ParentBranch = v }, { "u|username=", "TFS username", v => TfsUsername = v }, { "p|password=", "TFS password", v => TfsPassword = v }, { "a|authors=", "Path to an Authors file to map TFS users to Git users", v => AuthorsFilePath = v }, } .Merge(globals.OptionSet); } } public Branch(Globals globals, TextWriter stdout, Help helper, Cleanup cleanup, InitBranch initBranch) { this.globals = globals; this.stdout = stdout; this.helper = helper; this.cleanup = cleanup; this.initBranch = initBranch; //[Temporary] Remove in the next version! initBranch.DontDisplayObsoleteMessage = true; } public void SetInitBranchParameters() { initBranch.TfsUsername = TfsUsername; initBranch.TfsPassword = TfsPassword; initBranch.AuthorsFilePath = AuthorsFilePath; initBranch.CloneAllBranches = ManageAll; initBranch.ParentBranch = ParentBranch; initBranch.IgnoreRegex = IgnoreRegex; initBranch.ExceptRegex = ExceptRegex; initBranch.NoFetch = NoFetch; } public bool IsCommandWellUsed() { //Verify that some mutual exclusive options are not used together return new[] {ShouldDeleteRemote, ShouldInitBranch, ShouldRenameRemote}.Count(b => b) <= 1; } public int Run() { if (!IsCommandWellUsed()) return helper.Run(this); if (ShouldRenameRemote || ShouldDeleteRemote) return helper.Run(this); if (ShouldInitBranch) { SetInitBranchParameters(); return initBranch.Run(); } return DisplayBranchData(); } public int Run(string param) { if (!IsCommandWellUsed()) return helper.Run(this); if (ShouldRenameRemote) return helper.Run(this); if (ShouldInitBranch) { SetInitBranchParameters(); return initBranch.Run(param); } if (ShouldDeleteRemote) return DeleteRemote(param); return CreateRemote(param); } public int Run(string param1, string param2) { if (!IsCommandWellUsed()) return helper.Run(this); if (ShouldDeleteRemote) return helper.Run(this); if (ShouldInitBranch) { SetInitBranchParameters(); return initBranch.Run(param1, param2); } if (ShouldRenameRemote) return RenameRemote(param1, param2); return CreateRemote(param1, param2); } private int RenameRemote(string oldRemoteName, string newRemoteName) { var newRemoteNameExpected = globals.Repository.AssertValidBranchName(newRemoteName.ToGitRefName()); if (newRemoteNameExpected != newRemoteName) stdout.WriteLine("The name of the branch after renaming will be : " + newRemoteNameExpected); if (globals.Repository.HasRemote(newRemoteNameExpected)) { throw new GitTfsException("error: this remote name is already used!"); } stdout.WriteLine("Cleaning before processing rename..."); cleanup.Run(); globals.Repository.MoveRemote(oldRemoteName, newRemoteNameExpected); if(globals.Repository.RenameBranch(oldRemoteName, newRemoteName) == null) stdout.WriteLine("warning: no local branch found to rename"); return GitTfsExitCodes.OK; } private int CreateRemote(string tfsPath, string gitBranchNameExpected = null) { tfsPath.AssertValidTfsPath(); Trace.WriteLine("Getting commit informations..."); var commit = globals.Repository.GetCurrentTfsCommit(); if(commit == null) throw new GitTfsException("error : the current commit is not checked in TFS!"); var remote = commit.Remote; Trace.WriteLine("Creating branch in TFS..."); remote.Tfs.CreateBranch(remote.TfsRepositoryPath, tfsPath, (int)commit.ChangesetId, Comment ?? "Creation branch " + tfsPath); Trace.WriteLine("Init branch in local repository..."); return initBranch.Run(tfsPath, gitBranchNameExpected); } private int DeleteRemote(string remoteName) { var remote = globals.Repository.ReadTfsRemote(remoteName); if (remote == null) { throw new GitTfsException(string.Format("Error: Remote \"{0}\" not found!", remoteName)); } stdout.WriteLine("Cleaning before processing delete..."); cleanup.Run(); globals.Repository.DeleteTfsRemote(remote); return GitTfsExitCodes.OK; } public int DisplayBranchData() { // should probably pull this from options so that it is settable from the command-line const string remoteId = GitTfsConstants.DefaultRepositoryId; var tfsRemotes = globals.Repository.ReadAllTfsRemotes(); if (DisplayRemotes) { if (!ManageAll) { var remote = globals.Repository.ReadTfsRemote(remoteId); stdout.WriteLine("\nTFS branch structure:"); WriteRemoteTfsBranchStructure(remote.Tfs, stdout, remote.TfsRepositoryPath, tfsRemotes); return GitTfsExitCodes.OK; } else { var remote = tfsRemotes.First(r => r.Id == remoteId); if (!remote.Tfs.CanGetBranchInformation) { throw new GitTfsException("error: this version of TFS doesn't support this functionality"); } foreach (var branch in remote.Tfs.GetBranches().Where(b=>b.IsRoot)) { var root = remote.Tfs.GetRootTfsBranchForRemotePath(branch.Path); var visitor = new WriteBranchStructureTreeVisitor(remote.TfsRepositoryPath, stdout, tfsRemotes); root.AcceptVisitor(visitor); } return GitTfsExitCodes.OK; } } WriteTfsRemoteDetails(stdout, tfsRemotes); return GitTfsExitCodes.OK; } public static void WriteRemoteTfsBranchStructure(ITfsHelper tfsHelper, TextWriter writer, string tfsRepositoryPath, IEnumerable<IGitTfsRemote> tfsRemotes = null) { var root = tfsHelper.GetRootTfsBranchForRemotePath(tfsRepositoryPath); if (!tfsHelper.CanGetBranchInformation) { throw new GitTfsException("error: this version of TFS doesn't support this functionality"); } var visitor = new WriteBranchStructureTreeVisitor(tfsRepositoryPath, writer, tfsRemotes); root.AcceptVisitor(visitor); } private void WriteTfsRemoteDetails(TextWriter writer, IEnumerable<IGitTfsRemote> tfsRemotes) { writer.WriteLine("\nGit-tfs remote details:"); foreach (var remote in tfsRemotes) { writer.WriteLine("\n {0} -> {1} {2}", remote.Id, remote.TfsUrl, remote.TfsRepositoryPath); writer.WriteLine(" {0} - {1} @ {2}", remote.RemoteRef, remote.MaxCommitHash, remote.MaxChangesetId); } } private class WriteBranchStructureTreeVisitor : IBranchTreeVisitor { private readonly TextWriter _stdout; private readonly string _targetPath; private readonly IEnumerable<IGitTfsRemote> _tfsRemotes; public WriteBranchStructureTreeVisitor(string targetPath, TextWriter writer, IEnumerable<IGitTfsRemote> tfsRemotes = null) { _targetPath = targetPath; _stdout = writer; _tfsRemotes = tfsRemotes; } public void Visit(BranchTree branch, int level) { for (var i = 0; i < level; i++ ) _stdout.Write(" | "); _stdout.WriteLine(); for (var i = 0; i < level - 1; i++) _stdout.Write(" | "); if (level > 0) _stdout.Write(" +-"); _stdout.Write(" {0}", branch.Path); if (_tfsRemotes != null) { var remote = _tfsRemotes.FirstOrDefault(r => r.TfsRepositoryPath == branch.Path); if (remote != null) _stdout.Write(" -> " + remote.Id); } if (branch.Path.Equals(_targetPath)) _stdout.Write(" [*]"); _stdout.WriteLine(); } } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace tk2dEditor.SpriteCollectionEditor { // As nasty as this is, its a necessary evil for backwards compatibility public class SpriteCollectionProxy { public SpriteCollectionProxy() { } public SpriteCollectionProxy(tk2dSpriteCollection obj) { this.obj = obj; CopyFromSource(); } public void CopyFromSource() { this.obj.Upgrade(); // make sure its up to date textureParams = new List<tk2dSpriteCollectionDefinition>(obj.textureParams.Length); foreach (var v in obj.textureParams) { if (v == null) textureParams.Add(null); else { var t = new tk2dSpriteCollectionDefinition(); t.CopyFrom(v); textureParams.Add(t); } } spriteSheets = new List<tk2dSpriteSheetSource>(); if (obj.spriteSheets != null) { foreach (var v in obj.spriteSheets) { if (v == null) spriteSheets.Add(null); else { var t = new tk2dSpriteSheetSource(); t.CopyFrom(v); spriteSheets.Add(t); } } } fonts = new List<tk2dSpriteCollectionFont>(); if (obj.fonts != null) { foreach (var v in obj.fonts) { if (v == null) fonts.Add(null); else { var t = new tk2dSpriteCollectionFont(); t.CopyFrom(v); fonts.Add(t); } } } attachPointTestSprites.Clear(); foreach (var v in obj.attachPointTestSprites) { if (v.spriteCollection != null && v.spriteCollection.IsValidSpriteId(v.spriteId)) { tk2dSpriteCollection.AttachPointTestSprite ap = new tk2dSpriteCollection.AttachPointTestSprite(); ap.CopyFrom(v); attachPointTestSprites[v.attachPointName] = v; } } UpgradeLegacySpriteSheets(); var target = this; var source = obj; target.platforms = new List<tk2dSpriteCollectionPlatform>(); foreach (tk2dSpriteCollectionPlatform plat in source.platforms) { tk2dSpriteCollectionPlatform p = new tk2dSpriteCollectionPlatform(); p.CopyFrom(plat); target.platforms.Add(p); } if (target.platforms.Count == 0) { tk2dSpriteCollectionPlatform plat = new tk2dSpriteCollectionPlatform(); // add a null platform target.platforms.Add(plat); } target.assetName = source.assetName; target.loadable = source.loadable; target.atlasFormat = source.atlasFormat; target.maxTextureSize = source.maxTextureSize; target.forceTextureSize = source.forceTextureSize; target.forcedTextureWidth = source.forcedTextureWidth; target.forcedTextureHeight = source.forcedTextureHeight; target.textureCompression = source.textureCompression; target.atlasWidth = source.atlasWidth; target.atlasHeight = source.atlasHeight; target.forceSquareAtlas = source.forceSquareAtlas; target.atlasWastage = source.atlasWastage; target.allowMultipleAtlases = source.allowMultipleAtlases; target.disableRotation = source.disableRotation; target.removeDuplicates = source.removeDuplicates; target.spriteCollection = source.spriteCollection; target.premultipliedAlpha = source.premultipliedAlpha; CopyArray(ref target.altMaterials, source.altMaterials); CopyArray(ref target.atlasMaterials, source.atlasMaterials); CopyArray(ref target.atlasTextures, source.atlasTextures); CopyArray(ref target.atlasTextureFiles, source.atlasTextureFiles); target.sizeDef.CopyFrom( source.sizeDef ); target.globalScale = source.globalScale; target.globalTextureRescale = source.globalTextureRescale; target.physicsDepth = source.physicsDepth; target.physicsEngine = source.physicsEngine; target.disableTrimming = source.disableTrimming; target.normalGenerationMode = source.normalGenerationMode; target.padAmount = source.padAmount; target.autoUpdate = source.autoUpdate; target.editorDisplayScale = source.editorDisplayScale; // Texture settings target.filterMode = source.filterMode; target.wrapMode = source.wrapMode; target.userDefinedTextureSettings = source.userDefinedTextureSettings; target.mipmapEnabled = source.mipmapEnabled; target.anisoLevel = source.anisoLevel; } void CopyArray<T>(ref T[] dest, T[] source) { if (source == null) { dest = new T[0]; } else { dest = new T[source.Length]; for (int i = 0; i < source.Length; ++i) dest[i] = source[i]; } } void UpgradeLegacySpriteSheets() { if (spriteSheets != null) { for (int i = 0; i < spriteSheets.Count; ++i) { var spriteSheet = spriteSheets[i]; if (spriteSheet != null && spriteSheet.version == 0) { if (spriteSheet.texture == null) { spriteSheet.active = false; } else { spriteSheet.tileWidth = spriteSheet.texture.width / spriteSheet.tilesX; spriteSheet.tileHeight = spriteSheet.texture.height / spriteSheet.tilesY; spriteSheet.active = true; for (int j = 0; j < textureParams.Count; ++j) { var param = textureParams[j]; if (param.fromSpriteSheet && param.texture == spriteSheet.texture) { param.fromSpriteSheet = false; param.hasSpriteSheetId = true; param.spriteSheetId = i; param.spriteSheetX = param.regionId % spriteSheet.tilesX; param.spriteSheetY = param.regionId / spriteSheet.tilesX; } } } spriteSheet.version = tk2dSpriteSheetSource.CURRENT_VERSION; } } } } public void DeleteUnusedData() { foreach (tk2dSpriteCollectionFont font in obj.fonts) { bool found = false; foreach (tk2dSpriteCollectionFont f in fonts) { if (f.data == font.data && f.editorData == font.editorData) { found = true; break; } } if (!found) { tk2dEditorUtility.DeleteAsset(font.data); tk2dEditorUtility.DeleteAsset(font.editorData); } } if (obj.altMaterials != null) { foreach (Material material in obj.altMaterials) { bool found = false; if (altMaterials != null) { foreach (Material m in altMaterials) { if (m == material) { found = true; break; } } } if (!found) tk2dEditorUtility.DeleteAsset(material); } } List<tk2dSpriteCollectionPlatform> platformsToDelete = new List<tk2dSpriteCollectionPlatform>(); if (obj.HasPlatformData && !this.HasPlatformData) { platformsToDelete = new List<tk2dSpriteCollectionPlatform>(obj.platforms); atlasTextures = new Texture2D[0]; // clear all references atlasTextureFiles = new TextAsset[0]; atlasMaterials = new Material[0]; } else if (this.HasPlatformData && !obj.HasPlatformData) { // delete old sprite collection atlases and materials foreach (Material material in obj.atlasMaterials) tk2dEditorUtility.DeleteAsset(material); foreach (Texture2D texture in obj.atlasTextures) tk2dEditorUtility.DeleteAsset(texture); foreach (TextAsset textureFile in obj.atlasTextureFiles) tk2dEditorUtility.DeleteAsset(textureFile); } else if (obj.HasPlatformData && this.HasPlatformData) { foreach (tk2dSpriteCollectionPlatform platform in obj.platforms) { bool found = false; foreach (tk2dSpriteCollectionPlatform p in platforms) { if (p.spriteCollection == platform.spriteCollection) { found = true; break; } } if (!found) // platform existed previously, but does not any more platformsToDelete.Add(platform); } } foreach (tk2dSpriteCollectionPlatform platform in platformsToDelete) { if (platform.spriteCollection == null) continue; tk2dSpriteCollection sc = platform.spriteCollection; string path = AssetDatabase.GetAssetPath(sc.spriteCollection); tk2dEditorUtility.DeleteAsset(sc.spriteCollection); foreach (Material material in sc.atlasMaterials) tk2dEditorUtility.DeleteAsset(material); foreach (Texture2D texture in sc.atlasTextures) tk2dEditorUtility.DeleteAsset(texture); foreach (TextAsset textureFiles in sc.atlasTextureFiles) tk2dEditorUtility.DeleteAsset(textureFiles); foreach (tk2dSpriteCollectionFont font in sc.fonts) { tk2dEditorUtility.DeleteAsset(font.editorData); tk2dEditorUtility.DeleteAsset(font.data); } tk2dEditorUtility.DeleteAsset(sc); string dataDirName = System.IO.Path.GetDirectoryName(path); if (System.IO.Directory.Exists(dataDirName) && System.IO.Directory.GetFiles(dataDirName).Length == 0) AssetDatabase.DeleteAsset(dataDirName); } } public void ClearReferences() { altMaterials = new Material[0]; atlasMaterials = new Material[0]; atlasTextures = new Texture2D[0]; atlasTextureFiles = new TextAsset[0]; spriteCollection = null; obj.altMaterials = new Material[0]; obj.atlasMaterials = new Material[0]; obj.atlasTextures = new Texture2D[0]; obj.atlasTextureFiles = new TextAsset[0]; obj.spriteCollection = null; } public void CopyToTarget() { CopyToTarget(obj); } public void CopyToTarget(tk2dSpriteCollection target) { target.textureParams = textureParams.ToArray(); target.spriteSheets = spriteSheets.ToArray(); target.fonts = fonts.ToArray(); var source = this; target.platforms = new List<tk2dSpriteCollectionPlatform>(); foreach (tk2dSpriteCollectionPlatform plat in source.platforms) { tk2dSpriteCollectionPlatform p = new tk2dSpriteCollectionPlatform(); p.CopyFrom(plat); target.platforms.Add(p); } target.assetName = source.assetName; target.loadable = source.loadable; target.atlasFormat = source.atlasFormat; target.maxTextureSize = source.maxTextureSize; target.forceTextureSize = source.forceTextureSize; target.forcedTextureWidth = source.forcedTextureWidth; target.forcedTextureHeight = source.forcedTextureHeight; target.textureCompression = source.textureCompression; target.atlasWidth = source.atlasWidth; target.atlasHeight = source.atlasHeight; target.forceSquareAtlas = source.forceSquareAtlas; target.atlasWastage = source.atlasWastage; target.allowMultipleAtlases = source.allowMultipleAtlases; target.disableRotation = source.disableRotation; target.removeDuplicates = source.removeDuplicates; target.spriteCollection = source.spriteCollection; target.premultipliedAlpha = source.premultipliedAlpha; CopyArray(ref target.altMaterials, source.altMaterials); CopyArray(ref target.atlasMaterials, source.atlasMaterials); CopyArray(ref target.atlasTextures, source.atlasTextures); CopyArray(ref target.atlasTextureFiles, source.atlasTextureFiles); target.sizeDef.CopyFrom( source.sizeDef ); target.globalScale = source.globalScale; target.globalTextureRescale = source.globalTextureRescale; target.physicsDepth = source.physicsDepth; target.physicsEngine = source.physicsEngine; target.disableTrimming = source.disableTrimming; target.normalGenerationMode = source.normalGenerationMode; target.padAmount = source.padAmount; target.autoUpdate = source.autoUpdate; target.editorDisplayScale = source.editorDisplayScale; // Texture settings target.filterMode = source.filterMode; target.wrapMode = source.wrapMode; target.userDefinedTextureSettings = source.userDefinedTextureSettings; target.mipmapEnabled = source.mipmapEnabled; target.anisoLevel = source.anisoLevel; // Attach point test data // Make sure we only store relevant data HashSet<string> attachPointNames = new HashSet<string>(); foreach (tk2dSpriteCollectionDefinition def in textureParams) { foreach (tk2dSpriteDefinition.AttachPoint ap in def.attachPoints) { attachPointNames.Add(ap.name); } } target.attachPointTestSprites.Clear(); foreach (string name in attachPointTestSprites.Keys) { if (attachPointNames.Contains(name)) { tk2dSpriteCollection.AttachPointTestSprite lut = new tk2dSpriteCollection.AttachPointTestSprite(); lut.CopyFrom( attachPointTestSprites[name] ); lut.attachPointName = name; target.attachPointTestSprites.Add(lut); } } } public bool AllowAltMaterials { get { return !allowMultipleAtlases; } } public int FindOrCreateEmptySpriteSlot() { for (int index = 0; index < textureParams.Count; ++index) { if (textureParams[index].texture == null && textureParams[index].name.Length == 0) return index; } textureParams.Add(new tk2dSpriteCollectionDefinition()); return textureParams.Count - 1; } public int FindOrCreateEmptyFontSlot() { for (int index = 0; index < fonts.Count; ++index) { if (!fonts[index].active) { fonts[index].active = true; return index; } } var font = new tk2dSpriteCollectionFont(); font.active = true; fonts.Add(font); return fonts.Count - 1; } public int FindOrCreateEmptySpriteSheetSlot() { for (int index = 0; index < spriteSheets.Count; ++index) { if (!spriteSheets[index].active) { spriteSheets[index].active = true; spriteSheets[index].version = tk2dSpriteSheetSource.CURRENT_VERSION; return index; } } var spriteSheet = new tk2dSpriteSheetSource(); spriteSheet.active = true; spriteSheet.version = tk2dSpriteSheetSource.CURRENT_VERSION; spriteSheets.Add(spriteSheet); return spriteSheets.Count - 1; } public string FindUniqueTextureName(string name) { int at = name.LastIndexOf('@'); if (at != -1) { name = name.Substring(0, at); } List<string> textureNames = new List<string>(); foreach (var entry in textureParams) { textureNames.Add(entry.name); } if (textureNames.IndexOf(name) == -1) return name; int count = 1; do { string currName = name + " " + count.ToString(); if (textureNames.IndexOf(currName) == -1) return currName; ++count; } while(count < 1024); // arbitrary large number return name; // failed to find a name } public int FindSpriteBySource(Texture2D tex) { for (int i = 0; i < textureParams.Count; ++i) { if (textureParams[i].texture == tex) { return i; } } return -1; } public bool Empty { get { return textureParams.Count == 0 && fonts.Count == 0 && spriteSheets.Count == 0; } } // Call after deleting anything public void Trim() { int lastIndex = textureParams.Count - 1; while (lastIndex >= 0) { if (textureParams[lastIndex].texture != null || textureParams[lastIndex].name.Length > 0) break; lastIndex--; } int count = textureParams.Count - 1 - lastIndex; if (count > 0) { textureParams.RemoveRange( lastIndex + 1, count ); } lastIndex = fonts.Count - 1; while (lastIndex >= 0) { if (fonts[lastIndex].active) break; lastIndex--; } count = fonts.Count - 1 - lastIndex; if (count > 0) fonts.RemoveRange(lastIndex + 1, count); lastIndex = spriteSheets.Count - 1; while (lastIndex >= 0) { if (spriteSheets[lastIndex].active) break; lastIndex--; } count = spriteSheets.Count - 1 - lastIndex; if (count > 0) spriteSheets.RemoveRange(lastIndex + 1, count); lastIndex = atlasMaterials.Length - 1; while (lastIndex >= 0) { if (atlasMaterials[lastIndex] != null) break; lastIndex--; } count = atlasMaterials.Length - 1 - lastIndex; if (count > 0) System.Array.Resize(ref atlasMaterials, lastIndex + 1); } public int GetSpriteSheetId(tk2dSpriteSheetSource spriteSheet) { for (int index = 0; index < spriteSheets.Count; ++index) if (spriteSheets[index] == spriteSheet) return index; return 0; } // Delete all sprites from a spritesheet public void DeleteSpriteSheet(tk2dSpriteSheetSource spriteSheet) { int index = GetSpriteSheetId(spriteSheet); for (int i = 0; i < textureParams.Count; ++i) { if (textureParams[i].hasSpriteSheetId && textureParams[i].spriteSheetId == index) { textureParams[i] = new tk2dSpriteCollectionDefinition(); } } spriteSheets[index] = new tk2dSpriteSheetSource(); Trim(); } public string GetAssetPath() { return AssetDatabase.GetAssetPath(obj); } public string GetOrCreateDataPath() { return tk2dSpriteCollectionBuilder.GetOrCreateDataPath(obj); } public bool Ready { get { return obj != null; } } tk2dSpriteCollection obj; // Mirrored data objects public List<tk2dSpriteCollectionDefinition> textureParams = new List<tk2dSpriteCollectionDefinition>(); public List<tk2dSpriteSheetSource> spriteSheets = new List<tk2dSpriteSheetSource>(); public List<tk2dSpriteCollectionFont> fonts = new List<tk2dSpriteCollectionFont>(); // Mirrored from sprite collection public string assetName; public int maxTextureSize; public tk2dSpriteCollection.TextureCompression textureCompression; public int atlasWidth, atlasHeight; public bool forceSquareAtlas; public float atlasWastage; public bool allowMultipleAtlases; public bool disableRotation; public bool removeDuplicates; public tk2dSpriteCollectionData spriteCollection; public bool premultipliedAlpha; public List<tk2dSpriteCollectionPlatform> platforms = new List<tk2dSpriteCollectionPlatform>(); public bool HasPlatformData { get { return platforms.Count > 1; } } public Material[] altMaterials; public Material[] atlasMaterials; public Texture2D[] atlasTextures; public TextAsset[] atlasTextureFiles; public tk2dSpriteCollectionSize sizeDef = new tk2dSpriteCollectionSize(); public float globalScale; public float globalTextureRescale; // Attach point test data public Dictionary<string, tk2dSpriteCollection.AttachPointTestSprite> attachPointTestSprites = new Dictionary<string, tk2dSpriteCollection.AttachPointTestSprite>(); // Texture settings public FilterMode filterMode; public TextureWrapMode wrapMode; public bool userDefinedTextureSettings; public bool mipmapEnabled = true; public int anisoLevel = 1; public tk2dSpriteDefinition.PhysicsEngine physicsEngine; public float physicsDepth; public bool disableTrimming; public bool forceTextureSize = false; public int forcedTextureWidth = 1024; public int forcedTextureHeight = 1024; public tk2dSpriteCollection.NormalGenerationMode normalGenerationMode; public int padAmount; public bool autoUpdate; public bool loadable; public tk2dSpriteCollection.AtlasFormat atlasFormat; public float editorDisplayScale; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.PetstoreV2.Models { using PetstoreV2; using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; public partial class Pet { /// <summary> /// Initializes a new instance of the Pet class. /// </summary> public Pet() { } /// <summary> /// Initializes a new instance of the Pet class. /// </summary> /// <param name="status">pet status in the store. Possible values /// include: 'available', 'pending', 'sold'</param> public Pet(string name, IList<string> photoUrls, long? id = default(long?), Category category = default(Category), IList<Tag> tags = default(IList<Tag>), byte[] sByteProperty = default(byte[]), System.DateTime? birthday = default(System.DateTime?), IDictionary<string, Category> dictionary = default(IDictionary<string, Category>), string status = default(string)) { Id = id; Category = category; Name = name; PhotoUrls = photoUrls; Tags = tags; SByteProperty = sByteProperty; Birthday = birthday; Dictionary = dictionary; Status = status; } /// <summary> /// </summary> [JsonProperty(PropertyName = "id")] public long? Id { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "category")] public Category Category { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "photoUrls")] public IList<string> PhotoUrls { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "tags")] public IList<Tag> Tags { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sByte")] public byte[] SByteProperty { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "birthday")] public System.DateTime? Birthday { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "dictionary")] public IDictionary<string, Category> Dictionary { get; set; } /// <summary> /// Gets or sets pet status in the store. Possible values include: /// 'available', 'pending', 'sold' /// </summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Name"); } if (PhotoUrls == null) { throw new ValidationException(ValidationRules.CannotBeNull, "PhotoUrls"); } } /// <summary> /// Serializes the object to an XML node /// </summary> internal XElement XmlSerialize(XElement result) { if( null != Id ) { result.Add(new XElement("id", Id) ); } if( null != Category ) { result.Add(Category.XmlSerialize(new XElement( "category" ))); } if( null != Name ) { result.Add(new XElement("name", Name) ); } if( null != PhotoUrls ) { var seq = new XElement("photoUrl"); foreach( var value in PhotoUrls ){ seq.Add(new XElement( "photoUrl", value ) ); } result.Add(seq); } if( null != Tags ) { var seq = new XElement("tag"); foreach( var value in Tags ){ seq.Add(value.XmlSerialize( new XElement( "tag") ) ); } result.Add(seq); } if( null != SByteProperty ) { result.Add(new XElement("sByte", SByteProperty) ); } if( null != Birthday ) { result.Add(new XElement("birthday", Birthday) ); } if( null != Dictionary ) { var dict = new XElement("dictionary"); foreach( var key in Dictionary.Keys ) { dict.Add(Dictionary[key].XmlSerialize(new XElement(key) ) ); } result.Add(dict); } if( null != Status ) { result.Add(new XElement("status", Status) ); } return result; } /// <summary> /// Deserializes an XML node to an instance of Pet /// </summary> internal static Pet XmlDeserialize(string payload) { // deserialize to xml and use the overload to do the work return XmlDeserialize( XElement.Parse( payload ) ); } internal static Pet XmlDeserialize(XElement payload) { var result = new Pet(); var deserializeId = XmlSerialization.ToDeserializer(e => (long?)e); long? resultId; if (deserializeId(payload, "id", out resultId)) { result.Id = resultId; } var deserializeCategory = XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e)); Category resultCategory; if (deserializeCategory(payload, "category", out resultCategory)) { result.Category = resultCategory; } var deserializeName = XmlSerialization.ToDeserializer(e => (string)e); string resultName; if (deserializeName(payload, "name", out resultName)) { result.Name = resultName; } var deserializePhotoUrls = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => (string)e), "photoUrl"); IList<string> resultPhotoUrls; if (deserializePhotoUrls(payload, "photoUrl", out resultPhotoUrls)) { result.PhotoUrls = resultPhotoUrls; } var deserializeTags = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => Tag.XmlDeserialize(e)), "tag"); IList<Tag> resultTags; if (deserializeTags(payload, "tag", out resultTags)) { result.Tags = resultTags; } var deserializeSByteProperty = XmlSerialization.ToDeserializer(e => System.Convert.FromBase64String(e.Value)); byte[] resultSByteProperty; if (deserializeSByteProperty(payload, "sByte", out resultSByteProperty)) { result.SByteProperty = resultSByteProperty; } var deserializeBirthday = XmlSerialization.ToDeserializer(e => (System.DateTime?)e); System.DateTime? resultBirthday; if (deserializeBirthday(payload, "birthday", out resultBirthday)) { result.Birthday = resultBirthday; } var deserializeDictionary = XmlSerialization.CreateDictionaryXmlDeserializer(XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e))); IDictionary<string, Category> resultDictionary; if (deserializeDictionary(payload, "dictionary", out resultDictionary)) { result.Dictionary = resultDictionary; } var deserializeStatus = XmlSerialization.ToDeserializer(e => (string)e); string resultStatus; if (deserializeStatus(payload, "status", out resultStatus)) { result.Status = resultStatus; } return result; } } }
/* * Validator.cs - Implementation of the * System.CodeDom.Compiler.Validator class. * * Copyright (C) 2002, 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.CodeDom.Compiler { #if CONFIG_CODEDOM using System.IO; using System.Reflection; using System.Globalization; using System.Collections; // Helper class for validating the contents of a CodeDom tree. internal sealed class Validator { // Validate an identifier. private static void ValidateIdentifier(String value) { if(!CodeGenerator.IsValidLanguageIndependentIdentifier(value)) { throw new ArgumentException(S._("Arg_InvalidIdentifier")); } } // Validate a qualified identifier. private static void ValidateQualifiedIdentifier (String value, bool canBeNull) { if(value == null) { if(!canBeNull) { throw new ArgumentException (S._("Arg_InvalidIdentifier")); } } else { int posn = 0; int index; String component; while((index = value.IndexOf('.', posn)) != -1) { component = value.Substring(posn, index - posn); ValidateIdentifier(component); posn = index + 1; } component = value.Substring(posn); ValidateIdentifier(component); } } // Validate a code object. public static void Validate(Object e) { if(e == null) { // Nothing to do here. } else if(e is ICollection) { IEnumerator en = ((ICollection)e).GetEnumerator(); while(en.MoveNext()) { Validate(en.Current); } } else if(e is CodeArrayCreateExpression) { Validate(((CodeArrayCreateExpression)e).CreateType); Validate(((CodeArrayCreateExpression)e).Initializers); Validate(((CodeArrayCreateExpression)e).SizeExpression); } else if(e is CodeAttachEventStatement) { Validate(((CodeAttachEventStatement)e).Event); Validate(((CodeAttachEventStatement)e).Listener); } else if(e is CodeCastExpression) { Validate(((CodeCastExpression)e).TargetType); Validate(((CodeCastExpression)e).Expression); } else if(e is CodeCatchClause) { ValidateIdentifier(((CodeCatchClause)e).LocalName); Validate(((CodeCatchClause)e).CatchExceptionType); Validate(((CodeCatchClause)e).Statements); } else if(e is CodeConditionStatement) { Validate(((CodeConditionStatement)e).Condition); Validate(((CodeConditionStatement)e).TrueStatements); Validate(((CodeConditionStatement)e).FalseStatements); } else if(e is CodeGotoStatement) { ValidateIdentifier(((CodeGotoStatement)e).Label); } else if(e is CodeMemberEvent) { Validate(((CodeMemberEvent)e).CustomAttributes); ValidateIdentifier(((CodeMemberEvent)e).Name); Validate(((CodeMemberEvent)e).ImplementationTypes); Validate(((CodeMemberEvent)e).PrivateImplementationType); Validate(((CodeMemberEvent)e).Type); } else if(e is CodeMemberField) { Validate(((CodeMemberField)e).CustomAttributes); ValidateIdentifier(((CodeMemberField)e).Name); Validate(((CodeMemberField)e).Type); Validate(((CodeMemberField)e).InitExpression); } else if(e is CodeConstructor) { Validate(((CodeConstructor)e).CustomAttributes); ValidateIdentifier(((CodeConstructor)e).Name); Validate(((CodeConstructor)e).ImplementationTypes); Validate(((CodeConstructor)e).Parameters); Validate(((CodeConstructor)e).PrivateImplementationType); Validate(((CodeConstructor)e).ReturnType); Validate(((CodeConstructor)e).ReturnTypeCustomAttributes); Validate(((CodeConstructor)e).Statements); Validate(((CodeConstructor)e).BaseConstructorArgs); Validate(((CodeConstructor)e).ChainedConstructorArgs); } else if(e is CodeMemberMethod) { Validate(((CodeMemberMethod)e).CustomAttributes); ValidateIdentifier(((CodeMemberMethod)e).Name); Validate(((CodeMemberMethod)e).ImplementationTypes); Validate(((CodeMemberMethod)e).Parameters); Validate(((CodeMemberMethod)e).PrivateImplementationType); Validate(((CodeMemberMethod)e).ReturnType); Validate(((CodeMemberMethod)e).ReturnTypeCustomAttributes); Validate(((CodeMemberMethod)e).Statements); } else if(e is CodeMemberProperty) { Validate(((CodeMemberProperty)e).CustomAttributes); ValidateIdentifier(((CodeMemberProperty)e).Name); Validate(((CodeMemberProperty)e).GetStatements); Validate(((CodeMemberProperty)e).ImplementationTypes); Validate(((CodeMemberProperty)e).Parameters); Validate(((CodeMemberProperty)e).PrivateImplementationType); Validate(((CodeMemberProperty)e).SetStatements); Validate(((CodeMemberProperty)e).Type); } else if(e is CodeMethodInvokeExpression) { Validate(((CodeMethodInvokeExpression)e).Method); Validate(((CodeMethodInvokeExpression)e).Parameters); } else if(e is CodeNamespace) { Validate(((CodeNamespace)e).Imports); ValidateQualifiedIdentifier(((CodeNamespace)e).Name, false); Validate(((CodeNamespace)e).Types); } else if(e is CodeNamespaceImport) { ValidateQualifiedIdentifier (((CodeNamespaceImport)e).Namespace, false); } else if(e is CodeObjectCreateExpression) { Validate(((CodeObjectCreateExpression)e).CreateType); Validate(((CodeObjectCreateExpression)e).Parameters); } else if(e is CodeParameterDeclarationExpression) { Validate(((CodeParameterDeclarationExpression)e) .CustomAttributes); ValidateIdentifier (((CodeParameterDeclarationExpression)e).Name); Validate(((CodeParameterDeclarationExpression)e).Type); } else if(e is CodeRemoveEventStatement) { Validate(((CodeRemoveEventStatement)e).Event); Validate(((CodeRemoveEventStatement)e).Listener); } else if(e is CodeTypeDelegate) { Validate(((CodeTypeDelegate)e).CustomAttributes); ValidateIdentifier(((CodeTypeDelegate)e).Name); Validate(((CodeTypeDelegate)e).BaseTypes); Validate(((CodeTypeDelegate)e).Members); Validate(((CodeTypeDelegate)e).Parameters); Validate(((CodeTypeDelegate)e).ReturnType); } else if(e is CodeTypeDeclaration) { Validate(((CodeTypeDeclaration)e).CustomAttributes); ValidateIdentifier(((CodeTypeDeclaration)e).Name); Validate(((CodeTypeDeclaration)e).BaseTypes); Validate(((CodeTypeDeclaration)e).Members); } else if(e is CodeTypeOfExpression) { Validate(((CodeTypeOfExpression)e).Type); } else if(e is CodeTypeReference) { Validate(((CodeTypeReference)e).ArrayElementType); ValidateQualifiedIdentifier (((CodeTypeReference)e).BaseType, true); } else if(e is CodeTypeReferenceExpression) { Validate(((CodeTypeReferenceExpression)e).Type); } else if(e is CodeVariableDeclarationStatement) { Validate (((CodeVariableDeclarationStatement)e).InitExpression); ValidateIdentifier (((CodeVariableDeclarationStatement)e).Name); Validate(((CodeVariableDeclarationStatement)e).Type); } else if(e is CodeArgumentReferenceExpression) { ValidateIdentifier (((CodeArgumentReferenceExpression)e).ParameterName); } else if(e is CodeArrayIndexerExpression) { Validate(((CodeArrayIndexerExpression)e).TargetObject); Validate(((CodeArrayIndexerExpression)e).Indices); } else if(e is CodeAssignStatement) { Validate(((CodeAssignStatement)e).Left); Validate(((CodeAssignStatement)e).Right); } else if(e is CodeAttributeArgument) { ValidateIdentifier(((CodeAttributeArgument)e).Name); Validate(((CodeAttributeArgument)e).Value); } else if(e is CodeAttributeDeclaration) { ValidateIdentifier(((CodeAttributeDeclaration)e).Name); Validate(((CodeAttributeDeclaration)e).Arguments); } else if(e is CodeBinaryOperatorExpression) { Validate(((CodeBinaryOperatorExpression)e).Left); Validate(((CodeBinaryOperatorExpression)e).Right); } else if(e is CodeCompileUnit) { Validate(((CodeCompileUnit)e).AssemblyCustomAttributes); Validate(((CodeCompileUnit)e).Namespaces); } else if(e is CodeDelegateCreateExpression) { Validate(((CodeDelegateCreateExpression)e).DelegateType); Validate(((CodeDelegateCreateExpression)e).TargetObject); ValidateIdentifier (((CodeDelegateCreateExpression)e).MethodName); } else if(e is CodeDelegateInvokeExpression) { Validate(((CodeDelegateInvokeExpression)e).TargetObject); Validate(((CodeDelegateInvokeExpression)e).Parameters); } else if(e is CodeDirectionExpression) { Validate(((CodeDirectionExpression)e).Expression); } else if(e is CodeEventReferenceExpression) { Validate(((CodeEventReferenceExpression)e).TargetObject); ValidateIdentifier (((CodeEventReferenceExpression)e).EventName); } else if(e is CodeExpressionStatement) { Validate(((CodeExpressionStatement)e).Expression); } else if(e is CodeFieldReferenceExpression) { Validate(((CodeFieldReferenceExpression)e).TargetObject); ValidateIdentifier (((CodeFieldReferenceExpression)e).FieldName); } else if(e is CodeIndexerExpression) { Validate(((CodeIndexerExpression)e).TargetObject); Validate(((CodeIndexerExpression)e).Indices); } else if(e is CodeIterationStatement) { Validate(((CodeIterationStatement)e).InitStatement); Validate(((CodeIterationStatement)e).TestExpression); Validate(((CodeIterationStatement)e).IncrementStatement); Validate(((CodeIterationStatement)e).Statements); } else if(e is CodeLabeledStatement) { ValidateIdentifier(((CodeLabeledStatement)e).Label); Validate(((CodeLabeledStatement)e).Statement); } else if(e is CodeMethodReferenceExpression) { Validate(((CodeMethodReferenceExpression)e).TargetObject); ValidateIdentifier (((CodeMethodReferenceExpression)e).MethodName); } else if(e is CodeMethodReturnStatement) { Validate(((CodeMethodReturnStatement)e).Expression); } else if(e is CodePropertyReferenceExpression) { Validate(((CodePropertyReferenceExpression)e).TargetObject); ValidateIdentifier (((CodePropertyReferenceExpression)e).PropertyName); } else if(e is CodeThrowExceptionStatement) { Validate(((CodeThrowExceptionStatement)e).ToThrow); } else if(e is CodeTryCatchFinallyStatement) { Validate(((CodeTryCatchFinallyStatement)e).TryStatements); Validate(((CodeTryCatchFinallyStatement)e).CatchClauses); Validate (((CodeTryCatchFinallyStatement)e).FinallyStatements); } else if(e is CodeVariableReferenceExpression) { ValidateIdentifier (((CodeVariableReferenceExpression)e).VariableName); } } }; // class Validator #endif // CONFIG_CODEDOM }; // namespace System.CodeDom.Compiler
// 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.Net.Http.HPack; using System.Runtime.InteropServices; namespace System.Net.Http.Headers { internal static class KnownHeaders { // If you add a new entry here, you need to add it to TryGetKnownHeader below as well. public static readonly KnownHeader Accept = new KnownHeader("Accept", HttpHeaderType.Request, MediaTypeHeaderParser.MultipleValuesParser, null, StaticTable.Accept); public static readonly KnownHeader AcceptCharset = new KnownHeader("Accept-Charset", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser, null, StaticTable.AcceptCharset); public static readonly KnownHeader AcceptEncoding = new KnownHeader("Accept-Encoding", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser, null, StaticTable.AcceptEncoding); public static readonly KnownHeader AcceptLanguage = new KnownHeader("Accept-Language", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser, null, StaticTable.AcceptLanguage); public static readonly KnownHeader AcceptPatch = new KnownHeader("Accept-Patch"); public static readonly KnownHeader AcceptRanges = new KnownHeader("Accept-Ranges", HttpHeaderType.Response, GenericHeaderParser.TokenListParser, null, StaticTable.AcceptRanges); public static readonly KnownHeader AccessControlAllowCredentials = new KnownHeader("Access-Control-Allow-Credentials"); public static readonly KnownHeader AccessControlAllowHeaders = new KnownHeader("Access-Control-Allow-Headers"); public static readonly KnownHeader AccessControlAllowMethods = new KnownHeader("Access-Control-Allow-Methods"); public static readonly KnownHeader AccessControlAllowOrigin = new KnownHeader("Access-Control-Allow-Origin", StaticTable.AccessControlAllowOrigin); public static readonly KnownHeader AccessControlExposeHeaders = new KnownHeader("Access-Control-Expose-Headers"); public static readonly KnownHeader AccessControlMaxAge = new KnownHeader("Access-Control-Max-Age"); public static readonly KnownHeader Age = new KnownHeader("Age", HttpHeaderType.Response, TimeSpanHeaderParser.Parser, null, StaticTable.Age); public static readonly KnownHeader Allow = new KnownHeader("Allow", HttpHeaderType.Content, GenericHeaderParser.TokenListParser, null, StaticTable.Allow); public static readonly KnownHeader AltSvc = new KnownHeader("Alt-Svc"); public static readonly KnownHeader Authorization = new KnownHeader("Authorization", HttpHeaderType.Request, GenericHeaderParser.SingleValueAuthenticationParser, null, StaticTable.Authorization); public static readonly KnownHeader CacheControl = new KnownHeader("Cache-Control", HttpHeaderType.General, CacheControlHeaderParser.Parser, null, StaticTable.CacheControl); public static readonly KnownHeader Connection = new KnownHeader("Connection", HttpHeaderType.General, GenericHeaderParser.TokenListParser, new string[] { "close" }); public static readonly KnownHeader ContentDisposition = new KnownHeader("Content-Disposition", HttpHeaderType.Content, GenericHeaderParser.ContentDispositionParser, null, StaticTable.ContentDisposition); public static readonly KnownHeader ContentEncoding = new KnownHeader("Content-Encoding", HttpHeaderType.Content, GenericHeaderParser.TokenListParser, new string[] { "gzip", "deflate" }, StaticTable.ContentEncoding); public static readonly KnownHeader ContentLanguage = new KnownHeader("Content-Language", HttpHeaderType.Content, GenericHeaderParser.TokenListParser, null, StaticTable.ContentLanguage); public static readonly KnownHeader ContentLength = new KnownHeader("Content-Length", HttpHeaderType.Content, Int64NumberHeaderParser.Parser, null, StaticTable.ContentLength); public static readonly KnownHeader ContentLocation = new KnownHeader("Content-Location", HttpHeaderType.Content, UriHeaderParser.RelativeOrAbsoluteUriParser, null, StaticTable.ContentLocation); public static readonly KnownHeader ContentMD5 = new KnownHeader("Content-MD5", HttpHeaderType.Content, ByteArrayHeaderParser.Parser); public static readonly KnownHeader ContentRange = new KnownHeader("Content-Range", HttpHeaderType.Content, GenericHeaderParser.ContentRangeParser, null, StaticTable.ContentRange); public static readonly KnownHeader ContentSecurityPolicy = new KnownHeader("Content-Security-Policy"); public static readonly KnownHeader ContentType = new KnownHeader("Content-Type", HttpHeaderType.Content, MediaTypeHeaderParser.SingleValueParser, null, StaticTable.ContentType); public static readonly KnownHeader Cookie = new KnownHeader("Cookie", StaticTable.Cookie); public static readonly KnownHeader Cookie2 = new KnownHeader("Cookie2"); public static readonly KnownHeader Date = new KnownHeader("Date", HttpHeaderType.General, DateHeaderParser.Parser, null, StaticTable.Date); public static readonly KnownHeader ETag = new KnownHeader("ETag", HttpHeaderType.Response, GenericHeaderParser.SingleValueEntityTagParser, null, StaticTable.ETag); public static readonly KnownHeader Expect = new KnownHeader("Expect", HttpHeaderType.Request, GenericHeaderParser.MultipleValueNameValueWithParametersParser, new string[] { "100-continue" }, StaticTable.Expect); public static readonly KnownHeader Expires = new KnownHeader("Expires", HttpHeaderType.Content, DateHeaderParser.Parser, null, StaticTable.Expires); public static readonly KnownHeader From = new KnownHeader("From", HttpHeaderType.Request, GenericHeaderParser.MailAddressParser, null, StaticTable.From); public static readonly KnownHeader Host = new KnownHeader("Host", HttpHeaderType.Request, GenericHeaderParser.HostParser, null, StaticTable.Host); public static readonly KnownHeader IfMatch = new KnownHeader("If-Match", HttpHeaderType.Request, GenericHeaderParser.MultipleValueEntityTagParser, null, StaticTable.IfMatch); public static readonly KnownHeader IfModifiedSince = new KnownHeader("If-Modified-Since", HttpHeaderType.Request, DateHeaderParser.Parser, null, StaticTable.IfModifiedSince); public static readonly KnownHeader IfNoneMatch = new KnownHeader("If-None-Match", HttpHeaderType.Request, GenericHeaderParser.MultipleValueEntityTagParser, null, StaticTable.IfNoneMatch); public static readonly KnownHeader IfRange = new KnownHeader("If-Range", HttpHeaderType.Request, GenericHeaderParser.RangeConditionParser, null, StaticTable.IfRange); public static readonly KnownHeader IfUnmodifiedSince = new KnownHeader("If-Unmodified-Since", HttpHeaderType.Request, DateHeaderParser.Parser, null, StaticTable.IfUnmodifiedSince); public static readonly KnownHeader KeepAlive = new KnownHeader("Keep-Alive"); public static readonly KnownHeader LastModified = new KnownHeader("Last-Modified", HttpHeaderType.Content, DateHeaderParser.Parser, null, StaticTable.LastModified); public static readonly KnownHeader Link = new KnownHeader("Link", StaticTable.Link); public static readonly KnownHeader Location = new KnownHeader("Location", HttpHeaderType.Response, UriHeaderParser.RelativeOrAbsoluteUriParser, null, StaticTable.Location); public static readonly KnownHeader MaxForwards = new KnownHeader("Max-Forwards", HttpHeaderType.Request, Int32NumberHeaderParser.Parser, null, StaticTable.MaxForwards); public static readonly KnownHeader Origin = new KnownHeader("Origin"); public static readonly KnownHeader P3P = new KnownHeader("P3P"); public static readonly KnownHeader Pragma = new KnownHeader("Pragma", HttpHeaderType.General, GenericHeaderParser.MultipleValueNameValueParser); public static readonly KnownHeader ProxyAuthenticate = new KnownHeader("Proxy-Authenticate", HttpHeaderType.Response, GenericHeaderParser.MultipleValueAuthenticationParser, null, StaticTable.ProxyAuthenticate); public static readonly KnownHeader ProxyAuthorization = new KnownHeader("Proxy-Authorization", HttpHeaderType.Request, GenericHeaderParser.SingleValueAuthenticationParser, null, StaticTable.ProxyAuthorization); public static readonly KnownHeader ProxyConnection = new KnownHeader("Proxy-Connection"); public static readonly KnownHeader ProxySupport = new KnownHeader("Proxy-Support"); public static readonly KnownHeader PublicKeyPins = new KnownHeader("Public-Key-Pins"); public static readonly KnownHeader Range = new KnownHeader("Range", HttpHeaderType.Request, GenericHeaderParser.RangeParser, null, StaticTable.Range); public static readonly KnownHeader Referer = new KnownHeader("Referer", HttpHeaderType.Request, UriHeaderParser.RelativeOrAbsoluteUriParser, null, StaticTable.Referer); // NB: The spelling-mistake "Referer" for "Referrer" must be matched. public static readonly KnownHeader Refresh = new KnownHeader("Refresh", StaticTable.Refresh); public static readonly KnownHeader RetryAfter = new KnownHeader("Retry-After", HttpHeaderType.Response, GenericHeaderParser.RetryConditionParser, null, StaticTable.RetryAfter); public static readonly KnownHeader SecWebSocketAccept = new KnownHeader("Sec-WebSocket-Accept"); public static readonly KnownHeader SecWebSocketExtensions = new KnownHeader("Sec-WebSocket-Extensions"); public static readonly KnownHeader SecWebSocketKey = new KnownHeader("Sec-WebSocket-Key"); public static readonly KnownHeader SecWebSocketProtocol = new KnownHeader("Sec-WebSocket-Protocol"); public static readonly KnownHeader SecWebSocketVersion = new KnownHeader("Sec-WebSocket-Version"); public static readonly KnownHeader Server = new KnownHeader("Server", HttpHeaderType.Response, ProductInfoHeaderParser.MultipleValueParser, null, StaticTable.Server); public static readonly KnownHeader SetCookie = new KnownHeader("Set-Cookie", StaticTable.SetCookie); public static readonly KnownHeader SetCookie2 = new KnownHeader("Set-Cookie2"); public static readonly KnownHeader StrictTransportSecurity = new KnownHeader("Strict-Transport-Security", StaticTable.StrictTransportSecurity); public static readonly KnownHeader TE = new KnownHeader("TE", HttpHeaderType.Request, TransferCodingHeaderParser.MultipleValueWithQualityParser); public static readonly KnownHeader TSV = new KnownHeader("TSV"); public static readonly KnownHeader Trailer = new KnownHeader("Trailer", HttpHeaderType.General, GenericHeaderParser.TokenListParser); public static readonly KnownHeader TransferEncoding = new KnownHeader("Transfer-Encoding", HttpHeaderType.General, TransferCodingHeaderParser.MultipleValueParser, new string[] { "chunked" }, StaticTable.TransferEncoding); public static readonly KnownHeader Upgrade = new KnownHeader("Upgrade", HttpHeaderType.General, GenericHeaderParser.MultipleValueProductParser); public static readonly KnownHeader UpgradeInsecureRequests = new KnownHeader("Upgrade-Insecure-Requests"); public static readonly KnownHeader UserAgent = new KnownHeader("User-Agent", HttpHeaderType.Request, ProductInfoHeaderParser.MultipleValueParser, null, StaticTable.UserAgent); public static readonly KnownHeader Vary = new KnownHeader("Vary", HttpHeaderType.Response, GenericHeaderParser.TokenListParser, null, StaticTable.Vary); public static readonly KnownHeader Via = new KnownHeader("Via", HttpHeaderType.General, GenericHeaderParser.MultipleValueViaParser, null, StaticTable.Via); public static readonly KnownHeader WWWAuthenticate = new KnownHeader("WWW-Authenticate", HttpHeaderType.Response, GenericHeaderParser.MultipleValueAuthenticationParser, null, StaticTable.WwwAuthenticate); public static readonly KnownHeader Warning = new KnownHeader("Warning", HttpHeaderType.General, GenericHeaderParser.MultipleValueWarningParser); public static readonly KnownHeader XAspNetVersion = new KnownHeader("X-AspNet-Version"); public static readonly KnownHeader XContentDuration = new KnownHeader("X-Content-Duration"); public static readonly KnownHeader XContentTypeOptions = new KnownHeader("X-Content-Type-Options"); public static readonly KnownHeader XFrameOptions = new KnownHeader("X-Frame-Options"); public static readonly KnownHeader XMSEdgeRef = new KnownHeader("X-MSEdge-Ref"); public static readonly KnownHeader XPoweredBy = new KnownHeader("X-Powered-By"); public static readonly KnownHeader XRequestID = new KnownHeader("X-Request-ID"); public static readonly KnownHeader XUACompatible = new KnownHeader("X-UA-Compatible"); // Helper interface for making GetCandidate generic over strings, utf8, etc private interface IHeaderNameAccessor { int Length { get; } char this[int index] { get; } } private readonly struct StringAccessor : IHeaderNameAccessor { private readonly string _string; public StringAccessor(string s) { _string = s; } public int Length => _string.Length; public char this[int index] => _string[index]; } // Can't use Span here as it's unsupported. private readonly unsafe struct BytePtrAccessor : IHeaderNameAccessor { private readonly byte* _p; private readonly int _length; public BytePtrAccessor(byte* p, int length) { _p = p; _length = length; } public int Length => _length; public char this[int index] => (char)_p[index]; } // Find possible known header match via lookup on length and a distinguishing char for that length. // Matching is case-insenstive. // NOTE: Because of this, we do not preserve the case of the original header, // whether from the wire or from the user explicitly setting a known header using a header name string. private static KnownHeader GetCandidate<T>(T key) where T : struct, IHeaderNameAccessor // Enforce struct for performance { int length = key.Length; switch (length) { case 2: return TE; // TE case 3: switch (key[0]) { case 'A': case 'a': return Age; // [A]ge case 'P': case 'p': return P3P; // [P]3P case 'T': case 't': return TSV; // [T]SV case 'V': case 'v': return Via; // [V]ia } break; case 4: switch (key[0]) { case 'D': case 'd': return Date; // [D]ate case 'E': case 'e': return ETag; // [E]Tag case 'F': case 'f': return From; // [F]rom case 'H': case 'h': return Host; // [H]ost case 'L': case 'l': return Link; // [L]ink case 'V': case 'v': return Vary; // [V]ary } break; case 5: switch (key[0]) { case 'A': case 'a': return Allow; // [A]llow case 'R': case 'r': return Range; // [R]ange } break; case 6: switch (key[0]) { case 'A': case 'a': return Accept; // [A]ccept case 'C': case 'c': return Cookie; // [C]ookie case 'E': case 'e': return Expect; // [E]xpect case 'O': case 'o': return Origin; // [O]rigin case 'P': case 'p': return Pragma; // [P]ragma case 'S': case 's': return Server; // [S]erver } break; case 7: switch (key[0]) { case 'A': case 'a': return AltSvc; // [A]lt-Svc case 'C': case 'c': return Cookie2; // [C]ookie2 case 'E': case 'e': return Expires; // [E]xpires case 'R': case 'r': switch (key[3]) { case 'E': case 'e': return Referer; // [R]ef[e]rer case 'R': case 'r': return Refresh; // [R]ef[r]esh } break; case 'T': case 't': return Trailer; // [T]railer case 'U': case 'u': return Upgrade; // [U]pgrade case 'W': case 'w': return Warning; // [W]arning } break; case 8: switch (key[3]) { case 'M': case 'm': return IfMatch; // If-[M]atch case 'R': case 'r': return IfRange; // If-[R]ange case 'A': case 'a': return Location; // Loc[a]tion } break; case 10: switch (key[0]) { case 'C': case 'c': return Connection; // [C]onnection case 'K': case 'k': return KeepAlive; // [K]eep-Alive case 'S': case 's': return SetCookie; // [S]et-Cookie case 'U': case 'u': return UserAgent; // [U]ser-Agent } break; case 11: switch (key[0]) { case 'C': case 'c': return ContentMD5; // [C]ontent-MD5 case 'R': case 'r': return RetryAfter; // [R]etry-After case 'S': case 's': return SetCookie2; // [S]et-Cookie2 } break; case 12: switch (key[2]) { case 'C': case 'c': return AcceptPatch; // Ac[c]ept-Patch case 'N': case 'n': return ContentType; // Co[n]tent-Type case 'X': case 'x': return MaxForwards; // Ma[x]-Forwards case 'M': case 'm': return XMSEdgeRef; // X-[M]SEdge-Ref case 'P': case 'p': return XPoweredBy; // X-[P]owered-By case 'R': case 'r': return XRequestID; // X-[R]equest-ID } break; case 13: switch (key[6]) { case '-': return AcceptRanges; // Accept[-]Ranges case 'I': case 'i': return Authorization; // Author[i]zation case 'C': case 'c': return CacheControl; // Cache-[C]ontrol case 'T': case 't': return ContentRange; // Conten[t]-Range case 'E': case 'e': return IfNoneMatch; // If-Non[e]-Match case 'O': case 'o': return LastModified; // Last-M[o]dified case 'S': case 's': return ProxySupport; // Proxy-[S]upport } break; case 14: switch (key[0]) { case 'A': case 'a': return AcceptCharset; // [A]ccept-Charset case 'C': case 'c': return ContentLength; // [C]ontent-Length } break; case 15: switch (key[7]) { case '-': return XFrameOptions; // X-Frame[-]Options case 'M': case 'm': return XUACompatible; // X-UA-Co[m]patible case 'E': case 'e': return AcceptEncoding; // Accept-[E]ncoding case 'K': case 'k': return PublicKeyPins; // Public-[K]ey-Pins case 'L': case 'l': return AcceptLanguage; // Accept-[L]anguage } break; case 16: switch (key[11]) { case 'O': case 'o': return ContentEncoding; // Content-Enc[o]ding case 'G': case 'g': return ContentLanguage; // Content-Lan[g]uage case 'A': case 'a': return ContentLocation; // Content-Loc[a]tion case 'C': case 'c': return ProxyConnection; // Proxy-Conne[c]tion case 'I': case 'i': return WWWAuthenticate; // WWW-Authent[i]cate case 'R': case 'r': return XAspNetVersion; // X-AspNet-Ve[r]sion } break; case 17: switch (key[0]) { case 'I': case 'i': return IfModifiedSince; // [I]f-Modified-Since case 'S': case 's': return SecWebSocketKey; // [S]ec-WebSocket-Key case 'T': case 't': return TransferEncoding; // [T]ransfer-Encoding } break; case 18: switch (key[0]) { case 'P': case 'p': return ProxyAuthenticate; // [P]roxy-Authenticate case 'X': case 'x': return XContentDuration; // [X]-Content-Duration } break; case 19: switch (key[0]) { case 'C': case 'c': return ContentDisposition; // [C]ontent-Disposition case 'I': case 'i': return IfUnmodifiedSince; // [I]f-Unmodified-Since case 'P': case 'p': return ProxyAuthorization; // [P]roxy-Authorization } break; case 20: return SecWebSocketAccept; // Sec-WebSocket-Accept case 21: return SecWebSocketVersion; // Sec-WebSocket-Version case 22: switch (key[0]) { case 'A': case 'a': return AccessControlMaxAge; // [A]ccess-Control-Max-Age case 'S': case 's': return SecWebSocketProtocol; // [S]ec-WebSocket-Protocol case 'X': case 'x': return XContentTypeOptions; // [X]-Content-Type-Options } break; case 23: return ContentSecurityPolicy; // Content-Security-Policy case 24: return SecWebSocketExtensions; // Sec-WebSocket-Extensions case 25: switch (key[0]) { case 'S': case 's': return StrictTransportSecurity; // [S]trict-Transport-Security case 'U': case 'u': return UpgradeInsecureRequests; // [U]pgrade-Insecure-Requests } break; case 27: return AccessControlAllowOrigin; // Access-Control-Allow-Origin case 28: switch (key[21]) { case 'H': case 'h': return AccessControlAllowHeaders; // Access-Control-Allow-[H]eaders case 'M': case 'm': return AccessControlAllowMethods; // Access-Control-Allow-[M]ethods } break; case 29: return AccessControlExposeHeaders; // Access-Control-Expose-Headers case 32: return AccessControlAllowCredentials; // Access-Control-Allow-Credentials } return null; } internal static KnownHeader TryGetKnownHeader(string name) { KnownHeader candidate = GetCandidate(new StringAccessor(name)); if (candidate != null && StringComparer.OrdinalIgnoreCase.Equals(name, candidate.Name)) { return candidate; } return null; } internal static unsafe KnownHeader TryGetKnownHeader(ReadOnlySpan<byte> name) { fixed (byte* p = &MemoryMarshal.GetReference(name)) { KnownHeader candidate = GetCandidate(new BytePtrAccessor(p, name.Length)); if (candidate != null && ByteArrayHelpers.EqualsOrdinalAsciiIgnoreCase(candidate.Name, name)) { return candidate; } } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Wintellect.PowerCollections; internal class Program { private static StringBuilder output = new StringBuilder(); private static EventHolder events = new EventHolder(); private static void Main(string[] args) { while (ExecuteNextCommand()) { } Console.WriteLine(output); } private static bool ExecuteNextCommand() { string command = Console.ReadLine(); if (command[0] == 'A') { AddEvent(command); return true; } if (command[0] == 'D') { DeleteEvents(command); return true; } if (command[0] == 'L') { ListEvents(command); return true; } if (command[0] == 'E') { return false; } return false; } private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); DateTime date = GetDate(command, "ListEvents"); string countstring = command.Substring(pipeIndex + 1); int count = int.Parse(countstring); events.ListEvents(date, count); } private static void DeleteEvents(string command) { string title = command.Substring("DeleteEvents".Length + 1); events.DeleteEvents(title); } private static void AddEvent(string command) { DateTime date; string title; string location; GetParameters(command, "AddEvent", out date, out title, out location); events.AddEvent(date, title, location); } private static void GetParameters( string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation) { dateAndTime = GetDate(commandForExecution, commandType); int firstPipeIndex = commandForExecution.IndexOf('|'); int lastPipeIndex = commandForExecution.LastIndexOf('|'); if (firstPipeIndex == lastPipeIndex) { eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim(); eventLocation = string.Empty; } else { eventTitle = commandForExecution.Substring(firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1).Trim(); eventLocation = commandForExecution.Substring(lastPipeIndex + 1).Trim(); } } private static DateTime GetDate(string command, string commandType) { DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20)); return date; } private static class Messages { public static void EventAdded() { output.Append("Event added\n"); } public static void EventDeleted(int x) { if (x == 0) { NoEventsFound(); } else { output.AppendFormat("{0} events deleted\n", x); } } public static void NoEventsFound() { output.Append("No events found\n"); } public static void PrintEvent(Event eventToPrint) { if (eventToPrint != null) { output.Append(eventToPrint + "\n"); } } } private class Event : IComparable { private DateTime date; private string title; private string location; public Event(DateTime date, string title, string location) { this.date = date; this.title = title; this.location = location; } public int CompareTo(object obj) { Event other = obj as Event; int comparedByDate = this.date.CompareTo(other.date); int comparedByTitle = this.title.CompareTo(other.title); int comparedByLocation = this.location.CompareTo(other.location); if (comparedByDate == 0) { if (comparedByTitle == 0) { return comparedByLocation; } else { return comparedByTitle; } } else { return comparedByDate; } } public override string ToString() { StringBuilder tostring = new StringBuilder(); tostring.Append(this.date.ToString("yyyy-MM-ddTHH:mm:ss")); tostring.Append(" | " + this.title); if (this.location != null && this.location != string.Empty) { tostring.Append(" | " + this.location); } return tostring.ToString(); } } private class EventHolder { private MultiDictionary<string, Event> orderedByTitle = new MultiDictionary<string, Event>(true); private OrderedBag<Event> orderedByDate = new OrderedBag<Event>(); public void AddEvent(DateTime date, string title, string location) { Event newEvent = new Event(date, title, location); this.orderedByTitle.Add(title.ToLower(), newEvent); this.orderedByDate.Add(newEvent); Messages.EventAdded(); } public void DeleteEvents(string titleToDelete) { string title = titleToDelete.ToLower(); int removed = 0; foreach (var eventToRemove in this.orderedByTitle[title]) { removed++; this.orderedByDate.Remove(eventToRemove); } this.orderedByTitle.Remove(title); Messages.EventDeleted(removed); } public void ListEvents(DateTime date, int count) { OrderedBag<Event>.View eventsToShow = this.orderedByDate.RangeFrom(new Event(date, string.Empty, string.Empty), true); int showed = 0; foreach (var eventToShow in eventsToShow) { if (showed == count) { break; } Messages.PrintEvent(eventToShow); showed++; } if (showed == 0) { Messages.NoEventsFound(); } } } }
#pragma warning disable 0162 #pragma warning disable 0618 using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityObject = UnityEngine.Object; using UnityAction = UnityEngine.Events.UnityAction; namespace Zios{ using Event; #if UNITY_EDITOR using UnityEditor; using CallbackFunction = UnityEditor.EditorApplication.CallbackFunction; #else public delegate void CallbackFunction(); #endif [InitializeOnLoad] public static partial class Utility{ private static float sceneCheck; private static Dictionary<object,int> messages = new Dictionary<object,int>(); private static Dictionary<object,KeyValuePair<Action,float>> delayedMethods = new Dictionary<object,KeyValuePair<Action,float>>(); private static Dictionary<string,Type> internalTypes = new Dictionary<string,Type>(); static Utility(){Utility.Setup();} public static void Setup(){ Events.Add("On Late Update",(Method)Utility.CheckLoaded); Events.Add("On Late Update",(Method)Utility.CheckDelayed); #if UNITY_EDITOR Events.Register("On Global Event"); Events.Register("On Editor Update"); Events.Register("On Prefab Changed"); Events.Register("On Lightmap Baked"); Events.Register("On Windows Reordered"); Events.Register("On Hierarchy Changed"); Events.Register("On Asset Changed"); Events.Register("On Asset Saving"); Events.Register("On Asset Creating"); Events.Register("On Asset Deleting"); Events.Register("On Asset Moving"); Events.Register("On Scene Loaded"); Events.Register("On Editor Scene Loaded"); Events.Register("On Editor Quit"); Events.Register("On Mode Changed"); Events.Register("On Enter Play"); Events.Register("On Exit Play"); Events.Register("On Undo Flushing"); Events.Register("On Undo"); Events.Register("On Redo"); #if UNITY_5 Camera.onPostRender += (Camera camera)=>Events.Call("On Camera Post Render",camera); Camera.onPreRender += (Camera camera)=>Events.Call("On Camera Pre Render",camera); Camera.onPreCull += (Camera camera)=>Events.Call("On Camera Pre Cull",camera); Lightmapping.completed += ()=>Events.Call("On Lightmap Baked"); #endif Undo.willFlushUndoRecord += ()=>Events.Call("On Undo Flushing"); Undo.undoRedoPerformed += ()=>Events.Call("On Undo"); Undo.undoRedoPerformed += ()=>Events.Call("On Redo"); PrefabUtility.prefabInstanceUpdated += (GameObject target)=>Events.Call("On Prefab Changed",target); EditorApplication.projectWindowChanged += ()=>Events.Call("On Project Changed"); EditorApplication.playmodeStateChanged += ()=>{ Events.Call("On Mode Changed"); bool changing = EditorApplication.isPlayingOrWillChangePlaymode; bool playing = Application.isPlaying; if(changing && !playing){Events.Call("On Enter Play");} if(!changing && playing){Events.Call("On Exit Play");} }; EditorApplication.hierarchyWindowChanged += ()=>Events.DelayCall("On Hierarchy Changed",0.25f); EditorApplication.update += ()=>Events.Call("On Editor Update"); EditorApplication.update += ()=>Utility.CheckLoaded(true); EditorApplication.update += ()=>Utility.CheckDelayed(true); UnityAction editorQuitEvent = new UnityAction(()=>Events.Call("On Editor Quit")); CallbackFunction windowEvent = ()=>Events.Call("On Window Reordered"); CallbackFunction globalEvent = ()=>Events.Call("On Global Event"); var windowsReordered = typeof(EditorApplication).GetVariable<CallbackFunction>("windowsReordered"); typeof(EditorApplication).SetVariable("windowsReordered",windowsReordered+windowEvent); var globalEventHandler = typeof(EditorApplication).GetVariable<CallbackFunction>("globalEventHandler"); typeof(EditorApplication).SetVariable("globalEventHandler",globalEventHandler+globalEvent); var editorQuitHandler = typeof(EditorApplication).GetVariable<UnityAction>("editorApplicationQuit"); typeof(EditorApplication).SetVariable("editorApplicationQuit",editorQuitHandler+editorQuitEvent); #endif } public static void CheckLoaded(){Utility.CheckLoaded(false);} public static void CheckLoaded(bool editor){ if(editor && Application.isPlaying){return;} if(!editor && !Application.isPlaying){return;} if(Time.realtimeSinceStartup < 0.5 && Utility.sceneCheck == 0){ var term = editor ? " Editor" : ""; Events.Call("On" + term + " Scene Loaded"); Utility.sceneCheck = 1; } if(Time.realtimeSinceStartup > Utility.sceneCheck){ Utility.sceneCheck = 0; } } public static void CheckDelayed(){Utility.CheckDelayed(false);} public static void CheckDelayed(bool editorCheck){ if(editorCheck && Application.isPlaying){return;} if(!editorCheck && !Application.isPlaying){return;} if(Utility.delayedMethods.Count < 1){return;} foreach(var item in Utility.delayedMethods.Copy()){ var method = item.Value.Key; float callTime = item.Value.Value; if(Time.realtimeSinceStartup > callTime){ method(); Utility.delayedMethods.Remove(item.Key); } } } public static bool IsRepainting(){ return UnityEngine.Event.current.type == EventType.Repaint; } //============================ // General //============================ public static void Destroy(UnityObject target,bool destroyAssets=false){ if(target.IsNull()){return;} if(target is Component){ var component = target.As<Component>(); if(component.gameObject.IsNull()){return;} } if(!Application.isPlaying){UnityObject.DestroyImmediate(target,destroyAssets);} else{UnityObject.Destroy(target);} } public static List<Type> GetTypes<T>(){ var assemblies = ObjectExtension.GetAssemblies(); var matches = new List<Type>(); foreach(var assembly in assemblies){ var types = assembly.GetTypes(); foreach(var type in types){ if(type.IsSubclassOf(typeof(T))){ matches.Add(type); } } } return matches; } public static Type GetType(string path){ var assemblies = ObjectExtension.GetAssemblies(); foreach(var assembly in assemblies){ Type[] types = assembly.GetTypes(); foreach(Type type in types){ if(type.FullName == path){ return type; } } } return null; } public static void ResetTypeCache(){Utility.internalTypes.Clear();} public static Type GetUnityType(string name){ if(Utility.internalTypes.ContainsKey(name)){return Utility.internalTypes[name];} #if UNITY_EDITOR var fullCheck = name.ContainsAny(".","+"); var alternative = name.ReplaceLast(".","+"); var term = alternative.Split("+").Last(); foreach(var type in typeof(UnityEditor.Editor).Assembly.GetTypes()){ bool match = fullCheck && (type.FullName.Contains(name) || type.FullName.Contains(alternative)) && term.Matches(type.Name,true); if(type.Name == name || match){ Utility.internalTypes[name] = type; return type; } } foreach(var type in typeof(UnityEngine.Object).Assembly.GetTypes()){ bool match = fullCheck && (type.FullName.Contains(name) || type.FullName.Contains(alternative)) && term.Matches(type.Name,true); if(type.Name == name || match){ Utility.internalTypes[name] = type; return type; } } #endif return null; } //============================ // Logging //============================ public static void EditorLog(string text){ if(!Application.isPlaying){ Debug.Log(text); } } public enum LogType{Debug,Warning,Error}; public static void Log(object key,string text,UnityObject target,LogType type,int limit){ if(Utility.messages.AddNew(key) < limit || limit == -1){ Utility.messages[key] += 1; if(type==LogType.Debug){Debug.Log(text,target);} else if(type==LogType.Warning){Debug.LogWarning(text,target);} else if(type==LogType.Error){Debug.LogError(text,target);} } } public static void LogWarning(object key,string text,UnityObject target=null,int limit=-1){Utility.Log(key,text,target,LogType.Warning,limit);} public static void LogError(object key,string text,UnityObject target=null,int limit=-1){Utility.Log(key,text,target,LogType.Error,limit);} public static void LogWarning(string text,UnityObject target=null,int limit=-1){Utility.Log(text,text,target,LogType.Warning,limit);} public static void LogError(string text,UnityObject target=null,int limit=-1){Utility.Log(text,text,target,LogType.Error,limit);} //============================ // Callbacks //============================ public static void RepeatCall(CallbackFunction method,int amount){ var repeat = Enumerable.Range(0,amount).GetEnumerator(); while(repeat.MoveNext()){ method(); } } public static void EditorCall(Action method){ #if UNITY_EDITOR if(!Utility.IsPlaying()){ method(); } #endif } public static void DelayCall(Action method){ #if UNITY_EDITOR CallbackFunction callback = new CallbackFunction(method); if(EditorApplication.delayCall != callback){ EditorApplication.delayCall += callback; } return; #endif Utility.DelayCall(method,0); } public static void DelayCall(Action method,float seconds,bool overwrite=true){ Utility.DelayCall(method,method,seconds,overwrite); } public static void DelayCall(object key,Action method,float seconds,bool overwrite=true){ if(!key.IsNull() && !method.IsNull()){ if(seconds <= 0){ method(); return; } if(Utility.delayedMethods.ContainsKey(key) && !overwrite){return;} Utility.delayedMethods[key] = new KeyValuePair<Action,float>(method,Time.realtimeSinceStartup + seconds); } } } }
using System.Reflection; using System.Reflection.Emit; using System.Text; using System; using Jsonics.ToJson; namespace Jsonics { internal class JsonILGenerator { StringBuilder _appendQueue; ILGenerator _generator; public JsonILGenerator(ILGenerator generator, StringBuilder appendQueue) { _generator = generator; _appendQueue = appendQueue; } public StringBuilder AppendQueue { get { return _appendQueue; } } public void Append(string value) { _appendQueue.Append(value); } public void EmitQueuedAppends() { if(_appendQueue.Length == 0) { return; } if(_appendQueue.Length == 1) { _generator.Emit(OpCodes.Ldc_I4_S, (int)_appendQueue.ToString()[0]); EmitAppend(typeof(char)); _appendQueue.Clear(); return; } _generator.Emit(OpCodes.Ldstr, _appendQueue.ToString()); EmitAppend(typeof(string)); _appendQueue.Clear(); } public void EmitAppend(Type type) { _generator.Emit(OpCodes.Callvirt, typeof(StringBuilder).GetRuntimeMethod("Append", new Type[]{type})); } public LocalBuilder DeclareLocal<T>() { return _generator.DeclareLocal(typeof(T)); } public LocalBuilder DeclareLocal(Type type) { return _generator.DeclareLocal(type); } public void LoadNull() { EmitQueuedAppends(); _generator.Emit(OpCodes.Ldnull); } public void StoreLocal(LocalBuilder localBuilder) { EmitQueuedAppends(); int index = localBuilder.LocalIndex; if(index == 0) { _generator.Emit(OpCodes.Stloc_0); return; } if(index == 1) { _generator.Emit(OpCodes.Stloc_1); return; } if(index == 2) { _generator.Emit(OpCodes.Stloc_2); return; } if(index == 3) { _generator.Emit(OpCodes.Stloc_3); return; } if(index <= 255) { _generator.Emit(OpCodes.Stloc_S, localBuilder); return; } _generator.Emit(OpCodes.Stloc, localBuilder); } public void LoadLocal(LocalBuilder localBuilder) { EmitQueuedAppends(); int index = localBuilder.LocalIndex; if(index == 0) { _generator.Emit(OpCodes.Ldloc_0); return; } if(index == 1) { _generator.Emit(OpCodes.Ldloc_1); return; } if(index == 2) { _generator.Emit(OpCodes.Ldloc_2); return; } if(index == 3) { _generator.Emit(OpCodes.Ldloc_3); return; } if(index <= 255) { _generator.Emit(OpCodes.Ldloc_S, localBuilder); return; } _generator.Emit(OpCodes.Ldloc, localBuilder); } public void LoadLocalAddress(LocalBuilder localBuilder) { EmitQueuedAppends(); if(localBuilder.LocalIndex <= 255) { _generator.Emit(OpCodes.Ldloca_S, localBuilder); return; } _generator.Emit(OpCodes.Ldloca, localBuilder); } public void Constrain<T>() { EmitQueuedAppends(); _generator.Emit(OpCodes.Constrained, typeof(T)); } public void Constrain(Type type) { EmitQueuedAppends(); _generator.Emit(OpCodes.Constrained, type); } public void CallToString() { EmitQueuedAppends(); _generator.Emit(OpCodes.Callvirt, typeof(Object).GetRuntimeMethod("ToString", new Type[0])); } public void LoadArg(Type type, int arg, bool address) { EmitQueuedAppends(); //TODO: ldarg vs ldarga is situational, if you are loading a struct to call a method on the struct then you //need to call ldarga, if you want ot pass it to another method then you need to call ldarg if(address) //type.GetTypeInfo().IsValueType && !type.GetTypeInfo().IsPrimitive && type != typeof(DateTime) && type != typeof(Guid) && !type.GetTypeInfo().IsEnum && type != typeof(char?)) { _generator.Emit(OpCodes.Ldarga_S, arg); return; } if(arg == 0) { _generator.Emit(OpCodes.Ldarg_0); return; } if(arg == 1) { _generator.Emit(OpCodes.Ldarg_1); return; } if(arg == 2) { _generator.Emit(OpCodes.Ldarg_2); return; } if(arg == 3) { _generator.Emit(OpCodes.Ldarg_3); return; } _generator.Emit(OpCodes.Ldarg_S, (byte)arg); return; } public void GetProperty(PropertyInfo property) { EmitQueuedAppends(); _generator.Emit(OpCodes.Call, property.DeclaringType.GetRuntimeMethod($"get_{property.Name}", new Type[0])); } public void AppendDate() { EmitQueuedAppends(); _generator.Emit(OpCodes.Call, typeof(StringBuilderExtension).GetRuntimeMethod("AppendDate", new Type[]{typeof(StringBuilder), typeof(DateTime)})); } public Label DefineLabel() { return _generator.DefineLabel(); } public void Mark(Label label) { _generator.MarkLabel(label); } public void BrIfTrue(Label label) { EmitQueuedAppends(); _generator.Emit(OpCodes.Brtrue, label); } public void BranchIfFalse(Label label) { EmitQueuedAppends(); _generator.Emit(OpCodes.Brfalse, label); } public void LoadString(string value) { EmitQueuedAppends(); _generator.Emit(OpCodes.Ldstr, value); } public void Branch(Label label) { EmitQueuedAppends(); _generator.Emit(OpCodes.Br, label); } public void AppendInt() { EmitQueuedAppends(); _generator.Emit(OpCodes.Call, typeof(StringBuilderExtension).GetRuntimeMethod("AppendInt", new Type[]{typeof(StringBuilder), typeof(int)})); } public void EmitAppendEscaped() { EmitQueuedAppends(); _generator.Emit(OpCodes.Call, typeof(StringBuilderExtension).GetRuntimeMethod("AppendEscaped", new Type[]{typeof(StringBuilder), typeof(string)})); } public void EmitAppendChar() { EmitQueuedAppends(); _generator.Emit(OpCodes.Call, typeof(StringBuilderExtension).GetRuntimeMethod("AppendEscaped", new Type[]{typeof(StringBuilder), typeof(char)})); } public void EmitAppendNullableChar() { EmitQueuedAppends(); _generator.Emit(OpCodes.Call, typeof(StringBuilderExtension).GetRuntimeMethod("AppendEscaped", new Type[]{typeof(StringBuilder), typeof(char?)})); } public void Return() { EmitQueuedAppends(); _generator.Emit(OpCodes.Ret); } public void LoadStaticField(FieldBuilder fieldBuilder) { EmitQueuedAppends(); _generator.Emit(OpCodes.Ldsfld, fieldBuilder); } public void LoadField(FieldInfo fieldInfo) { EmitQueuedAppends(); _generator.Emit(OpCodes.Ldfld, fieldInfo); } public void StoreField(FieldInfo fieldInfo) { EmitQueuedAppends(); _generator.Emit(OpCodes.Stfld, fieldInfo); } public void StoreStaticField(FieldBuilder fieldBuilder) { EmitQueuedAppends(); _generator.Emit(OpCodes.Stsfld, fieldBuilder); } public void NewObject(ConstructorInfo constructorInfo) { EmitQueuedAppends(); _generator.Emit(OpCodes.Newobj, constructorInfo); } public void InitObject(Type type) { EmitQueuedAppends(); _generator.Emit(OpCodes.Initobj, type); } public void CallVirtual(MethodInfo methodInfo) { EmitQueuedAppends(); _generator.EmitCall(OpCodes.Callvirt, methodInfo, null); } public void Call(MethodInfo methodInfo) { EmitQueuedAppends(); _generator.Emit(OpCodes.Call, methodInfo); } public void Call(ConstructorInfo constructorInfo) { EmitQueuedAppends(); _generator.Emit(OpCodes.Call, constructorInfo); } public void Duplicate() { EmitQueuedAppends(); _generator.Emit(OpCodes.Dup); } public void LoadLength() { EmitQueuedAppends(); _generator.Emit(OpCodes.Ldlen); } public void ConvertToInt32() { EmitQueuedAppends(); _generator.Emit(OpCodes.Conv_I4); } public void LoadConstantInt32(int val) { EmitQueuedAppends(); if(val == 0) { _generator.Emit(OpCodes.Ldc_I4_0); return; } if(val == 1) { _generator.Emit(OpCodes.Ldc_I4_1); return; } if(val == 2) { _generator.Emit(OpCodes.Ldc_I4_2); return; } if(val == 3) { _generator.Emit(OpCodes.Ldc_I4_3); return; } if(val == 4) { _generator.Emit(OpCodes.Ldc_I4_4); return; } if(val == 5) { _generator.Emit(OpCodes.Ldc_I4_5); return; } if(val == 6) { _generator.Emit(OpCodes.Ldc_I4_6); return; } if(val == 7) { _generator.Emit(OpCodes.Ldc_I4_7); return; } if(val == 8) { _generator.Emit(OpCodes.Ldc_I4_8); return; } if(val == -1) { _generator.Emit(OpCodes.Ldc_I4_M1); return; } if((val > 8 && val < 128) || (val < -1 && val > -129)) { _generator.Emit(OpCodes.Ldc_I4_S, (byte)val); return; } _generator.Emit(OpCodes.Ldc_I4, val); } public void BranchIfLargerThan(Label label) { EmitQueuedAppends(); _generator.Emit(OpCodes.Blt, label); } public void BranchIfEqual(Label label) { EmitQueuedAppends(); _generator.Emit(OpCodes.Beq, label); } public void BranchIfNotEqualUnsigned(Label label) { EmitQueuedAppends(); _generator.Emit(OpCodes.Bne_Un, label); } public void Pop() { EmitQueuedAppends(); _generator.Emit(OpCodes.Pop); } public void LoadArrayElement(Type elementType, bool address) { EmitQueuedAppends(); if(elementType == typeof(byte) || elementType == typeof(bool)) { _generator.Emit(OpCodes.Ldelem_I1); return; } if(elementType == typeof(sbyte)) { _generator.Emit(OpCodes.Ldelem_U1); return; } if(elementType == typeof(char)) { _generator.Emit(OpCodes.Ldelem_I2); return; } if(elementType == typeof(short)) { _generator.Emit(OpCodes.Ldelem_I2); return; } if(elementType == typeof(ushort)) { _generator.Emit(OpCodes.Ldelem_U2); return; } if(elementType == typeof(int)) { _generator.Emit(OpCodes.Ldelem_I4); return; } if(elementType == typeof(uint)) { _generator.Emit(OpCodes.Ldelem_U4); return; } if(elementType == typeof(float)) { _generator.Emit(OpCodes.Ldelem_R4); return; } if(elementType == typeof(double)) { _generator.Emit(OpCodes.Ldelem_R8); return; } if(elementType.GetTypeInfo().IsValueType) { if(address) { _generator.Emit(OpCodes.Ldelem, elementType); var local = _generator.DeclareLocal(elementType); this.StoreLocal(local); this.LoadLocalAddress(local); return; } _generator.Emit(OpCodes.Ldelem, elementType); return; } _generator.Emit(OpCodes.Ldelem_Ref); } public void LoadListElement(Type listType) { CallVirtual(listType.GetRuntimeMethod("get_Item", new Type[]{typeof(int)})); } public void Add() { EmitQueuedAppends(); _generator.Emit(OpCodes.Add); } public void Subtract() { EmitQueuedAppends(); _generator.Emit(OpCodes.Sub); } public void WriteConsoleInt() { EmitQueuedAppends(); var temp = _generator.DeclareLocal(typeof(int)); _generator.Emit(OpCodes.Stloc, temp); _generator.EmitWriteLine(temp); } public void WriteConsole(string str) { _generator.EmitWriteLine(str); } public void WriteConsole(LocalBuilder localBuilder) { _generator.EmitWriteLine(localBuilder); } public void Remainder() { EmitQueuedAppends(); _generator.Emit(OpCodes.Rem); } public void Switch(Label[] labels) { EmitQueuedAppends(); _generator.Emit(OpCodes.Switch, labels); } public void Box(Type type) { EmitQueuedAppends(); _generator.Emit(OpCodes.Box, type); } } }
using System; using ModestTree; namespace Zenject { public class SubContainerBinder { readonly BindInfo _bindInfo; readonly BindFinalizerWrapper _finalizerWrapper; readonly object _subIdentifier; readonly bool _resolveAll; public SubContainerBinder( BindInfo bindInfo, BindFinalizerWrapper finalizerWrapper, object subIdentifier, bool resolveAll) { _bindInfo = bindInfo; _finalizerWrapper = finalizerWrapper; _subIdentifier = subIdentifier; _resolveAll = resolveAll; // Reset in case the user ends the binding here finalizerWrapper.SubFinalizer = null; } protected IBindingFinalizer SubFinalizer { set { _finalizerWrapper.SubFinalizer = value; } } public ScopeConcreteIdArgConditionCopyNonLazyBinder ByInstance(DiContainer subContainer) { SubFinalizer = new SubContainerBindingFinalizer( _bindInfo, _subIdentifier, _resolveAll, (_) => new SubContainerCreatorByInstance(subContainer)); return new ScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo); } public #if NOT_UNITY3D WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder #else WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder #endif ByInstaller<TInstaller>() where TInstaller : InstallerBase { return ByInstaller(typeof(TInstaller)); } public #if NOT_UNITY3D WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder #else WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder #endif ByInstaller(Type installerType) { Assert.That(installerType.DerivesFrom<InstallerBase>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType); var subContainerBindInfo = new SubContainerCreatorBindInfo(); SubFinalizer = new SubContainerBindingFinalizer( _bindInfo, _subIdentifier, _resolveAll, (container) => new SubContainerCreatorByInstaller(container, subContainerBindInfo, installerType)); return new #if NOT_UNITY3D WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder #else WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder #endif (subContainerBindInfo, _bindInfo); } public #if NOT_UNITY3D WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder #else WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder #endif ByMethod(Action<DiContainer> installerMethod) { var subContainerBindInfo = new SubContainerCreatorBindInfo(); SubFinalizer = new SubContainerBindingFinalizer( _bindInfo, _subIdentifier, _resolveAll, (container) => new SubContainerCreatorByMethod(container, subContainerBindInfo, installerMethod)); return new #if NOT_UNITY3D WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder #else WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder #endif (subContainerBindInfo, _bindInfo); } #if !NOT_UNITY3D public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabMethod( UnityEngine.Object prefab, Action<DiContainer> installerMethod) { BindingUtil.AssertIsValidPrefab(prefab); var gameObjectInfo = new GameObjectCreationParameters(); SubFinalizer = new SubContainerPrefabBindingFinalizer( _bindInfo, _subIdentifier, _resolveAll, (container) => new SubContainerCreatorByNewPrefabMethod( container, new PrefabProvider(prefab), gameObjectInfo, installerMethod)); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller<TInstaller>( UnityEngine.Object prefab) where TInstaller : InstallerBase { return ByNewPrefabInstaller(prefab, typeof(TInstaller)); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller( UnityEngine.Object prefab, Type installerType) { Assert.That(installerType.DerivesFrom<InstallerBase>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType); var gameObjectInfo = new GameObjectCreationParameters(); SubFinalizer = new SubContainerPrefabBindingFinalizer( _bindInfo, _subIdentifier, _resolveAll, (container) => new SubContainerCreatorByNewPrefabInstaller( container, new PrefabProvider(prefab), gameObjectInfo, installerType, _bindInfo.Arguments)); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceMethod( string resourcePath, Action<DiContainer> installerMethod) { BindingUtil.AssertIsValidResourcePath(resourcePath); var gameObjectInfo = new GameObjectCreationParameters(); SubFinalizer = new SubContainerPrefabBindingFinalizer( _bindInfo, _subIdentifier, _resolveAll, (container) => new SubContainerCreatorByNewPrefabMethod( container, new PrefabProviderResource(resourcePath), gameObjectInfo, installerMethod)); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceInstaller<TInstaller>( string resourcePath) where TInstaller : InstallerBase { return ByNewPrefabResourceInstaller(resourcePath, typeof(TInstaller)); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceInstaller( string resourcePath, Type installerType) { BindingUtil.AssertIsValidResourcePath(resourcePath); Assert.That(installerType.DerivesFrom<InstallerBase>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType); var gameObjectInfo = new GameObjectCreationParameters(); SubFinalizer = new SubContainerPrefabBindingFinalizer( _bindInfo, _subIdentifier, _resolveAll, (container) => new SubContainerCreatorByNewPrefabInstaller( container, new PrefabProviderResource(resourcePath), gameObjectInfo, installerType, _bindInfo.Arguments)); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo); } [System.Obsolete("ByNewPrefab has been renamed to ByNewContextPrefab to avoid confusion with ByNewPrefabInstaller and ByNewPrefabMethod")] public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefab(UnityEngine.Object prefab) { return ByNewContextPrefab(prefab); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewContextPrefab(UnityEngine.Object prefab) { BindingUtil.AssertIsValidPrefab(prefab); var gameObjectInfo = new GameObjectCreationParameters(); SubFinalizer = new SubContainerPrefabBindingFinalizer( _bindInfo, _subIdentifier, _resolveAll, (container) => new SubContainerCreatorByNewPrefab( container, new PrefabProvider(prefab), gameObjectInfo)); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo); } public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResource(string resourcePath) { BindingUtil.AssertIsValidResourcePath(resourcePath); var gameObjectInfo = new GameObjectCreationParameters(); SubFinalizer = new SubContainerPrefabBindingFinalizer( _bindInfo, _subIdentifier, _resolveAll, (container) => new SubContainerCreatorByNewPrefab( container, new PrefabProviderResource(resourcePath), gameObjectInfo)); return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo); } #endif } }
using System; /// <summary> /// UIntPtr.Zero /// A read-only field that represents a pointer or handle that has been initialized to zero. /// This field is not CLS-compliant. /// </summary> public class UIntPtrZero { private static UIntPtr m_zeroUIntPtr = new UIntPtr(); public static int Main() { UIntPtrZero testObj = new UIntPtrZero(); TestLibrary.TestFramework.BeginTestCase("for field: UIntPtr.Zero"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; const string c_TEST_ID = "P001"; const string c_TEST_DESC = "PosTest1: UIntPtr.Zero vs auto initianlized static UIntPtr"; string errorDesc; UIntPtr expectedUIntPtr, actualUIntPtr; bool actualResult; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedUIntPtr = UIntPtrZero.m_zeroUIntPtr; actualUIntPtr = UIntPtr.Zero; actualResult = actualUIntPtr == expectedUIntPtr; if (!actualResult) { errorDesc = "Actual UIntPtr value is not " + expectedUIntPtr + " as expected: Actual(" + actualUIntPtr + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_ID = "P002"; const string c_TEST_DESC = "PosTest2: UIntPtr.Zero vs UIntPtr(0)"; string errorDesc; UIntPtr expectedUIntPtr, actualUIntPtr; bool actualResult; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedUIntPtr = new UIntPtr(0); actualUIntPtr = UIntPtr.Zero; actualResult = actualUIntPtr == expectedUIntPtr; if (!actualResult) { errorDesc = "Actual UIntPtr value is not " + expectedUIntPtr + " as expected: Actual(" + actualUIntPtr + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_ID = "P003"; const string c_TEST_DESC = "PosTest3: UIntPtr.Zero vs nonzero UIntPtr"; string errorDesc; UIntPtr expectedUIntPtr, actualUIntPtr; bool actualResult; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedUIntPtr = new UIntPtr(123); actualUIntPtr = UIntPtr.Zero; actualResult = actualUIntPtr != expectedUIntPtr; if (!actualResult) { errorDesc = "Actual UIntPtr value is not " + expectedUIntPtr + " as expected: Actual(" + actualUIntPtr + ")"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } [System.Security.SecuritySafeCritical] public unsafe bool PosTest4() { bool retVal = true; const string c_TEST_ID = "P004"; const string c_TEST_DESC = "PosTest4: UIntPtr.Zero vs new UIntPtr((void *)0)"; string errorDesc; UIntPtr expectedUIntPtr, actualUIntPtr; void *zeroPtr = (void *)0; bool actualResult; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedUIntPtr = new UIntPtr(zeroPtr); actualUIntPtr = UIntPtr.Zero; actualResult = actualUIntPtr == expectedUIntPtr; if (!actualResult) { errorDesc = "Actual UIntPtr value is not UIntPtr((void *) 0 )" + expectedUIntPtr + " as expected: Actual(" + actualUIntPtr + ")"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } [System.Security.SecuritySafeCritical] public unsafe bool PosTest5() { bool retVal = true; const string c_TEST_ID = "P005"; const string c_TEST_DESC = "PosTest5: UIntPtr.Zero vs new UIntPtr((ulong)0)"; string errorDesc; UIntPtr expectedUIntPtr, actualUIntPtr; bool actualResult; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedUIntPtr = new UIntPtr((ulong) 0); actualUIntPtr = UIntPtr.Zero; actualResult = actualUIntPtr == expectedUIntPtr; if (!actualResult) { errorDesc = "Actual UIntPtr value is not UIntPtr((void *) 0 )" + expectedUIntPtr + " as expected: Actual(" + actualUIntPtr + ")"; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } }
// 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.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DocumentationCommentFormatting; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { internal class DocCommentFormatter { private static int s_indentSize = 2; private static int s_wrapLength = 80; private static string s_summaryHeader = FeaturesResources.Summary; private static string s_paramHeader = FeaturesResources.Parameters; private static string s_labelFormat = "{0}:"; private static string s_typeParameterHeader = FeaturesResources.TypeParameters; private static string s_returnsHeader = FeaturesResources.Returns; private static string s_exceptionsHeader = FeaturesResources.Exceptions; private static string s_remarksHeader = FeaturesResources.Remarks; internal static ImmutableArray<string> Format(IDocumentationCommentFormattingService docCommentFormattingService, DocumentationComment docComment) { var formattedCommentLinesBuilder = ImmutableArray.CreateBuilder<string>(); var lineBuilder = new StringBuilder(); var formattedSummaryText = docCommentFormattingService.Format(docComment.SummaryText); if (!string.IsNullOrWhiteSpace(formattedSummaryText)) { formattedCommentLinesBuilder.Add(s_summaryHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedSummaryText)); } var parameterNames = docComment.ParameterNames; if (parameterNames.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_paramHeader); for (int i = 0; i < parameterNames.Length; i++) { if (i != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, parameterNames[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var rawParameterText = docComment.GetParameterText(parameterNames[i]); var formattedParameterText = docCommentFormattingService.Format(rawParameterText); if (!string.IsNullOrWhiteSpace(formattedParameterText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedParameterText)); } } } var typeParameterNames = docComment.TypeParameterNames; if (typeParameterNames.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_typeParameterHeader); for (int i = 0; i < typeParameterNames.Length; i++) { if (i != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, typeParameterNames[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var rawTypeParameterText = docComment.GetTypeParameterText(typeParameterNames[i]); var formattedTypeParameterText = docCommentFormattingService.Format(rawTypeParameterText); if (!string.IsNullOrWhiteSpace(formattedTypeParameterText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedTypeParameterText)); } } } var formattedReturnsText = docCommentFormattingService.Format(docComment.ReturnsText); if (!string.IsNullOrWhiteSpace(formattedReturnsText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_returnsHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedReturnsText)); } var exceptionTypes = docComment.ExceptionTypes; if (exceptionTypes.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_exceptionsHeader); for (int i = 0; i < exceptionTypes.Length; i++) { var rawExceptionTexts = docComment.GetExceptionTexts(exceptionTypes[i]); for (int j = 0; j < rawExceptionTexts.Length; j++) { if (i != 0 || j != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, exceptionTypes[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var formattedExceptionText = docCommentFormattingService.Format(rawExceptionTexts[j]); if (!string.IsNullOrWhiteSpace(formattedExceptionText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedExceptionText)); } } } } var formattedRemarksText = docCommentFormattingService.Format(docComment.RemarksText); if (!string.IsNullOrWhiteSpace(formattedRemarksText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_remarksHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedRemarksText)); } // Eliminate any blank lines at the beginning. while (formattedCommentLinesBuilder.Count > 0 && formattedCommentLinesBuilder[0].Length == 0) { formattedCommentLinesBuilder.RemoveAt(0); } // Eliminate any blank lines at the end. while (formattedCommentLinesBuilder.Count > 0 && formattedCommentLinesBuilder[formattedCommentLinesBuilder.Count - 1].Length == 0) { formattedCommentLinesBuilder.RemoveAt(formattedCommentLinesBuilder.Count - 1); } return formattedCommentLinesBuilder.ToImmutable(); } private static ImmutableArray<string> CreateWrappedTextFromRawText(string rawText) { var lines = ImmutableArray.CreateBuilder<string>(); // First split the string into constituent lines. var split = rawText.Split(new[] { "\r\n" }, System.StringSplitOptions.None); // Now split each line into multiple lines. foreach (var item in split) { SplitRawLineIntoFormattedLines(item, lines); } return lines.ToImmutable(); } private static void SplitRawLineIntoFormattedLines(string line, ImmutableArray<string>.Builder lines) { var indent = new StringBuilder().Append(' ', s_indentSize * 2).ToString(); var words = line.Split(' '); bool firstInLine = true; var sb = new StringBuilder(); sb.Append(indent); foreach (var word in words) { // We must always append at least one word to ensure progress. if (firstInLine) { firstInLine = false; } else { sb.Append(' '); } sb.Append(word); if (sb.Length >= s_wrapLength) { lines.Add(sb.ToString()); sb.Clear(); sb.Append(indent); firstInLine = true; } } if (sb.ToString().Trim() != string.Empty) { lines.Add(sb.ToString()); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Tools; using Xunit; namespace System.Numerics.Tests { public class logTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunLogTests() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; BigInteger bi; // Log Method - Log(1,+Infinity) Assert.Equal(0, BigInteger.Log(1, Double.PositiveInfinity)); // Log Method - Log(1,0) VerifyLogString("0 1 bLog"); // Log Method - Log(0, >1) for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 10); VerifyLogString(Print(tempByteArray1) + "0 bLog"); } // Log Method - Log(0, 0>x>1) for (int i = 0; i < s_samples; i++) { Assert.Equal(Double.PositiveInfinity, BigInteger.Log(0, s_random.NextDouble())); } // Log Method - base = 0 for (int i = 0; i < s_samples; i++) { bi = 1; while (bi == 1) { bi = new BigInteger(GetRandomPosByteArray(s_random, 8)); } Assert.True((Double.IsNaN(BigInteger.Log(bi, 0)))); } // Log Method - base = 1 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); VerifyLogString("1 " + Print(tempByteArray1) + "bLog"); } // Log Method - base = NaN for (int i = 0; i < s_samples; i++) { Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.NaN))); } // Log Method - base = +Infinity for (int i = 0; i < s_samples; i++) { Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.PositiveInfinity))); } // Log Method - Log(0,1) VerifyLogString("1 0 bLog"); // Log Method - base < 0 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 10); tempByteArray2 = GetRandomNegByteArray(s_random, 1); VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog"); Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), -s_random.NextDouble()))); } // Log Method - value < 0 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomNegByteArray(s_random, 10); tempByteArray2 = GetRandomPosByteArray(s_random, 1); VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog"); } // Log Method - Small BigInteger and 0<base<0.5 for (int i = 0; i < s_samples; i++) { BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, 10)); Double newbase = Math.Min(s_random.NextDouble(), 0.5); Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase))); } // Log Method - Large BigInteger and 0<base<0.5 for (int i = 0; i < s_samples; i++) { BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, s_random.Next(1, 100))); Double newbase = Math.Min(s_random.NextDouble(), 0.5); Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase))); } // Log Method - two small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 3); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - one small and one large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 1); tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - two large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } } private static void VerifyLogString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(0, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetRandomByteArray(random, size); } private static Byte[] GetRandomPosByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; i++) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] &= 0x7F; return value; } private static Byte[] GetRandomNegByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] |= 0x80; return value; } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } private static bool ApproxEqual(double value1, double value2) { //Special case values; if (Double.IsNaN(value1)) { return Double.IsNaN(value2); } if (Double.IsNegativeInfinity(value1)) { return Double.IsNegativeInfinity(value2); } if (Double.IsPositiveInfinity(value1)) { return Double.IsPositiveInfinity(value2); } if (value2 == 0) { return (value1 == 0); } double result = Math.Abs((value1 / value2) - 1); return (result <= Double.Parse("1e-15")); } } }
namespace Mac_Layer { using com.ibm.saguaro.system; using com.ibm.saguaro.logger; internal class Frame { const byte beaconFCF = Radio.FCF_BEACON; // FCF header: data-frame & no-SRCPAN const byte beaconFCA = Radio.FCA_DST_SADDR | Radio.FCA_SRC_SADDR; // FCA header to use short-addresses const byte cmdFCF = Radio.FCF_CMD | Radio.FCF_ACKRQ; // FCF header: CMD + Acq request internal const byte DST_ADDR = (byte)1; internal const byte SRC_ADDR = (byte)2; static Frame () { } public static byte[] getBeaconFrame (uint panId, uint saddr, MacCoordinatorState state) { #if DEBUG Logger.appendString(csr.s2b("getBeaconFrame(")); Logger.appendUInt (panId); Logger.appendString(csr.s2b(", ")); Logger.appendUInt (saddr); Logger.appendString(csr.s2b(");")); Logger.flush(Mote.INFO); #endif byte[] beacon = new byte[14]; beacon [0] = beaconFCF; beacon [1] = beaconFCA; beacon [2] = (byte)state.beaconSequence; state.beaconSequence += 1; Util.set16 (beacon, 3, Radio.PAN_BROADCAST); Util.set16 (beacon, 5, Radio.SADDR_BROADCAST); Util.set16 (beacon, 7, panId); Util.set16 (beacon, 9, saddr); beacon [11] = (byte)(state.BO << 4 | state.SO); if (state.associationPermitted) beacon [12] = (byte)(state.nSlot << 3 | 1 << 1 | 1); else beacon [12] = (byte)(state.nSlot << 3 | 1 << 1 | 0); if (state.gtsEnabled) beacon [13] = (byte)(state.gtsSlots << 5 | 1); else beacon [13] = (byte)(state.gtsSlots << 5 | 0); return beacon; } public static byte[] getBeaconFrame (uint panId, uint saddr, uint dstSaddr, MacCoordinatorState state) { #if DEBUG Logger.appendString(csr.s2b("getBeaconFrame(")); Logger.appendUInt (panId); Logger.appendString(csr.s2b(", ")); Logger.appendUInt (saddr); Logger.appendString(csr.s2b(");")); Logger.flush(Mote.INFO); #endif byte[] beacon = new byte[16]; beacon [0] = beaconFCF; beacon [1] = beaconFCA; beacon [2] = (byte)state.beaconSequence; state.beaconSequence += 1; Util.set16 (beacon, 3, Radio.PAN_BROADCAST); Util.set16 (beacon, 5, Radio.SADDR_BROADCAST); Util.set16 (beacon, 7, panId); Util.set16 (beacon, 9, saddr); Util.set16 (beacon, 14, dstSaddr); beacon [11] = (byte)(state.BO << 4 | state.SO); if (state.associationPermitted) beacon [12] = (byte)(state.nSlot << 3 | 1 << 1 | 1); else beacon [12] = (byte)(state.nSlot << 3 | 1 << 1 | 0); if (state.gtsEnabled) beacon [13] = (byte)(state.gtsSlots << 5 | 1); else beacon [13] = (byte)(state.gtsSlots << 5 | 0); return beacon; } public static uint getBeaconInfo (byte[] beacon, uint len, MacUnassociatedState state) { state.coordinatorSADDR = Util.get16 (beacon, 9); state.BO = (uint)(beacon [11] & 0xF0) >> 4; state.SO = (uint)beacon [11] & 0x0F; state.panId = Util.get16 (beacon, 7); if (len > 15) { uint pendingAddr = Util.get16 (beacon, 14); if (pendingAddr == state.mySaddr || pendingAddr == Radio.SADDR_BROADCAST) { state.dataPending = true; } else { state.dataPending = false; } } else { state.dataPending = false; } #if DEBUG || DBG Logger.appendString(csr.s2b("coordinatorSADDR: ")); Logger.appendUInt (state.coordinatorSADDR); Logger.appendString(csr.s2b(", ")); Logger.appendString(csr.s2b("BO: ")); Logger.appendUInt (state.BO); Logger.appendString(csr.s2b(", ")); Logger.appendString(csr.s2b("SO: ")); Logger.appendUInt (state.SO); Logger.appendString(csr.s2b(", ")); Logger.appendString(csr.s2b("panId: ")); Logger.appendUInt (state.panId); Logger.appendString(csr.s2b(", ")); Logger.appendString(csr.s2b("dataPending: ")); if(state.dataPending) Logger.appendUInt(1); else Logger.appendUInt(0); Logger.flush(Mote.INFO); #endif return 1; } public static byte[] getCMDAssReqFrame (uint panId, uint saddr, MacState state) { #if DEBUG Logger.appendString(csr.s2b("getCMDAssReqFrame(")); Logger.appendUInt (panId); Logger.appendString(csr.s2b(", ")); Logger.appendUInt (saddr); Logger.appendString(csr.s2b(");")); Logger.flush(Mote.INFO); #endif byte[] cmd = new byte[19]; cmd [0] = Radio.FCF_CMD | Radio.FCF_ACKRQ; cmd [1] = Radio.FCA_DST_SADDR | Radio.FCA_SRC_XADDR; cmd [2] = (byte)Util.rand8 (); Util.set16 (cmd, 3, panId); Util.set16 (cmd, 5, saddr); Util.set16 (cmd, 7, Radio.SADDR_BROADCAST); Mote.getParam (Mote.EUI64, cmd, 9); cmd [17] = (byte)MacState.ASS_REQ; cmd [18] = (byte)(1 << 7 | 1 << 6 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0); return cmd; } public static byte[] getCMDAssRespFrame (byte[] req, uint panId, MacCoordinatorState state) { #if DEBUG Logger.appendString(csr.s2b("getCMDAssRespFrame(")); Logger.appendUInt (panId); Logger.appendString(csr.s2b(");")); Logger.flush(Mote.INFO); #endif byte[] cmd = new byte[27]; cmd [0] = req [0]; cmd [1] = Radio.FCA_SRC_XADDR | Radio.FCA_DST_XADDR; cmd [2] = Util.rand8 (); Util.set16 (cmd, 3, panId); Util.copyData (req, 9, cmd, 5, 8); Util.set16 (cmd, 13, panId); Mote.getParam (Mote.EUI64, cmd, 15); cmd [23] = (byte)MacState.ASS_RES; if (state.associationPermitted) { Util.set16 (cmd, 24, state.getNextAddr ()); cmd [26] = (byte)MacState.ASS_SUCC; } else { cmd [26] = (byte)MacState.ASS_FAIL; } return cmd; } public static byte[] getCMDDataFrame (uint panId, uint saddr, MacUnassociatedState state) { byte[] cmd; if (state.mySaddr != 0) { cmd = new byte[20]; cmd [1] = Radio.FCA_SRC_SADDR | Radio.FCA_DST_SADDR; Util.set16 (cmd, 9, state.mySaddr); cmd [11] = (byte)MacState.DATA_REQ; Mote.getParam ((uint)Mote.EUI64, cmd, 12); } else { cmd = new byte[18]; cmd [1] = Radio.FCA_SRC_XADDR | Radio.FCA_DST_SADDR; Mote.getParam (Mote.EUI64, cmd, 9); cmd [17] = (byte)MacState.DATA_REQ; } cmd [0] = Radio.FCF_CMD | Radio.FCF_ACKRQ; cmd [2] = (byte)Util.rand8 (); Util.set16 (cmd, 3, panId); Util.set16 (cmd, 5, saddr); if (state.coordinatorSADDR != 0) // it's associated Util.set16 (cmd, 7, panId); else Util.set16 (cmd, 7, Radio.PAN_BROADCAST); return cmd; } // public static void setDataFrame(ref object frame, ref object data, uint panId, uint saddr, uint dsaddr, short seq) { //#if DEBUG // Logger.appendString(csr.s2b("getDataFrame(")); // Logger.appendUInt (panId); // Logger.appendString(csr.s2b(", ")); // Logger.appendUInt (saddr); // Logger.appendString(csr.s2b(", ")); // Logger.appendUInt (dsaddr); // Logger.appendString(csr.s2b(", ")); // Logger.appendInt (seq); // Logger.appendString(csr.s2b(");")); // Logger.flush(Mote.INFO); //#endif // frame = Util.alloca ((byte)(11 + ((byte[])data).Length), Util.BYTE_ARRAY); // Util.set16((byte[])frame,2, (uint)seq); // Util.set16((byte[])frame,0, ((Radio.FCF_DATA | Radio.FCF_ACKRQ)<<8)|Radio.FCA_DST_SADDR | Radio.FCA_SRC_SADDR); // Util.set16(((byte[])frame),3, panId); // Util.set16(((byte[])frame), 5, dsaddr); // Util.set16(((byte[])frame), 7, panId); // Util.set16(((byte[])frame), 9, saddr); // Util.copyData(data, 0, frame, 11, (uint)((byte[])data).Length); // Insert data from upper layer into MAC frame // } public static byte[] getDataHeader (uint panId, uint saddr, uint dsaddr, short seq) { byte[] header = new byte[11]; header [0] = Radio.FCF_DATA | Radio.FCF_ACKRQ; header [1] = Radio.FCA_SRC_SADDR | Radio.FCA_DST_SADDR; header [2] = (byte)seq; Util.set16 (header, 3, panId); Util.set16 (header, 5, dsaddr); // Util.set16 (header, 5, Radio.SADDR_BROADCAST); Util.set16 (header, 7, panId); Util.set16 (header, 9, saddr); return header; } public static byte[] getDataHeader (uint panId, uint saddr, byte[] dsaddr, short seq) { #if DEBUG Logger.appendString(csr.s2b("getDataHaeder(")); Logger.appendUInt (panId); Logger.appendString(csr.s2b(", ")); Logger.appendUInt (saddr); Logger.appendString(csr.s2b(", ")); Logger.appendString(csr.s2b(", ")); Logger.appendInt (seq); Logger.appendString(csr.s2b(");")); Logger.flush(Mote.INFO); #endif Logger.appendString (csr.s2b ("M ")); Logger.appendUInt (panId); Logger.flush (Mote.INFO); byte[] header = new byte[17]; header [0] = Radio.FCF_DATA | Radio.FCF_ACKRQ; header [1] = Radio.FCA_SRC_SADDR | Radio.FCA_DST_XADDR; header [2] = (byte)seq; Util.set16 (header, 3, panId); if (dsaddr != null && dsaddr.Length == 8) { Util.copyData (dsaddr, 0, header, 5, 8); } Util.set16 (header, 13, panId); Util.set16 (header, 15, saddr); return header; } // public static byte[] getDataHeader (uint panId, byte[] saddr, byte[] dsaddr, short seq) // { // settare correttamente FCA in base alla dimensione degli indirizzi //#if DEBUG // Logger.appendString(csr.s2b("getDataHaeder(")); // Logger.appendUInt (panId); // Logger.appendString(csr.s2b(", ")); // Logger.appendInt (seq); // Logger.appendString(csr.s2b(");")); // Logger.flush(Mote.INFO); //#endif // uint dlen = (uint)dsaddr.Length; // uint slen = (uint)saddr.Length; // byte[] header = new byte[7 + slen + dlen]; // header [0] = Radio.FCF_DATA | Radio.FCF_ACKRQ; // header [1] = Radio.FCA_DST_SADDR | Radio.FCA_SRC_SADDR; // header [2] = (byte)seq; // Util.set16 (header, 3, panId); // Util.copyData (dsaddr, 0, header, 5, dlen); // Util.set16 (header, 5 + dlen - 1, panId); // Util.copyData (saddr, 0, header, 7 + dlen - 1, slen); // return header; // } public static uint setEUI (uint flag, byte[] data, byte[] addr, uint off) { if (data == null) return 0; Logger.appendString (csr.s2b ("Setting EUI")); Logger.flush (Mote.INFO); uint srcSaddr = (uint)(data [1] & Radio.FCA_SRC_MASK); uint dstSaddr = (uint)(data [1] & Radio.FCA_DST_MASK); if (flag == DST_ADDR) { if (dstSaddr == Radio.FCA_DST_XADDR) { Util.copyData (addr, off, data, 5, 8); } else ArgumentException.throwIt (ArgumentException.TOO_BIG); } else { if (dstSaddr == Radio.FCA_DST_SADDR && srcSaddr == Radio.FCA_SRC_XADDR) Mote.getParam ((uint)Mote.EUI64, data, 9); else if (dstSaddr == Radio.FCA_DST_XADDR && srcSaddr == Radio.FCA_SRC_XADDR) Mote.getParam ((uint)Mote.EUI64, data, 15); else ArgumentException.throwIt (ArgumentException.TOO_BIG); } return 0; } public static uint getCMDType (byte[] cmd) { uint srcSaddr = (uint)(cmd [1] & Radio.FCA_SRC_MASK); uint dstSaddr = (uint)(cmd [1] & Radio.FCA_DST_MASK); #if DEBUG Logger.appendString(csr.s2b("getCMDType-")); Logger.appendString(csr.s2b("srcSaddr")); Logger.appendUInt (srcSaddr); Logger.appendString(csr.s2b(", ")); Logger.appendString(csr.s2b("dstSaddr")); Logger.appendUInt (dstSaddr); Logger.flush(Mote.INFO); #endif if (dstSaddr == Radio.FCA_DST_SADDR && srcSaddr == Radio.FCA_SRC_SADDR) return (uint)cmd [11]; else if ((dstSaddr == Radio.FCA_DST_SADDR && srcSaddr == Radio.FCA_SRC_XADDR) || (dstSaddr == Radio.FCA_DST_XADDR && srcSaddr == Radio.FCA_SRC_SADDR)) return (uint)cmd [17]; else if (dstSaddr == Radio.FCA_DST_XADDR && srcSaddr == Radio.FCA_SRC_XADDR) return (uint)cmd [23]; else SystemException.throwIt (SystemException.NOT_SUPPORTED); return 0; } public static uint getPayloadPosition (byte[] data) { uint srcSaddr = (uint)(data [1] & Radio.FCA_SRC_MASK); uint dstSaddr = (uint)(data [1] & Radio.FCA_DST_MASK); if (dstSaddr == Radio.FCA_DST_SADDR && srcSaddr == Radio.FCA_SRC_SADDR) return 11; else if ((dstSaddr == Radio.FCA_DST_SADDR && srcSaddr == Radio.FCA_SRC_XADDR) || (dstSaddr == Radio.FCA_DST_XADDR && srcSaddr == Radio.FCA_SRC_SADDR)) return 17; else if (dstSaddr == Radio.FCA_DST_XADDR && srcSaddr == Radio.FCA_SRC_XADDR) return 23; else SystemException.throwIt (SystemException.NOT_SUPPORTED); return 0; } public static uint getSrcSADDR (byte[] data) { uint srcSaddr = (uint)(data [1] & Radio.FCA_SRC_MASK); uint dstSaddr = (uint)(data [1] & Radio.FCA_DST_MASK); if (dstSaddr == Radio.FCA_DST_SADDR && srcSaddr == Radio.FCA_SRC_SADDR) return Util.get16 (data, 9); else if (dstSaddr == Radio.FCA_DST_XADDR && srcSaddr == Radio.FCA_SRC_SADDR) return Util.get16 (data, 15); else ArgumentException.throwIt (ArgumentException.TOO_BIG); return 0; } public static uint getDestSAddr (byte[] data) { uint srcSaddr = (uint)(data [1] & Radio.FCA_SRC_MASK); uint dstSaddr = (uint)(data [1] & Radio.FCA_DST_MASK); if ((dstSaddr == Radio.FCA_DST_SADDR && srcSaddr == Radio.FCA_SRC_SADDR) || (dstSaddr == Radio.FCA_DST_SADDR && srcSaddr == Radio.FCA_SRC_XADDR)) return Util.get16 (data, 5); else ArgumentException.throwIt (ArgumentException.TOO_BIG); return 0; } } }
//--------------------------------------------------------------------------- // // File: RootBrowserWindow.cs // // Description: This class will implement the hosting and bridging logic // between the browser and Avalon. This will be the top // level "frame" that hosts all content in IE. This class // will not be public. // // Created: 04/28/03 // // Copyright (C) 2001 by Microsoft Corporation. All rights reserved. // // History: // hamidm 06/11/03 moved over to wcp tree //--------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Navigation; using MS.Internal.Commands; using MS.Internal.Controls; using MS.Win32; //In order to avoid generating warnings about unknown message numbers and //unknown pragmas when compiling your C# source code with the actual C# compiler, //you need to disable warnings 1634 and 1691. (Presharp Documentation) #pragma warning disable 1634, 1691 namespace MS.Internal.AppModel { /// <summary> /// /// </summary> internal sealed class RootBrowserWindow : NavigationWindow, IWindowService, IJournalNavigationScopeHost { //---------------------------------------------- // // Constructors // //---------------------------------------------- #region Constructors static RootBrowserWindow() { CommandHelpers.RegisterCommandHandler(typeof(RootBrowserWindow), ApplicationCommands.Print, new ExecutedRoutedEventHandler(OnCommandPrint), new CanExecuteRoutedEventHandler(OnQueryEnabledCommandPrint)); } /// <summary> /// /// </summary> /// <SecurityNote> /// Critical:Calls base class constructor that is only present for RBW scenario /// </SecurityNote> [SecurityCritical] private RootBrowserWindow():base(true) { // Allow tabbing out to the browser - see KeyInputSite and OnKeyDown(). // IE 6 doesn't provide the necessary support; notice IsDownlevelPlatform covers Firefox too, // hence the additional IsHostedInIE check. // By checking for the negative top-level case, we allow to tab out of XBAPs hosted in an iframe; // this support is enabled regardless of the browser we're on (to avoid browser-specifics here). bool isIE6 = IsDownlevelPlatform && BrowserInteropHelper.IsHostedInIEorWebOC; if (!(isIE6 && BrowserInteropHelper.IsAvalonTopLevel)) { SetValue(KeyboardNavigation.TabNavigationProperty, KeyboardNavigationMode.Continue); SetValue(KeyboardNavigation.ControlTabNavigationProperty, KeyboardNavigationMode.Continue); } } #endregion Constructors //---------------------------------------------- // // Protected Methods // //---------------------------------------------- #region Protected Methods /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new RootBrowserWindowAutomationPeer(this); } /// <SecurityNote> /// Critical - Hooks up the event handler that sets the status bar text (OnRequestSetStatusBar_Hyperlink). /// TreatAsSafe - Safe to set up the handler over here; OnRequestSetStatusBar_Hyperlink is connected to /// RequestSetStatusBarEvent which is supposed to be raised only by Hyperlink which has the /// anti-spoofing mitigations in place. The RequestSetStatusBarEventArgs used in the event /// is protected as well. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void OnInitialized(EventArgs args) { AddHandler(Hyperlink.RequestSetStatusBarEvent, new RoutedEventHandler(OnRequestSetStatusBar_Hyperlink)); base.OnInitialized(args); } protected override Size MeasureOverride(Size constraint) { return base.MeasureOverride(GetSizeInLogicalUnits()); } protected override Size ArrangeOverride(Size arrangeBounds) { // Get the size of the avalon window and pass it to // the base implementation. The return value tells the Size // that we are occupying. Since, we are RBW we will occupy the // entire available size and thus we don't care what our child wants. base.ArrangeOverride(GetSizeInLogicalUnits()); return arrangeBounds; } protected override void OnStateChanged(EventArgs e) { } protected override void OnLocationChanged(EventArgs e) { } protected override void OnClosing(CancelEventArgs e) { } protected override void OnClosed(EventArgs e) { } ///<SecurityNote> /// Critical - calls the SUC'd IBCS.PostReadyStateChange(). /// TreatAsSafe - Only READYSTATE_COMPLETE is posted, once, at the end of the activation sequence, /// when the browser expects it. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void OnContentRendered(EventArgs e) { base.OnContentRendered(e); // Posting READYSTATE_COMPLETE triggers the WebOC's DocumentComplete event. // Media Center, in particular, uses this to make the WebOC it hosts visible. if (!_loadingCompletePosted) { Browser.PostReadyStateChange(READYSTATE_COMPLETE); _loadingCompletePosted = true; } } protected override void OnKeyDown(KeyEventArgs e) { // In browser apps, Ctrl+Tab switches tabs. F6 simulates it here. if (e.Key == Key.F6 && (e.KeyboardDevice.Modifiers & ~ModifierKeys.Shift) == 0) { if (KeyboardNavigation.Navigate( e.KeyboardDevice.FocusedElement as DependencyObject ?? this, Key.Tab, e.KeyboardDevice.Modifiers | ModifierKeys.Control)) { e.Handled = true; } } if (!e.Handled) { base.OnKeyDown(e); } } #endregion Protected methods //---------------------------------------------- // // Internal Methods // //---------------------------------------------- #region Internal Methods /// <summary> /// Creates the RBW object and sets the Style property on it /// to the correct value /// </summary> /// <SecurityNote> /// Critical: Calls RBW class constructor /// </SecurityNote> [SecurityCritical] internal static RootBrowserWindow CreateAndInitialize() { RootBrowserWindow rbw = new RootBrowserWindow(); rbw.InitializeRBWStyle(); return rbw; } /// <SecurityNote> /// Critical: This code elevates to all window permission /// </SecurityNote> [SecurityCritical] internal override void CreateAllStyle() { Invariant.Assert(App != null, "RootBrowserWindow must be created in an Application"); IHostService ihs = (IHostService)App.GetService(typeof(IHostService)); Invariant.Assert(ihs!=null, "IHostService in RootBrowserWindow cannot be null"); Invariant.Assert(ihs.HostWindowHandle != IntPtr.Zero, "IHostService.HostWindowHandle in RootBrowserWindow cannot be null"); //This sets the _ownerHandle correctly and will be used to create the _sourceWindow //with the correct parent UIPermission uip = new UIPermission(UIPermissionWindow.AllWindows); uip.Assert();//Blessed Assert to set owner handle and to set styles try { this.OwnerHandle = ihs.HostWindowHandle; this.Win32Style = NativeMethods.WS_CHILD | NativeMethods.WS_CLIPCHILDREN | NativeMethods.WS_CLIPSIBLINGS; } finally { CodeAccessPermission.RevertAssert(); } } ///<SecurityNote> /// Critical: Exposes a window handle (ParentWindow). Base class implementation is also Critical. ///</SecurityNote> [SecurityCritical] internal override HwndSourceParameters CreateHwndSourceParameters() { HwndSourceParameters parameters = base.CreateHwndSourceParameters(); parameters.TreatAsInputRoot = true; parameters.TreatAncestorsAsNonClientArea = true; return parameters; } /// <summary> /// Override for SourceWindow creation. /// Virtual only so that we may assert. /// </summary> /// <SecurityNote> /// Critical - Calls critical base-class function. /// Calls critical functions GetAncestor and GetForegroundWindow. /// </SecurityNote> [SecurityCritical] internal override void CreateSourceWindowDuringShow() { Browser.OnBeforeShowNavigationWindow(); base.CreateSourceWindowDuringShow(); Invariant.Assert(IsSourceWindowNull == false, "Failed to create HwndSourceWindow for browser hosting"); // _sourceWindowCreationCompleted specifies that HwndSource creation has completed. This is used // to minimize the SetWindowPos calls from ResizeMove when Height/Width is set prior to calling // show on RBW (this also occurs when Height/Width is set in the style of RBW) _sourceWindowCreationCompleted = true; if (_rectSet) { _rectSet = false; ResizeMove(_xDeviceUnits, _yDeviceUnits, _widthDeviceUnits, _heightDeviceUnits); } // The above window move (resize) operation causes message dispatching, which allows reentrancy // from the browser, which can initiate premature shutdown. if (IsSourceWindowNull) return; SetUpInputHooks(); // // While the RBW is created and shown, the Top Browser window should have already been created and shown, // Browser doesn't notify this RBW of the activation status again unless user activates/deactivates the main // window. It is time to transfer the Top Browser Window's activation status to this RBW so that user's // code can get correct status through property IsActivate. // IntPtr topWindow = UnsafeNativeMethods.GetAncestor(new HandleRef(this, CriticalHandle), 2/*GA_ROOT*/); Debug.Assert(topWindow != IntPtr.Zero); IntPtr activeWindow = UnsafeNativeMethods.GetForegroundWindow(); HandleActivate(activeWindow == topWindow); } // No need to clear App.MainWindow for RBW case. It throws an exception if attempted internal override void TryClearingMainWindow() { } internal override void CorrectStyleForBorderlessWindowCase() { } internal override void GetRequestedDimensions(ref double requestedLeft, ref double requestedTop, ref double requestedWidth, ref double requestedHeight) { requestedTop = 0; requestedLeft = 0; requestedWidth = this.Width; requestedHeight = this.Height; } ///<SecurityNote> /// Critical - It also calls critical method (SetRootVisual) ///</SecurityNote> [SecurityCritical] internal override void SetupInitialState(double requestedTop, double requestedLeft, double requestedWidth, double requestedHeight) { // If RBW Height/Width was set before calling show in RBW, we need // to update the browser with that size now SetBrowserSize(); SetRootVisual(); } internal override int nCmdForShow() { return NativeMethods.SW_SHOW; } internal override bool HandleWmNcHitTestMsg(IntPtr lParam, ref IntPtr refInt) { return false; } internal override WindowMinMax GetWindowMinMax() { return new WindowMinMax(0, double.PositiveInfinity); } // RBW overrides WmMoveChangedHelper default behavior where it calls // either SetValue/CoerceValue on Top/Left DPs since that will // throw an exception for RBW. Furthermore, in RBW, we don't want // to fire LocationChanged event. internal override void WmMoveChangedHelper() { } /// <summary> /// Resizes and moves the RBW (which is a WS_CHILD window). This is called by /// AppProxyInternal when the host callsbacks into it with the new size/location. /// We need this internal since Height/Width/Top/Left on RBW govern the host'ss /// properties. /// </summary> /// <remarks> /// The location of WS_CHILD window is relative to it parent window thus when the /// browser moves it does not call this method since the relative position of this window /// wrt the browser hasn't changed. /// </remarks> /// <param name="xDeviceUnits">New left of the RBW</param> /// <param name="yDeviceUnits">New top of the RBW</param> /// <param name="widthDeviceUnits">New width of the RBW</param> /// <param name="heightDeviceUnits">New height of the RBW</param> ///<SecurityNote> /// Critical as this method handles critical data. /// TreatAsSafe - as the RBW is always contained within the browser's window. /// you can move the internal window all you want - but given that you're really /// contained within the BrowserWindow - the worse you could do is make some of your content not visible. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal void ResizeMove(int xDeviceUnits, int yDeviceUnits, int widthDeviceUnits, int heightDeviceUnits) { // _sourceWindowCreationCompleted specifies that HwndSource creation has completed. This is used // to minimize the SetWindowPos calls from ResizeMove when Height/Width is set prior to calling // show on RBW (this also occurs when Height/Width is set in the style of RBW). Thus, we want to // resize the underlying avalon hwnd only after its creation is completed if (_sourceWindowCreationCompleted == false) { _xDeviceUnits = xDeviceUnits; _yDeviceUnits = yDeviceUnits; _widthDeviceUnits = widthDeviceUnits; _heightDeviceUnits = heightDeviceUnits; _rectSet = true; return; } Invariant.Assert(IsSourceWindowNull == false, "sourceWindow cannot be null if _sourceWindowCreationCompleted is true"); HandleRef handleRef; handleRef = new HandleRef( this, CriticalHandle ) ; UnsafeNativeMethods.SetWindowPos( handleRef , NativeMethods.NullHandleRef, xDeviceUnits, yDeviceUnits, widthDeviceUnits, heightDeviceUnits, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE | NativeMethods.SWP_SHOWWINDOW); } /// <summary> /// This is called when the Title dependency property changes in the Window. /// </summary> ///<SecurityNote> /// Critical - calls SUC'd IHostBrowser.SetTitle /// TreatAsSafe - setting the text on the browser's window is considered safe. /// - spoofing is not possible as the browser prepends it's own string to the string /// e.g. Microsoft Internet Explorer /// - it can be done in partial trust in HTML via the TITLE tag. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override void UpdateTitle(string titleStr) { IBrowserCallbackServices ibcs = Browser; if (ibcs != null) // null on shutdown { string title = PruneTitleString(titleStr); // It's not the end of the world if this fails. // VS's browser in particular returns RPC_E_CALL_REJECTED. // Not sure of other exceptions that might be thrown here, // so keeping this scoped to what's been reported. const int RPC_E_CALL_REJECTED = unchecked((int)0x80010001); try { // SHOULD NOT CALL BASE; BASE IMPLEMENTS TEXT PROPERTY ON WINDOW BrowserInteropHelper.HostBrowser.SetTitle(title); } catch (COMException e) { if (e.ErrorCode != RPC_E_CALL_REJECTED) { throw; } } } } /// <summary> /// This is called by NavigationService to set the status bar content /// for the browser /// </summary> /// <remarks> /// We propagate object.ToString() to the browser's status bar. /// </remarks> ///<SecurityNote> /// Critical - calls SetStatusText which is SUC'ed. /// /// No longer considered TreatAsSafe in order to protect against hyperlink spoofing. /// Browsers implement access restriction to the status bar from script nowadays. ///</SecurityNote> [SecurityCritical] internal void SetStatusBarText(string statusString) { if (BrowserInteropHelper.HostBrowser != null) // could be null if shutting down { BrowserInteropHelper.HostBrowser.SetStatusText(statusString); } } /// <summary> /// Called to update Height of the browser. Currently, this method is called from /// two places: /// /// 1) OnHeightInvalidated from window.cs /// 2) SetBrowserSize in RBW /// </summary> ///<SecurityNote> /// Critical - Can be used to change the size of the browser /// TreatAsSafe - clamps values so that window cannot be sized greater than desktop bounds. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override void UpdateHeight(double newHeightLogicalUnits) { Point sizeDeviceUnits = LogicalToDeviceUnits(new Point(0, newHeightLogicalUnits)); uint heightDeviceUnits = (uint)Math.Round(sizeDeviceUnits.Y); if (BrowserInteropHelper.HostBrowser != null) { // // Note: right now IE is clipping browser height to desktop size. // However it should be clipped to available desktop size. See Windows OS Bug #1045038 // The code below is to fix this for now. // Even if IE's code is changed - likely we keep this as defense in-depth. // uint maxHeightDeviceUnits = GetMaxWindowHeight(); heightDeviceUnits = heightDeviceUnits > maxHeightDeviceUnits ? maxHeightDeviceUnits : heightDeviceUnits; heightDeviceUnits = heightDeviceUnits < MIN_BROWSER_HEIGHT_DEVICE_UNITS ? MIN_BROWSER_HEIGHT_DEVICE_UNITS : heightDeviceUnits; BrowserInteropHelper.HostBrowser.SetHeight(heightDeviceUnits); } } ///<SecurityNote> /// Critical - Can be used to change the size of the browser /// TreatAsSafe - clamps values so that window cannot be sized greater than desktop bounds. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override void UpdateWidth(double newWidthLogicalUnits) { Point sizeDeviceUnits = LogicalToDeviceUnits(new Point(newWidthLogicalUnits, 0)); uint widthDeviceUnits = (uint)Math.Round(sizeDeviceUnits.X); if (BrowserInteropHelper.HostBrowser != null) { // // Note: right now IE is clipping browser width to desktop size. // However it should be clipped to available desktop size. See Windows OS Bug #1045038 // The code below is to fix this for now. // Even if IE's code is changed - likely we keep this as defense in-depth. // uint maxWidthDeviceUnits = GetMaxWindowWidth(); widthDeviceUnits = widthDeviceUnits > maxWidthDeviceUnits ? maxWidthDeviceUnits : widthDeviceUnits; widthDeviceUnits = widthDeviceUnits < MIN_BROWSER_WIDTH_DEVICE_UNITS ? MIN_BROWSER_WIDTH_DEVICE_UNITS : widthDeviceUnits; BrowserInteropHelper.HostBrowser.SetWidth(widthDeviceUnits); } } /// <summary> /// When being reloaded from history in the browser, we need to /// set up the journal again /// </summary> /// <param name="journal"></param> internal void SetJournalForBrowserInterop(Journal journal) { Invariant.Assert(journal != null, "Failed to get Journal for browser integration"); base.JournalNavigationScope.Journal = journal; } void IJournalNavigationScopeHost.OnJournalAvailable() { base.Journal.BackForwardStateChange += new EventHandler(HandleBackForwardStateChange); } // For downlevel platforms, we don't have integration with the journal, so we have to // use our own Journal. ///<SecurityNote> /// Critical - calls IBCS.GoBack ///</SecurityNote> [SecurityCritical] bool IJournalNavigationScopeHost.GoBackOverride() { if (HasTravelLogIntegration) { if (BrowserInteropHelper.HostBrowser != null) { try { BrowserInteropHelper.HostBrowser.GoBack(); } #pragma warning disable 6502 // PRESharp - Catch statements should not have empty bodies catch (OperationCanceledException) { // Catch the OperationCanceledException when the navigation is canceled. // See comments in applicationproxyinternal._LoadHistoryStreamDelegate. } #pragma warning restore 6502 } return true; } return false; // Proceed with internal GoBack. } // For downlevel platforms, we don't have integration with the journal, so we have to // use our own Journal. ///<SecurityNote> /// Critical - calls IBCS.GoForward ///</SecurityNote> [SecurityCritical] bool IJournalNavigationScopeHost.GoForwardOverride() { if (HasTravelLogIntegration) { if (BrowserInteropHelper.HostBrowser != null) { try { BrowserInteropHelper.HostBrowser.GoForward(); } #pragma warning disable 6502 // PRESharp - Catch statements should not have empty bodies catch (OperationCanceledException) { // Catch the OperationCanceledException when the navigation is canceled. // See comments in applicationproxyinternal._LoadHistoryStreamDelegate. } #pragma warning restore 6502 } return true; } return false; // Proceed with internal GoForward. } internal override void VerifyApiSupported() { throw new InvalidOperationException(SR.Get(SRID.NotSupportedInBrowser)); } internal override void ClearResizeGripControl(Control oldCtrl) { // don't do anything here since we do not support // ResizeGrip for RBW } internal override void SetResizeGripControl(Control ctrl) { // don't do anything here since we do not support // ResizeGrip for RBW } // This is called in weboc's static constructor. internal void AddLayoutUpdatedHandler() { LayoutUpdated += new EventHandler(OnLayoutUpdated); } internal void TabInto(bool forward) { TraversalRequest tr = new TraversalRequest( forward ? FocusNavigationDirection.First : FocusNavigationDirection.Last); MoveFocus(tr); } #endregion Internal Methods //---------------------------------------------- // // Private Methods // //---------------------------------------------- #region Private methods /// <summary> /// Sets the correct style property on the RBW object based on the /// browser version /// </summary> private void InitializeRBWStyle() { // If we are on a downlevel platform, then we don't integrate with the browser's // travellog, so we have to use our own Journal and supply our own navigation chrome. if (!HasTravelLogIntegration) { SetResourceReference(StyleProperty, SystemParameters.NavigationChromeDownLevelStyleKey); // if the Template property is not defined in a custom style, the property system gets // the Template property value for the NavigationWindow from the theme file. Since, // we want to get the Template property value from the browser styles, we need to // set the DefaultStyleKeyProperty here. SetValue(DefaultStyleKeyProperty, SystemParameters.NavigationChromeDownLevelStyleKey); } else { SetResourceReference(StyleProperty, SystemParameters.NavigationChromeStyleKey); // if the Template property is not defined in a custom style, the property system gets // the Template property value for the NavigationWindow from the theme file. Since, // we want to get the Template property value from the browser styles, we need to // set the DefaultStyleKeyProperty here. SetValue(DefaultStyleKeyProperty, SystemParameters.NavigationChromeStyleKey); } } /// <SecurityNote> /// Critical - Elevates to get access to the HwndSource and installs hooks. /// TreatAsSafe - The HwndSoure is not exposed. The message hooks installed are internal ones, and they are for the RBW specifically. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void SetUpInputHooks() { IKeyboardInputSink sink; new UIPermission(PermissionState.Unrestricted).Assert(); //BlessedAssert try { _inputPostFilter = new HwndWrapperHook(BrowserInteropHelper.PostFilterInput); HwndSource hwndSource = base.HwndSourceWindow; hwndSource.HwndWrapper.AddHookLast(_inputPostFilter); sink = (IKeyboardInputSink)hwndSource; } finally { UIPermission.RevertAll(); } new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); //BlessedAssert try { Debug.Assert(sink.KeyboardInputSite == null); sink.KeyboardInputSite = new KeyInputSite(new SecurityCriticalData<IKeyboardInputSink>(sink)); } finally { SecurityPermission.RevertAll(); } } /// <summary> /// Updates browser size if Height/Width is not set to default value (NaN). This /// means that Height/Width was set prior to calling Show on RBW and we need to /// propagate that to the browser. This method is called from SetupInitialize which /// is called from CreateSourceWindowImpl /// </summary> private void SetBrowserSize() { Point requestedSizeDeviceUnits = LogicalToDeviceUnits(new Point(this.Width, this.Height)); // if Width was specified if (!DoubleUtil.IsNaN(this.Width)) { // at this stage, ActualWidth/Height is not set since // layout has not happened (it happens when we set the // RootVisual of the HwndSource) UpdateWidth(requestedSizeDeviceUnits.X); } // if Height was specified if (!DoubleUtil.IsNaN(this.Height)) { // at this stage, ActualWidth/Height is not set since // layout has not happened (it happens when we set the // RootVisual of the HwndSource) UpdateHeight(requestedSizeDeviceUnits.Y); } } private string PruneTitleString(string rawString) { StringBuilder sb = new StringBuilder(); bool inMiddleOfWord = false; for (int i=0; i < rawString.Length; i++) { if (Char.IsWhiteSpace(rawString[i]) == false) { sb.Append(rawString[i]); inMiddleOfWord = true; } else { if (inMiddleOfWord == true) { sb.Append(' '); inMiddleOfWord = false; } } } // remove the last space if it exists return sb.ToString().TrimEnd(' '); } private void OnLayoutUpdated(object obj, EventArgs args) { try { VerifyWebOCOverlap(NavigationService); } finally { _webBrowserList.Clear(); } } private void VerifyWebOCOverlap(NavigationService navigationService) { for (int i = 0; i < navigationService.ChildNavigationServices.Count; i++) { NavigationService childNavService = (NavigationService)(navigationService.ChildNavigationServices[i]); WebBrowser webBrowser = childNavService.WebBrowser; if (webBrowser != null) { for (int j = 0; j < _webBrowserList.Count; j++) { // Note: We are using WebBrowser.BoundRect, which is relative to parent window. // Since WebBrowsers are all siblings child windows right now, e.g., we don't allow WebOC inside // Popup window, this is a better performed way. If we change that, we should make sure the rects // to compare are relative to desktop. Rect rect = Rect.Intersect(webBrowser.BoundRect, _webBrowserList[j].BoundRect); // Only when the intersect rect's Width and Height are both bigger than 0, we consider them overlapping. // Even when 2 edges are next to each other, it is considered as intersect by the Rect class. if ((rect.Width > 0) && (rect.Height > 0)) { throw new InvalidOperationException(SR.Get(SRID.WebBrowserOverlap)); } } _webBrowserList.Add(webBrowser); } else { VerifyWebOCOverlap(childNavService); } } } /// <summary> /// We are not using the CanGoBack/CanGoForward property change since that is fired only /// if the value changes eg. if we had 3 entries in the backstack, then a back navigation /// won't fire this since the value is still 'true' and has not changed. /// What we need is the UpdateView() notification or the BackForwardState change /// notification which is fired from UpdateView() of the Journal. /// Trying to hook the event will create the journal even if there was no navigation /// so just using an virtual override to do the work. /// </summary> ///<SecurityNote> /// Critical - as this method calls into Browser call back method for back and forward. /// This is a pinoke call. /// TreatAsSafe - as this is a safe operation. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void HandleBackForwardStateChange(object sender, EventArgs args) { //Nothing to do for downlevel platform if (!HasTravelLogIntegration) return; IBrowserCallbackServices ibcs = Browser; if (ibcs != null) { ibcs.UpdateBackForwardState(); } } ///<summary> /// Given a proposed width - and curWidth - return the MaxWidth the window can be opened to. /// Used to prevent sizing of window > desktop bounds in browser. ///</summary> ///<SecurityNote> /// Critical - calls back to browser to get the current left. /// TreatAsSafe - this value isn't returned or stored. /// value returned is the current maximum width allowed considered safe. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe ] private uint GetMaxWindowWidth() { NativeMethods.RECT desktopArea = WorkAreaBoundsForNearestMonitor; int browserLeft = BrowserInteropHelper.HostBrowser.GetLeft(); uint curBrowserWidth = BrowserInteropHelper.HostBrowser.GetWidth(); uint availableWidth = (uint)(desktopArea.right - browserLeft); uint maxWidth = availableWidth > curBrowserWidth ? availableWidth : curBrowserWidth; return maxWidth; } ///<summary> /// Given a proposed height - and curHeight - return the MaxHeight the window can be opened to. /// Used to prevent sizing of window > desktop bounds in browser. ///</summary> ///<SecurityNote> /// Critical - calls back to browser to get the current top. /// TreatAsSafe - this value isn't returned or stored. /// value returned is the current maximum height allowed considered safe. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe ] private uint GetMaxWindowHeight() { NativeMethods.RECT desktopArea = WorkAreaBoundsForNearestMonitor; int browserTop = BrowserInteropHelper.HostBrowser.GetTop(); uint curBrowserHeight = BrowserInteropHelper.HostBrowser.GetHeight(); uint availableHeight = (uint)(desktopArea.bottom - browserTop); uint maxHeight = availableHeight > curBrowserHeight ? availableHeight : curBrowserHeight; return maxHeight; } ///<summary> ///For browser hosting cases, we get the rects through OLE activation before we create the ///RootBrowserWindow. Even if SourceWindow or Handle are null, we can return the cached rects ///</summary> private Size GetSizeInLogicalUnits() { Size size; // Adding check for IsCompositionTargetInvalid as part of the fix for WOSB 1453012 if (IsSourceWindowNull || IsCompositionTargetInvalid) { // return _widthDeviceUnits & _heightDeviceUnits if hwndsource is not yet available. // We will resize when hwnd becomes available, because the DeviceToLogicalUnits calculation // depends on hwnd being available. If it's not high dpi, the second resize will be optimized // by layout system. size = new Size(_widthDeviceUnits, _heightDeviceUnits); } else { // It's better to get WindowSize instead of doing WindowSize.Width & WindowSize.Height // because WindowSize queries HwndSource. size = WindowSize; Point ptLogicalUnits = DeviceToLogicalUnits(new Point(size.Width, size.Height)); size = new Size(ptLogicalUnits.X, ptLogicalUnits.Y); } return size; } /// <SecurityNote> /// Critical - Sets the status bar text. Can be used to do URL spoofing. /// </SecurityNote> [SecurityCritical] private void OnRequestSetStatusBar_Hyperlink(object sender, RoutedEventArgs e) { RequestSetStatusBarEventArgs statusEvent = e as RequestSetStatusBarEventArgs; if ( statusEvent != null ) { SetStatusBarText(statusEvent.Text); } } ///<summary> /// Prints the content of the App's MainWindow. The logic is that if the content is not visual but IInputElement /// we will try to let it handle the command first. If it does not handle the print command we will get the corresponding /// visual in the visual tree and use that to print. ///</summary> private static void OnCommandPrint(object sender, ExecutedRoutedEventArgs e) { #if !DONOTREFPRINTINGASMMETA RootBrowserWindow rbw = sender as RootBrowserWindow; Invariant.Assert(rbw != null); if (! rbw._isPrintingFromRBW) { Visual vis = rbw.Content as Visual; if (vis == null) { // If the content is not Visual but IInputElement, try to let it handle the command first. // This is for the document scenario. Printing a document is different from printing a visual. // Printing a visual is to print how it is rendered on screen. Printing a doc prints the full // doc inculding the part that is not visible. There might be other functionalities that are // specific for document. FlowDocument's viewer knows how to print the doc. IInputElement target = rbw.Content as IInputElement; if (target != null) { // CanExecute will bubble up. If nobody between the content and rbw can handle it, // It would call back on RBW again. Use _isPrintingFromRBW to prevent the loop. rbw._isPrintingFromRBW = true; try { if (ApplicationCommands.Print.CanExecute(null, target)) { ApplicationCommands.Print.Execute(null, target); return; } } finally { rbw._isPrintingFromRBW = false; } } } // Let the user choose a printer and set print options. PrintDialog printDlg = new PrintDialog(); // If the user pressed the OK button on the print dialog, we proceed if (printDlg.ShowDialog() == true) { string printJobDescription = GetPrintJobDescription(App.MainWindow); // If the root is not visual and does not know how to print itself, we find the // corresponding visual and use that to print. if (vis == null) { INavigatorImpl navigator = rbw as INavigatorImpl; Invariant.Assert(navigator != null); vis = navigator.FindRootViewer(); Invariant.Assert(vis != null); } // Area we can print to for the chosen printer Rect imageableRect = GetImageableRect(printDlg); // We print Visuals aligned with the top/left corner of the printable area. // We do not attempt to print very large Visuals across multiple pages. // Any portion that doesn't fit on a single page will get cropped by the // print system. // Used to draw our visual into another visual for printing purposes VisualBrush visualBrush = new VisualBrush(vis); visualBrush.Stretch = Stretch.None; // Visual we will print - containing a rectangle the size of our // original Visual but offset into the printable area DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext context = drawingVisual.RenderOpen(); context.DrawRectangle(visualBrush, null, new Rect(imageableRect.X, imageableRect.Y, vis.VisualDescendantBounds.Width, vis.VisualDescendantBounds.Height)); context.Close(); printDlg.PrintVisual(drawingVisual, printJobDescription); } } #endif // DONOTREFPRINTINGASMMETA } private static void OnQueryEnabledCommandPrint(object sender, CanExecuteRoutedEventArgs e) { RootBrowserWindow rbw = sender as RootBrowserWindow; Invariant.Assert(rbw != null); if ((!e.Handled) && (!rbw._isPrintingFromRBW)) { // While we could print null it doesn't really make sense to do so e.CanExecute = rbw.Content != null; } } #if !DONOTREFPRINTINGASMMETA ///<SecurityNote> /// Critical - calls out to PrintDialog to get the PrintQueue and its PrintCapabilities /// TreatAsSafe - these values aren't returned or stored ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private static Rect GetImageableRect(PrintDialog dialog) { Rect imageableRect = Rect.Empty; Invariant.Assert(dialog != null, "Dialog should not be null."); System.Printing.PrintQueue queue = null; System.Printing.PrintCapabilities capabilities = null; System.Printing.PageImageableArea imageableArea = null; // This gets the PringDocumentImageableArea.OriginWidth/OriginHeight // of the PrintQueue the user chose in the dialog. CodeAccessPermission printp = SystemDrawingHelper.NewDefaultPrintingPermission(); printp.Assert();//Blessed Assert to get PrintQueue and call GetPrintCapabilities try { queue = dialog.PrintQueue; if (queue != null) { capabilities = queue.GetPrintCapabilities(); } } finally { CodeAccessPermission.RevertAssert(); } if (capabilities != null) { imageableArea = capabilities.PageImageableArea; if (imageableArea != null) { imageableRect = new Rect(imageableArea.OriginWidth, imageableArea.OriginHeight, imageableArea.ExtentWidth, imageableArea.ExtentHeight); } } // If for any reason we couldn't get the actual printer's values // we fallback to a constant and the values available from the // PrintDialog. if (imageableRect == Rect.Empty) { imageableRect = new Rect(NON_PRINTABLE_MARGIN, NON_PRINTABLE_MARGIN, dialog.PrintableAreaWidth, dialog.PrintableAreaHeight); } return imageableRect; } #endif /// <summary> /// Generate the title of the print job for a given Window. /// </summary> private static string GetPrintJobDescription(Window window) { Invariant.Assert(window != null, "Window should not be null."); string description = null; string pageTitle = null; // Get the window title string windowTitle = window.Title; if (windowTitle != null) { windowTitle = windowTitle.Trim(); } // Get the page title, if available Page page = window.Content as Page; if (page != null) { pageTitle = page.Title; if (pageTitle != null) { pageTitle = pageTitle.Trim(); } } // If window and page title are available, use them together, // otherwise use which ever is available if (!String.IsNullOrEmpty(windowTitle)) { if (!String.IsNullOrEmpty(pageTitle)) { description = SR.Get(SRID.PrintJobDescription, windowTitle, pageTitle); } else { description = windowTitle; } } // No window title so use the page title on its own if (description == null && !String.IsNullOrEmpty(pageTitle)) { description = pageTitle; } // If neither window or page titles are available, try and use // the source URI for the content if (description == null && BrowserInteropHelper.Source != null) { Uri source = BrowserInteropHelper.Source; if (source.IsFile) { description = source.LocalPath; } else { description = source.ToString(); } } // If no other option, use a localized constant if (description == null) { description = SR.Get(SRID.UntitledPrintJobDescription); } return description; } #endregion Private methods //---------------------------------------------- // // Private Properties // //---------------------------------------------- #region Private properties private static Application App { get { return Application.Current; } } private static IBrowserCallbackServices Browser { get { // There will be no IBrowserCallbackServices available in some situations, e.g., during shutdown IBrowserCallbackServices ibcs = (App == null ? null : App.BrowserCallbackServices); return ibcs; } } ///<SecurityNote> /// Critical - calls the SUC'd IBCS.IsDownlevelPlatform. /// TreatAsSafe - this information is okay to give out. ///</SecurityNote> private bool IsDownlevelPlatform { [SecurityCritical, SecurityTreatAsSafe] get { if (!_isDownlevelPlatformValid) { IBrowserCallbackServices ibcs = Browser; _isDownlevelPlatform = (ibcs != null) ? ibcs.IsDownlevelPlatform() : false; _isDownlevelPlatformValid = true; } return _isDownlevelPlatform; } } internal bool HasTravelLogIntegration { get { return !IsDownlevelPlatform && BrowserInteropHelper.IsAvalonTopLevel; } } #endregion Private properties //---------------------------------------------- // // Private Classes // //---------------------------------------------- #region Private Classes /// <summary> /// This class is used to print objects which are not directly supported by XpsDocumentWriter. /// It's sole purpose is to make a non-abstract version of Visual. /// </summary> private class PrintVisual : ContainerVisual { } private class KeyInputSite : IKeyboardInputSite { internal KeyInputSite(SecurityCriticalData<IKeyboardInputSink> sink) { _sink = sink; } /// <SecurityNote> /// Critical: sets critical data. /// Safe: setting to null is okay. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] void IKeyboardInputSite.Unregister() { _sink = new SecurityCriticalData<IKeyboardInputSink>(null); } /// <SecurityNote> /// Critical: IKeyboardInputSink could be used to spoof input. /// </SecurityNote> IKeyboardInputSink IKeyboardInputSite.Sink { [SecurityCritical] get { return _sink.Value; } } /// <SecurityNote> /// Critical: calls the SUC'd IBCS.TabOut(). /// Safe: tabbing out of the application is safe. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] bool IKeyboardInputSite.OnNoMoreTabStops(TraversalRequest request) { return Browser.TabOut(request.FocusNavigationDirection == FocusNavigationDirection.Next); // i. Tabbing-in is handled by ApplicationProxyInternal. } /// <SecurityNote> /// Critical: The encapsulated interface could be used to spoof input. /// </SecurityNote> SecurityCriticalData<IKeyboardInputSink> _sink; }; #endregion Private Classes //---------------------------------------------- // // Private Members // //---------------------------------------------- #region private members //Cache the values until the HwndSourceWindow is created private int _xDeviceUnits, _yDeviceUnits, _widthDeviceUnits, _heightDeviceUnits; private bool _rectSet; private bool _isPrintingFromRBW; private bool _isDownlevelPlatformValid; private bool _isDownlevelPlatform; private bool _sourceWindowCreationCompleted; private List<WebBrowser> _webBrowserList = new List<WebBrowser>(); /// <summary> /// The event delegate has to be stored because HwndWrapper keeps only a weak reference to it. /// </summary> /// <SecurityNote> /// Critical: could be used to spoof input /// </SecurityNote> [SecurityCritical] private HwndWrapperHook _inputPostFilter; private bool _loadingCompletePosted; const int READYSTATE_COMPLETE = 4; // Fallback constant for the size of non-printable margin. This is used if // we cant retrieve the actual size from the PrintQueue. private const int NON_PRINTABLE_MARGIN = 15; // // Setting these as the min-browser width & height. // Note that we can't use User's min window-width & height - these are specifically about browser window. // private const int MIN_BROWSER_WIDTH_DEVICE_UNITS = 200; private const int MIN_BROWSER_HEIGHT_DEVICE_UNITS = 200; #endregion private members } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Msagl.Core; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.GraphAlgorithms; using Graph = Microsoft.Msagl.Core.GraphAlgorithms.BasicGraph<Microsoft.Msagl.Layout.Layered.IntEdge>; namespace Microsoft.Msagl.Layout.Layered { /// <summary> /// balances the layers by moving vertices with /// the same number of input-output edges to feasible layers with fewer nodes /// </summary> internal class Balancing : AlgorithmBase{ Set<int> jumpers = new Set<int>(); Dictionary<int, IntPair> possibleJumperFeasibleIntervals; /// <summary> /// numbers of vertices in layers /// </summary> int[] vertsCounts; Graph dag; int[] layering; int[] nodeCount; /// <summary> /// balances the layers by moving vertices with /// the same number of input-output edges to feasible layers with fiewer nodes /// </summary> /// <param name="dag">the layered graph</param> /// <param name="layering">the layering to change</param> /// <param name="nodeCount">shows how many nodes are represented be a node</param> /// <param name="cancelObj"></param> static internal void Balance(Graph dag, int[] layering, int[] nodeCount, CancelToken cancelObj) { Balancing b = new Balancing(dag, layering, nodeCount); b.Run(cancelObj); } Balancing(Graph dag, int[] layering, int[]nodeCount) { this.nodeCount = nodeCount; this.dag = dag; this.layering = layering; Init(); } protected override void RunInternal() { while (jumpers.Count > 0) Jump(ChooseJumper()); } void Init() { CalculateLayerCounts(); InitJumpers(); } void Jump(int jumper) { ProgressStep(); this.jumpers.Delete(jumper); IntPair upLow = this.possibleJumperFeasibleIntervals[jumper]; int jumperLayer, layerToJumpTo; if (this.CalcJumpInfo(upLow.x, upLow.y, jumper, out jumperLayer, out layerToJumpTo)) { this.layering[jumper] = layerToJumpTo; int jumperCount = nodeCount[jumper]; this.vertsCounts[jumperLayer] -= jumperCount; this.vertsCounts[layerToJumpTo] += jumperCount; UpdateRegionsForPossibleJumpersAndInsertJumpers(jumperLayer, jumper); } } bool IsJumper(int v) { return possibleJumperFeasibleIntervals.ContainsKey(v); } /// <summary> /// some other jumpers may stop being ones if the jump /// was just in to their destination layer, so before the actual /// jump we have to recheck if the jump makes sense /// /// </summary> /// <param name="jumperLayer">old layer of jumper</param> /// <param name="jumper"></param> void UpdateRegionsForPossibleJumpersAndInsertJumpers(int jumperLayer, int jumper) { Set<int> neighborPossibleJumpers = new Set<int>(); //update possible jumpers neighbors foreach (int v in new Pred(dag, jumper)) if (IsJumper(v)) { this.CalculateRegionAndInsertJumper(v); neighborPossibleJumpers.Insert(v); } foreach (int v in new Succ(dag, jumper)) if (IsJumper(v)) { this.CalculateRegionAndInsertJumper(v); neighborPossibleJumpers.Insert(v); } List<int> possibleJumpersToUpdate = new List<int>(); foreach (KeyValuePair<int, IntPair> kv in this.possibleJumperFeasibleIntervals) { if (!neighborPossibleJumpers.Contains(kv.Key)) if (kv.Value.x > jumperLayer && kv.Value.y < jumperLayer) possibleJumpersToUpdate.Add(kv.Key); } foreach (int v in possibleJumpersToUpdate) this.CalculateRegionAndInsertJumper(v); } void InitJumpers() { int[] deltas = new int[this.dag.NodeCount]; foreach (IntEdge ie in dag.Edges) { deltas[ie.Source] -= ie.Weight; deltas[ie.Target] += ie.Weight; } this.possibleJumperFeasibleIntervals = new Dictionary<int, IntPair>(); for (int i = 0; i < dag.NodeCount; i++) if (deltas[i] == 0) CalculateRegionAndInsertJumper(i); } void CalculateRegionAndInsertJumper(int i) { IntPair ip = new IntPair(Up(i), Down(i)); this.possibleJumperFeasibleIntervals[i] = ip; InsertJumper(ip.x, ip.y, i); } void InsertJumper(int upLayer, int lowLayer, int jumper) { int jumperLayer; int layerToJumpTo; if (CalcJumpInfo(upLayer, lowLayer, jumper, out jumperLayer, out layerToJumpTo)) this.jumpers.Insert(jumper); } /// <summary> /// layerToJumpTo is -1 if there is no jump /// </summary> /// <param name="upLayer"></param> /// <param name="lowLayer"></param> /// <param name="jumper"></param> /// <param name="jumperLayer"></param> /// <param name="layerToJumpTo"></param> private bool CalcJumpInfo(int upLayer, int lowLayer, int jumper, out int jumperLayer, out int layerToJumpTo) { jumperLayer = layering[jumper]; layerToJumpTo = -1; int min = this.vertsCounts[jumperLayer] - 2*nodeCount[jumper]; // jump makes sense if some layer has less than min vertices for (int i = upLayer - 1; i > jumperLayer; i--) if (vertsCounts[i] < min) { min = vertsCounts[i]; layerToJumpTo = i; } for (int i = jumperLayer - 1; i > lowLayer; i--) if (vertsCounts[i] < min) { min = vertsCounts[i]; layerToJumpTo = i; } return layerToJumpTo != -1; } /// <summary> /// Up returns the first infeasible layer up from i that i cannot jump to /// </summary> /// <param name="i"></param> /// <returns></returns> int Up(int i) { int ret = Int32.MaxValue; //minimum of incoming edge sources layeres foreach (IntEdge ie in dag.InEdges(i)) { int r = layering[ie.Source] - ie.Separation + 1; if (r < ret) ret = r; } if (ret == Int32.MaxValue) ret = layering[i] + 1;// return ret; } /// <summary> /// Returns the first infeasible layer down from i that i cannot jump to /// </summary> /// <param name="i"></param> /// <returns></returns> int Down(int i) { int ret = -Int32.MaxValue; foreach (IntEdge ie in dag.OutEdges(i)) { int r = layering[ie.Target] + ie.Separation - 1; if (r > ret) ret = r; } if (ret == -Int32.MaxValue) ret = layering[i] - 1; return ret; } void CalculateLayerCounts() { this.vertsCounts = new int[layering.Max() + 1]; foreach (int r in layering) vertsCounts[r] += nodeCount[r]; } int ChooseJumper() { //just return the first available foreach (int jumper in this.jumpers) return jumper; System.Diagnostics.Debug.Assert(false,"there are no jumpers to choose"); return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Net; namespace AdnWebAPI { #region Categories & Severity Enum /// <summary> /// Helps enumerate the Activity from where the log is being made /// </summary> internal enum Categories { Configuration = 2010, ServiceCall = 3010, Outlook = 4010, Outlook_StarterKit = 4020, Outlook_GetAll = 4030, Outlook_Create = 4040, Outlook_Update = 4050, Outlook_Delete = 4060, Outlook_RelatedEntity = 4070, Outlook_CustomTab = 4080, Outlook_WF = 4090, Unknown = 5010, Excel = 6010, Excel_StarterKit = 6020, Excel_GetAll = 6030, Excel_Create = 6040, Excel_Update = 6050, Excel_Delete = 6060, }; /// <summary> /// Severity of the message being logged /// </summary> internal enum Severity { Info = 0, Warning = 1, Error = 2, Verbose = 3 }; #endregion #region Logger Class /// <summary> /// This class provides api to log the necessary information to eventviewer or local file. The class uses System.Trace api and therefore the logging can be enabled through app.config. For details ref /// This class can be extended to support any other custom logging (including third party logs) /// </summary> static class Logger { #region Logger Initializer /// <summary> /// We initialize the logger activitiy id /// </summary> static Logger() { GenerateActivityID(); } #endregion #region Log Methods internal static System.Diagnostics.TraceSwitch traceLevel = new System.Diagnostics.TraceSwitch("TraceLevel", "Level of messages to log"); /// <summary> /// This method would allow the user to log messages to the configured log location /// You may choose not to enter any object[] args at the end. /// </summary> /// <param name="severityInfo">Please set the severity of the message being logged</param> /// <param name="categoryType">This would help the user to mention the scenario from where the message is being logged</param> /// <param name="logMessage">The actual message that needs to be logged</param> /// <param name="args">Place holder for any variable that needs to be logged (Type: object[])</param> internal static void Log(Severity severityInfo, Categories categoryType, string logMessage, params object[] args) { if (traceLevel.Level != System.Diagnostics.TraceLevel.Off) { string formattedLogMessage = GetFormattedMessage(logMessage, categoryType,severityInfo,args); switch (severityInfo) { case Severity.Verbose: if (traceLevel.Level == System.Diagnostics.TraceLevel.Verbose) { Trace.TraceInformation(formattedLogMessage); } break; case Severity.Info: if (traceLevel.Level == System.Diagnostics.TraceLevel.Info||traceLevel.Level == TraceLevel.Verbose) { Trace.TraceInformation(formattedLogMessage); } break; case Severity.Error: Trace.TraceError(formattedLogMessage); break; case Severity.Warning: if (traceLevel.Level == System.Diagnostics.TraceLevel.Verbose || traceLevel.Level == System.Diagnostics.TraceLevel.Info || traceLevel.Level == System.Diagnostics.TraceLevel.Warning) { Trace.TraceWarning(formattedLogMessage); } break; default: break; } } } #endregion #region Log Exceptions Handler /// <summary> /// This method will log the exception message /// </summary> /// <param name="exception">exception</param> /// <param name="categoryType">cateogry type - outlook,read,getall, create..</param> /// <param name="severityInfo">severity info - error, info,verbose,warning</param> internal static void LogException(Severity severityInfo, Categories categoryType, Exception exception) { StringBuilder errorBuilder = new StringBuilder(); GetExceptionMessage(exception, ref errorBuilder); if (exception.InnerException != null) { GetExceptionMessage(exception.InnerException, ref errorBuilder); } Log(severityInfo, categoryType, errorBuilder.ToString()); } /// <summary> /// This method will log the custom message along with the exception traces /// </summary> /// <param name="exception">exception</param> /// <param name="categoryType">cateogry type - outlook,read,getall, create..</param> /// <param name="severityInfo">severity info - error, info,verbose,warning</param> /// <param name="customErrorMessage">custom messages</param> internal static void LogException(Severity severityInfo, Categories categoryType, string customErrorMessage,Exception exception) { Logger.Log(severityInfo, categoryType, customErrorMessage); Logger.LogException(severityInfo, categoryType, exception); } /// <summary> /// This method will log the exception message /// </summary> /// <param name="exception">exception</param> /// <param name="categoryType">cateogry type - outlook,read,getall, create..</param> /// <param name="severityInfo">severity info - error, info,verbose,warning</param> internal static void LogException(Severity severityInfo, Categories categoryType, WebException exception) { StringBuilder errorBuilder = new StringBuilder(); GetExceptionMessage(exception, ref errorBuilder); if (exception.InnerException != null) { GetExceptionMessage(exception.InnerException, ref errorBuilder); } Log(severityInfo, categoryType, errorBuilder.ToString()); } /// <summary> /// This method will log the custom message along with the exception traces /// </summary> /// <param name="exception">exception</param> /// <param name="categoryType">cateogry type - outlook,read,getall, create..</param> /// <param name="severityInfo">severity info - error, info,verbose,warning</param> /// <param name="customErrorMessage">custom messages</param> internal static void LogException(Severity severityInfo, Categories categoryType, string customErrorMessage, WebException exception) { Logger.Log(severityInfo, categoryType, customErrorMessage); Logger.LogException(severityInfo, categoryType, exception); } /// <summary> /// This method will log the exception message /// </summary> /// <param name="exception">exception</param> /// <param name="categoryType">cateogry type - outlook,read,getall, create..</param> /// <param name="severityInfo">severity info - error, info,verbose,warning</param> internal static void LogException(Severity severityInfo, Categories categoryType, COMException exception) { StringBuilder errorBuilder = new StringBuilder(); GetExceptionMessage(exception, ref errorBuilder); if (exception.InnerException != null) { GetExceptionMessage(exception.InnerException, ref errorBuilder); } Log(severityInfo, categoryType, errorBuilder.ToString()); } /// <summary> /// This method will log the custom message along with the exception traces /// </summary> /// <param name="exception">exception</param> /// <param name="categoryType">cateogry type - outlook,read,getall, create..</param> /// <param name="severityInfo">severity info - error, info,verbose,warning</param> /// <param name="customErrorMessage">custom messages</param> internal static void LogException(Severity severityInfo, Categories categoryType, string customErrorMessage, COMException exception) { Logger.Log(severityInfo, categoryType, customErrorMessage); Logger.LogException(severityInfo, categoryType, exception); } #endregion #region Activity Id Handling public static string ActivityID { get; set; } /// <summary> /// This method will generate a new guid for the E2E tracing. /// </summary> public static string GenerateActivityID() { ActivityID = System.Guid.NewGuid().ToString().Replace("-", ""); return ActivityID; } #endregion #region Log Helper methods /// <summary> /// This method will return the formatted message /// </summary> /// <param name="message">log message</param> /// <param name="severity">severity type like info, verbose,error, warning</param> /// <param name="categoryType">category type</param> /// <param name="args">additional params</param> /// <returns>formatted string</returns> private static string GetFormattedMessage(string message, Categories categoryType,Severity severity, params object[] args) { string formattedMessage = message; if (args.Length != 0) { formattedMessage = String.Format(CultureInfo.InvariantCulture, formattedMessage, args); } formattedMessage = string.Format(CultureInfo.InvariantCulture, "{4} \t ActivityID: {3} \t Category: {1} \t Severity: {2} \t Details: {0}", formattedMessage, categoryType,severity,ActivityID,DateTime.Now); return formattedMessage; } /// <summary> /// This method will get the detailed error from the exception /// </summary> /// <param name="exception"></param> /// <param name="errorBuilder"></param> private static void GetExceptionMessage(Exception exception, ref StringBuilder errorBuilder) { errorBuilder.Append("Error Source: " + exception.Source); errorBuilder.Append("Error Message: " + exception.Message); errorBuilder.Append("StackTrace: " + exception.StackTrace); } /// <summary> /// This method will get the detailed error from the com exception /// </summary> /// <param name="exception"></param> /// <param name="errorBuilder"></param> private static void GetDetailedErrorFromException(COMException exception, ref StringBuilder errorBuilder) { errorBuilder.Append("HResult: " + exception.ErrorCode); GetExceptionMessage(exception, ref errorBuilder); } /// <summary> /// This method will get the detailed error from the WebException exception /// </summary> /// <param name="exception"></param> /// <param name="errorBuilder"></param> private static void GetDetailedErrorFromException(WebException exception, ref StringBuilder errorBuilder) { if (exception.Response != null) { errorBuilder.Append("Status Code: " + ((HttpWebResponse)exception.Response).StatusCode); } GetExceptionMessage(exception, ref errorBuilder); } #endregion } #endregion }
/* * 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.Collections.Specialized; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenMetaverse; using OpenMetaverse.StructuredData; using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo; namespace OpenSim.Services.Connectors.SimianGrid { /// <summary> /// Connects avatar presence information (for tracking current location and /// message routing) to the SimianGrid backend /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class SimianPresenceServiceConnector : IPresenceService, IGridUserService, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_serverUrl = String.Empty; private SimianActivityDetector m_activityDetector; private bool m_Enabled = false; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { } public SimianPresenceServiceConnector() { m_activityDetector = new SimianActivityDetector(this); } public string Name { get { return "SimianPresenceServiceConnector"; } } public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IPresenceService>(this); scene.RegisterModuleInterface<IGridUserService>(this); m_activityDetector.AddRegion(scene); LogoutRegionAgents(scene.RegionInfo.RegionID); } } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IPresenceService>(this); scene.UnregisterModuleInterface<IGridUserService>(this); m_activityDetector.RemoveRegion(scene); LogoutRegionAgents(scene.RegionInfo.RegionID); } } #endregion ISharedRegionModule public SimianPresenceServiceConnector(IConfigSource source) { CommonInit(source); } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("PresenceServices", ""); if (name == Name) CommonInit(source); } } private void CommonInit(IConfigSource source) { IConfig gridConfig = source.Configs["PresenceService"]; if (gridConfig != null) { string serviceUrl = gridConfig.GetString("PresenceServerURI"); if (!String.IsNullOrEmpty(serviceUrl)) { if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("=")) serviceUrl = serviceUrl + '/'; m_serverUrl = serviceUrl; m_Enabled = true; } } if (String.IsNullOrEmpty(m_serverUrl)) m_log.Info("[SIMIAN PRESENCE CONNECTOR]: No PresenceServerURI specified, disabling connector"); } #region IPresenceService public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID) { m_log.ErrorFormat("[SIMIAN PRESENCE CONNECTOR]: Login requested, UserID={0}, SessionID={1}, SecureSessionID={2}", userID, sessionID, secureSessionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddSession" }, { "UserID", userID.ToString() } }; if (sessionID != UUID.Zero) { requestArgs["SessionID"] = sessionID.ToString(); requestArgs["SecureSessionID"] = secureSessionID.ToString(); } OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to login agent " + userID + ": " + response["Message"].AsString()); return success; } public bool LogoutAgent(UUID sessionID) { // m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for agent with sessionID " + sessionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "RemoveSession" }, { "SessionID", sessionID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agent with sessionID " + sessionID + ": " + response["Message"].AsString()); return success; } public bool LogoutRegionAgents(UUID regionID) { // m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for all agents in region " + regionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "RemoveSessions" }, { "SceneID", regionID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agents from region " + regionID + ": " + response["Message"].AsString()); return success; } public bool ReportAgent(UUID sessionID, UUID regionID) { // Not needed for SimianGrid return true; } public PresenceInfo GetAgent(UUID sessionID) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent with sessionID " + sessionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetSession" }, { "SessionID", sessionID.ToString() } }; OSDMap sessionResponse = WebUtil.PostToService(m_serverUrl, requestArgs); if (sessionResponse["Success"].AsBoolean()) { UUID userID = sessionResponse["UserID"].AsUUID(); m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID); requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs); if (userResponse["Success"].AsBoolean()) return ResponseToPresenceInfo(sessionResponse, userResponse); else m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString()); } else { m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session " + sessionID + ": " + sessionResponse["Message"].AsString()); } return null; } public PresenceInfo[] GetAgents(string[] userIDs) { List<PresenceInfo> presences = new List<PresenceInfo>(userIDs.Length); for (int i = 0; i < userIDs.Length; i++) { UUID userID; if (UUID.TryParse(userIDs[i], out userID) && userID != UUID.Zero) presences.AddRange(GetSessions(userID)); } return presences.ToArray(); } #endregion IPresenceService #region IGridUserService public GridUserInfo LoggedIn(string userID) { // Never implemented at the sim return null; } public bool LoggedOut(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Logging out user " + userID); // Remove the session to mark this user offline if (!LogoutAgent(sessionID)) return false; // Save our last position as user data NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "LastLocation", SerializeLocation(regionID, lastPosition, lastLookAt) } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString()); return success; } public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Setting home location for user " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "HomeLocation", SerializeLocation(regionID, position, lookAt) } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set home location for " + userID + ": " + response["Message"].AsString()); return success; } public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { return UpdateSession(sessionID, regionID, lastPosition, lastLookAt); } public GridUserInfo GetGridUserInfo(string user) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent " + user); UUID userID = new UUID(user); // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs); if (userResponse["Success"].AsBoolean()) return ResponseToGridUserInfo(userResponse); else m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString()); return null; } #endregion #region Helpers private OSDMap GetUserData(UUID userID) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean() && response["User"] is OSDMap) return response; else m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + response["Message"].AsString()); return null; } private List<PresenceInfo> GetSessions(UUID userID) { List<PresenceInfo> presences = new List<PresenceInfo>(1); OSDMap userResponse = GetUserData(userID); if (userResponse != null) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting sessions for " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetSession" }, { "UserID", userID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { PresenceInfo presence = ResponseToPresenceInfo(response, userResponse); if (presence != null) presences.Add(presence); } // else // { // m_log.Debug("[SIMIAN PRESENCE CONNECTOR]: No session returned for " + userID + ": " + response["Message"].AsString()); // } } return presences; } private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { // Save our current location as session data NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "UpdateSession" }, { "SessionID", sessionID.ToString() }, { "SceneID", regionID.ToString() }, { "ScenePosition", lastPosition.ToString() }, { "SceneLookAt", lastLookAt.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString()); return success; } private PresenceInfo ResponseToPresenceInfo(OSDMap sessionResponse, OSDMap userResponse) { if (sessionResponse == null) return null; PresenceInfo info = new PresenceInfo(); info.UserID = sessionResponse["UserID"].AsUUID().ToString(); info.RegionID = sessionResponse["SceneID"].AsUUID(); return info; } private GridUserInfo ResponseToGridUserInfo(OSDMap userResponse) { if (userResponse != null && userResponse["User"] is OSDMap) { GridUserInfo info = new GridUserInfo(); info.Online = true; info.UserID = userResponse["UserID"].AsUUID().ToString(); info.LastRegionID = userResponse["SceneID"].AsUUID(); info.LastPosition = userResponse["ScenePosition"].AsVector3(); info.LastLookAt = userResponse["SceneLookAt"].AsVector3(); OSDMap user = (OSDMap)userResponse["User"]; info.Login = user["LastLoginDate"].AsDate(); info.Logout = user["LastLogoutDate"].AsDate(); DeserializeLocation(user["HomeLocation"].AsString(), out info.HomeRegionID, out info.HomePosition, out info.HomeLookAt); return info; } return null; } private string SerializeLocation(UUID regionID, Vector3 position, Vector3 lookAt) { return "{" + String.Format("\"SceneID\":\"{0}\",\"Position\":\"{1}\",\"LookAt\":\"{2}\"", regionID, position, lookAt) + "}"; } private bool DeserializeLocation(string location, out UUID regionID, out Vector3 position, out Vector3 lookAt) { OSDMap map = null; try { map = OSDParser.DeserializeJson(location) as OSDMap; } catch { } if (map != null) { regionID = map["SceneID"].AsUUID(); if (Vector3.TryParse(map["Position"].AsString(), out position) && Vector3.TryParse(map["LookAt"].AsString(), out lookAt)) { return true; } } regionID = UUID.Zero; position = Vector3.Zero; lookAt = Vector3.Zero; return false; } #endregion Helpers } }
using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography; using Neo.Cryptography.ECC; using Neo.IO; using Neo.Network.P2P; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.SmartContract.Manifest; using Neo.SmartContract.Native; using Neo.UnitTests.Extensions; using Neo.VM; using Neo.Wallets; using System; using System.Linq; namespace Neo.UnitTests.SmartContract { public partial class UT_InteropService { [TestMethod] public void TestCheckSig() { var engine = GetEngine(true); IVerifiable iv = engine.ScriptContainer; byte[] message = iv.GetSignData(ProtocolSettings.Default.Network); byte[] privateKey = { 0x01,0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}; KeyPair keyPair = new KeyPair(privateKey); ECPoint pubkey = keyPair.PublicKey; byte[] signature = Crypto.Sign(message, privateKey, pubkey.EncodePoint(false).Skip(1).ToArray()); engine.CheckSig(pubkey.EncodePoint(false), signature).Should().BeTrue(); Action action = () => engine.CheckSig(new byte[70], signature); action.Should().Throw<FormatException>(); } [TestMethod] public void TestCrypto_CheckMultiSig() { var engine = GetEngine(true); IVerifiable iv = engine.ScriptContainer; byte[] message = iv.GetSignData(ProtocolSettings.Default.Network); byte[] privkey1 = { 0x01,0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}; KeyPair key1 = new KeyPair(privkey1); ECPoint pubkey1 = key1.PublicKey; byte[] signature1 = Crypto.Sign(message, privkey1, pubkey1.EncodePoint(false).Skip(1).ToArray()); byte[] privkey2 = { 0x01,0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02}; KeyPair key2 = new KeyPair(privkey2); ECPoint pubkey2 = key2.PublicKey; byte[] signature2 = Crypto.Sign(message, privkey2, pubkey2.EncodePoint(false).Skip(1).ToArray()); var pubkeys = new[] { pubkey1.EncodePoint(false), pubkey2.EncodePoint(false) }; var signatures = new[] { signature1, signature2 }; engine.CheckMultisig(pubkeys, signatures).Should().BeTrue(); pubkeys = new byte[0][]; Assert.ThrowsException<ArgumentException>(() => engine.CheckMultisig(pubkeys, signatures)); pubkeys = new[] { pubkey1.EncodePoint(false), pubkey2.EncodePoint(false) }; signatures = new byte[0][]; Assert.ThrowsException<ArgumentException>(() => engine.CheckMultisig(pubkeys, signatures)); pubkeys = new[] { pubkey1.EncodePoint(false), pubkey2.EncodePoint(false) }; signatures = new[] { signature1, new byte[64] }; engine.CheckMultisig(pubkeys, signatures).Should().BeFalse(); pubkeys = new[] { pubkey1.EncodePoint(false), new byte[70] }; signatures = new[] { signature1, signature2 }; Assert.ThrowsException<FormatException>(() => engine.CheckMultisig(pubkeys, signatures)); } [TestMethod] public void TestContract_Create() { var snapshot = TestBlockchain.GetTestSnapshot(); var nef = new NefFile() { Script = Enumerable.Repeat((byte)OpCode.RET, byte.MaxValue).ToArray(), Source = string.Empty, Compiler = "", Tokens = System.Array.Empty<MethodToken>() }; nef.CheckSum = NefFile.ComputeChecksum(nef); var nefFile = nef.ToArray(); var manifest = TestUtils.CreateDefaultManifest(); Assert.ThrowsException<InvalidOperationException>(() => snapshot.DeployContract(null, nefFile, manifest.ToJson().ToByteArray(false))); Assert.ThrowsException<ArgumentException>(() => snapshot.DeployContract(UInt160.Zero, nefFile, new byte[ContractManifest.MaxLength + 1])); Assert.ThrowsException<InvalidOperationException>(() => snapshot.DeployContract(UInt160.Zero, nefFile, manifest.ToJson().ToByteArray(true), 10000000)); var script_exceedMaxLength = new NefFile() { Script = new byte[NefFile.MaxScriptLength - 1], Source = string.Empty, Compiler = "", Tokens = System.Array.Empty<MethodToken>() }; script_exceedMaxLength.CheckSum = NefFile.ComputeChecksum(nef); Assert.ThrowsException<InvalidOperationException>(() => snapshot.DeployContract(UInt160.Zero, script_exceedMaxLength.ToArray(), manifest.ToJson().ToByteArray(true))); var script_zeroLength = System.Array.Empty<byte>(); Assert.ThrowsException<ArgumentException>(() => snapshot.DeployContract(UInt160.Zero, script_zeroLength, manifest.ToJson().ToByteArray(true))); var manifest_zeroLength = System.Array.Empty<byte>(); Assert.ThrowsException<ArgumentException>(() => snapshot.DeployContract(UInt160.Zero, nefFile, manifest_zeroLength)); manifest = TestUtils.CreateDefaultManifest(); var ret = snapshot.DeployContract(UInt160.Zero, nefFile, manifest.ToJson().ToByteArray(false)); ret.Hash.ToString().Should().Be("0x7b37d4bd3d87f53825c3554bd1a617318235a685"); Assert.ThrowsException<InvalidOperationException>(() => snapshot.DeployContract(UInt160.Zero, nefFile, manifest.ToJson().ToByteArray(false))); var state = TestUtils.GetContract(); snapshot.AddContract(state.Hash, state); Assert.ThrowsException<InvalidOperationException>(() => snapshot.DeployContract(UInt160.Zero, nefFile, manifest.ToJson().ToByteArray(false))); } [TestMethod] public void TestContract_Update() { var snapshot = TestBlockchain.GetTestSnapshot(); var nef = new NefFile() { Script = new[] { (byte)OpCode.RET }, Source = string.Empty, Compiler = "", Tokens = System.Array.Empty<MethodToken>() }; nef.CheckSum = NefFile.ComputeChecksum(nef); Assert.ThrowsException<InvalidOperationException>(() => snapshot.UpdateContract(null, nef.ToArray(), new byte[0])); var manifest = TestUtils.CreateDefaultManifest(); byte[] privkey = { 0x01,0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}; KeyPair key = new KeyPair(privkey); ECPoint pubkey = key.PublicKey; var state = TestUtils.GetContract(); byte[] signature = Crypto.Sign(state.Hash.ToArray(), privkey, pubkey.EncodePoint(false).Skip(1).ToArray()); manifest.Groups = new ContractGroup[] { new ContractGroup() { PubKey = pubkey, Signature = signature } }; var storageItem = new StorageItem { Value = new byte[] { 0x01 } }; var storageKey = new StorageKey { Id = state.Id, Key = new byte[] { 0x01 } }; snapshot.AddContract(state.Hash, state); snapshot.Add(storageKey, storageItem); state.UpdateCounter.Should().Be(0); snapshot.UpdateContract(state.Hash, nef.ToArray(), manifest.ToJson().ToByteArray(false)); var ret = NativeContract.ContractManagement.GetContract(snapshot, state.Hash); snapshot.Find(BitConverter.GetBytes(state.Id)).ToList().Count().Should().Be(1); ret.UpdateCounter.Should().Be(1); ret.Id.Should().Be(state.Id); ret.Manifest.ToJson().ToString().Should().Be(manifest.ToJson().ToString()); ret.Script.ToHexString().Should().Be(nef.Script.ToHexString().ToString()); } [TestMethod] public void TestContract_Update_Invalid() { var nefFile = new NefFile() { Script = new byte[] { 0x01 }, Source = string.Empty, Compiler = "", Tokens = System.Array.Empty<MethodToken>() }; nefFile.CheckSum = NefFile.ComputeChecksum(nefFile); var snapshot = TestBlockchain.GetTestSnapshot(); Assert.ThrowsException<InvalidOperationException>(() => snapshot.UpdateContract(null, null, new byte[] { 0x01 })); Assert.ThrowsException<InvalidOperationException>(() => snapshot.UpdateContract(null, nefFile.ToArray(), null)); Assert.ThrowsException<ArgumentException>(() => snapshot.UpdateContract(null, null, null)); nefFile = new NefFile() { Script = new byte[0], Source = string.Empty, Compiler = "", Tokens = System.Array.Empty<MethodToken>() }; nefFile.CheckSum = NefFile.ComputeChecksum(nefFile); Assert.ThrowsException<InvalidOperationException>(() => snapshot.UpdateContract(null, nefFile.ToArray(), new byte[] { 0x01 })); Assert.ThrowsException<InvalidOperationException>(() => snapshot.UpdateContract(null, nefFile.ToArray(), new byte[0])); } [TestMethod] public void TestStorage_Find() { var snapshot = TestBlockchain.GetTestSnapshot(); var state = TestUtils.GetContract(); var storageItem = new StorageItem { Value = new byte[] { 0x01, 0x02, 0x03, 0x04 } }; var storageKey = new StorageKey { Id = state.Id, Key = new byte[] { 0x01 } }; snapshot.AddContract(state.Hash, state); snapshot.Add(storageKey, storageItem); var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot); engine.LoadScript(new byte[] { 0x01 }); var iterator = engine.Find(new StorageContext { Id = state.Id, IsReadOnly = false }, new byte[] { 0x01 }, FindOptions.ValuesOnly); iterator.Next(); var ele = iterator.Value(); ele.GetSpan().ToHexString().Should().Be(storageItem.Value.ToHexString()); } } }
/* Copyright 2019 Esri 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.Windows.Forms; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.SystemUI; using ESRI.ArcGIS; using ESRI.ArcGIS.ADF.CATIDs; namespace CommandsEnvironment { public class CommandsEnvironment : System.Windows.Forms.Form { internal System.Windows.Forms.ComboBox ComboBox1; private ESRI.ArcGIS.Controls.AxSymbologyControl axSymbologyControl1; private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1; private ESRI.ArcGIS.Controls.AxPageLayoutControl axPageLayoutControl1; private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1; private System.ComponentModel.Container components = null; private IGraphicProperties m_graphicProperties; public CommandsEnvironment() { InitializeComponent(); } protected override void Dispose( bool disposing ) { //Release COM objects ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown(); if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(CommandsEnvironment)); this.ComboBox1 = new System.Windows.Forms.ComboBox(); this.axSymbologyControl1 = new ESRI.ArcGIS.Controls.AxSymbologyControl(); this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.axPageLayoutControl1 = new ESRI.ArcGIS.Controls.AxPageLayoutControl(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); ((System.ComponentModel.ISupportInitialize)(this.axSymbologyControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); this.SuspendLayout(); // // ComboBox1 // this.ComboBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ComboBox1.Location = new System.Drawing.Point(456, 8); this.ComboBox1.Name = "ComboBox1"; this.ComboBox1.Size = new System.Drawing.Size(264, 21); this.ComboBox1.TabIndex = 4; this.ComboBox1.Text = "ComboBox1"; this.ComboBox1.SelectedIndexChanged += new System.EventHandler(this.ComboBox1_SelectedIndexChanged); // // axSymbologyControl1 // this.axSymbologyControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.axSymbologyControl1.Location = new System.Drawing.Point(456, 40); this.axSymbologyControl1.Name = "axSymbologyControl1"; this.axSymbologyControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axSymbologyControl1.OcxState"))); this.axSymbologyControl1.Size = new System.Drawing.Size(265, 265); this.axSymbologyControl1.TabIndex = 5; this.axSymbologyControl1.OnItemSelected += new ESRI.ArcGIS.Controls.ISymbologyControlEvents_Ax_OnItemSelectedEventHandler(this.axSymbologyControl1_OnItemSelected); // // axToolbarControl1 // this.axToolbarControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.axToolbarControl1.Location = new System.Drawing.Point(8, 8); this.axToolbarControl1.Name = "axToolbarControl1"; this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState"))); this.axToolbarControl1.Size = new System.Drawing.Size(440, 28); this.axToolbarControl1.TabIndex = 6; // // axPageLayoutControl1 // this.axPageLayoutControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.axPageLayoutControl1.Location = new System.Drawing.Point(8, 40); this.axPageLayoutControl1.Name = "axPageLayoutControl1"; this.axPageLayoutControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axPageLayoutControl1.OcxState"))); this.axPageLayoutControl1.Size = new System.Drawing.Size(440, 432); this.axPageLayoutControl1.TabIndex = 7; this.axPageLayoutControl1.OnMouseDown += new ESRI.ArcGIS.Controls.IPageLayoutControlEvents_Ax_OnMouseDownEventHandler(this.axPageLayoutControl1_OnMouseDown); // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(336, 24); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(32, 32); this.axLicenseControl1.TabIndex = 8; // // Form1 // //Removed setting for AutoScaleBaseSize //this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); //set AutoScaleDimensions & AutoScaleMode to allow AdjustBounds to scale controls correctly at 120 dpi this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(728, 478); this.Controls.Add(this.axLicenseControl1); this.Controls.Add(this.axPageLayoutControl1); this.Controls.Add(this.axToolbarControl1); this.Controls.Add(this.axSymbologyControl1); this.Controls.Add(this.ComboBox1); this.Name = "Form1"; this.Text = "Updating the Command Environment"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.axSymbologyControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); this.ResumeLayout(false); } #endregion [STAThread] static void Main() { if (!RuntimeManager.Bind(ProductCode.Engine)) { if (!RuntimeManager.Bind(ProductCode.Desktop)) { MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down."); return; } } Application.Run(new CommandsEnvironment()); } private void Form1_Load(object sender, System.EventArgs e) { //Resize the controls so that they scale correctly at both 96 and 120 dpi AdjustBounds(this.axToolbarControl1); AdjustBounds(this.axLicenseControl1); AdjustBounds(this.axPageLayoutControl1); AdjustBounds(this.axSymbologyControl1); //Set the buddy control axToolbarControl1.SetBuddyControl(axPageLayoutControl1); //Add items to the ToolbarControl axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand", -1, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsPageZoomInTool", -1, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsPageZoomOutTool", -1, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsPageZoomWholePageCommand", -1, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsSelectTool", -1, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsNewMarkerTool", -1, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsNewLineTool", -1, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsNewFreeHandTool", -1, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsNewRectangleTool", -1, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); axToolbarControl1.AddItem("esriControls.ControlsNewPolygonTool", -1, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); //Get the ArcGIS install location by opening the subkey for reading //Load the ESRI.ServerStyle file into the SymbologyControl string installationFolder = ESRI.ArcGIS.RuntimeManager.ActiveRuntime.Path; axSymbologyControl1.LoadStyleFile(installationFolder + "\\Styles\\ESRI.ServerStyle"); //Add style classes to the combo box ComboBox1.Items.Add("Default Marker Symbol"); ComboBox1.Items.Add("Default Line Symbol"); ComboBox1.Items.Add("Default Fill Symbol"); ComboBox1.Items.Add("Default Text Symbol"); ComboBox1.SelectedIndex = 0; //Update each style class. This forces item to be loaded into each style class. //When the contents of a server style file are loaded into the SymbologyControl //items are 'demand loaded'. This is done to increase performance and means //items are only loaded into a SymbologyStyleClass when it is the current StyleClass. axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassMarkerSymbols).Update(); axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassLineSymbols).Update(); axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassFillSymbols).Update(); axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassTextSymbols).Update(); //Get the CommandsEnvironment singleton m_graphicProperties = new CommandsEnvironmentClass(); //Create a new ServerStyleGalleryItem and set its name IStyleGalleryItem styleGalleryItem = new ServerStyleGalleryItemClass(); styleGalleryItem.Name = "myStyle"; ISymbologyStyleClass styleClass; //Get the marker symbol style class styleClass = axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassMarkerSymbols); //Set the commands environment marker symbol into the item styleGalleryItem.Item = m_graphicProperties.MarkerSymbol; //Add the item to the style class styleClass.AddItem(styleGalleryItem, 0); //Get the line symbol style class styleClass = axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassLineSymbols); //Set the commands environment line symbol into the item styleGalleryItem.Item = m_graphicProperties.LineSymbol; //Add the item to the style class styleClass.AddItem(styleGalleryItem, 0); //Get the fill symbol style class styleClass = axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassFillSymbols); //Set the commands environment fill symbol into the item styleGalleryItem.Item = m_graphicProperties.FillSymbol; //Add the item to the style class styleClass.AddItem(styleGalleryItem, 0); //Get the text symbol style class styleClass = axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassTextSymbols); //Set the commands environment text symbol into the item styleGalleryItem.Item = m_graphicProperties.TextSymbol; //Add the item to the style class styleClass.AddItem(styleGalleryItem, 0); } private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e) { //Set the SymbologyControl style class if (ComboBox1.SelectedItem.ToString() == "Default Marker Symbol") axSymbologyControl1.StyleClass = esriSymbologyStyleClass.esriStyleClassMarkerSymbols; else if (ComboBox1.SelectedItem.ToString() == "Default Line Symbol") axSymbologyControl1.StyleClass = esriSymbologyStyleClass.esriStyleClassLineSymbols; else if (ComboBox1.SelectedItem.ToString() == "Default Fill Symbol") axSymbologyControl1.StyleClass = esriSymbologyStyleClass.esriStyleClassFillSymbols; else if (ComboBox1.SelectedItem.ToString() == "Default Text Symbol") axSymbologyControl1.StyleClass = esriSymbologyStyleClass.esriStyleClassTextSymbols; } private void axSymbologyControl1_OnItemSelected(object sender, ESRI.ArcGIS.Controls.ISymbologyControlEvents_OnItemSelectedEvent e) { IStyleGalleryItem styleGalleryItem = (IStyleGalleryItem) e.styleGalleryItem; if (styleGalleryItem.Item is IMarkerSymbol) //Set the default marker symbol m_graphicProperties.MarkerSymbol = (IMarkerSymbol) styleGalleryItem.Item; else if (styleGalleryItem.Item is ILineSymbol) //Set the default line symbol m_graphicProperties.LineSymbol = (ILineSymbol) styleGalleryItem.Item; else if (styleGalleryItem.Item is IFillSymbol) //Set the default fill symbol m_graphicProperties.FillSymbol = (IFillSymbol) styleGalleryItem.Item; else if (styleGalleryItem.Item is ITextSymbol) //Set the default text symbol m_graphicProperties.TextSymbol = (ITextSymbol) styleGalleryItem.Item; } private void axPageLayoutControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IPageLayoutControlEvents_OnMouseDownEvent e) { if (e.button != 2) return; //Create a new point IPoint pPoint = new PointClass(); pPoint.PutCoords(e.pageX, e.pageY); //Create a new text element ITextElement textElement = new TextElementClass(); //Set the text to display today's date textElement.Text = DateTime.Now.ToShortDateString(); //Add element to graphics container using the CommandsEnvironment default text symbol axPageLayoutControl1.AddElement((IElement) textElement, pPoint, m_graphicProperties.TextSymbol, "", 0); //Refresh the graphics axPageLayoutControl1.Refresh(esriViewDrawPhase.esriViewGraphics, null, null); } private void AdjustBounds(AxHost controlToAdjust) { if (this.CurrentAutoScaleDimensions.Width != 6F) { //Adjust location: ActiveX control doesn't do this by itself controlToAdjust.Left = Convert.ToInt32(controlToAdjust.Left * this.CurrentAutoScaleDimensions.Width / 6F); //Undo the automatic resize... controlToAdjust.Width = controlToAdjust.Width / DPIX() * 96; //...and apply the appropriate resize controlToAdjust.Width = Convert.ToInt32(controlToAdjust.Width * this.CurrentAutoScaleDimensions.Width / 6F); } if (this.CurrentAutoScaleDimensions.Height != 13F) { //Adjust location: ActiveX control doesn't do this by itself controlToAdjust.Top = Convert.ToInt32(controlToAdjust.Top * this.CurrentAutoScaleDimensions.Height / 13F); //Undo the automatic resize... controlToAdjust.Height = controlToAdjust.Height / DPIY() * 96; //...and apply the appropriate resize controlToAdjust.Height = Convert.ToInt32(controlToAdjust.Height * this.CurrentAutoScaleDimensions.Height / 13F); } } [System.Runtime.InteropServices.DllImport("Gdi32.dll")] static extern int GetDeviceCaps(IntPtr hDC, int nIndex); [System.Runtime.InteropServices.DllImport("Gdi32.dll")] static extern IntPtr CreateDC(string lpszDriver, string lpszDeviceName, string lpszOutput, IntPtr devMode); const int LOGPIXELSX = 88; const int LOGPIXELSY = 90; int DPIX() { return DPI(LOGPIXELSX); } int DPIY() { return DPI(LOGPIXELSY); } int DPI(int logPixelOrientation) { IntPtr displayPointer = CreateDC("DISPLAY", null, null, IntPtr.Zero); return Convert.ToInt32(GetDeviceCaps(displayPointer, logPixelOrientation)); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; [Flags] public enum InterruptSettings { Normal = 0x00000000, Fast = 0x00000001, LevelSensitive = 0x00000000, EdgeSensitive = 0x00000002, ActiveLowOrFalling = 0x00000000, ActiveHighOrRising = 0x00000004, ActiveLow = LevelSensitive | ActiveLowOrFalling, ActiveHigh = LevelSensitive | ActiveHighOrRising, FallingEdge = EdgeSensitive | ActiveLowOrFalling, RisingEdge = EdgeSensitive | ActiveHighOrRising, } public enum InterruptPriority { Lowest = 255, BelowNormal = 200, Normal = 127, AboveNormal = 50, Highest = 0, } public abstract class InterruptController { public delegate void Callback( InterruptData data ); /// <summary> /// This structure contains the interrupt handler and any data associated with the interrupt. /// Context and Subcontext is interrupt dependent data and is not required to be set. /// </summary> public struct InterruptData { public uint Context; public uint Subcontext; public Handler Handler; } public class Handler { // // State // private readonly int m_index; internal readonly InterruptPriority m_priority; private readonly InterruptSettings m_settings; private readonly Callback m_callback; internal readonly RT.KernelNode< Handler > m_node; // // Constructor Methods // private Handler( int index , InterruptPriority priority , InterruptSettings settings , Callback callback ) { m_index = index; m_priority = priority; m_settings = settings; m_callback = callback; m_node = new RT.KernelNode< Handler >( this ); } // // Helper Methods // public static Handler Create( int index , InterruptPriority priority , InterruptSettings settings , Callback callback ) { return new Handler( index, priority, settings, callback ); } public void Enable() { NVIC.EnableInterrupt( m_index ); } public void Disable() { NVIC.DisableInterrupt( m_index ); } public void Invoke( InterruptData interruptData ) { m_callback( interruptData ); } // // Access Methods // public int Index { get { return m_index; } } public bool IsFastHandler { [RT.Inline] get { return (m_settings & InterruptSettings.Fast) != 0; } } public bool IsEdgeSensitive { [RT.Inline] get { return (m_settings & InterruptSettings.EdgeSensitive) != 0; } } public bool IsActiveHighOrRising { [RT.Inline] get { return (m_settings & InterruptSettings.ActiveHighOrRising) != 0;; } } } //--// static private readonly int c_Invalid = 0xFFFF; // ProcessorARMv[7|6]M.IRQn_Type.Invalid // // State // private RT.KernelList< Handler > m_handlers; private System.Threading.Thread m_interruptThread; private RT.KernelCircularBuffer<InterruptData> m_interrupts; // // Helper Methods // public void Initialize() { m_handlers = new RT.KernelList< Handler >(); m_interrupts = new RT.KernelCircularBuffer<InterruptData>(32); m_interruptThread = new System.Threading.Thread(DispatchInterrupts); m_interruptThread.Priority = System.Threading.ThreadPriority.Highest; } public void Activate() { m_interruptThread.Start(); } //--// public void RegisterAndEnable( Handler hnd ) { Register( hnd ); hnd.Enable(); } public void Register( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); var newPriority = hnd.m_priority; int priorityIdx = 0; // // Insert the handler in priority order and rebuild the Interrupt Priority Registers table. // for(RT.KernelNode<Handler> node = m_handlers.StartOfForwardWalk; ; node = node.Next) { if(hnd != null) { if(node.IsValidForForwardMove == false || node.Target.m_priority < newPriority) { var newNode = hnd.m_node; newNode.InsertBefore( node ); node = newNode; hnd = null; } } if(node.IsValidForForwardMove == false) { break; } NVIC.SetPriority( node.Target.Index, (uint)priorityIdx++ ); } } //--// public void DeregisterAndDisable( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.Disable(); Deregister( hnd ); } public void Deregister( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.m_node.RemoveFromList(); } //--// public void ProcessInterrupt() { ProcessInterrupt( false ); } //// [RT.MemoryRequirements( RT.MemoryAttributes.Unpaged )] public void ProcessFastInterrupt() { ProcessInterrupt( true ); } public void ProcessInterrupt( bool fFastOnly ) { InterruptData data; int activeInterrupt = GetNextActiveInterupt(); data.Context = 0; data.Subcontext = 0; while (activeInterrupt != c_Invalid) { RT.KernelNode<Handler> node = m_handlers.StartOfForwardWalk; while (true) { if (node.IsValidForForwardMove == false) { break; } Handler hnd = node.Target; if (hnd.Index == activeInterrupt) { data.Handler = hnd; if ( hnd.IsFastHandler ) { hnd.Invoke(data); } else { PostInterrupt(data); } } node = node.Next; } ClearInterrupt(activeInterrupt); activeInterrupt = GetNextActiveInterupt(); } } public virtual int GetNextActiveInterupt() { return c_Invalid; } public virtual void ClearInterrupt( int interrupt ) { } public void CauseInterrupt() { NVIC.SetPending( Board.Instance.GetSystemTimerIRQNumber() ); } public void ContinueUnderNormalInterrupt( RT.Peripherals.Continuation dlg ) { } public void PostInterrupt(InterruptData interruptData) { RT.BugCheck.AssertInterruptsOff(); m_interrupts.EnqueueNonblocking(interruptData); } private void DispatchInterrupts() { while (true) { InterruptData intr = m_interrupts.DequeueBlocking(); if (intr.Handler != null) { intr.Handler.Invoke( intr ); } } } // // Access Methods // public static extern InterruptController Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Nest { [ContractJsonConverter(typeof(IndexSettingsConverter))] public interface IDynamicIndexSettings : IIsADictionary<string, object> { /// <summary> ///The number of replicas each primary shard has. Defaults to 1. /// </summary> int? NumberOfReplicas { get; set; } /// <summary> ///Auto-expand the number of replicas based on the number of available nodes. /// Set to a dash delimited lower and upper bound (e.g. 0-5) or use all for the upper bound (e.g. 0-all). Defaults to false (i.e. disabled). /// </summary> //TODO SPECIAL TYPE FOR THIS INSTEAD OF JUST STRING string AutoExpandReplicas { get; set; } /// <summary> /// How often to perform a refresh operation, which makes recent changes to the index visible to search. /// Defaults to 1s. Can be set to -1 to disable refresh. /// </summary> Time RefreshInterval { get; set; } /// <summary> /// Set to true to make the index and index metadata read only, false to allow writes and metadata changes. /// </summary> bool? BlocksReadOnly { get; set; } /// <summary> /// Set to true to disable read operations against the index. /// </summary> bool? BlocksRead { get; set; } /// <summary> /// Set to true to disable write operations against the index. /// </summary> bool? BlocksWrite { get; set; } /// <summary> /// Set to true to disable index metadata reads and writes. /// </summary> bool? BlocksMetadata { get; set; } /// <summary> /// Unallocated shards are recovered in order of priority when set /// </summary> int? Priority { get; set; } /// <summary> /// A primary shard is only recovered only if there are /// enough nodes available to allocate sufficient replicas to form a quorum. /// </summary> Union<int, RecoveryInitialShards> RecoveryInitialShards { get; set; } /// <summary> /// Enables the shard-level request cache. Not enabled by default. /// </summary> bool? RequestsCacheEnabled { get; set; } /// <summary> /// The allocation of replica shards which become unassigned because a node has left can be /// delayed with this dynamic setting, which defaults to 1m. /// </summary> Time UnassignedNodeLeftDelayedTimeout { get; set; } /// <summary> /// The maximum number of shards (replicas and primaries) that will be allocated to a single node. Defaults to unbounded. /// </summary> int? RoutingAllocationTotalShardsPerNode { get; set; } /// <summary> /// All of the settings exposed in the merge module are expert only and may be obsoleted in the future at any time! /// </summary> IMergeSettings Merge { get; set; } /// <summary> /// Configure logging thresholds and levels in elasticsearch for search/fetch and indexing /// </summary> ISlowLog SlowLog { get; set; } /// <summary> /// Configure translog settings. This should only be used by experts who know what they're doing /// </summary> ITranslogSettings Translog { get; set; } /// <summary> /// Configure analysis /// </summary> IAnalysis Analysis { get; set; } } public class DynamicIndexSettings : IsADictionaryBase<string, object>, IDynamicIndexSettings { public DynamicIndexSettings() { } public DynamicIndexSettings(IDictionary<string, object> container) : base(container) { } /// <inheritdoc/> public int? NumberOfReplicas { get; set; } /// <inheritdoc/> public string AutoExpandReplicas { get; set; } /// <inheritdoc/> public bool? BlocksMetadata { get; set; } /// <inheritdoc/> public bool? BlocksRead { get; set; } /// <inheritdoc/> public bool? BlocksReadOnly { get; set; } /// <inheritdoc/> public bool? BlocksWrite { get; set; } /// <inheritdoc/> public int? Priority { get; set; } /// <inheritdoc/> public bool? RequestsCacheEnabled { get; set; } /// <inheritdoc/> public IMergeSettings Merge { get; set; } /// <inheritdoc/> public Union<int, RecoveryInitialShards> RecoveryInitialShards { get; set; } /// <inheritdoc/> public Time RefreshInterval { get; set; } /// <inheritdoc/> public int? RoutingAllocationTotalShardsPerNode { get; set; } /// <inheritdoc/> public ISlowLog SlowLog { get; set; } /// <inheritdoc/> public ITranslogSettings Translog { get; set; } /// <inheritdoc/> public Time UnassignedNodeLeftDelayedTimeout { get; set; } /// <inheritdoc/> public IAnalysis Analysis { get; set; } /// <summary> /// Add any setting to the index /// </summary> public void Add(string setting, object value) => this.BackingDictionary.Add(setting, value); } public class DynamicIndexSettingsDescriptor : DynamicIndexSettingsDescriptorBase<DynamicIndexSettingsDescriptor, DynamicIndexSettings> { public DynamicIndexSettingsDescriptor() : base(new DynamicIndexSettings()) { } } public abstract class DynamicIndexSettingsDescriptorBase<TDescriptor, TIndexSettings> : IsADictionaryDescriptorBase<TDescriptor, TIndexSettings, string, object> where TDescriptor : DynamicIndexSettingsDescriptorBase<TDescriptor, TIndexSettings> where TIndexSettings : class, IDynamicIndexSettings { protected DynamicIndexSettingsDescriptorBase(TIndexSettings instance) : base(instance) { } /// <summary> /// Add any setting to the index /// </summary> public TDescriptor Setting(string setting, object value) { this.PromisedValue.Add(setting, value); return (TDescriptor)this; } /// <inheritdoc/> public TDescriptor NumberOfReplicas(int? numberOfReplicas) => Assign(a => a.NumberOfReplicas = numberOfReplicas); /// <inheritdoc/> public TDescriptor AutoExpandReplicas(string autoExpandReplicas) => Assign(a => a.AutoExpandReplicas = autoExpandReplicas); /// <inheritdoc/> public TDescriptor BlocksMetadata(bool? blocksMetadata = true) => Assign(a => a.BlocksMetadata = blocksMetadata); /// <inheritdoc/> public TDescriptor BlocksRead(bool? blocksRead = true) => Assign(a => a.BlocksRead = blocksRead); /// <inheritdoc/> public TDescriptor BlocksReadOnly(bool? blocksReadOnly = true) => Assign(a => a.BlocksReadOnly = blocksReadOnly); /// <inheritdoc/> public TDescriptor BlocksWrite(bool? blocksWrite = true) => Assign(a => a.BlocksWrite = blocksWrite); /// <inheritdoc/> public TDescriptor Priority(int? priority) => Assign(a => a.Priority = priority); /// <inheritdoc/> public TDescriptor Merge(Func<MergeSettingsDescriptor, IMergeSettings> merge) => Assign(a => a.Merge = merge?.Invoke(new MergeSettingsDescriptor())); /// <inheritdoc/> public TDescriptor RecoveryInitialShards(Union<int, RecoveryInitialShards> initialShards) => Assign(a => a.RecoveryInitialShards = initialShards); /// <inheritdoc/> public TDescriptor RequestsCacheEnabled(bool? enable = true) => Assign(a => a.RequestsCacheEnabled = enable); /// <inheritdoc/> public TDescriptor RefreshInterval(Time time) => Assign(a => a.RefreshInterval = time); /// <inheritdoc/> public TDescriptor TotalShardsPerNode(int? totalShardsPerNode) => Assign(a => a.RoutingAllocationTotalShardsPerNode = totalShardsPerNode); /// <inheritdoc/> public TDescriptor SlowLog(Func<SlowLogDescriptor, ISlowLog> slowLogSelector) => Assign(a => a.SlowLog = slowLogSelector?.Invoke(new SlowLogDescriptor())); /// <inheritdoc/> public TDescriptor Translog(Func<TranslogSettingsDescriptor, ITranslogSettings> translogSelector) => Assign(a => a.Translog = translogSelector?.Invoke(new TranslogSettingsDescriptor())); /// <inheritdoc/> public TDescriptor UnassignedNodeLeftDelayedTimeout(Time time) => Assign(a => a.UnassignedNodeLeftDelayedTimeout = time); public TDescriptor Analysis(Func<AnalysisDescriptor, IAnalysis> selector) => Assign(a => a.Analysis = selector?.Invoke(new AnalysisDescriptor())); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.ExtractMethod { internal abstract class AbstractExtractMethodCommandHandler : ICommandHandler<ExtractMethodCommandArgs> { private readonly ITextBufferUndoManagerProvider _undoManager; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; private readonly IInlineRenameService _renameService; private readonly IWaitIndicator _waitIndicator; public AbstractExtractMethodCommandHandler( ITextBufferUndoManagerProvider undoManager, IEditorOperationsFactoryService editorOperationsFactoryService, IInlineRenameService renameService, IWaitIndicator waitIndicator) { Contract.ThrowIfNull(undoManager); Contract.ThrowIfNull(editorOperationsFactoryService); Contract.ThrowIfNull(renameService); Contract.ThrowIfNull(waitIndicator); _undoManager = undoManager; _editorOperationsFactoryService = editorOperationsFactoryService; _renameService = renameService; _waitIndicator = waitIndicator; } public CommandState GetCommandState(ExtractMethodCommandArgs args, Func<CommandState> nextHandler) { var spans = args.TextView.Selection.GetSnapshotSpansOnBuffer(args.SubjectBuffer); if (spans.Count(s => s.Length > 0) != 1) { return nextHandler(); } var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return nextHandler(); } if (!document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { return nextHandler(); } var supportsFeatureService = document.Project.Solution.Workspace.Services.GetService<IDocumentSupportsFeatureService>(); if (!supportsFeatureService.SupportsRefactorings(document)) { return nextHandler(); } return CommandState.Available; } public void ExecuteCommand(ExtractMethodCommandArgs args, Action nextHandler) { var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { nextHandler(); return; } var supportsFeatureService = document.Project.Solution.Workspace.Services.GetService<IDocumentSupportsFeatureService>(); if (!supportsFeatureService.SupportsRefactorings(document)) { nextHandler(); return; } // Finish any rename that had been started. We'll do this here before we enter the // wait indicator for Extract Method if (_renameService.ActiveSession != null) { _renameService.ActiveSession.Commit(); } var executed = false; _waitIndicator.Wait( title: EditorFeaturesResources.Extract_Method, message: EditorFeaturesResources.Applying_Extract_Method_refactoring, allowCancel: true, action: waitContext => { executed = this.Execute(args.SubjectBuffer, args.TextView, waitContext.CancellationToken); }); if (!executed) { nextHandler(); } } private bool Execute( ITextBuffer textBuffer, ITextView view, CancellationToken cancellationToken) { var spans = view.Selection.GetSnapshotSpansOnBuffer(textBuffer); if (spans.Count(s => s.Length > 0) != 1) { return false; } var document = textBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } var result = ExtractMethodService.ExtractMethodAsync( document, spans.Single().Span.ToTextSpan(), cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); Contract.ThrowIfNull(result); if (!result.Succeeded && !result.SucceededWithSuggestion) { // if it failed due to out/ref parameter in async method, try it with different option var newResult = TryWithoutMakingValueTypesRef(document, spans, result, cancellationToken); if (newResult != null) { var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>(); if (notificationService != null) { if (!notificationService.ConfirmMessageBox( EditorFeaturesResources.Extract_method_failed_with_following_reasons_colon + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, result.Reasons) + Environment.NewLine + Environment.NewLine + EditorFeaturesResources.We_can_fix_the_error_by_not_making_struct_out_ref_parameter_s_Do_you_want_to_proceed, title: EditorFeaturesResources.Extract_Method, severity: NotificationSeverity.Error)) { // We handled the command, displayed a notification and did not produce code. return true; } } // reset result result = newResult; } else if (TryNotifyFailureToUser(document, result)) { // We handled the command, displayed a notification and did not produce code. return true; } } // apply the change to buffer // get method name token ApplyChangesToBuffer(result, textBuffer, cancellationToken); // start inline rename var methodNameAtInvocation = result.InvocationNameToken; var snapshotAfterFormatting = textBuffer.CurrentSnapshot; var documentAfterFormatting = snapshotAfterFormatting.GetOpenDocumentInCurrentContextWithChanges(); _renameService.StartInlineSession(documentAfterFormatting, methodNameAtInvocation.Span, cancellationToken); // select invocation span view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(snapshotAfterFormatting, methodNameAtInvocation.Span.End)); view.SetSelection( methodNameAtInvocation.Span.ToSnapshotSpan(snapshotAfterFormatting)); return true; } /// <returns> /// True: if a failure notification was displayed or the user did not want to proceed in a best effort scenario. /// Extract Method does not proceed further and is done. /// False: the user proceeded to a best effort scenario. /// </returns> private bool TryNotifyFailureToUser(Document document, ExtractMethodResult result) { var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>(); // see whether we will allow best effort extraction and if it is possible. if (!document.Project.Solution.Options.GetOption(ExtractMethodOptions.AllowBestEffort, document.Project.Language) || !result.Status.HasBestEffort() || result.Document == null) { if (notificationService != null) { notificationService.SendNotification( EditorFeaturesResources.Extract_method_failed_with_following_reasons_colon + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, result.Reasons), title: EditorFeaturesResources.Extract_Method, severity: NotificationSeverity.Error); } return true; } // okay, best effort is turned on, let user know it is an best effort if (notificationService != null) { if (!notificationService.ConfirmMessageBox( EditorFeaturesResources.Extract_method_failed_with_following_reasons_colon + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, result.Reasons) + Environment.NewLine + Environment.NewLine + EditorFeaturesResources.Do_you_still_want_to_proceed_it_will_generate_broken_code, title: EditorFeaturesResources.Extract_Method, severity: NotificationSeverity.Error)) { return true; } } return false; } private static ExtractMethodResult TryWithoutMakingValueTypesRef( Document document, NormalizedSnapshotSpanCollection spans, ExtractMethodResult result, CancellationToken cancellationToken) { OptionSet options = document.Project.Solution.Options; if (options.GetOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language) || !result.Reasons.IsSingle()) { return null; } var reason = result.Reasons.FirstOrDefault(); var length = FeaturesResources.Asynchronous_method_cannot_have_ref_out_parameters_colon_bracket_0_bracket.IndexOf(':'); if (reason != null && length > 0 && reason.IndexOf(FeaturesResources.Asynchronous_method_cannot_have_ref_out_parameters_colon_bracket_0_bracket.Substring(0, length), 0, length, StringComparison.Ordinal) >= 0) { options = options.WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, true); var newResult = ExtractMethodService.ExtractMethodAsync( document, spans.Single().Span.ToTextSpan(), options, cancellationToken).WaitAndGetResult(cancellationToken); // retry succeeded, return new result if (newResult.Succeeded || newResult.SucceededWithSuggestion) { return newResult; } } return null; } /// <summary> /// Applies an ExtractMethodResult to the editor. /// </summary> private void ApplyChangesToBuffer(ExtractMethodResult extractMethodResult, ITextBuffer subjectBuffer, CancellationToken cancellationToken) { using (var undoTransaction = _undoManager.GetTextBufferUndoManager(subjectBuffer).TextBufferUndoHistory.CreateTransaction("Extract Method")) { // apply extract method code to buffer var document = extractMethodResult.Document; document.Project.Solution.Workspace.ApplyDocumentChanges(document, cancellationToken); // apply changes undoTransaction.Complete(); } } } }
namespace Nancy.Authentication.Forms.Tests { using System; using System.Linq; using Bootstrapper; using Cryptography; using FakeItEasy; using Fakes; using Helpers; using Nancy.Security; using Nancy.Tests; using Nancy.Tests.Fakes; using Xunit; public class FormsAuthenticationFixture { private FormsAuthenticationConfiguration config; private FormsAuthenticationConfiguration secureConfig; private FormsAuthenticationConfiguration domainPathConfig; private NancyContext context; private Guid userGuid; private string validCookieValue = HttpUtility.UrlEncode("C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithNoHmac = HttpUtility.UrlEncode("k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithEmptyHmac = HttpUtility.UrlEncode("k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithInvalidHmac = HttpUtility.UrlEncode("C+QzbqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithBrokenEncryptedData = HttpUtility.UrlEncode("C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3spwI0jB0KeVY9"); private CryptographyConfiguration cryptographyConfiguration; private string domain = ".nancyfx.org"; private string path = "/"; public FormsAuthenticationFixture() { this.cryptographyConfiguration = new CryptographyConfiguration( new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)), new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000))); this.config = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = false }; this.secureConfig = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = true }; this.domainPathConfig = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = false, Domain = domain, Path = path }; this.context = new NancyContext { Request = new Request( "GET", new Url { Scheme = "http", BasePath = "/testing", HostName = "test.com", Path = "test" }) }; this.userGuid = new Guid("3D97EB33-824A-4173-A2C1-633AC16C1010"); } [Fact] public void Should_throw_with_null_application_pipelines_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable(null, this.config)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_null_config_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), null)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_invalid_config_passed_to_enable() { var fakeConfig = A.Fake<FormsAuthenticationConfiguration>(); A.CallTo(() => fakeConfig.IsValid).Returns(false); var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), fakeConfig)); result.ShouldBeOfType(typeof(ArgumentException)); } [Fact] public void Should_add_a_pre_and_post_hook_when_enabled() { var pipelines = A.Fake<IPipelines>(); FormsAuthentication.Enable(pipelines, this.config); A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_add_a_pre_hook_but_not_a_post_hook_when_DisableRedirect_is_true() { var pipelines = A.Fake<IPipelines>(); this.config.DisableRedirect = true; FormsAuthentication.Enable(pipelines, this.config); A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored)) .MustNotHaveHappened(); } [Fact] public void Should_return_redirect_response_when_user_logs_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); } [Fact] public void Should_return_ok_response_when_user_logs_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.OK); } [Fact] public void Should_have_authentication_cookie_in_login_response_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue(); } [Fact] public void Should_have_authentication_cookie_in_login_response_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_httponly_when_logging_in_with_redirect() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .HttpOnly.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_httponly_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .HttpOnly.ShouldBeTrue(); } [Fact] public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldBeNull(); } [Fact] public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldBeNull(); } [Fact] public void Should_set_expiry_date_if_one_specified_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldNotBeNull(); } [Fact] public void Should_set_expiry_date_if_one_specified_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldNotBeNull(); } [Fact] public void Should_encrypt_cookie_when_logging_in_with_redirect() { var mockEncrypter = A.Fake<IEncryptionProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_encrypt_cookie_when_logging_in_without_redirect() { // Given var mockEncrypter = A.Fake<IEncryptionProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_with_redirect() { var fakeEncrypter = A.Fake<IEncryptionProvider>(); var fakeCryptoText = "FakeText"; A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored)) .Returns(fakeCryptoText); var mockHmac = A.Fake<IHmacProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_without_redirect() { // Given var fakeEncrypter = A.Fake<IEncryptionProvider>(); var fakeCryptoText = "FakeText"; A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored)) .Returns(fakeCryptoText); var mockHmac = A.Fake<IHmacProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_return_redirect_response_when_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); } [Fact] public void Should_return_ok_response_when_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.LogOutResponse(); // Then result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.OK); } [Fact] public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Value.ShouldBeEmpty(); cookie.Expires.ShouldNotBeNull(); (cookie.Expires < DateTime.Now).ShouldBeTrue(); } [Fact] public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.LogOutResponse(); // Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Value.ShouldBeEmpty(); cookie.Expires.ShouldNotBeNull(); (cookie.Expires < DateTime.Now).ShouldBeTrue(); } [Fact] public void Should_get_username_from_mapping_service_with_valid_cookie() { var fakePipelines = new Pipelines(); var mockMapper = A.Fake<IUserMapper>(); this.config.UserMapper = mockMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue); fakePipelines.BeforeRequest.Invoke(this.context); A.CallTo(() => mockMapper.GetUserFromIdentifier(this.userGuid, this.context)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_set_user_in_context_with_valid_cookie() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity {UserName = "Bob"}; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue); var result = fakePipelines.BeforeRequest.Invoke(this.context); context.CurrentUser.ShouldBeSameAs(fakeUser); } [Fact] public void Should_not_set_user_in_context_with_invalid_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithInvalidHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_empty_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithEmptyHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_no_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithNoHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_username_in_context_with_broken_encryption_data() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithBrokenEncryptedData); var result = fakePipelines.BeforeRequest.Invoke(this.context); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_retain_querystring_when_redirecting_to_login_page() { // Given var fakePipelines = new Pipelines(); FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = "next"; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?next=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_null() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = null; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_empty() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = string.Empty; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_retain_querystring_when_redirecting_after_successfull_login() { // Given var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "returnUrl=/secure%3Ffoo%3Dbar") }; FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInRedirectResponse(queryContext, userGuid, DateTime.Now.AddDays(1)); // Then result.Headers["Location"].ShouldEqual("/secure?foo=bar"); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_with_redirect() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then result.Cookies .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName) .First() .Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName) .First() .Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); // When var result = FormsAuthentication.LogOutResponse(); // Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Secure.ShouldBeTrue(); } [Fact] public void Should_redirect_to_base_path_if_non_local_url_and_no_fallback() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/testing"); } [Fact] public void Should_redirect_to_fallback_if_non_local_url_and_fallback_set() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, fallbackRedirectUrl:"/moo"); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/moo"); } [Fact] public void Should_redirect_to_given_url_if_local() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "~/login"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/testing/login"); } [Fact] public void Should_set_Domain_when_config_provides_domain_value() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Domain.ShouldEqual(domain); } [Fact] public void Should_set_Path_when_config_provides_path_value() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Path.ShouldEqual(path); } } }
//--------------------------------------------------------------------------- // // File: HtmlFromXamlConverter.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Prototype for Xaml - Html conversion // //--------------------------------------------------------------------------- namespace HTMLConverter { using System; using System.Diagnostics; using System.Text; using System.IO; using System.Xml; /// <summary> /// HtmlToXamlConverter is a static class that takes an HTML string /// and converts it into XAML /// </summary> internal static class HtmlFromXamlConverter { // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// Main entry point for Xaml-to-Html converter. /// Converts a xaml string into html string. /// </summary> /// <param name="xamlString"> /// Xaml strinng to convert. /// </param> /// <returns> /// Html string produced from a source xaml. /// </returns> internal static string ConvertXamlToHtml(string xamlString) { XmlTextReader xamlReader; StringBuilder htmlStringBuilder; XmlTextWriter htmlWriter; xamlReader = new XmlTextReader(new StringReader(xamlString)); htmlStringBuilder = new StringBuilder(100); htmlWriter = new XmlTextWriter(new StringWriter(htmlStringBuilder)); if (!WriteFlowDocument(xamlReader, htmlWriter)) { return ""; } string htmlString = htmlStringBuilder.ToString(); return htmlString; } #endregion Internal Methods // --------------------------------------------------------------------- // // Private Methods // // --------------------------------------------------------------------- #region Private Methods /// <summary> /// Processes a root level element of XAML (normally it's FlowDocument element). /// </summary> /// <param name="xamlReader"> /// XmlTextReader for a source xaml. /// </param> /// <param name="htmlWriter"> /// XmlTextWriter producing resulting html /// </param> private static bool WriteFlowDocument(XmlTextReader xamlReader, XmlTextWriter htmlWriter) { if (!ReadNextToken(xamlReader)) { // Xaml content is empty - nothing to convert return false; } if (xamlReader.NodeType != XmlNodeType.Element || xamlReader.Name != "FlowDocument") { // Root FlowDocument elemet is missing return false; } // Create a buffer StringBuilder for collecting css properties for inline STYLE attributes // on every element level (it will be re-initialized on every level). StringBuilder inlineStyle = new StringBuilder(); htmlWriter.WriteStartElement("HTML"); htmlWriter.WriteStartElement("BODY"); WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle); WriteElementContent(xamlReader, htmlWriter, inlineStyle); htmlWriter.WriteEndElement(); htmlWriter.WriteEndElement(); return true; } /// <summary> /// Reads attributes of the current xaml element and converts /// them into appropriate html attributes or css styles. /// </summary> /// <param name="xamlReader"> /// XmlTextReader which is expected to be at XmlNodeType.Element /// (opening element tag) position. /// The reader will remain at the same level after function complete. /// </param> /// <param name="htmlWriter"> /// XmlTextWriter for output html, which is expected to be in /// after WriteStartElement state. /// </param> /// <param name="inlineStyle"> /// String builder for collecting css properties for inline STYLE attribute. /// </param> private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); // Clear string builder for the inline style inlineStyle.Remove(0, inlineStyle.Length); if (!xamlReader.HasAttributes) { return; } bool borderSet = false; while (xamlReader.MoveToNextAttribute()) { string css = null; switch (xamlReader.Name) { // Character fomatting properties // ------------------------------ case "Background": css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";"; break; case "FontFamily": css = "font-family:" + xamlReader.Value + ";"; break; case "FontStyle": css = "font-style:" + xamlReader.Value.ToLower() + ";"; break; case "FontWeight": css = "font-weight:" + xamlReader.Value.ToLower() + ";"; break; case "FontStretch": break; case "FontSize": css = "font-size:" + xamlReader.Value + ";"; break; case "Foreground": css = "color:" + ParseXamlColor(xamlReader.Value) + ";"; break; case "TextDecorations": css = "text-decoration:underline;"; break; case "TextEffects": break; case "Emphasis": break; case "StandardLigatures": break; case "Variants": break; case "Capitals": break; case "Fraction": break; // Paragraph formatting properties // ------------------------------- case "Padding": css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";"; break; case "Margin": css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";"; break; case "BorderThickness": css = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";"; borderSet = true; break; case "BorderBrush": css = "border-color:" + ParseXamlColor(xamlReader.Value) + ";"; borderSet = true; break; case "LineHeight": break; case "TextIndent": css = "text-indent:" + xamlReader.Value + ";"; break; case "TextAlignment": css = "text-align:" + xamlReader.Value + ";"; break; case "IsKeptTogether": break; case "IsKeptWithNext": break; case "ColumnBreakBefore": break; case "PageBreakBefore": break; case "FlowDirection": break; // Table attributes // ---------------- case "Width": css = "width:" + xamlReader.Value + ";"; break; case "ColumnSpan": htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value); break; case "RowSpan": htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value); break; } if (css != null) { inlineStyle.Append(css); } } if (borderSet) { inlineStyle.Append("border-style:solid;mso-element:para-border-div;"); } // Return the xamlReader back to element level xamlReader.MoveToElement(); Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); } private static string ParseXamlColor(string color) { if (color.StartsWith("#")) { // Remove transparancy value color = "#" + color.Substring(3); } return color; } private static string ParseXamlThickness(string thickness) { string[] values = thickness.Split(','); for (int i = 0; i < values.Length; i++) { double value; if (double.TryParse(values[i], out value)) { values[i] = Math.Ceiling(value).ToString(); } else { values[i] = "1"; } } string cssThickness; switch (values.Length) { case 1: cssThickness = thickness; break; case 2: cssThickness = values[1] + " " + values[0]; break; case 4: cssThickness = values[1] + " " + values[2] + " " + values[3] + " " + values[0]; break; default: cssThickness = values[0]; break; } return cssThickness; } /// <summary> /// Reads a content of current xaml element, converts it /// </summary> /// <param name="xamlReader"> /// XmlTextReader which is expected to be at XmlNodeType.Element /// (opening element tag) position. /// </param> /// <param name="htmlWriter"> /// May be null, in which case we are skipping the xaml element; /// witout producing any output to html. /// </param> /// <param name="inlineStyle"> /// StringBuilder used for collecting css properties for inline STYLE attribute. /// </param> private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); bool elementContentStarted = false; if (xamlReader.IsEmptyElement) { if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0) { // Output STYLE attribute and clear inlineStyle buffer. htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); inlineStyle.Remove(0, inlineStyle.Length); } elementContentStarted = true; } else { while (ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement) { switch (xamlReader.NodeType) { case XmlNodeType.Element: if (xamlReader.Name.Contains(".")) { AddComplexProperty(xamlReader, inlineStyle); } else { if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0) { // Output STYLE attribute and clear inlineStyle buffer. htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); inlineStyle.Remove(0, inlineStyle.Length); } elementContentStarted = true; WriteElement(xamlReader, htmlWriter, inlineStyle); } Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement || xamlReader.NodeType == XmlNodeType.Element && xamlReader.IsEmptyElement); break; case XmlNodeType.Comment: if (htmlWriter != null) { if (!elementContentStarted && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); } htmlWriter.WriteComment(xamlReader.Value); } elementContentStarted = true; break; case XmlNodeType.CDATA: case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: if (htmlWriter != null) { if (!elementContentStarted && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); } htmlWriter.WriteString(xamlReader.Value); } elementContentStarted = true; break; } } Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement); } } /// <summary> /// Conberts an element notation of complex property into /// </summary> /// <param name="xamlReader"> /// On entry this XmlTextReader must be on Element start tag; /// on exit - on EndElement tag. /// </param> /// <param name="inlineStyle"> /// StringBuilder containing a value for STYLE attribute. /// </param> private static void AddComplexProperty(XmlTextReader xamlReader, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); if (inlineStyle != null && xamlReader.Name.EndsWith(".TextDecorations")) { inlineStyle.Append("text-decoration:underline;"); } // Skip the element representing the complex property WriteElementContent(xamlReader, /*htmlWriter:*/null, /*inlineStyle:*/null); } /// <summary> /// Converts a xaml element into an appropriate html element. /// </summary> /// <param name="xamlReader"> /// On entry this XmlTextReader must be on Element start tag; /// on exit - on EndElement tag. /// </param> /// <param name="htmlWriter"> /// May be null, in which case we are skipping xaml content /// without producing any html output /// </param> /// <param name="inlineStyle"> /// StringBuilder used for collecting css properties for inline STYLE attributes on every level. /// </param> private static void WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); if (htmlWriter == null) { // Skipping mode; recurse into the xaml element without any output WriteElementContent(xamlReader, /*htmlWriter:*/null, null); } else { string htmlElementName = null; switch (xamlReader.Name) { case "Run" : case "Span": htmlElementName = "SPAN"; break; case "InlineUIContainer": htmlElementName = "SPAN"; break; case "Bold": htmlElementName = "B"; break; case "Italic" : htmlElementName = "I"; break; case "Paragraph" : htmlElementName = "P"; break; case "BlockUIContainer": htmlElementName = "DIV"; break; case "Section": htmlElementName = "DIV"; break; case "Table": htmlElementName = "TABLE"; break; case "TableColumn": htmlElementName = "COL"; break; case "TableRowGroup" : htmlElementName = "TBODY"; break; case "TableRow" : htmlElementName = "TR"; break; case "TableCell" : htmlElementName = "TD"; break; case "List" : string marker = xamlReader.GetAttribute("MarkerStyle"); if (marker == null || marker == "None" || marker == "Disc" || marker == "Circle" || marker == "Square" || marker == "Box") { htmlElementName = "UL"; } else { htmlElementName = "OL"; } break; case "ListItem" : htmlElementName = "LI"; break; default : htmlElementName = null; // Ignore the element break; } if (htmlWriter != null && htmlElementName != null) { htmlWriter.WriteStartElement(htmlElementName); WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle); WriteElementContent(xamlReader, htmlWriter, inlineStyle); htmlWriter.WriteEndElement(); } else { // Skip this unrecognized xaml element WriteElementContent(xamlReader, /*htmlWriter:*/null, null); } } } // Reader advance helpers // ---------------------- /// <summary> /// Reads several items from xamlReader skipping all non-significant stuff. /// </summary> /// <param name="xamlReader"> /// XmlTextReader from tokens are being read. /// </param> /// <returns> /// True if new token is available; false if end of stream reached. /// </returns> private static bool ReadNextToken(XmlReader xamlReader) { while (xamlReader.Read()) { Debug.Assert(xamlReader.ReadState == ReadState.Interactive, "Reader is expected to be in Interactive state (" + xamlReader.ReadState + ")"); switch (xamlReader.NodeType) { case XmlNodeType.Element: case XmlNodeType.EndElement: case XmlNodeType.None: case XmlNodeType.CDATA: case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: return true; case XmlNodeType.Whitespace: if (xamlReader.XmlSpace == XmlSpace.Preserve) { return true; } // ignore insignificant whitespace break; case XmlNodeType.EndEntity: case XmlNodeType.EntityReference: // Implement entity reading //xamlReader.ResolveEntity(); //xamlReader.Read(); //ReadChildNodes( parent, parentBaseUri, xamlReader, positionInfo); break; // for now we ignore entities as insignificant stuff case XmlNodeType.Comment: return true; case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: case XmlNodeType.XmlDeclaration: default: // Ignorable stuff break; } } return false; } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields #endregion Private Fields } }
/* * Copyright (c) 2009 Jim Radford http://www.jimradford.com * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.Win32; using System.Web; using SuperPutty.Data; using SuperPutty.Utils; using SuperPutty.Gui; using log4net; namespace SuperPutty { public partial class dlgEditSession : Form { private static readonly ILog Log = LogManager.GetLogger(typeof(dlgEditSession)); public delegate bool SessionNameValidationHandler(string name, out string error); private SessionData Session; private String OldHostname; private bool isInitialized = false; private ImageListPopup imgPopup = null; public dlgEditSession(SessionData session, ImageList iconList) { Session = session; InitializeComponent(); // get putty saved settings from the registry to populate // the dropdown PopulatePuttySettings(); if (!String.IsNullOrEmpty(Session.SessionName)) { this.Text = "Edit session: " + session.SessionName; this.textBoxSessionName.Text = Session.SessionName; this.textBoxHostname.Text = Session.Host; this.textBoxPort.Text = Session.Port.ToString(); this.textBoxExtraArgs.Text = Session.ExtraArgs; this.textBoxUsername.Text = Session.Username; this.textBoxRemotePathSesion.Text = Session.RemotePath; this.textBoxLocalPathSesion.Text = Session.LocalPath; switch (Session.Proto) { case ConnectionProtocol.Raw: radioButtonRaw.Checked = true; break; case ConnectionProtocol.Rlogin: radioButtonRlogin.Checked = true; break; case ConnectionProtocol.Serial: radioButtonSerial.Checked = true; break; case ConnectionProtocol.SSH: radioButtonSSH.Checked = true; break; case ConnectionProtocol.Telnet: radioButtonTelnet.Checked = true; break; case ConnectionProtocol.Cygterm: radioButtonCygterm.Checked = true; break; case ConnectionProtocol.Mintty: radioButtonMintty.Checked = true; break; default: radioButtonSSH.Checked = true; break; } foreach(String settings in this.comboBoxPuttyProfile.Items){ if (settings == session.PuttySession) { this.comboBoxPuttyProfile.SelectedItem = settings; break; } } this.buttonSave.Enabled = true; } else { this.Text = "Create new session"; radioButtonSSH.Checked = true; this.buttonSave.Enabled = false; } // Setup icon chooser this.buttonImageSelect.ImageList = iconList; this.buttonImageSelect.ImageKey = string.IsNullOrEmpty(Session.ImageKey) ? SessionTreeview.ImageKeySession : Session.ImageKey; this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey); this.isInitialized = true; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.BeginInvoke(new MethodInvoker(delegate { this.textBoxSessionName.Focus(); })); } private void PopulatePuttySettings() { foreach (String sessionName in PuttyDataHelper.GetSessionNames()) { comboBoxPuttyProfile.Items.Add(sessionName); } comboBoxPuttyProfile.SelectedItem = PuttyDataHelper.SessionDefaultSettings; } private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } private void buttonSave_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(CommandLineOptions.getcommand(textBoxExtraArgs.Text, "-pw"))) { if (MessageBox.Show("SuperPutty encrypts the password in Sessions.xml file with the master password, but using a password in 'Extra PuTTY Arguments' is very insecure.\nFor a secure connection use SSH authentication with Pageant. \nSelect yes, if you want save the password", "Are you sure that you want to save the password?", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)==DialogResult.Cancel){ return; } } Session.SessionName = textBoxSessionName.Text.Trim(); Session.PuttySession = comboBoxPuttyProfile.Text.Trim(); Session.Host = textBoxHostname.Text.Trim(); Session.ExtraArgs = textBoxExtraArgs.Text.Trim(); Session.RemotePath = textBoxRemotePathSesion.Text.Trim(); Session.LocalPath = textBoxLocalPathSesion.Text.Trim(); Session.Port = int.Parse(textBoxPort.Text.Trim()); Session.Username = textBoxUsername.Text.Trim(); Session.SessionId = SessionData.CombineSessionIds(SessionData.GetSessionParentId(Session.SessionId), Session.SessionName); Session.ImageKey = buttonImageSelect.ImageKey; for (int i = 0; i < groupBox1.Controls.Count; i++) { RadioButton rb = (RadioButton)groupBox1.Controls[i]; if (rb.Checked) { Session.Proto = (ConnectionProtocol)rb.Tag; } } DialogResult = DialogResult.OK; } /// <summary> /// Special UI handling for cygterm or mintty sessions /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void radioButtonCygterm_CheckedChanged(object sender, EventArgs e) { string host = this.textBoxHostname.Text; bool isLocalShell = this.radioButtonCygterm.Checked || this.radioButtonMintty.Checked; this.textBoxPort.Enabled = !isLocalShell; this.textBoxExtraArgs.Enabled = !isLocalShell; this.textBoxUsername.Enabled = !isLocalShell; if (isLocalShell) { if (String.IsNullOrEmpty(host) || !host.StartsWith(CygtermStartInfo.LocalHost)) { OldHostname = this.textBoxHostname.Text; this.textBoxHostname.Text = CygtermStartInfo.LocalHost; } } } private void radioButtonRaw_CheckedChanged(object sender, EventArgs e) { if (this.radioButtonRaw.Checked && this.isInitialized) { if (!string.IsNullOrEmpty(OldHostname)) { this.textBoxHostname.Text = OldHostname; OldHostname = null; } } } private void radioButtonTelnet_CheckedChanged(object sender, EventArgs e) { if (this.radioButtonTelnet.Checked && this.isInitialized) { if (!string.IsNullOrEmpty(OldHostname)) { this.textBoxHostname.Text = OldHostname; OldHostname = null; } this.textBoxPort.Text = "23"; } } private void radioButtonRlogin_CheckedChanged(object sender, EventArgs e) { if (this.radioButtonRlogin.Checked && this.isInitialized) { if (!string.IsNullOrEmpty(OldHostname)) { this.textBoxHostname.Text = OldHostname; OldHostname = null; } this.textBoxPort.Text = "513"; } } private void radioButtonSSH_CheckedChanged(object sender, EventArgs e) { if (this.radioButtonSSH.Checked && this.isInitialized) { if (!string.IsNullOrEmpty(OldHostname)) { this.textBoxHostname.Text = OldHostname; OldHostname = null; } this.textBoxPort.Text = "22"; } } public static int GetDefaultPort(ConnectionProtocol protocol) { int port = 22; switch (protocol) { case ConnectionProtocol.Raw: break; case ConnectionProtocol.Rlogin: port = 513; break; case ConnectionProtocol.Serial: break; case ConnectionProtocol.Telnet: port = 23; break; } return port; } #region Icon private void buttonImageSelect_Click(object sender, EventArgs e) { if (this.imgPopup == null) { // TODO: ImageList is null on initial installation and will throw a nullreference exception when creating a new session and trying to select an image. int n = buttonImageSelect.ImageList.Images.Count; int x = (int) Math.Floor(Math.Sqrt(n)) + 1; int cols = x; int rows = x; imgPopup = new ImageListPopup(); imgPopup.BackgroundColor = Color.FromArgb(241, 241, 241); imgPopup.BackgroundOverColor = Color.FromArgb(102, 154, 204); imgPopup.Init(this.buttonImageSelect.ImageList, 8, 8, cols, rows); imgPopup.ItemClick += new ImageListPopupEventHandler(this.OnItemClicked); } Point pt = PointToScreen(new Point(buttonImageSelect.Left, buttonImageSelect.Bottom)); imgPopup.Show(pt.X + 2, pt.Y); } private void OnItemClicked(object sender, ImageListPopupEventArgs e) { if (imgPopup == sender) { buttonImageSelect.ImageKey = e.SelectedItem; this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey); } } #endregion #region Validation Logic public SessionNameValidationHandler SessionNameValidator { get; set; } private void textBoxSessionName_Validating(object sender, CancelEventArgs e) { if (this.SessionNameValidator != null) { string error; if (!this.SessionNameValidator(this.textBoxSessionName.Text, out error)) { e.Cancel = true; this.SetError(this.textBoxSessionName, error ?? "Invalid Session Name"); } } } private void textBoxSessionName_Validated(object sender, EventArgs e) { this.SetError(this.textBoxSessionName, String.Empty); } private void textBoxPort_Validating(object sender, CancelEventArgs e) { int val; if (!Int32.TryParse(this.textBoxPort.Text, out val)) { e.Cancel = true; this.SetError(this.textBoxPort, "Invalid Port"); } } private void textBoxPort_Validated(object sender, EventArgs e) { this.SetError(this.textBoxPort, String.Empty); } private void textBoxHostname_Validating(object sender, CancelEventArgs e) { if (string.IsNullOrEmpty((string)this.comboBoxPuttyProfile.SelectedItem) && string.IsNullOrEmpty(this.textBoxHostname.Text.Trim())) { if (sender == this.textBoxHostname) { this.SetError(this.textBoxHostname, "A host name must be specified if a Putty Session Profile is not selected"); } else if (sender == this.comboBoxPuttyProfile) { this.SetError(this.comboBoxPuttyProfile, "A Putty Session Profile must be selected if a Host Name is not provided"); } } else { this.SetError(this.textBoxHostname, String.Empty); this.SetError(this.comboBoxPuttyProfile, String.Empty); } } private void comboBoxPuttyProfile_Validating(object sender, CancelEventArgs e) { this.textBoxHostname_Validating(sender, e); } private void comboBoxPuttyProfile_SelectedIndexChanged(object sender, EventArgs e) { this.ValidateChildren(ValidationConstraints.ImmediateChildren); } void SetError(Control control, string error) { this.errorProvider.SetError(control, error); this.EnableDisableSaveButton(); } void EnableDisableSaveButton() { this.buttonSave.Enabled = ( this.errorProvider.GetError(this.textBoxSessionName) == String.Empty && this.errorProvider.GetError(this.textBoxHostname) == String.Empty && this.errorProvider.GetError(this.textBoxPort) == String.Empty && this.errorProvider.GetError(this.comboBoxPuttyProfile) == String.Empty); } #endregion private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBoxShowHidePW.Checked) { textBoxExtraArgs.PasswordChar = '*'; } else { textBoxExtraArgs.PasswordChar='\0'; } } private void dlgEditSession_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(CommandLineOptions.getcommand(this.Session.ExtraArgs, "-pw"))) { checkBoxShowHidePW.Checked = true; textBoxExtraArgs.PasswordChar = '*'; } else { textBoxExtraArgs.PasswordChar = '\0'; } } private void textBoxExtraArgs_TextChanged(object sender, EventArgs e) { //if extra Args contains a password, change the backgroudn if (!String.IsNullOrEmpty(CommandLineOptions.getcommand(textBoxExtraArgs.Text, "-pw"))) { textBoxExtraArgs.BackColor = Color.LightCoral; } else { textBoxExtraArgs.BackColor = Color.White; } } } }
#region Using declarations using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Xml.Serialization; using NinjaTrader.Cbi; using NinjaTrader.Gui; using NinjaTrader.Gui.Chart; using NinjaTrader.Gui.SuperDom; using NinjaTrader.Gui.Tools; using NinjaTrader.Data; using NinjaTrader.NinjaScript; using NinjaTrader.Core.FloatingPoint; using NinjaTrader.NinjaScript.DrawingTools; using System.Web.Script.Serialization; using System.Net; #endregion //This namespace holds Indicators in this folder and is required. Do not change it. namespace NinjaTrader.NinjaScript.Indicators { public class SignificantMove : Indicator { private const string frogboxUrl = "http://127.0.0.1:8888/query?ticker={0}&date={1}"; private const string smUrl = "http://127.0.0.1:8889/query?ticker={0}"; private const int BARS_IGNORE = 45; private LinReg RL30; private MAX periodMax; private MIN periodMin; private double signalThreshold = -1; private int lastSignal = 0, lastNotSignal = 0; private int todayStartBar = 0; private double sm_multiplier = double.MinValue; private bool isIgnore = false; private FrogModel fm; protected override void OnStateChange() { if (State == State.SetDefaults) { Description = @""; Name = "SignificantMove"; Calculate = Calculate.OnPriceChange; IsOverlay = true; DisplayInDataBox = true; DrawOnPricePanel = true; DrawHorizontalGridLines = true; DrawVerticalGridLines = true; PaintPriceMarkers = true; ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right; //Disable this property if your indicator requires custom values that cumulate with each new market data event. //See Help Guide for additional information. IsSuspendedWhileInactive = true; Period = 20; Multiplier = 0.5; SignalAreaColor = Brushes.Orange; SignalAreaOpacity = 30; AddPlot(Brushes.Transparent, "MarketAnalyzerPlot"); } else if (State == State.Configure) { RL30 = LinReg(Period); periodMax = MAX(RL30, Period); periodMin = MIN(RL30, Period); } } protected override void OnBarUpdate() { if (sm_multiplier < 0) { using (var client = new WebClient()) { var val = client.DownloadString(String.Format(smUrl, base.Instrument.FullName)); sm_multiplier = double.Parse(val); } } if (CurrentBar < Period) { return; } // update signalThreshold if needed if (signalThreshold < 0 || Time[0].Date != Time[1].Date) { fm = getFrogModel(); signalThreshold = sm_multiplier; todayStartBar = CurrentBar; updateIgnoreFlag(); } if (periodMax[0] - periodMin[0] > signalThreshold && !ignoreSignal()) { // Log(String.Format("isSignal: {0}, diff: {1}, threshold: {2}", periodMax[0] - periodMin[0] > signalThreshold, periodMax[0] - periodMin[0], signalThreshold), LogLevel.Information); MarketAnalyzerPlot[0] = 1; if (lastSignal > lastNotSignal) // indicates the previous bar is a signal bar too { RemoveDrawObject(getTagString(CurrentBar)); } else { lastSignal = CurrentBar; } Draw.Rectangle(this, getTagString(lastSignal), true, CurrentBar - lastSignal, periodMin[0], -1, periodMax[0], Brushes.Transparent, SignalAreaColor, (int)SignalAreaOpacity); } else { // Log(String.Format("isSignal: {0}, diff: {1}, threshold: {2}", periodMax[0] - periodMin[0] > signalThreshold, periodMax[0] - periodMin[0], signalThreshold), LogLevel.Information); MarketAnalyzerPlot[0] = 0; lastNotSignal = CurrentBar; } } private string getTagString(int bar) { return "SignificantMove" + bar; } private FrogModel getFrogModel() { string url = String.Format(frogboxUrl, base.Instrument.FullName, Time[0].Date.ToString("yyyy-MM-dd")); using (var client = new WebClient()) { var model = new FrogModel(); try { var json = client.DownloadString(url); var serializer = new JavaScriptSerializer(); model = serializer.Deserialize<FrogModel>(json); model.hfb = model.fb * Multiplier; model.range = model.rangestat; } catch (Exception e) { } return model; } } public class FrogModel { public double rangestat {get;set;} public double fb {get;set;} public double hfb {get;set;} public double range {get;set;} } private void updateIgnoreFlag() { // first call on OnUpdate, no data of previous day close if (CurrentBar == Period) { return; } isIgnore = Math.Abs(Open[0] - Close[1]) > fm.fb * 0.7; } private bool ignoreSignal() { return isIgnore && (CurrentBar - todayStartBar <= BARS_IGNORE); } #region Properties [NinjaScriptProperty] [Range(1, int.MaxValue)] [Display(Name="Period", Order=1, GroupName="Parameters")] public int Period { get; set; } [NinjaScriptProperty] [Range(0, double.MaxValue)] [Display(Name="Multiplier", Order=2, GroupName="Parameters")] public double Multiplier { get; set; } [NinjaScriptProperty] [XmlIgnore] [Display(Name="SignalAreaColor", Order=3, GroupName="Parameters")] public Brush SignalAreaColor { get; set; } [Browsable(false)] public string SignalAreaColorSerializable { get { return Serialize.BrushToString(SignalAreaColor); } set { SignalAreaColor = Serialize.StringToBrush(value); } } [NinjaScriptProperty] [Range(0, double.MaxValue)] [Display(Name="SignalAreaOpacity", Order=4, GroupName="Parameters")] public double SignalAreaOpacity { get; set; } [Browsable(false)] [XmlIgnore] public Series<double> MarketAnalyzerPlot { get { return Values[0]; } } #endregion } } #region NinjaScript generated code. Neither change nor remove. namespace NinjaTrader.NinjaScript.Indicators { public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase { private SignificantMove[] cacheSignificantMove; public SignificantMove SignificantMove(int period, double multiplier, Brush signalAreaColor, double signalAreaOpacity) { return SignificantMove(Input, period, multiplier, signalAreaColor, signalAreaOpacity); } public SignificantMove SignificantMove(ISeries<double> input, int period, double multiplier, Brush signalAreaColor, double signalAreaOpacity) { if (cacheSignificantMove != null) for (int idx = 0; idx < cacheSignificantMove.Length; idx++) if (cacheSignificantMove[idx] != null && cacheSignificantMove[idx].Period == period && cacheSignificantMove[idx].Multiplier == multiplier && cacheSignificantMove[idx].SignalAreaColor == signalAreaColor && cacheSignificantMove[idx].SignalAreaOpacity == signalAreaOpacity && cacheSignificantMove[idx].EqualsInput(input)) return cacheSignificantMove[idx]; return CacheIndicator<SignificantMove>(new SignificantMove(){ Period = period, Multiplier = multiplier, SignalAreaColor = signalAreaColor, SignalAreaOpacity = signalAreaOpacity }, input, ref cacheSignificantMove); } } } namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns { public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase { public Indicators.SignificantMove SignificantMove(int period, double multiplier, Brush signalAreaColor, double signalAreaOpacity) { return indicator.SignificantMove(Input, period, multiplier, signalAreaColor, signalAreaOpacity); } public Indicators.SignificantMove SignificantMove(ISeries<double> input , int period, double multiplier, Brush signalAreaColor, double signalAreaOpacity) { return indicator.SignificantMove(input, period, multiplier, signalAreaColor, signalAreaOpacity); } } } namespace NinjaTrader.NinjaScript.Strategies { public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase { public Indicators.SignificantMove SignificantMove(int period, double multiplier, Brush signalAreaColor, double signalAreaOpacity) { return indicator.SignificantMove(Input, period, multiplier, signalAreaColor, signalAreaOpacity); } public Indicators.SignificantMove SignificantMove(ISeries<double> input , int period, double multiplier, Brush signalAreaColor, double signalAreaOpacity) { return indicator.SignificantMove(input, period, multiplier, signalAreaColor, signalAreaOpacity); } } } #endregion
using System; using System.Drawing; using System.Drawing.Drawing2D; using SharpVectors.Dom.Svg; using SharpVectors.Dom.Css; namespace SharpVectors.Renderers.Gdi { public sealed class GdiSvgPaint : SvgPaint { #region Private Fields private GdiFill _paintFill; private SvgStyleableElement _element; #endregion #region Constructors and Destructor public GdiSvgPaint(SvgStyleableElement elm, string propName) : base(elm.GetComputedStyle("").GetPropertyValue(propName)) { _element = elm; } #endregion #region Public Properties public GdiFill PaintFill { get { return _paintFill; } } #endregion #region Public Methods public Brush GetBrush(GraphicsPath gp) { return GetBrush(gp, "fill"); } public Pen GetPen(GraphicsPath gp) { float strokeWidth = GetStrokeWidth(); if (strokeWidth == 0) return null; GdiSvgPaint stroke; if (PaintType == SvgPaintType.None) { return null; } else if (PaintType == SvgPaintType.CurrentColor) { stroke = new GdiSvgPaint(_element, "color"); } else { stroke = this; } Pen pen = new Pen(stroke.GetBrush(gp, "stroke"), strokeWidth); pen.StartCap = pen.EndCap = GetLineCap(); pen.LineJoin = GetLineJoin(); pen.MiterLimit = GetMiterLimit(); float[] fDashArray = GetDashArray(strokeWidth); if (fDashArray != null) { // Do not draw if dash array had a zero value in it for (int i = 0; i < fDashArray.Length; i++) { if (fDashArray[i] == 0) return null; } pen.DashPattern = fDashArray; } pen.DashOffset = GetDashOffset(strokeWidth); return pen; } #endregion #region Private Methods private int GetOpacity(string fillOrStroke) { double alpha = 255; string opacity; opacity = _element.GetPropertyValue(fillOrStroke + "-opacity"); if (opacity.Length > 0) alpha *= SvgNumber.ParseNumber(opacity); opacity = _element.GetPropertyValue("opacity"); if (opacity.Length > 0) alpha *= SvgNumber.ParseNumber(opacity); alpha = Math.Min(alpha, 255); alpha = Math.Max(alpha, 0); return Convert.ToInt32(alpha); } private LineCap GetLineCap() { switch (_element.GetPropertyValue("stroke-linecap")) { case "round": return LineCap.Round; case "square": return LineCap.Square; default: return LineCap.Flat; } } private LineJoin GetLineJoin() { switch (_element.GetPropertyValue("stroke-linejoin")) { case "round": return LineJoin.Round; case "bevel": return LineJoin.Bevel; default: return LineJoin.Miter; } } private float GetStrokeWidth() { string strokeWidth = _element.GetPropertyValue("stroke-width"); if (strokeWidth.Length == 0) strokeWidth = "1px"; SvgLength strokeWidthLength = new SvgLength(_element, "stroke-width", SvgLengthDirection.Viewport, strokeWidth); return (float)strokeWidthLength.Value; } private float GetMiterLimit() { string miterLimitStr = _element.GetPropertyValue("stroke-miterlimit"); if (miterLimitStr.Length == 0) miterLimitStr = "4"; float miterLimit = (float)SvgNumber.ParseNumber(miterLimitStr); if (miterLimit < 1) throw new SvgException(SvgExceptionType.SvgInvalidValueErr, "stroke-miterlimit can not be less then 1"); return miterLimit; } private float[] GetDashArray(float strokeWidth) { string dashArray = _element.GetPropertyValue("stroke-dasharray"); if (dashArray.Length == 0 || dashArray == "none") { return null; } else { SvgNumberList list = new SvgNumberList(dashArray); uint len = list.NumberOfItems; float[] fDashArray = new float[len]; for (uint i = 0; i < len; i++) { //divide by strokeWidth to take care of the difference between Svg and GDI+ fDashArray[i] = (float)(list.GetItem(i).Value / strokeWidth); } if (len % 2 == 1) { //odd number of values, duplicate float[] tmpArray = new float[len * 2]; fDashArray.CopyTo(tmpArray, 0); fDashArray.CopyTo(tmpArray, (int)len); fDashArray = tmpArray; } return fDashArray; } } private float GetDashOffset(float strokeWidth) { string dashOffset = _element.GetPropertyValue("stroke-dashoffset"); if (dashOffset.Length > 0) { //divide by strokeWidth to take care of the difference between Svg and GDI+ SvgLength dashOffsetLength = new SvgLength(_element, "stroke-dashoffset", SvgLengthDirection.Viewport, dashOffset); return (float)dashOffsetLength.Value; } else { return 0; } } private GdiFill GetPaintFill(string uri) { string absoluteUri = _element.ResolveUri(uri); return GdiFill.CreateFill(_element.OwnerDocument, absoluteUri); } private Brush GetBrush(GraphicsPath gp, string propPrefix) { SvgPaint painter; SvgPaintType curPaintType = this.PaintType; if (curPaintType == SvgPaintType.None) { return null; } else if (curPaintType == SvgPaintType.CurrentColor) { painter = new GdiSvgPaint(_element, "color"); } else { painter = this; } SvgPaintType paintType = painter.PaintType; if (paintType == SvgPaintType.Uri || paintType == SvgPaintType.UriCurrentColor || paintType == SvgPaintType.UriNone || paintType == SvgPaintType.UriRgbColor || paintType == SvgPaintType.UriRgbColorIccColor) { _paintFill = GetPaintFill(painter.Uri); if (_paintFill != null) { Brush br = _paintFill.GetBrush(gp.GetBounds()); LinearGradientBrush lgb = br as LinearGradientBrush; if (lgb != null) { int opacityl = GetOpacity(propPrefix); for (int i = 0; i < lgb.InterpolationColors.Colors.Length; i++) { lgb.InterpolationColors.Colors[i] = Color.FromArgb(opacityl, lgb.InterpolationColors.Colors[i]); } for (int i = 0; i < lgb.LinearColors.Length; i++) { lgb.LinearColors[i] = Color.FromArgb(opacityl, lgb.LinearColors[i]); } return br; } PathGradientBrush pgb = br as PathGradientBrush; if (pgb != null) { int opacityl = GetOpacity(propPrefix); for (int i = 0; i < pgb.InterpolationColors.Colors.Length; i++) { pgb.InterpolationColors.Colors[i] = Color.FromArgb(opacityl, pgb.InterpolationColors.Colors[i]); } for (int i = 0; i < pgb.SurroundColors.Length; i++) { pgb.SurroundColors[i] = Color.FromArgb(opacityl, pgb.SurroundColors[i]); } return br; } } else { if (curPaintType == SvgPaintType.UriNone || curPaintType == SvgPaintType.Uri) { return null; } else if (curPaintType == SvgPaintType.UriCurrentColor) { painter = new GdiSvgPaint(_element, "color"); } else { painter = this; } } } if (painter == null || painter.RgbColor == null) { return null; } SolidBrush brush = new SolidBrush(GdiConverter.ToColor(painter.RgbColor)); int opacity = GetOpacity(propPrefix); brush.Color = Color.FromArgb(opacity, brush.Color); return brush; } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // X509Utils.cs // namespace System.Security.Cryptography.X509Certificates { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; internal class X509Utils { private X509Utils () {} internal static bool IsCertRdnCharString (uint dwValueType) { return ((dwValueType & CAPI.CERT_RDN_TYPE_MASK) >= CAPI.CERT_RDN_NUMERIC_STRING); } // this method maps a cert content type returned from CryptQueryObject // to a value in the managed X509ContentType enum internal static X509ContentType MapContentType (uint contentType) { switch (contentType) { case CAPI.CERT_QUERY_CONTENT_CERT: return X509ContentType.Cert; case CAPI.CERT_QUERY_CONTENT_SERIALIZED_STORE: return X509ContentType.SerializedStore; case CAPI.CERT_QUERY_CONTENT_SERIALIZED_CERT: return X509ContentType.SerializedCert; case CAPI.CERT_QUERY_CONTENT_PKCS7_SIGNED: case CAPI.CERT_QUERY_CONTENT_PKCS7_UNSIGNED: return X509ContentType.Pkcs7; case CAPI.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED: return X509ContentType.Authenticode; case CAPI.CERT_QUERY_CONTENT_PFX: return X509ContentType.Pkcs12; default: return X509ContentType.Unknown; } } // this method maps a X509KeyStorageFlags enum to a combination of crypto API flags internal static uint MapKeyStorageFlags (X509KeyStorageFlags keyStorageFlags) { uint dwFlags = 0; if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet) dwFlags |= CAPI.CRYPT_USER_KEYSET; else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet) dwFlags |= CAPI.CRYPT_MACHINE_KEYSET; if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable) dwFlags |= CAPI.CRYPT_EXPORTABLE; if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected) dwFlags |= CAPI.CRYPT_USER_PROTECTED; return dwFlags; } // this method maps X509Store OpenFlags to a combination of crypto API flags internal static uint MapX509StoreFlags (StoreLocation storeLocation, OpenFlags flags) { uint dwFlags = 0; uint openMode = ((uint)flags) & 0x3; switch (openMode) { case (uint) OpenFlags.ReadOnly: dwFlags |= CAPI.CERT_STORE_READONLY_FLAG; break; case (uint) OpenFlags.MaxAllowed: dwFlags |= CAPI.CERT_STORE_MAXIMUM_ALLOWED_FLAG; break; } if ((flags & OpenFlags.OpenExistingOnly) == OpenFlags.OpenExistingOnly) dwFlags |= CAPI.CERT_STORE_OPEN_EXISTING_FLAG; if ((flags & OpenFlags.IncludeArchived) == OpenFlags.IncludeArchived) dwFlags |= CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG; if (storeLocation == StoreLocation.LocalMachine) dwFlags |= CAPI.CERT_SYSTEM_STORE_LOCAL_MACHINE; else if (storeLocation == StoreLocation.CurrentUser) dwFlags |= CAPI.CERT_SYSTEM_STORE_CURRENT_USER; return dwFlags; } // this method maps an X509NameType to crypto API flags. internal static uint MapNameType (X509NameType nameType) { uint type = 0; switch (nameType) { case X509NameType.SimpleName: type = CAPI.CERT_NAME_SIMPLE_DISPLAY_TYPE; break; case X509NameType.EmailName: type = CAPI.CERT_NAME_EMAIL_TYPE; break; case X509NameType.UpnName: type = CAPI.CERT_NAME_UPN_TYPE; break; case X509NameType.DnsName: case X509NameType.DnsFromAlternativeName: type = CAPI.CERT_NAME_DNS_TYPE; break; case X509NameType.UrlName: type = CAPI.CERT_NAME_URL_TYPE; break; default: throw new ArgumentException(SR.GetString(SR.Argument_InvalidNameType)); } return type; } // this method maps X509RevocationFlag to crypto API flags. internal static uint MapRevocationFlags (X509RevocationMode revocationMode, X509RevocationFlag revocationFlag) { uint dwFlags = 0; if (revocationMode == X509RevocationMode.NoCheck) return dwFlags; if (revocationMode == X509RevocationMode.Offline) dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY; if (revocationFlag == X509RevocationFlag.EndCertificateOnly) dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_END_CERT; else if (revocationFlag == X509RevocationFlag.EntireChain) dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_CHAIN; else dwFlags |= CAPI.CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT; return dwFlags; } private static readonly char[] hexValues = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; internal static string EncodeHexString (byte[] sArray) { return EncodeHexString(sArray, 0, (uint) sArray.Length); } internal static string EncodeHexString (byte[] sArray, uint start, uint end) { String result = null; if (sArray != null) { char[] hexOrder = new char[(end - start) * 2]; uint digit; for (uint i = start, j = 0; i < end; i++) { digit = (uint) ((sArray[i] & 0xf0) >> 4); hexOrder[j++] = hexValues[digit]; digit = (uint) (sArray[i] & 0x0f); hexOrder[j++] = hexValues[digit]; } result = new String(hexOrder); } return result; } internal static string EncodeHexStringFromInt (byte[] sArray, uint start, uint end) { String result = null; if(sArray != null) { char[] hexOrder = new char[(end - start) * 2]; uint i = end; uint digit, j=0; while (i-- > start) { digit = (uint) (sArray[i] & 0xf0) >> 4; hexOrder[j++] = hexValues[digit]; digit = (uint) (sArray[i] & 0x0f); hexOrder[j++] = hexValues[digit]; } result = new String(hexOrder); } return result; } internal static byte HexToByte (char val) { if (val <= '9' && val >= '0') return (byte) (val - '0'); else if (val >= 'a' && val <= 'f') return (byte) ((val - 'a') + 10); else if (val >= 'A' && val <= 'F') return (byte) ((val - 'A') + 10); else return 0xFF; } internal static uint AlignedLength (uint length) { return ((length + (uint) 7) & ((uint) 0xfffffff8)); } internal static String DiscardWhiteSpaces (string inputBuffer) { return DiscardWhiteSpaces(inputBuffer, 0, inputBuffer.Length); } internal static String DiscardWhiteSpaces (string inputBuffer, int inputOffset, int inputCount) { int i, iCount = 0; for (i=0; i<inputCount; i++) if (Char.IsWhiteSpace(inputBuffer[inputOffset + i])) iCount++; char[] rgbOut = new char[inputCount - iCount]; iCount = 0; for (i=0; i<inputCount; i++) if (!Char.IsWhiteSpace(inputBuffer[inputOffset + i])) { rgbOut[iCount++] = inputBuffer[inputOffset + i]; } return new String(rgbOut); } internal static byte[] DecodeHexString (string s) { string hexString = X509Utils.DiscardWhiteSpaces(s); uint cbHex = (uint) hexString.Length / 2; byte[] hex = new byte[cbHex]; int i = 0; for (int index = 0; index < cbHex; index++) { hex[index] = (byte) ((HexToByte(hexString[i]) << 4) | HexToByte(hexString[i+1])); i += 2; } return hex; } internal static int GetHexArraySize (byte[] hex) { int index = hex.Length; while (index-- > 0) { if (hex[index] != 0) break; } return index + 1; } internal static SafeLocalAllocHandle ByteToPtr (byte[] managed) { SafeLocalAllocHandle pb = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(managed.Length)); Marshal.Copy(managed, 0, pb.DangerousGetHandle(), managed.Length); return pb; } // // This method copies an unmanaged structure into the address of a managed structure. // This is useful when the structure is returned to us by Crypto API and its size varies // following the platform. // internal unsafe static void memcpy (IntPtr source, IntPtr dest, uint size) { for (uint index = 0; index < size; index++) { *(byte*) ((long)dest + index) = Marshal.ReadByte(new IntPtr((long)source + index)); } } internal static byte[] PtrToByte (IntPtr unmanaged, uint size) { byte[] array = new byte[(int) size]; Marshal.Copy(unmanaged, array, 0, array.Length); return array; } internal static unsafe bool MemEqual (byte * pbBuf1, uint cbBuf1, byte * pbBuf2, uint cbBuf2) { if (cbBuf1 != cbBuf2) return false; while (cbBuf1-- > 0) { if (*pbBuf1++ != *pbBuf2++) { return false; } } return true; } internal static SafeLocalAllocHandle StringToAnsiPtr (string s) { byte[] arr = new byte[s.Length + 1]; Encoding.ASCII.GetBytes(s, 0, s.Length, arr, 0); SafeLocalAllocHandle pb = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(arr.Length)); Marshal.Copy(arr, 0, pb.DangerousGetHandle(), arr.Length); return pb; } internal static SafeLocalAllocHandle StringToUniPtr (string s) { byte[] arr = new byte[2 * (s.Length + 1)]; Encoding.Unicode.GetBytes(s, 0, s.Length, arr, 0); SafeLocalAllocHandle pb = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(arr.Length)); Marshal.Copy(arr, 0, pb.DangerousGetHandle(), arr.Length); return pb; } // this method create a memory store from a certificate collection internal static SafeCertStoreHandle ExportToMemoryStore (X509Certificate2Collection collection) { // // We need to Assert all StorePermission flags since this is a memory store and we want // semi-trusted code to be able to export certificates to a memory store. // StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags); sp.Assert(); SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle; // we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation. // By default, Archived certificates will not be included. safeCertStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY), CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, IntPtr.Zero, CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG, null); if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); // // We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get // applied to the original store. This has a limit of 99 links per cert context however. // foreach (X509Certificate2 x509 in collection) { if (!CAPI.CertAddCertificateLinkToStore(safeCertStoreHandle, x509.CertContext, CAPI.CERT_STORE_ADD_ALWAYS, SafeCertContextHandle.InvalidHandle)) throw new CryptographicException(Marshal.GetLastWin32Error()); } return safeCertStoreHandle; } internal static uint OidToAlgId (string value) { SafeLocalAllocHandle pszOid = StringToAnsiPtr(value); CAPI.CRYPT_OID_INFO pOIDInfo = CAPI.CryptFindOIDInfo(CAPI.CRYPT_OID_INFO_OID_KEY, pszOid, 0); return pOIDInfo.Algid; } internal static string FindOidInfo(uint keyType, string keyValue, OidGroup oidGroup) { if (keyValue == null) throw new ArgumentNullException("keyValue"); if (keyValue.Length == 0) return null; SafeLocalAllocHandle pvKey = SafeLocalAllocHandle.InvalidHandle; try { switch(keyType) { case CAPI.CRYPT_OID_INFO_OID_KEY: pvKey = StringToAnsiPtr(keyValue); break; case CAPI.CRYPT_OID_INFO_NAME_KEY: pvKey = StringToUniPtr(keyValue); break; default: Debug.Assert(false); break; } CAPI.CRYPT_OID_INFO pOidInfo = CAPI.CryptFindOIDInfo(keyType, pvKey, oidGroup); if (keyType == CAPI.CRYPT_OID_INFO_OID_KEY) { return pOidInfo.pwszName; } else { return pOidInfo.pszOID; } } finally { pvKey.Dispose(); } } // Try to find OID info within a specific group, and if that doesn't work fall back to all // groups for compatibility with previous frameworks internal static string FindOidInfoWithFallback(uint key, string value, OidGroup group) { string info = FindOidInfo(key, value, group); // If we couldn't find it in the requested group, then try again in all groups if (info == null && group != OidGroup.All) { info = FindOidInfo(key, value, OidGroup.All); } return info; } // // verify the passed keyValue is valid as per X.208 // // The first number must be 0, 1 or 2. // Enforce all characters are digits and dots. // Enforce that no dot starts or ends the Oid, and disallow double dots. // Enforce there is at least one dot separator. // internal static void ValidateOidValue (string keyValue) { if (keyValue == null) throw new ArgumentNullException("keyValue"); int len = keyValue.Length; if (len < 2) goto error; // should not start with a dot. The first digit must be 0, 1 or 2. char c = keyValue[0]; if (c != '0' && c != '1' && c != '2') goto error; if (keyValue[1] != '.' || keyValue[len - 1] == '.') // should not end in a dot goto error; bool hasAtLeastOneDot = false; for (int i = 1; i < len; i++) { // ensure every character is either a digit or a dot if (Char.IsDigit(keyValue[i])) continue; if (keyValue[i] != '.' || keyValue[i + 1] == '.') // disallow double dots goto error; hasAtLeastOneDot = true; } if (hasAtLeastOneDot) return; error: throw new ArgumentException(SR.GetString(SR.Argument_InvalidOidValue)); } internal static SafeLocalAllocHandle CopyOidsToUnmanagedMemory (OidCollection oids) { SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle; if (oids == null || oids.Count == 0) return safeLocalAllocHandle; // Copy the oid strings to a local list to prevent a security race condition where // the OidCollection or individual oids can be modified by another thread and // potentially cause a buffer overflow List<string> oidStrs = new List<string>(); foreach (Oid oid in oids) { oidStrs.Add(oid.Value); } IntPtr pOid = IntPtr.Zero; // Needs to be checked to avoid having large sets of oids overflow the sizes and allow // a potential buffer overflow checked { int ptrSize = oidStrs.Count * Marshal.SizeOf(typeof(IntPtr)); int oidSize = 0; foreach (string oidStr in oidStrs) { oidSize += (oidStr.Length + 1); } safeLocalAllocHandle = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr((uint)ptrSize + (uint)oidSize)); pOid = new IntPtr((long)safeLocalAllocHandle.DangerousGetHandle() + ptrSize); } for (int index = 0; index < oidStrs.Count; index++) { Marshal.WriteIntPtr(new IntPtr((long) safeLocalAllocHandle.DangerousGetHandle() + index * Marshal.SizeOf(typeof(IntPtr))), pOid); byte[] ansiOid = Encoding.ASCII.GetBytes(oidStrs[index]); Marshal.Copy(ansiOid, 0, pOid, ansiOid.Length); pOid = new IntPtr((long)pOid + oidStrs[index].Length + 1); } return safeLocalAllocHandle; } internal static X509Certificate2Collection GetCertificates(SafeCertStoreHandle safeCertStoreHandle) { X509Certificate2Collection collection = new X509Certificate2Collection(); IntPtr pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, IntPtr.Zero); while (pEnumContext != IntPtr.Zero) { X509Certificate2 certificate = new X509Certificate2(pEnumContext); collection.Add(certificate); pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, pEnumContext); } return collection; } // // Verifies whether a certificate is valid for the specified policy. // S_OK means the certificate is valid for the specified policy. // S_FALSE means the certificate is invalid for the specified policy. // Anything else is an error. // internal static unsafe int VerifyCertificate (SafeCertContextHandle pCertContext, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, X509Certificate2Collection extraStore, IntPtr pszPolicy, IntPtr pdwErrorStatus) { if (pCertContext == null || pCertContext.IsInvalid) throw new ArgumentException("pCertContext"); CAPI.CERT_CHAIN_POLICY_PARA PolicyPara = new CAPI.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_PARA))); CAPI.CERT_CHAIN_POLICY_STATUS PolicyStatus = new CAPI.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_STATUS))); // Build the chain. SafeCertChainHandle pChainContext = SafeCertChainHandle.InvalidHandle; int hr = X509Chain.BuildChain(new IntPtr(CAPI.HCCE_CURRENT_USER), pCertContext, extraStore, applicationPolicy, certificatePolicy, revocationMode, revocationFlag, verificationTime, timeout, ref pChainContext); if (hr != CAPI.S_OK) return hr; // Verify the chain using the specified policy. if (CAPI.CertVerifyCertificateChainPolicy(pszPolicy, pChainContext, ref PolicyPara, ref PolicyStatus)) { if (pdwErrorStatus != IntPtr.Zero) *(uint*) pdwErrorStatus = PolicyStatus.dwError; if (PolicyStatus.dwError != 0) return CAPI.S_FALSE; } else { // The API failed. return Marshal.GetHRForLastWin32Error(); } return CAPI.S_OK; } internal static string GetSystemErrorString (int hr) { StringBuilder strMessage = new StringBuilder(512); uint dwErrorCode = CAPI.FormatMessage (CAPI.FORMAT_MESSAGE_FROM_SYSTEM | CAPI.FORMAT_MESSAGE_IGNORE_INSERTS, IntPtr.Zero, (uint) hr, 0, strMessage, (uint)strMessage.Capacity, IntPtr.Zero); if (dwErrorCode != 0) return strMessage.ToString(); else return SR.GetString(SR.Unknown_Error); } } }
////////////////////////////////////////////////////////////////////////////////////// // Author : Shukri Adams // // Contact : shukri.adams@gmail.com // // Compiler requirement : .Net 4.0 // // // // vcFramework : A reuseable library of utility classes // // Copyright (C) // // // // This program is free software; you can redistribute it and/or modify it under // // the terms of the GNU General Public License as published by the Free Software // // Foundation; either version 2 of the License, or (at your option) any later // // version. // // // // This program is distributed in the hope that it will be useful, but WITHOUT ANY // // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A // // PARTICULAR PURPOSE. See the GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License along with // // this program; if not, write to the Free Software Foundation, Inc., 59 Temple // // Place, Suite 330, Boston, MA 02111-1307 USA // ////////////////////////////////////////////////////////////////////////////////////// using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace vcFramework.Windows.Forms { /// <summary> Simple generic splash screen </summary> public class Splash : System.Windows.Forms.Form { #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.imgSplash = new System.Windows.Forms.PictureBox(); this.lblSplashText = new System.Windows.Forms.Label(); this.SuspendLayout(); // // imgSplash // this.imgSplash.Dock = System.Windows.Forms.DockStyle.Top; this.imgSplash.Location = new System.Drawing.Point(0, 0); this.imgSplash.Name = "imgSplash"; this.imgSplash.Size = new System.Drawing.Size(296, 232); this.imgSplash.TabIndex = 0; this.imgSplash.TabStop = false; // // lblSplashText // this.lblSplashText.Dock = System.Windows.Forms.DockStyle.Fill; this.lblSplashText.Location = new System.Drawing.Point(0, 232); this.lblSplashText.Name = "lblSplashText"; this.lblSplashText.Size = new System.Drawing.Size(296, 24); this.lblSplashText.TabIndex = 1; // // Splash // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(296, 256); this.Controls.Add(this.lblSplashText); this.Controls.Add(this.imgSplash); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "Splash"; this.Load += new System.EventHandler(this.Splash_Load); this.ResumeLayout(false); } #endregion #region MEMBERS private PictureBox imgSplash; private Container components = null; private Label lblSplashText; /// <summary> Timer object used to control spash timeout </summary> private Timer m_Timer; /// <summary> timer object used to control the automatic shutdown of splash screen </summary> private int m_intSplashTimeOut; /// <summary> /// Preset height of the "label" area of splash. /// </summary> private const int M_INTSPLASHTEXTHEIGHT = 30; private int m_intSplashTextHeight; #endregion #region PROPERTIES /// <summary> Gets or sets text on splash screen </summary> public string SplashText { set{lblSplashText.Text = value;} get{return lblSplashText.Text;} } /// <summary> Sets the backcolor of the text area on the splash screen </summary> public Color SplashTextBackColor { set{lblSplashText.BackColor = value;} } #endregion #region CONSTRUCTORS public Splash( Form frmApplication, Bitmap imgSplashPicture, int intTimeOut, bool DisplaySplashText) { InitializeComponent(); // stores arguments in members where necessary m_intSplashTimeOut = intTimeOut; imgSplash.Image = imgSplashPicture; m_intSplashTextHeight = 0; lblSplashText.Visible = false; if (DisplaySplashText) { m_intSplashTextHeight = M_INTSPLASHTEXTHEIGHT; lblSplashText.Visible = true; } // sets proportions of form and label on form this.Size = imgSplash.Size = imgSplashPicture.Size; this.lblSplashText.Height = m_intSplashTextHeight; this.ShowInTaskbar = false; // sets start location - splash is forced to middle of the "application" form that is passed in to constructor FormLib.ScreenCenterForm(this); // sets up events imgSplash.MouseDown += new MouseEventHandler(imgSplash_MouseDown); this.LostFocus += new EventHandler(Splash_LostFocus); } #endregion #region DESTRUCTORS protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region METHODS /// <summary> Writes a text message to splash's visible label </summary> /// <param name="strMessage"></param> public void WriteTextMessage(string strMessage) { lblSplashText.Text = strMessage; } #endregion #region EVENTS private void Splash_Load(object sender, EventArgs e) { m_Timer = new Timer { Interval = m_intSplashTimeOut }; m_Timer.Tick += SplashTimeout; m_Timer.Start(); } /// <summary> /// Invoked when splash loses focus - forces focus back on form for the duration of its life /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Splash_LostFocus(object sender, EventArgs e) { this.Focus(); } /// <summary> /// Called by timer - handles timeout behaviour of splash /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SplashTimeout(object sender, EventArgs e) { m_Timer.Stop(); m_Timer.Dispose(); this.Visible = false; this.Close(); } /// <summary> /// Allows a mouse click on splash form to shut it down /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void imgSplash_MouseDown(object sender, MouseEventArgs e) { this.Visible = false; this.Close(); } #endregion } }
namespace PhotoDealer.Data.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Linq; using Microsoft.AspNet.Identity.EntityFramework; using PhotoDealer.Common; using PhotoDealer.Data.Models; using Microsoft.AspNet.Identity; internal sealed class Configuration : DbMigrationsConfiguration<PhotoDealer.Data.AppDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(AppDbContext context) { if (!context.CategoryGroups.Any()) { this.SeedCategories(context); } if (!context.Roles.Any()) { var roles = new List<IdentityRole>() { // new IdentityRole(GlobalConstants.RegularUserRoleName), new IdentityRole(GlobalConstants.TrustedUserRoleName), new IdentityRole(GlobalConstants.ModeratorRoleName), new IdentityRole(GlobalConstants.AdministratorRoleName), }; context.Roles.AddOrUpdate(roles.ToArray()); context.SaveChanges(); } if (!context.Users.Any()) { var userManager = new UserManager<User>(new UserStore<User>(context)); var adminEmail = "admin@photodealer.com"; var admin = new User() { UserName = adminEmail, Email = adminEmail }; userManager.Create(admin, "123456"); userManager.AddToRole(admin.Id, GlobalConstants.AdministratorRoleName); var userEmail = "user@photodealer.com"; var user = new User() { UserName = userEmail, Email = userEmail }; userManager.Create(user, "123456"); context.SaveChanges(); } } private void SeedCategories(AppDbContext context) { var categoryGroups = new List<CategoryGroup>(); var categories = new List<Category>(); categoryGroups.Add(new CategoryGroup() { GroupName = "Buildings" }); categories.Add(new Category() { Name = "Agricultural", CategoryGroup = categoryGroups[0] }); categories.Add(new Category() { Name = "Architectural", CategoryGroup = categoryGroups[0] }); categories.Add(new Category() { Name = "Bridges", CategoryGroup = categoryGroups[0] }); categories.Add(new Category() { Name = "Industrial", CategoryGroup = categoryGroups[0] }); categories.Add(new Category() { Name = "Interiors", CategoryGroup = categoryGroups[0] }); categories.Add(new Category() { Name = "Monuments", CategoryGroup = categoryGroups[0] }); categories.Add(new Category() { Name = "Religious", CategoryGroup = categoryGroups[0] }); categories.Add(new Category() { Name = "Residences", CategoryGroup = categoryGroups[0] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Man-made spaces" }); categories.Add(new Category() { Name = "Cemeteries", CategoryGroup = categoryGroups[1] }); categories.Add(new Category() { Name = "Cities From Above", CategoryGroup = categoryGroups[1] }); categories.Add(new Category() { Name = "Gardens", CategoryGroup = categoryGroups[1] }); categories.Add(new Category() { Name = "Amusement Parks", CategoryGroup = categoryGroups[1] }); categories.Add(new Category() { Name = "Public benches", CategoryGroup = categoryGroups[1] }); categories.Add(new Category() { Name = "Trails", CategoryGroup = categoryGroups[1] }); categories.Add(new Category() { Name = "Walkways", CategoryGroup = categoryGroups[1] }); categories.Add(new Category() { Name = "Skylines", CategoryGroup = categoryGroups[1] }); categories.Add(new Category() { Name = "Tunnels", CategoryGroup = categoryGroups[1] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Roads" }); categories.Add(new Category() { Name = "Border Crossings", CategoryGroup = categoryGroups[2] }); categories.Add(new Category() { Name = "Road curves", CategoryGroup = categoryGroups[2] }); categories.Add(new Category() { Name = "Highways", CategoryGroup = categoryGroups[2] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Transportation" }); categories.Add(new Category() { Name = "Small Planes", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "ATVs", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "Autos", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "Bicycles", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "Boats", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "Busses", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "Trains", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "Carriages", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "Classic Cars", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "Motorbikes", CategoryGroup = categoryGroups[3] }); categories.Add(new Category() { Name = "Trucks", CategoryGroup = categoryGroups[3] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Animals and Wildlife" }); categories.Add(new Category() { Name = "Animal Tracks", CategoryGroup = categoryGroups[4] }); categories.Add(new Category() { Name = "Birds", CategoryGroup = categoryGroups[4] }); categories.Add(new Category() { Name = "Fish", CategoryGroup = categoryGroups[4] }); categories.Add(new Category() { Name = "Insects", CategoryGroup = categoryGroups[4] }); categories.Add(new Category() { Name = "Mammals", CategoryGroup = categoryGroups[4] }); categories.Add(new Category() { Name = "Marine Life", CategoryGroup = categoryGroups[4] }); categories.Add(new Category() { Name = "Pets", CategoryGroup = categoryGroups[4] }); categories.Add(new Category() { Name = "Reptiles", CategoryGroup = categoryGroups[4] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Atmosphere and Sky" }); categories.Add(new Category() { Name = "Alpenglow", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Aurora Borealis", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Cloudless Sky", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Clouds", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Fog", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Moon", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Rain", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Sea of Clouds", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Stars", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Sun", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Sunrises", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Sunsets", CategoryGroup = categoryGroups[5] }); categories.Add(new Category() { Name = "Twilight", CategoryGroup = categoryGroups[5] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Nature Environments" }); categories.Add(new Category() { Name = "Deserts", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "Grasslands", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "High Altitude", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "Middle Mountain", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "North Woods", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "Oasis", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "Subtropics", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "Timberline", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "Tropics", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "Tundra", CategoryGroup = categoryGroups[6] }); categories.Add(new Category() { Name = "Wetlands", CategoryGroup = categoryGroups[6] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Flowers" }); categories.Add(new Category() { Name = "Alpine Flowers", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Beargrass", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Brittlebush", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Cactus Blooms", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Coreopsis Flowers", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Daffodils", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Daisies", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Dalhias", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Decorative Flowers", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Flower Carpets", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Iceplant", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Irises", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Lupine", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Morning Glories", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Orchids", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Rododendrons", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Roses", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Sunflowers", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Trillium", CategoryGroup = categoryGroups[7] }); categories.Add(new Category() { Name = "Tulips", CategoryGroup = categoryGroups[7] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Freshwater" }); categories.Add(new Category() { Name = "Braided Rivers", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Cascades", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Flooded Plains", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Islets In Lakes", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Lakes", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Ponds", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Rainbows", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Rivers", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Streams", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Swamps", CategoryGroup = categoryGroups[8] }); categories.Add(new Category() { Name = "Waterfalls", CategoryGroup = categoryGroups[8] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Mountains" }); categories.Add(new Category() { Name = "Distant Ranges", CategoryGroup = categoryGroups[9] }); categories.Add(new Category() { Name = "Forested Peaks", CategoryGroup = categoryGroups[9] }); categories.Add(new Category() { Name = "Moraines", CategoryGroup = categoryGroups[9] }); categories.Add(new Category() { Name = "Mountain Vistas", CategoryGroup = categoryGroups[9] }); categories.Add(new Category() { Name = "Ridges", CategoryGroup = categoryGroups[9] }); categories.Add(new Category() { Name = "Rocky Peaks", CategoryGroup = categoryGroups[9] }); categories.Add(new Category() { Name = "Snowy Peaks", CategoryGroup = categoryGroups[9] }); categories.Add(new Category() { Name = "Valleys", CategoryGroup = categoryGroups[9] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Ice and Snow" }); categories.Add(new Category() { Name = "Frost", CategoryGroup = categoryGroups[10] }); categories.Add(new Category() { Name = "Frozen Rivers", CategoryGroup = categoryGroups[10] }); categories.Add(new Category() { Name = "Frozen Waterfalls", CategoryGroup = categoryGroups[10] }); categories.Add(new Category() { Name = "Glaciers", CategoryGroup = categoryGroups[10] }); categories.Add(new Category() { Name = "Hail", CategoryGroup = categoryGroups[10] }); categories.Add(new Category() { Name = "Icebergs", CategoryGroup = categoryGroups[10] }); categories.Add(new Category() { Name = "Permanent Snow", CategoryGroup = categoryGroups[10] }); categories.Add(new Category() { Name = "Seasonal Snow", CategoryGroup = categoryGroups[10] }); categoryGroups.Add(new CategoryGroup() { GroupName = "Vegetation" }); categories.Add(new Category() { Name = "Aquatic Plants", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Bamboo", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Blossoms", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Carnivorous Plants", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Desert Plants", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Epiphytes", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Fall Colors", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Ferns", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Forests", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Grasses", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Mushrooms", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Shrubs", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Trees", CategoryGroup = categoryGroups[11] }); categories.Add(new Category() { Name = "Vines", CategoryGroup = categoryGroups[11] }); categoryGroups.Add(new CategoryGroup() { GroupName = "People" }); categories.Add(new Category() { Name = "Artists", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Children", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Couples", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Crowds", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Families", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Monks", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Portraits", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Uniformed People", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Weddings", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Men", CategoryGroup = categoryGroups[12] }); categories.Add(new Category() { Name = "Women", CategoryGroup = categoryGroups[12] }); context.CategoryGroups.AddOrUpdate(categoryGroups.ToArray()); context.Categories.AddOrUpdate(categories.ToArray()); context.SaveChanges(); } } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. 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. //using System; using System.Collections.Generic; using System.IO; using Couchbase.Lite; using Couchbase.Lite.Internal; using Sharpen; namespace Couchbase.Lite { /// <summary>A Couchbase Lite Document Attachment.</summary> /// <remarks>A Couchbase Lite Document Attachment.</remarks> public sealed class Attachment { /// <summary>The owning document revision.</summary> /// <remarks>The owning document revision.</remarks> private Revision revision; /// <summary>Whether or not this attachment is gzipped</summary> private bool gzipped; /// <summary>The owning document.</summary> /// <remarks>The owning document.</remarks> private Document document; /// <summary>The filename.</summary> /// <remarks>The filename.</remarks> private string name; /// <summary>The CouchbaseLite metadata about the attachment, that lives in the document. /// </summary> /// <remarks>The CouchbaseLite metadata about the attachment, that lives in the document. /// </remarks> private IDictionary<string, object> metadata; /// <summary>The body data.</summary> /// <remarks>The body data.</remarks> private InputStream body; /// <summary>Constructor</summary> [InterfaceAudience.Private] internal Attachment(InputStream contentStream, string contentType) { this.body = contentStream; metadata = new Dictionary<string, object>(); metadata.Put("content_type", contentType); metadata.Put("follows", true); this.gzipped = false; } /// <summary>Constructor</summary> [InterfaceAudience.Private] internal Attachment(Revision revision, string name, IDictionary<string, object> metadata ) { this.revision = revision; this.name = name; this.metadata = metadata; this.gzipped = false; } /// <summary>Get the owning document revision.</summary> /// <remarks>Get the owning document revision.</remarks> [InterfaceAudience.Public] public Revision GetRevision() { return revision; } /// <summary>Get the owning document.</summary> /// <remarks>Get the owning document.</remarks> [InterfaceAudience.Public] public Document GetDocument() { return revision.GetDocument(); } /// <summary>Get the filename.</summary> /// <remarks>Get the filename.</remarks> [InterfaceAudience.Public] public string GetName() { return name; } /// <summary>Get the MIME type of the contents.</summary> /// <remarks>Get the MIME type of the contents.</remarks> [InterfaceAudience.Public] public string GetContentType() { return (string)metadata.Get("content_type"); } /// <summary>Get the content (aka 'body') data.</summary> /// <remarks>Get the content (aka 'body') data.</remarks> /// <exception cref="CouchbaseLiteException">CouchbaseLiteException</exception> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [InterfaceAudience.Public] public InputStream GetContent() { if (body != null) { return body; } else { Database db = revision.GetDatabase(); Couchbase.Lite.Attachment attachment = db.GetAttachmentForSequence(revision.GetSequence (), this.name); body = attachment.GetContent(); return body; } } /// <summary>Get the length in bytes of the contents.</summary> /// <remarks>Get the length in bytes of the contents.</remarks> [InterfaceAudience.Public] public long GetLength() { Number length = (Number)metadata.Get("length"); if (length != null) { return length; } else { return 0; } } /// <summary>The CouchbaseLite metadata about the attachment, that lives in the document. /// </summary> /// <remarks>The CouchbaseLite metadata about the attachment, that lives in the document. /// </remarks> [InterfaceAudience.Public] public IDictionary<string, object> GetMetadata() { return Sharpen.Collections.UnmodifiableMap(metadata); } [InterfaceAudience.Private] internal void SetName(string name) { this.name = name; } [InterfaceAudience.Private] internal void SetRevision(Revision revision) { this.revision = revision; } [InterfaceAudience.Private] internal InputStream GetBodyIfNew() { return body; } /// <summary> /// Goes through an _attachments dictionary and replaces any values that are Attachment objects /// with proper JSON metadata dicts. /// </summary> /// <remarks> /// Goes through an _attachments dictionary and replaces any values that are Attachment objects /// with proper JSON metadata dicts. It registers the attachment bodies with the blob store and sets /// the metadata 'digest' and 'follows' properties accordingly. /// </remarks> [InterfaceAudience.Private] internal static IDictionary<string, object> InstallAttachmentBodies(IDictionary<string , object> attachments, Database database) { IDictionary<string, object> updatedAttachments = new Dictionary<string, object>(); foreach (string name in attachments.Keys) { object value = attachments.Get(name); if (value is Couchbase.Lite.Attachment) { Couchbase.Lite.Attachment attachment = (Couchbase.Lite.Attachment)value; IDictionary<string, object> metadataMutable = new Dictionary<string, object>(); metadataMutable.PutAll(attachment.GetMetadata()); InputStream body = attachment.GetBodyIfNew(); if (body != null) { // Copy attachment body into the database's blob store: BlobStoreWriter writer = BlobStoreWriterForBody(body, database); metadataMutable.Put("length", (long)writer.GetLength()); metadataMutable.Put("digest", writer.MD5DigestString()); metadataMutable.Put("follows", true); database.RememberAttachmentWriter(writer); } updatedAttachments.Put(name, metadataMutable); } else { if (value is AttachmentInternal) { throw new ArgumentException("AttachmentInternal objects not expected here. Could indicate a bug" ); } else { if (value != null) { updatedAttachments.Put(name, value); } } } } return updatedAttachments; } [InterfaceAudience.Private] internal static BlobStoreWriter BlobStoreWriterForBody(InputStream body, Database database) { BlobStoreWriter writer = database.GetAttachmentWriter(); writer.Read(body); writer.Finish(); return writer; } /// <exclude></exclude> [InterfaceAudience.Private] public bool GetGZipped() { return gzipped; } /// <exclude></exclude> [InterfaceAudience.Private] public void SetGZipped(bool gzipped) { this.gzipped = gzipped; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SAF.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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 Gallio.Common.Collections; using Gallio.Runtime.Conversions; using Gallio.Runtime.Extensibility; using MbUnit.Framework; using Rhino.Mocks; namespace Gallio.Tests.Runtime.Conversions { [TestFixture] [TestsOn(typeof(RuleBasedConverter))] [DependsOn(typeof(BaseConverterTest))] public class RuleBasedConverterTest { [Test, ExpectedArgumentNullException] public void Constructs_with_null_extensionPoints_should_throw_Exception() { new RuleBasedConverter(null, EmptyArray<IConversionRule>.Instance); } [Test, ExpectedArgumentNullException] public void Constructs_with_null_rules_should_throw_Exception() { var mockExtensionPoints = MockRepository.GenerateStub<IExtensionPoints>(); new RuleBasedConverter(mockExtensionPoints, null); } [Test] public void GetConversionCost_chooses_least_costly_rule() { var mockRule0 = MockRepository.GenerateStub<IConversionRule>(); var mockRule1 = MockRepository.GenerateStub<IConversionRule>(); var mockRule2 = MockRepository.GenerateStub<IConversionRule>(); var converter = new RuleBasedConverter(new DefaultExtensionPoints(), new[] { mockRule0, mockRule1, mockRule2 });; mockRule0.Stub(x => x.GetConversionCost(typeof(int), typeof(string), converter)).Return(ConversionCost.Best); mockRule1.Stub(x => x.GetConversionCost(typeof(int), typeof(string), converter)).Return(ConversionCost.Invalid); mockRule2.Stub(x => x.GetConversionCost(typeof(int), typeof(string), converter)).Return(ConversionCost.Default); Assert.AreEqual(ConversionCost.Best, converter.GetConversionCost(typeof(int), typeof(string))); } [Test] public void CanConvert_returns_true_if_and_only_if_a_conversion_rule_supports_the_conversion() { var mockRule0 = MockRepository.GenerateStub<IConversionRule>(); var mockRule1 = MockRepository.GenerateStub<IConversionRule>(); var converter = new RuleBasedConverter(new DefaultExtensionPoints(), new[] { mockRule0, mockRule1 });; mockRule0.Stub(x => x.GetConversionCost(typeof(int), typeof(string), converter)).Return(ConversionCost.Invalid); mockRule1.Stub(x => x.GetConversionCost(typeof(int), typeof(string), converter)).Return(ConversionCost.Invalid); mockRule0.Stub(x => x.GetConversionCost(typeof(double), typeof(string), converter)).Return(ConversionCost.Default); mockRule1.Stub(x => x.GetConversionCost(typeof(double), typeof(string), converter)).Return(ConversionCost.Invalid); Assert.IsFalse(converter.CanConvert(typeof(int), typeof(string))); Assert.IsTrue(converter.CanConvert(typeof(double), typeof(string))); } [Test] public void Convert_caches_the_conversion_so_GetConversionCost_is_only_called_once_for_a_pair_of_types() { var mockRule0 = MockRepository.GenerateMock<IConversionRule>(); var mockRule1 = MockRepository.GenerateMock<IConversionRule>(); var converter = new RuleBasedConverter(new DefaultExtensionPoints(), new[] { mockRule0, mockRule1 }); mockRule0.Expect(x => x.GetConversionCost(typeof(int), typeof(string), converter)).Return(ConversionCost.Invalid); mockRule1.Expect(x => x.GetConversionCost(typeof(int), typeof(string), converter)).Return(ConversionCost.Default); mockRule1.Expect(x => x.Convert(42, typeof(string), converter, true)).Return("42"); mockRule1.Expect(x => x.Convert(53, typeof(string), converter, true)).Return("53"); Assert.AreEqual("42", converter.Convert(42, typeof(string))); Assert.AreEqual("53", converter.Convert(53, typeof(string))); mockRule0.VerifyAllExpectations(); mockRule1.VerifyAllExpectations(); } private delegate ConversionCost GetConversionCostDelegate(Type sourceType, Type targetType, IConverter converter); [Test] public void Recursive_conversions_attempts_are_denied() { var mockRule = MockRepository.GenerateMock<IConversionRule>(); var converter = new RuleBasedConverter(new DefaultExtensionPoints(), new[] { mockRule }); mockRule.Expect(x => x.GetConversionCost(typeof(int), typeof(string), converter)).Do((GetConversionCostDelegate)delegate { Assert.AreEqual(ConversionCost.Invalid, converter.GetConversionCost(typeof(int), typeof(string))); return ConversionCost.Best; }); Assert.AreEqual(ConversionCost.Best, converter.GetConversionCost(typeof(int), typeof(string))); mockRule.VerifyAllExpectations(); } [Test] public void CanConvert_always_returns_true_if_types_are_same() { var converter = new RuleBasedConverter(new DefaultExtensionPoints(), EmptyArray<IConversionRule>.Instance); Assert.IsTrue(converter.CanConvert(typeof(int), typeof(int))); Assert.IsFalse(converter.CanConvert(typeof(int), typeof(string))); } [Test] public void GetConversionCost_always_returns_zero_if_types_are_same() { var converter = new RuleBasedConverter(new DefaultExtensionPoints(), EmptyArray<IConversionRule>.Instance); Assert.AreEqual(ConversionCost.Zero, converter.GetConversionCost(typeof(int), typeof(int))); Assert.AreEqual(ConversionCost.Invalid, converter.GetConversionCost(typeof(int), typeof(string))); } [Test] public void Convert_returns_same_value_if_types_are_same() { var converter = new RuleBasedConverter(new DefaultExtensionPoints(), EmptyArray<IConversionRule>.Instance); Assert.AreEqual(42, converter.Convert(42, typeof(int))); } [Test, ExpectedException(typeof(InvalidOperationException))] public void Convert_throws_if_conversion_not_supported() { var converter = new RuleBasedConverter(new DefaultExtensionPoints(), EmptyArray<IConversionRule>.Instance); converter.Convert("42", typeof(int)); } [Test] public void Nulls_remain_null_during_conversions_to_reference_types() { var converter = new RuleBasedConverter(new DefaultExtensionPoints(), EmptyArray<IConversionRule>.Instance); Assert.IsNull(converter.Convert(null, typeof(string))); } [Test] public void Nulls_remain_rull_during_conversions_to_nullable_ValueTypes() { var converter = new RuleBasedConverter(new DefaultExtensionPoints(), EmptyArray<IConversionRule>.Instance); Assert.IsNull(converter.Convert(null, typeof(int?))); } [Test, ExpectedException(typeof(InvalidOperationException))] public void Nulls_cannot_be_converted_to_non_nullable_ValueTypes() { var converter = new RuleBasedConverter(new DefaultExtensionPoints(), EmptyArray<IConversionRule>.Instance); converter.Convert(null, typeof(int)); } [Test] public void Nullable_types_are_equivalent_to_non_nullable_types_of_same_underlying_type() { var converter = new RuleBasedConverter(new DefaultExtensionPoints(), EmptyArray<IConversionRule>.Instance); Assert.AreEqual(ConversionCost.Zero, converter.GetConversionCost(typeof(int?), typeof(int))); Assert.AreEqual(ConversionCost.Zero, converter.GetConversionCost(typeof(int), typeof(int?))); Assert.AreEqual(ConversionCost.Zero, converter.GetConversionCost(typeof(int?), typeof(int?))); } [Test] public void Nullable_target_type_is_translated_before_being_passed_to_the_conversion_rule() { var mockRule = MockRepository.GenerateMock<IConversionRule>(); var converter = new RuleBasedConverter(new DefaultExtensionPoints(), new[] { mockRule }); mockRule.Expect(x => x.GetConversionCost(typeof(int), typeof(double), converter)).Return(ConversionCost.Best); Assert.AreEqual(ConversionCost.Best, converter.GetConversionCost(typeof(int?), typeof(double))); Assert.AreEqual(ConversionCost.Best, converter.GetConversionCost(typeof(int), typeof(double?))); Assert.AreEqual(ConversionCost.Best, converter.GetConversionCost(typeof(int?), typeof(double?))); mockRule.VerifyAllExpectations(); } internal class Foo { private readonly int value; public int Value { get { return value; } } public Foo(int value) { this.value = value; } } [Test] public void Custom_conversion() { var extensionPoints = new DefaultExtensionPoints(); extensionPoints.CustomConverters.Register<string, Foo>(x => new Foo(Int32.Parse(x))); var converter = new RuleBasedConverter(extensionPoints, EmptyArray<IConversionRule>.Instance); var actual = (Foo)converter.Convert("123", typeof(Foo)); Assert.AreEqual(123, actual.Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 SubtractSingle() { var test = new SimpleBinaryOpTest__SubtractSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractSingle { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[ElementCount]; private static Single[] _data2 = new Single[ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single> _dataTable; static SimpleBinaryOpTest__SubtractSingle() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__SubtractSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.Subtract( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.Subtract( Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.Subtract( Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var result = Avx.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)); var result = Avx.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)); var result = Avx.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractSingle(); var result = Avx.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.Subtract(_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<Single> left, Vector256<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, 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 = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(left[0] - right[0]) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.SingleToInt32Bits(left[i] - right[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Subtract)}<Single>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
#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): // // James Driscoll, mailto:jamesdriscoll@btinternet.com // with contributions from Hath1 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // All code in this file requires .NET Framework 1.1 or later. #if !NET_1_0 [assembly: Elmah.Scc("$Id: OracleErrorLog.cs 566 2009-05-11 10:37:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Data; using System.Data.OracleClient; using System.IO; using System.Text; using IDictionary = System.Collections.IDictionary; using IList = System.Collections.IList; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses Oracle as its backing store. /// </summary> public class OracleErrorLog : ErrorLog { private readonly string _connectionString; private readonly string _schemaOwner; private const int _maxAppNameLength = 60; private const int _maxSchemaNameLength = 30; /// <summary> /// Initializes a new instance of the <see cref="OracleErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public OracleErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); string connectionString = ConnectionStringHelper.GetConnectionString(config); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new ApplicationException("Connection string is missing for the Oracle error log."); _connectionString = connectionString; // // Set the application name as this implementation provides // per-application isolation over a single store. // string appName = Mask.NullString((string)config["applicationName"]); if (appName.Length > _maxAppNameLength) { throw new ApplicationException(string.Format( "Application name is too long. Maximum length allowed is {0} characters.", _maxAppNameLength.ToString("N0"))); } ApplicationName = appName; _schemaOwner = Mask.NullString((string)config["schemaOwner"]); if(_schemaOwner.Length > _maxSchemaNameLength) { throw new ApplicationException(string.Format( "Oracle schema owner is too long. Maximum length allowed is {0} characters.", _maxSchemaNameLength.ToString("N0"))); } if (_schemaOwner.Length > 0) _schemaOwner = _schemaOwner + "."; } /// <summary> /// Initializes a new instance of the <see cref="OracleErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public OracleErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = connectionString; } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "Oracle Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); Guid id = Guid.NewGuid(); using (OracleConnection connection = new OracleConnection(this.ConnectionString)) using (OracleCommand command = connection.CreateCommand()) { connection.Open(); using (OracleTransaction transaction = connection.BeginTransaction()) { // because we are storing the XML data in a NClob, we need to jump through a few hoops!! // so first we've got to operate within a transaction command.Transaction = transaction; // then we need to create a temporary lob on the database server command.CommandText = "declare xx nclob; begin dbms_lob.createtemporary(xx, false, 0); :tempblob := xx; end;"; command.CommandType = CommandType.Text; OracleParameterCollection parameters = command.Parameters; parameters.Add("tempblob", OracleType.NClob).Direction = ParameterDirection.Output; command.ExecuteNonQuery(); // now we can get a handle to the NClob OracleLob xmlLob = (OracleLob)parameters[0].Value; // create a temporary buffer in which to store the XML byte[] tempbuff = Encoding.Unicode.GetBytes(errorXml); // and finally we can write to it! xmlLob.BeginBatch(OracleLobOpenMode.ReadWrite); xmlLob.Write(tempbuff,0,tempbuff.Length); xmlLob.EndBatch(); command.CommandText = _schemaOwner + "pkg_elmah$log_error.LogError"; command.CommandType = CommandType.StoredProcedure; parameters.Clear(); parameters.Add("v_ErrorId", OracleType.NVarChar, 32).Value = id.ToString("N"); parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName; parameters.Add("v_Host", OracleType.NVarChar, 30).Value = error.HostName; parameters.Add("v_Type", OracleType.NVarChar, 100).Value = error.Type; parameters.Add("v_Source", OracleType.NVarChar, 60).Value = error.Source; parameters.Add("v_Message", OracleType.NVarChar, 500).Value = error.Message; parameters.Add("v_User", OracleType.NVarChar, 50).Value = error.User; parameters.Add("v_AllXml", OracleType.NClob).Value = xmlLob; parameters.Add("v_StatusCode", OracleType.Int32).Value = error.StatusCode; parameters.Add("v_TimeUtc", OracleType.DateTime).Value = error.Time.ToUniversalTime(); command.ExecuteNonQuery(); transaction.Commit(); } return id.ToString(); } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); using (OracleConnection connection = new OracleConnection(this.ConnectionString)) using (OracleCommand command = connection.CreateCommand()) { command.CommandText = _schemaOwner + "pkg_elmah$get_error.GetErrorsXml"; command.CommandType = CommandType.StoredProcedure; OracleParameterCollection parameters = command.Parameters; parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName; parameters.Add("v_PageIndex", OracleType.Int32).Value = pageIndex; parameters.Add("v_PageSize", OracleType.Int32).Value = pageSize; parameters.Add("v_TotalCount", OracleType.Int32).Direction = ParameterDirection.Output; parameters.Add("v_Results", OracleType.Cursor).Direction = ParameterDirection.Output; connection.Open(); using (OracleDataReader reader = command.ExecuteReader()) { Debug.Assert(reader != null); if (errorEntryList != null) { while (reader.Read()) { string id = reader["ErrorId"].ToString(); Guid guid = new Guid(id); Error error = new Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["UserName"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, guid.ToString(), error)); } } reader.Close(); } return (int)command.Parameters["v_TotalCount"].Value; } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); Guid errorGuid; try { errorGuid = new Guid(id); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } string errorXml; using (OracleConnection connection = new OracleConnection(this.ConnectionString)) using (OracleCommand command = connection.CreateCommand()) { command.CommandText = _schemaOwner + "pkg_elmah$get_error.GetErrorXml"; command.CommandType = CommandType.StoredProcedure; OracleParameterCollection parameters = command.Parameters; parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName; parameters.Add("v_ErrorId", OracleType.NVarChar, 32).Value = errorGuid.ToString("N"); parameters.Add("v_AllXml", OracleType.NClob).Direction = ParameterDirection.Output; connection.Open(); command.ExecuteNonQuery(); OracleLob xmlLob = (OracleLob)command.Parameters["v_AllXml"].Value; StreamReader streamreader = new StreamReader(xmlLob, Encoding.Unicode); char[] cbuffer = new char[1000]; int actual; StringBuilder sb = new StringBuilder(); while((actual = streamreader.Read(cbuffer, 0, cbuffer.Length)) >0) sb.Append(cbuffer, 0, actual); errorXml = sb.ToString(); } if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } } } #endif //!NET_1_0
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using BenchmarkDotNet.Running; using Benchmarks.MapReduce; using Benchmarks.Ping; using Benchmarks.Transactions; using Benchmarks.GrainStorage; namespace Benchmarks { class Program { private static readonly Dictionary<string, Action> _benchmarks = new Dictionary<string, Action> { ["MapReduce"] = () => { RunBenchmark( "Running MapReduce benchmark", () => { var mapReduceBenchmark = new MapReduceBenchmark(); mapReduceBenchmark.BenchmarkSetup(); return mapReduceBenchmark; }, benchmark => benchmark.Bench().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Memory"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 20000, 5000); benchmark.MemorySetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Memory.Throttled"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 200000, 15000); benchmark.MemoryThrottledSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Azure"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 20000, 5000); benchmark.AzureSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Azure.Throttled"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 200000, 15000); benchmark.AzureThrottledSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Azure.Overloaded"] = () => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 200000, 15000); benchmark.AzureSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["SequentialPing"] = () => { BenchmarkRunner.Run<PingBenchmark>(); }, ["ConcurrentPing"] = () => { { Console.WriteLine("## Client to Silo ##"); var test = new PingBenchmark(numSilos: 1, startClient: true); test.PingConcurrent().GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } GC.Collect(); { Console.WriteLine("## Client to 2 Silos ##"); var test = new PingBenchmark(numSilos: 2, startClient: true); test.PingConcurrent().GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } GC.Collect(); { Console.WriteLine("## Hosted Client ##"); var test = new PingBenchmark(numSilos: 1, startClient: false); test.PingConcurrentHostedClient().GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } GC.Collect(); { // All calls are cross-silo because the calling silo doesn't have any grain classes. Console.WriteLine("## Silo to Silo ##"); var test = new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true); test.PingConcurrentHostedClient(blocksPerWorker: 10).GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } }, ["ConcurrentPing_OneSilo"] = () => { new PingBenchmark(numSilos: 1, startClient: true).PingConcurrent().GetAwaiter().GetResult(); }, ["ConcurrentPing_TwoSilos"] = () => { new PingBenchmark(numSilos: 2, startClient: true).PingConcurrent().GetAwaiter().GetResult(); }, ["ConcurrentPing_HostedClient"] = () => { new PingBenchmark(numSilos: 1, startClient: false).PingConcurrentHostedClient().GetAwaiter().GetResult(); }, ["ConcurrentPing_HostedClient_Forever"] = () => { var benchmark = new PingBenchmark(numSilos: 1, startClient: false); Console.WriteLine("Press any key to begin."); Console.ReadKey(); Console.WriteLine("Press any key to end."); Console.WriteLine("## Hosted Client ##"); while (!Console.KeyAvailable) { benchmark.PingConcurrentHostedClient().GetAwaiter().GetResult(); } Console.WriteLine("Interrupted by user"); }, ["ConcurrentPing_SiloToSilo"] = () => { new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true).PingConcurrentHostedClient(blocksPerWorker: 10).GetAwaiter().GetResult(); }, ["ConcurrentPing_SiloToSilo_Forever"] = () => { Console.WriteLine("Press any key to begin."); Console.ReadKey(); Console.WriteLine("Press any key to end."); Console.WriteLine("## Silo to Silo ##"); while (!Console.KeyAvailable) { var test = new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true); Console.WriteLine("Starting"); test.PingConcurrentHostedClient(blocksPerWorker: 10).GetAwaiter().GetResult(); Console.WriteLine("Stopping"); test.Shutdown().GetAwaiter().GetResult(); } Console.WriteLine("Interrupted by user"); }, ["ConcurrentPing_SiloToSilo_Long"] = () => { new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true).PingConcurrentHostedClient(blocksPerWorker: 1000).GetAwaiter().GetResult(); }, ["ConcurrentPing_OneSilo_Forever"] = () => { new PingBenchmark(numSilos: 1, startClient: true).PingConcurrentForever().GetAwaiter().GetResult(); }, ["PingOnce"] = () => { new PingBenchmark().Ping().GetAwaiter().GetResult(); }, ["PingForever"] = () => { new PingBenchmark().PingForever().GetAwaiter().GetResult(); }, ["PingPongForever"] = () => { new PingBenchmark().PingPongForever().GetAwaiter().GetResult(); }, ["GrainStorage.Memory"] = () => { RunBenchmark( "Running grain storage benchmark against memory", () => { var benchmark = new GrainStorageBenchmark(10, 10000, TimeSpan.FromSeconds( 30 )); benchmark.MemorySetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["GrainStorage.AzureTable"] = () => { RunBenchmark( "Running grain storage benchmark against Azure Table", () => { var benchmark = new GrainStorageBenchmark(100, 10000, TimeSpan.FromSeconds( 30 )); benchmark.AzureTableSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["GrainStorage.AzureBlob"] = () => { RunBenchmark( "Running grain storage benchmark against Azure Blob", () => { var benchmark = new GrainStorageBenchmark(10, 10000, TimeSpan.FromSeconds( 30 )); benchmark.AzureBlobSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["GrainStorage.AdoNet"] = () => { RunBenchmark( "Running grain storage benchmark against AdoNet", () => { var benchmark = new GrainStorageBenchmark(100, 10000, TimeSpan.FromSeconds( 30 )); benchmark.AdoNetSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, }; // requires benchmark name or 'All' word as first parameter public static void Main(string[] args) { if (args.Length > 0 && args[0].Equals("all", StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine("Running full benchmarks suite"); _benchmarks.Select(pair => pair.Value).ToList().ForEach(action => action()); return; } if (args.Length == 0 || !_benchmarks.ContainsKey(args[0])) { Console.WriteLine("Please, select benchmark, list of available:"); _benchmarks .Select(pair => pair.Key) .ToList() .ForEach(Console.WriteLine); Console.WriteLine("All"); return; } _benchmarks[args[0]](); } private static void RunBenchmark<T>(string name, Func<T> init, Action<T> benchmarkAction, Action<T> tearDown) { Console.WriteLine(name); var bench = init(); var stopWatch = Stopwatch.StartNew(); benchmarkAction(bench); Console.WriteLine($"Elapsed milliseconds: {stopWatch.ElapsedMilliseconds}"); Console.WriteLine("Press any key to continue ..."); tearDown(bench); Console.ReadLine(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Examples.Datagrid { using System; using System.Collections.Generic; using Apache.Ignite.Core; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.ExamplesDll.Binary; /// <summary> /// This example demonstrates several put-get operations on Ignite cache /// with binary values. Note that binary object can be retrieved in /// fully-deserialized form or in binary object format using special /// cache projection. /// <para /> /// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build). /// Apache.Ignite.ExamplesDll.dll must appear in %IGNITE_HOME%/platforms/dotnet/examples/Apache.Ignite.ExamplesDll/bin/${Platform]/${Configuration} folder. /// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties -> /// Application -> Startup object); /// 3) Start example (F5 or Ctrl+F5). /// <para /> /// This example can be run with standalone Apache Ignite.NET node: /// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe: /// Apache.Ignite.exe -configFileName=platforms\dotnet\examples\apache.ignite.examples\app.config -assembly=[path_to_Apache.Ignite.ExamplesDll.dll] /// 2) Start example. /// </summary> public class PutGetExample { /// <summary>Cache name.</summary> private const string CacheName = "dotnet_cache_put_get"; /// <summary> /// Runs the example. /// </summary> [STAThread] public static void Main() { using (var ignite = Ignition.StartFromApplicationConfiguration()) { Console.WriteLine(); Console.WriteLine(">>> Cache put-get example started."); // Clean up caches on all nodes before run. ignite.GetOrCreateCache<object, object>(CacheName).Clear(); PutGet(ignite); PutGetBinary(ignite); PutAllGetAll(ignite); PutAllGetAllBinary(ignite); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(">>> Example finished, press any key to exit ..."); Console.ReadKey(); } /// <summary> /// Execute individual Put and Get. /// </summary> /// <param name="ignite">Ignite instance.</param> private static void PutGet(IIgnite ignite) { var cache = ignite.GetCache<int, Organization>(CacheName); // Create new Organization to store in cache. Organization org = new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now ); // Put created data entry to cache. cache.Put(1, org); // Get recently created employee as a strongly-typed fully de-serialized instance. Organization orgFromCache = cache.Get(1); Console.WriteLine(); Console.WriteLine(">>> Retrieved organization instance from cache: " + orgFromCache); } /// <summary> /// Execute individual Put and Get, getting value in binary format, without de-serializing it. /// </summary> /// <param name="ignite">Ignite instance.</param> private static void PutGetBinary(IIgnite ignite) { var cache = ignite.GetCache<int, Organization>(CacheName); // Create new Organization to store in cache. Organization org = new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now ); // Put created data entry to cache. cache.Put(1, org); // Create projection that will get values as binary objects. var binaryCache = cache.WithKeepBinary<int, IBinaryObject>(); // Get recently created organization as a binary object. var binaryOrg = binaryCache.Get(1); // Get organization's name from binary object (note that object doesn't need to be fully deserialized). string name = binaryOrg.GetField<string>("name"); Console.WriteLine(); Console.WriteLine(">>> Retrieved organization name from binary object: " + name); } /// <summary> /// Execute bulk Put and Get operations. /// </summary> /// <param name="ignite">Ignite instance.</param> private static void PutAllGetAll(IIgnite ignite) { var cache = ignite.GetCache<int, Organization>(CacheName); // Create new Organizations to store in cache. Organization org1 = new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now ); Organization org2 = new Organization( "Red Cross", new Address("184 Fidler Drive, San Antonio, TX", 78205), OrganizationType.NonProfit, DateTime.Now ); var map = new Dictionary<int, Organization> { { 1, org1 }, { 2, org2 } }; // Put created data entries to cache. cache.PutAll(map); // Get recently created organizations as a strongly-typed fully de-serialized instances. ICollection<ICacheEntry<int, Organization>> mapFromCache = cache.GetAll(new List<int> { 1, 2 }); Console.WriteLine(); Console.WriteLine(">>> Retrieved organization instances from cache:"); foreach (ICacheEntry<int, Organization> org in mapFromCache) Console.WriteLine(">>> " + org.Value); } /// <summary> /// Execute bulk Put and Get operations getting values in binary format, without de-serializing it. /// </summary> /// <param name="ignite">Ignite instance.</param> private static void PutAllGetAllBinary(IIgnite ignite) { var cache = ignite.GetCache<int, Organization>(CacheName); // Create new Organizations to store in cache. Organization org1 = new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now ); Organization org2 = new Organization( "Red Cross", new Address("184 Fidler Drive, San Antonio, TX", 78205), OrganizationType.NonProfit, DateTime.Now ); var map = new Dictionary<int, Organization> { { 1, org1 }, { 2, org2 } }; // Put created data entries to cache. cache.PutAll(map); // Create projection that will get values as binary objects. var binaryCache = cache.WithKeepBinary<int, IBinaryObject>(); // Get recently created organizations as binary objects. ICollection<ICacheEntry<int, IBinaryObject>> binaryMap = binaryCache.GetAll(new List<int> { 1, 2 }); Console.WriteLine(); Console.WriteLine(">>> Retrieved organization names from binary objects:"); foreach (var pair in binaryMap) Console.WriteLine(">>> " + pair.Value.GetField<string>("name")); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.Linq; using Aurora.Framework; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Interfaces { public interface IAvatarService { /// <summary> /// The local service (if possible) /// </summary> IAvatarService InnerService { get; } /// <summary> /// Called by the login service /// </summary> /// <param name = "userID"></param> /// <returns></returns> AvatarAppearance GetAppearance(UUID userID); /// <summary> /// Called by everyone who can change the avatar data (so, regions) /// </summary> /// <param name = "userID"></param> /// <param name = "appearance"></param> /// <returns></returns> bool SetAppearance(UUID userID, AvatarAppearance appearance); /// <summary> /// Called by the login service /// </summary> /// <param name = "userID"></param> /// <returns></returns> AvatarData GetAvatar(UUID userID); /// <summary> /// Called by everyone who can change the avatar data (so, regions) /// </summary> /// <param name = "userID"></param> /// <param name = "avatar"></param> /// <returns></returns> bool SetAvatar(UUID userID, AvatarData avatar); /// <summary> /// Not sure if it's needed /// </summary> /// <param name = "userID"></param> /// <returns></returns> bool ResetAvatar(UUID userID); /// <summary> /// Cache the given avatarWearable for the client /// </summary> /// <param name = "principalID"></param> /// <param name = "cachedWearable"></param> void CacheWearableData(UUID principalID, AvatarWearable cachedWearable); } /// <summary> /// Each region/client that uses avatars will have a data structure /// of this type representing the avatars. /// </summary> public class AvatarData : IDataTransferable { // This pretty much determines which name/value pairs will be // present below. The name/value pair describe a part of // the avatar. For SL avatars, these would be "shape", "texture1", // etc. For other avatars, they might be "mesh", "skin", etc. // The value portion is a URL that is expected to resolve to an // asset of the type required by the handler for that field. // It is required that regions can access these URLs. Allowing // direct access by a viewer is not required, and, if provided, // may be read-only. A "naked" UUID can be used to refer to an // asset int he current region's asset service, which is not // portable, but allows legacy appearance to continue to // function. Closed, LL-based grids will never need URLs here. public int AvatarType; public Dictionary<string, string> Data; public AvatarData() { } public AvatarData(Dictionary<string, object> kvp) { FromKVP(kvp); } public AvatarData(AvatarAppearance appearance) { AvatarType = 1; // SL avatars Data = new Dictionary<string, string>(); Data["Serial"] = appearance.Serial.ToString(); // Wearables Data["AvatarHeight"] = appearance.AvatarHeight.ToString(); if(appearance.Texture != null) Data["Textures"] = OSDParser.SerializeJsonString(appearance.Texture.GetOSD()); for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) { for (int j = 0; j < appearance.Wearables[i].Count; j++) { string fieldName = String.Format("Wearable {0}:{1}", i, j); Data[fieldName] = String.Format("{0}:{1}", appearance.Wearables[i][j].ItemID.ToString(), appearance.Wearables[i][j].AssetID.ToString()); } } // Visual Params string[] vps = new string[AvatarAppearance.VISUALPARAM_COUNT]; byte[] binary = appearance.VisualParams; for (int i = 0; i < AvatarAppearance.VISUALPARAM_COUNT; i++) { vps[i] = binary[i].ToString(); } Data["VisualParams"] = String.Join(",", vps); // Attachments var attachments = appearance.GetAttachmentsDictionary(); foreach (KeyValuePair<int, List<AvatarAttachment>> kvp in attachments) { for (int i = 0; i < kvp.Value.Count; i++) { var attach = kvp.Value[i]; Data["_ap_" + attach.AttachPoint + "_" + i] = attach.ItemID.ToString(); Data["_apa_" + attach.AttachPoint + "_" + i] = attach.AssetID.ToString(); } } } /// <summary> /// </summary> /// <returns></returns> public override Dictionary<string, object> ToKVP() { Dictionary<string, object> result = new Dictionary<string, object>(); result["AvatarType"] = AvatarType.ToString(); #if (!ISWIN) foreach (KeyValuePair<string, string> _kvp in Data) { if (_kvp.Value != null) { //Remove spaces result[_kvp.Key.Replace(" ", "").Replace(":", "")] = _kvp.Value; } } #else foreach (KeyValuePair<string, string> _kvp in Data.Where(_kvp => _kvp.Value != null)) { //Remove spaces result[_kvp.Key.Replace(" ", "").Replace(":", "")] = _kvp.Value; } #endif return result; } public override OSDMap ToOSD() { OSDMap result = new OSDMap(); result["AvatarType"] = AvatarType; foreach (KeyValuePair<string, string> _kvp in Data) { if (_kvp.Value != null) { //Remove spaces result[_kvp.Key.Replace(" ", "").Replace(":", "")] = _kvp.Value; } } return result; } public override void FromKVP(Dictionary<string, object> kvp) { Data = new Dictionary<string, string>(); if (kvp.ContainsKey("AvatarType")) Int32.TryParse(kvp["AvatarType"].ToString(), out AvatarType); foreach (KeyValuePair<string, object> _kvp in kvp) { if (_kvp.Value != null) { string key = _kvp.Key; if (_kvp.Key.StartsWith("Wearable")) { key = _kvp.Key.Replace("Wearable", ""); key = key.Insert(key.Length == 2 ? 1 : 2, ":"); key = "Wearable " + key; //Add the space back } Data[key] = _kvp.Value.ToString(); } } } public override void FromOSD(OSDMap map) { Data = new Dictionary<string, string>(); if (map.ContainsKey("AvatarType")) AvatarType = map["AvatarType"]; foreach (KeyValuePair<string, OSD> _kvp in map) { if (_kvp.Value != null) { string key = _kvp.Key; if (_kvp.Key.StartsWith("Wearable")) { key = _kvp.Key.Replace("Wearable", ""); key = key.Insert(key.Length == 2 ? 1 : 2, ":"); key = "Wearable " + key; //Add the space back } Data[key] = _kvp.Value.ToString(); } } } public AvatarAppearance ToAvatarAppearance(UUID owner) { AvatarAppearance appearance = new AvatarAppearance(owner); if (Data.Count == 0) return appearance; appearance.ClearWearables(); try { if (Data.ContainsKey("Serial")) appearance.Serial = Int32.Parse(Data["Serial"]); if (Data.ContainsKey("AvatarHeight")) appearance.AvatarHeight = float.Parse(Data["AvatarHeight"]); // Legacy Wearables if (Data.ContainsKey("BodyItem")) appearance.Wearables[AvatarWearable.BODY].Wear( UUID.Parse(Data["BodyItem"]), UUID.Parse(Data["BodyAsset"])); if (Data.ContainsKey("SkinItem")) appearance.Wearables[AvatarWearable.SKIN].Wear( UUID.Parse(Data["SkinItem"]), UUID.Parse(Data["SkinAsset"])); if (Data.ContainsKey("HairItem")) appearance.Wearables[AvatarWearable.HAIR].Wear( UUID.Parse(Data["HairItem"]), UUID.Parse(Data["HairAsset"])); if (Data.ContainsKey("EyesItem")) appearance.Wearables[AvatarWearable.EYES].Wear( UUID.Parse(Data["EyesItem"]), UUID.Parse(Data["EyesAsset"])); if (Data.ContainsKey("ShirtItem")) appearance.Wearables[AvatarWearable.SHIRT].Wear( UUID.Parse(Data["ShirtItem"]), UUID.Parse(Data["ShirtAsset"])); if (Data.ContainsKey("PantsItem")) appearance.Wearables[AvatarWearable.PANTS].Wear( UUID.Parse(Data["PantsItem"]), UUID.Parse(Data["PantsAsset"])); if (Data.ContainsKey("ShoesItem")) appearance.Wearables[AvatarWearable.SHOES].Wear( UUID.Parse(Data["ShoesItem"]), UUID.Parse(Data["ShoesAsset"])); if (Data.ContainsKey("SocksItem")) appearance.Wearables[AvatarWearable.SOCKS].Wear( UUID.Parse(Data["SocksItem"]), UUID.Parse(Data["SocksAsset"])); if (Data.ContainsKey("JacketItem")) appearance.Wearables[AvatarWearable.JACKET].Wear( UUID.Parse(Data["JacketItem"]), UUID.Parse(Data["JacketAsset"])); if (Data.ContainsKey("GlovesItem")) appearance.Wearables[AvatarWearable.GLOVES].Wear( UUID.Parse(Data["GlovesItem"]), UUID.Parse(Data["GlovesAsset"])); if (Data.ContainsKey("UnderShirtItem")) appearance.Wearables[AvatarWearable.UNDERSHIRT].Wear( UUID.Parse(Data["UnderShirtItem"]), UUID.Parse(Data["UnderShirtAsset"])); if (Data.ContainsKey("UnderPantsItem")) appearance.Wearables[AvatarWearable.UNDERPANTS].Wear( UUID.Parse(Data["UnderPantsItem"]), UUID.Parse(Data["UnderPantsAsset"])); if (Data.ContainsKey("SkirtItem")) appearance.Wearables[AvatarWearable.SKIRT].Wear( UUID.Parse(Data["SkirtItem"]), UUID.Parse(Data["SkirtAsset"])); if (Data.ContainsKey("VisualParams")) { string[] vps = Data["VisualParams"].Split(new[] {','}); byte[] binary = new byte[AvatarAppearance.VISUALPARAM_COUNT]; for (int i = 0; i < vps.Length && i < binary.Length; i++) binary[i] = (byte) Convert.ToInt32(vps[i]); appearance.VisualParams = binary; } if (Data.ContainsKey("Textures")) { string t = Data["Textures"]; OSD tex = OSDParser.DeserializeJson(t); appearance.Texture = Primitive.TextureEntry.FromOSD(tex); } // New style wearables foreach (KeyValuePair<string, string> _kvp in Data) { if (_kvp.Key.StartsWith("Wearable ")) { string wearIndex = _kvp.Key.Substring(9); string[] wearIndices = wearIndex.Split(new[] {':'}); if (wearIndices.Length == 2 && wearIndices[1].Length == 1) { int index = Convert.ToInt32(wearIndices[0]); string[] ids = _kvp.Value.Split(new[] { ':' }); UUID itemID = new UUID(ids[0]); UUID assetID = new UUID(ids[1]); appearance.Wearables[index].Add(itemID, assetID); } else { //For when we get stuff like 0020_0_x003A_0 var index2 = wearIndices[1].Split('_'); int index = Convert.ToInt32(index2[1]); string[] ids = _kvp.Value.Split(new[] { ':' }); UUID itemID = new UUID(ids[0]); UUID assetID = new UUID(ids[1]); appearance.Wearables[index].Add(itemID, assetID); } } } // Attachments Dictionary<string, string> attchs = new Dictionary<string, string>(); Dictionary<string, string> attchsAssets = new Dictionary<string, string>(); #if (!ISWIN) foreach (KeyValuePair<string, string> _kvp in Data) { if (_kvp.Key.StartsWith("_ap_")) attchs[_kvp.Key] = _kvp.Value; if (_kvp.Key.StartsWith("_apa_")) attchsAssets[_kvp.Key] = _kvp.Value; } #else foreach (KeyValuePair<string, string> _kvp in Data.Where(_kvp => _kvp.Key.StartsWith("_ap_"))) attchs[_kvp.Key] = _kvp.Value; #endif foreach (KeyValuePair<string, string> _kvp in attchs) { string pointStr = _kvp.Key.Substring(4,1); int point = 0; if (!Int32.TryParse(pointStr, out point)) continue; UUID uuid = UUID.Zero; UUID.TryParse(_kvp.Value, out uuid); UUID assetuuid = UUID.Zero; if(attchsAssets.ContainsKey(_kvp.Key)) UUID.TryParse(attchsAssets[_kvp.Key], out uuid); appearance.SetAttachment(point, uuid, assetuuid); } if (appearance.Wearables[AvatarWearable.BODY].Count == 0) appearance.Wearables[AvatarWearable.BODY].Wear( AvatarWearable.DefaultWearables[ AvatarWearable.BODY][0]); if (appearance.Wearables[AvatarWearable.SKIN].Count == 0) appearance.Wearables[AvatarWearable.SKIN].Wear( AvatarWearable.DefaultWearables[ AvatarWearable.SKIN][0]); if (appearance.Wearables[AvatarWearable.HAIR].Count == 0) appearance.Wearables[AvatarWearable.HAIR].Wear( AvatarWearable.DefaultWearables[ AvatarWearable.HAIR][0]); if (appearance.Wearables[AvatarWearable.EYES].Count == 0) appearance.Wearables[AvatarWearable.EYES].Wear( AvatarWearable.DefaultWearables[ AvatarWearable.EYES][0]); } catch { // We really should report something here, returning null // will at least break the wrapper return null; } return appearance; } } public interface IAvatarData : IAuroraDataPlugin { AvatarData Get(string field, string val); bool Store(UUID PrincipalID, AvatarData data); bool Delete(string field, string val); } }
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using BinaryBitmap = com.google.zxing.BinaryBitmap; using ReaderException = com.google.zxing.ReaderException; using ResultPoint = com.google.zxing.ResultPoint; using BitMatrix = com.google.zxing.common.BitMatrix; using DetectorResult = com.google.zxing.common.DetectorResult; using GridSampler = com.google.zxing.common.GridSampler; using System.Collections.Generic; namespace com.google.zxing.pdf417.detector { /// <summary> <p>Encapsulates logic that can detect a PDF417 Code in an image, even if the /// PDF417 Code is rotated or skewed, or partially obscured.</p> /// /// </summary> /// <author> SITA Lab (kevin.osullivan@sita.aero) /// </author> /// <author> dswitkin@google.com (Daniel Switkin) /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> public sealed class Detector { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" private static int MAX_AVG_VARIANCE = (int) SupportClass.Identity(((1 << 8) * 0.42f)); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" private static int MAX_INDIVIDUAL_VARIANCE = (int) SupportClass.Identity(((1 << 8) * 0.8f)); private const int SKEW_THRESHOLD = 2; // B S B S B S B S Bar/Space pattern // 11111111 0 1 0 1 0 1 000 //UPGRADE_NOTE: Final was removed from the declaration of 'START_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly int[] START_PATTERN = new int[]{8, 1, 1, 1, 1, 1, 1, 3}; // 11111111 0 1 0 1 0 1 000 //UPGRADE_NOTE: Final was removed from the declaration of 'START_PATTERN_REVERSE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly int[] START_PATTERN_REVERSE = new int[]{3, 1, 1, 1, 1, 1, 1, 8}; // 1111111 0 1 000 1 0 1 00 1 //UPGRADE_NOTE: Final was removed from the declaration of 'STOP_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly int[] STOP_PATTERN = new int[]{7, 1, 1, 3, 1, 1, 1, 2, 1}; // B S B S B S B S B Bar/Space pattern // 1111111 0 1 000 1 0 1 00 1 //UPGRADE_NOTE: Final was removed from the declaration of 'STOP_PATTERN_REVERSE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly int[] STOP_PATTERN_REVERSE = new int[]{1, 2, 1, 1, 1, 3, 1, 1, 7}; //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private BinaryBitmap image; public Detector(BinaryBitmap image) { this.image = image; } /// <summary> <p>Detects a PDF417 Code in an image, simply.</p> /// /// </summary> /// <returns> {@link DetectorResult} encapsulating results of detecting a PDF417 Code /// </returns> /// <throws> ReaderException if no QR Code can be found </throws> public DetectorResult detect() { return detect(null); } /// <summary> <p>Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.</p> /// /// </summary> /// <param name="hints">optional hints to detector /// </param> /// <returns> {@link DetectorResult} encapsulating results of detecting a PDF417 Code /// </returns> /// <throws> ReaderException if no PDF417 Code can be found </throws> public DetectorResult detect(Dictionary<object, object> hints) { // Fetch the 1 bit matrix once up front. BitMatrix matrix = image.BlackMatrix; // Try to find the vertices assuming the image is upright. ResultPoint[] vertices = findVertices(matrix); if (vertices == null) { // Maybe the image is rotated 180 degrees? vertices = findVertices180(matrix); if (vertices != null) { correctCodeWordVertices(vertices, true); } } else { correctCodeWordVertices(vertices, false); } if (vertices != null) { float moduleWidth = computeModuleWidth(vertices); if (moduleWidth < 1.0f) { throw ReaderException.Instance; } int dimension = computeDimension(vertices[4], vertices[6], vertices[5], vertices[7], moduleWidth); if (dimension < 1) { throw ReaderException.Instance; } // Deskew and sample image. BitMatrix bits = sampleGrid(matrix, vertices[4], vertices[5], vertices[6], vertices[7], dimension); return new DetectorResult(bits, new ResultPoint[]{vertices[4], vertices[5], vertices[6], vertices[7]}); } else { throw ReaderException.Instance; } } /// <summary> Locate the vertices and the codewords area of a black blob using the Start /// and Stop patterns as locators. Assumes that the barcode begins in the left half /// of the image, and ends in the right half. /// TODO: Fix this assumption, allowing the barcode to be anywhere in the image. /// TODO: Scanning every row is very expensive. We should only do this for TRY_HARDER. /// /// </summary> /// <param name="matrix">the scanned barcode image. /// </param> /// <returns> an array containing the vertices: /// vertices[0] x, y top left barcode /// vertices[1] x, y bottom left barcode /// vertices[2] x, y top right barcode /// vertices[3] x, y bottom right barcode /// vertices[4] x, y top left codeword area /// vertices[5] x, y bottom left codeword area /// vertices[6] x, y top right codeword area /// vertices[7] x, y bottom right codeword area /// </returns> private static ResultPoint[] findVertices(BitMatrix matrix) { int height = matrix.Height; int width = matrix.Width; int halfWidth = width >> 1; ResultPoint[] result = new ResultPoint[8]; bool found = false; // Top Left for (int i = 0; i < height; i++) { int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, START_PATTERN); if (loc != null) { result[0] = new ResultPoint(loc[0], i); result[4] = new ResultPoint(loc[1], i); found = true; break; } } // Bottom left if (found) { // Found the Top Left vertex found = false; for (int i = height - 1; i > 0; i--) { int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, START_PATTERN); if (loc != null) { result[1] = new ResultPoint(loc[0], i); result[5] = new ResultPoint(loc[1], i); found = true; break; } } } // Top right if (found) { // Found the Bottom Left vertex found = false; for (int i = 0; i < height; i++) { int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, false, STOP_PATTERN); if (loc != null) { result[2] = new ResultPoint(loc[1], i); result[6] = new ResultPoint(loc[0], i); found = true; break; } } } // Bottom right if (found) { // Found the Top right vertex found = false; for (int i = height - 1; i > 0; i--) { int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, false, STOP_PATTERN); if (loc != null) { result[3] = new ResultPoint(loc[1], i); result[7] = new ResultPoint(loc[0], i); found = true; break; } } } return found?result:null; } /// <summary> Locate the vertices and the codewords area of a black blob using the Start /// and Stop patterns as locators. This assumes that the image is rotated 180 /// degrees and if it locates the start and stop patterns at it will re-map /// the vertices for a 0 degree rotation. /// TODO: Change assumption about barcode location. /// TODO: Scanning every row is very expensive. We should only do this for TRY_HARDER. /// /// </summary> /// <param name="matrix">the scanned barcode image. /// </param> /// <returns> an array containing the vertices: /// vertices[0] x, y top left barcode /// vertices[1] x, y bottom left barcode /// vertices[2] x, y top right barcode /// vertices[3] x, y bottom right barcode /// vertices[4] x, y top left codeword area /// vertices[5] x, y bottom left codeword area /// vertices[6] x, y top right codeword area /// vertices[7] x, y bottom right codeword area /// </returns> private static ResultPoint[] findVertices180(BitMatrix matrix) { int height = matrix.Height; int width = matrix.Width; int halfWidth = width >> 1; ResultPoint[] result = new ResultPoint[8]; bool found = false; // Top Left for (int i = height - 1; i > 0; i--) { int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, true, START_PATTERN_REVERSE); if (loc != null) { result[0] = new ResultPoint(loc[1], i); result[4] = new ResultPoint(loc[0], i); found = true; break; } } // Bottom Left if (found) { // Found the Top Left vertex found = false; for (int i = 0; i < height; i++) { int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, true, START_PATTERN_REVERSE); if (loc != null) { result[1] = new ResultPoint(loc[1], i); result[5] = new ResultPoint(loc[0], i); found = true; break; } } } // Top Right if (found) { // Found the Bottom Left vertex found = false; for (int i = height - 1; i > 0; i--) { int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, STOP_PATTERN_REVERSE); if (loc != null) { result[2] = new ResultPoint(loc[0], i); result[6] = new ResultPoint(loc[1], i); found = true; break; } } } // Bottom Right if (found) { // Found the Top Right vertex found = false; for (int i = 0; i < height; i++) { int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, STOP_PATTERN_REVERSE); if (loc != null) { result[3] = new ResultPoint(loc[0], i); result[7] = new ResultPoint(loc[1], i); found = true; break; } } } return found?result:null; } /// <summary> Because we scan horizontally to detect the start and stop patterns, the vertical component of /// the codeword coordinates will be slightly wrong if there is any skew or rotation in the image. /// This method moves those points back onto the edges of the theoretically perfect bounding /// quadrilateral if needed. /// /// </summary> /// <param name="vertices">The eight vertices located by findVertices(). /// </param> private static void correctCodeWordVertices(ResultPoint[] vertices, bool upsideDown) { float skew = vertices[4].Y - vertices[6].Y; if (upsideDown) { skew = - skew; } if (skew > SKEW_THRESHOLD) { // Fix v4 float length = vertices[4].X - vertices[0].X; float deltax = vertices[6].X - vertices[0].X; float deltay = vertices[6].Y - vertices[0].Y; float correction = length * deltay / deltax; vertices[4] = new ResultPoint(vertices[4].X, vertices[4].Y + correction); } else if (- skew > SKEW_THRESHOLD) { // Fix v6 float length = vertices[2].X - vertices[6].X; float deltax = vertices[2].X - vertices[4].X; float deltay = vertices[2].Y - vertices[4].Y; float correction = length * deltay / deltax; vertices[6] = new ResultPoint(vertices[6].X, vertices[6].Y - correction); } skew = vertices[7].Y - vertices[5].Y; if (upsideDown) { skew = - skew; } if (skew > SKEW_THRESHOLD) { // Fix v5 float length = vertices[5].X - vertices[1].X; float deltax = vertices[7].X - vertices[1].X; float deltay = vertices[7].Y - vertices[1].Y; float correction = length * deltay / deltax; vertices[5] = new ResultPoint(vertices[5].X, vertices[5].Y + correction); } else if (- skew > SKEW_THRESHOLD) { // Fix v7 float length = vertices[3].X - vertices[7].X; float deltax = vertices[3].X - vertices[5].X; float deltay = vertices[3].Y - vertices[5].Y; float correction = length * deltay / deltax; vertices[7] = new ResultPoint(vertices[7].X, vertices[7].Y - correction); } } /// <summary> <p>Estimates module size (pixels in a module) based on the Start and End /// finder patterns.</p> /// /// </summary> /// <param name="vertices">an array of vertices: /// vertices[0] x, y top left barcode /// vertices[1] x, y bottom left barcode /// vertices[2] x, y top right barcode /// vertices[3] x, y bottom right barcode /// vertices[4] x, y top left codeword area /// vertices[5] x, y bottom left codeword area /// vertices[6] x, y top right codeword area /// vertices[7] x, y bottom right codeword area /// </param> /// <returns> the module size. /// </returns> private static float computeModuleWidth(ResultPoint[] vertices) { float pixels1 = ResultPoint.distance(vertices[0], vertices[4]); float pixels2 = ResultPoint.distance(vertices[1], vertices[5]); float moduleWidth1 = (pixels1 + pixels2) / (17 * 2.0f); float pixels3 = ResultPoint.distance(vertices[6], vertices[2]); float pixels4 = ResultPoint.distance(vertices[7], vertices[3]); float moduleWidth2 = (pixels3 + pixels4) / (18 * 2.0f); return (moduleWidth1 + moduleWidth2) / 2.0f; } /// <summary> Computes the dimension (number of modules in a row) of the PDF417 Code /// based on vertices of the codeword area and estimated module size. /// /// </summary> /// <param name="topLeft"> of codeword area /// </param> /// <param name="topRight"> of codeword area /// </param> /// <param name="bottomLeft"> of codeword area /// </param> /// <param name="bottomRight">of codeword are /// </param> /// <param name="moduleWidth">estimated module size /// </param> /// <returns> the number of modules in a row. /// </returns> private static int computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, ResultPoint bottomRight, float moduleWidth) { int topRowDimension = round(ResultPoint.distance(topLeft, topRight) / moduleWidth); int bottomRowDimension = round(ResultPoint.distance(bottomLeft, bottomRight) / moduleWidth); return ((((topRowDimension + bottomRowDimension) >> 1) + 8) / 17) * 17; /* * int topRowDimension = round(ResultPoint.distance(topLeft, * topRight)); //moduleWidth); int bottomRowDimension = * round(ResultPoint.distance(bottomLeft, bottomRight)); // * moduleWidth); int dimension = ((topRowDimension + bottomRowDimension) * >> 1); // Round up to nearest 17 modules i.e. there are 17 modules per * codeword //int dimension = ((((topRowDimension + bottomRowDimension) >> * 1) + 8) / 17) * 17; return dimension; */ } private static BitMatrix sampleGrid(BitMatrix matrix, ResultPoint topLeft, ResultPoint bottomLeft, ResultPoint topRight, ResultPoint bottomRight, int dimension) { // Note that unlike the QR Code sampler, we didn't find the center of modules, but the // very corners. So there is no 0.5f here; 0.0f is right. GridSampler sampler = GridSampler.Instance; return sampler.sampleGrid(matrix, dimension, 0.0f, 0.0f, dimension, 0.0f, dimension, dimension, 0.0f, dimension, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRight.X, bottomRight.Y, bottomLeft.X, bottomLeft.Y); // p4FromY } /// <summary> Ends up being a bit faster than Math.round(). This merely rounds its /// argument to the nearest int, where x.5 rounds up. /// </summary> private static int round(float d) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (int) (d + 0.5f); } /// <param name="matrix">row of black/white values to search /// </param> /// <param name="column">x position to start search /// </param> /// <param name="row">y position to start search /// </param> /// <param name="width">the number of pixels to search on this row /// </param> /// <param name="pattern">pattern of counts of number of black and white pixels that are /// being searched for as a pattern /// </param> /// <returns> start/end horizontal offset of guard pattern, as an array of two ints. /// </returns> private static int[] findGuardPattern(BitMatrix matrix, int column, int row, int width, bool whiteFirst, int[] pattern) { int patternLength = pattern.Length; // TODO: Find a way to cache this array, as this method is called hundreds of times // per image, and we want to allocate as seldom as possible. int[] counters = new int[patternLength]; bool isWhite = whiteFirst; int counterPosition = 0; int patternStart = column; for (int x = column; x < column + width; x++) { bool pixel = matrix.get_Renamed(x, row); if (pixel ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { return new int[]{patternStart, x}; } patternStart += counters[0] + counters[1]; for (int y = 2; y < patternLength; y++) { counters[y - 2] = counters[y]; } counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } return null; } /// <summary> Determines how closely a set of observed counts of runs of black/white /// values matches a given target pattern. This is reported as the ratio of /// the total variance from the expected pattern proportions across all /// pattern elements, to the length of the pattern. /// /// </summary> /// <param name="counters">observed counters /// </param> /// <param name="pattern">expected pattern /// </param> /// <param name="maxIndividualVariance">The most any counter can differ before we give up /// </param> /// <returns> ratio of total variance between counters and pattern compared to /// total pattern size, where the ratio has been multiplied by 256. /// So, 0 means no variance (perfect match); 256 means the total /// variance between counters and patterns equals the pattern length, /// higher values mean even more variance /// </returns> private static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) { int numCounters = counters.Length; int total = 0; int patternLength = 0; for (int i = 0; i < numCounters; i++) { total += counters[i]; patternLength += pattern[i]; } if (total < patternLength) { // If we don't even have one pixel per unit of bar width, assume this // is too small to reliably match, so fail: return System.Int32.MaxValue; } // We're going to fake floating-point math in integers. We just need to use more bits. // Scale up patternLength so that intermediate values below like scaledCounter will have // more "significant digits". int unitBarWidth = (total << 8) / patternLength; maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> 8; int totalVariance = 0; for (int x = 0; x < numCounters; x++) { int counter = counters[x] << 8; int scaledPattern = pattern[x] * unitBarWidth; int variance = counter > scaledPattern?counter - scaledPattern:scaledPattern - counter; if (variance > maxIndividualVariance) { return System.Int32.MaxValue; } totalVariance += variance; } return totalVariance / total; } } }
// 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 AndUInt16() { var test = new SimpleBinaryOpTest__AndUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt16> _fld1; public Vector128<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndUInt16 testClass) { var result = Sse2.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndUInt16 testClass) { fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = Sse2.And( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public SimpleBinaryOpTest__AndUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.And( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.And( Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.And( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt16>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt16>* pClsVar2 = &_clsVar2) { var result = Sse2.And( Sse2.LoadVector128((UInt16*)(pClsVar1)), Sse2.LoadVector128((UInt16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndUInt16(); var result = Sse2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndUInt16(); fixed (Vector128<UInt16>* pFld1 = &test._fld1) fixed (Vector128<UInt16>* pFld2 = &test._fld2) { var result = Sse2.And( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = Sse2.And( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.And( Sse2.LoadVector128((UInt16*)(&test._fld1)), Sse2.LoadVector128((UInt16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((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) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.And)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Cassandra.Data.Linq; using Cassandra.IntegrationTests.SimulacronAPI; using Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then; using Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.When; using Cassandra.Mapping; using NUnit.Framework; #pragma warning disable 618 #pragma warning disable 612 namespace Cassandra.IntegrationTests.Linq.LinqMethods { public class Counter : SimulacronTest { private void PrimeLinqCounterQuery(CounterEntityWithLinqAttributes counter) { TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT \"Counter\", \"KeyPart1\", \"KeyPart2\" " + "FROM \"CounterEntityWithLinqAttributes\" " + "WHERE \"KeyPart1\" = ? AND \"KeyPart2\" = ?", when => counter.WithParams(when, "KeyPart1", "KeyPart2")) .ThenRowsSuccess(counter.CreateRowsResult())); } private RowsResult AddRows(IEnumerable<CounterEntityWithLinqAttributes> counters) { return counters.Aggregate(CounterEntityWithLinqAttributes.GetEmptyRowsResult(), (current, c) => c.AddRow(current)); } private void PrimeLinqCounterRangeQuery( IEnumerable<CounterEntityWithLinqAttributes> counters, string tableName = "CounterEntityWithLinqAttributes", bool caseSensitive = true) { var cql = caseSensitive ? $"SELECT \"Counter\", \"KeyPart1\", \"KeyPart2\" FROM \"{tableName}\"" : $"SELECT Counter, KeyPart1, KeyPart2 FROM {tableName}"; TestCluster.PrimeDelete(); TestCluster.PrimeFluent(b => b.WhenQuery(cql).ThenRowsSuccess(AddRows(counters))); } [Test] public void LinqAttributes_Counter_SelectRange() { //var mapping = new Map<PocoWithCounter>(); var mappingConfig = new MappingConfiguration(); mappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(CounterEntityWithLinqAttributes), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(CounterEntityWithLinqAttributes))); var table = new Table<CounterEntityWithLinqAttributes>(Session, mappingConfig); table.Create(); var expectedCounters = new List<CounterEntityWithLinqAttributes>(); for (var i = 0; i < 10; i++) { expectedCounters.Add( new CounterEntityWithLinqAttributes { KeyPart1 = Guid.NewGuid(), KeyPart2 = Guid.NewGuid().GetHashCode(), Counter = Guid.NewGuid().GetHashCode() }); } PrimeLinqCounterRangeQuery(expectedCounters); var countersQueried = table.Select(m => m).Execute().ToList(); Assert.AreEqual(10, countersQueried.Count); foreach (var expectedCounter in expectedCounters) { var actualCounter = countersQueried.Single(c => c.KeyPart1 == expectedCounter.KeyPart1); Assert.AreEqual(expectedCounter.KeyPart2, actualCounter.KeyPart2); Assert.AreEqual(expectedCounter.Counter, actualCounter.Counter); } } /// <summary> /// Validate expected error message when attempting to insert a row that contains a counter /// </summary> [Test] public void LinqAttributes_Counter_AttemptInsert() { // Create config that uses linq based attributes var mappingConfig = new MappingConfiguration(); mappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(CounterEntityWithLinqAttributes), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(CounterEntityWithLinqAttributes))); var table = new Table<CounterEntityWithLinqAttributes>(Session, mappingConfig); CounterEntityWithLinqAttributes pocoAndLinqAttributesLinqPocos = new CounterEntityWithLinqAttributes() { KeyPart1 = Guid.NewGuid(), KeyPart2 = (decimal)123, }; var expectedErrMsg = "INSERT statement(s)? are not allowed on counter tables, use UPDATE instead"; TestCluster.PrimeFluent( b => b.WhenQuery( "INSERT INTO \"CounterEntityWithLinqAttributes\" (\"Counter\", \"KeyPart1\", \"KeyPart2\") VALUES (?, ?, ?)", when => pocoAndLinqAttributesLinqPocos.WithParams(when)) .ThenServerError( ServerError.Invalid, expectedErrMsg)); var e = Assert.Throws<InvalidQueryException>(() => Session.Execute(table.Insert(pocoAndLinqAttributesLinqPocos))); Assert.AreEqual(expectedErrMsg, e.Message); } [TestCase(-21)] [TestCase(-13)] [TestCase(-8)] [TestCase(-5)] [TestCase(-3)] [TestCase(-2)] [TestCase(-1)] [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(5)] [TestCase(8)] [TestCase(13)] [TestCase(21)] public void LinqAttributes_Counter_Increments(int increment) { // Create config that uses linq based attributes var mappingConfig = new MappingConfiguration(); var counterTable = new Table<CounterEntityWithLinqAttributes>(Session, mappingConfig); var counter = new CounterEntityWithLinqAttributes { KeyPart1 = Guid.NewGuid(), KeyPart2 = 1 }; var updateCounterCql = "UPDATE \"CounterEntityWithLinqAttributes\" " + "SET \"Counter\" = \"Counter\" + ? " + "WHERE \"KeyPart1\" = ? AND \"KeyPart2\" = ?"; // first update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = increment }) .Update() .Execute(); VerifyBoundStatement(updateCounterCql, 1, (long)increment, counter.KeyPart1, counter.KeyPart2); counter.Counter = increment; // counter = increment PrimeLinqCounterQuery(counter); var updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute() .First(); Assert.AreEqual(increment, updatedCounter.Counter); // second update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = increment }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 2, (long)increment, counter.KeyPart1, counter.KeyPart2); counter.Counter += increment; // counter = increment*2; PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(increment * 2, updatedCounter.Counter); // third update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = increment }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 3, (long)increment, counter.KeyPart1, counter.KeyPart2); counter.Counter += increment; // counter = increment*3; PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(increment * 3, updatedCounter.Counter); // testing negative values var negativeIncrement = -1 * increment; // first negative update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = negativeIncrement }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 1, (long)negativeIncrement, counter.KeyPart1, counter.KeyPart2); counter.Counter += negativeIncrement; PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(increment * 2, updatedCounter.Counter); // second negative update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = negativeIncrement }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 2, (long)negativeIncrement, counter.KeyPart1, counter.KeyPart2); counter.Counter += negativeIncrement; // counter -= increment = increment PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(increment, updatedCounter.Counter); // third negative update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = negativeIncrement }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 3, (long)negativeIncrement, counter.KeyPart1, counter.KeyPart2); counter.Counter += negativeIncrement; // counter -= increment = 0 PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(0, updatedCounter.Counter); } [Test] public void LinqCounter_BatchTest() { var mappingConfig = new MappingConfiguration(); mappingConfig.Define(new Map<CounterEntityWithLinqAttributes>() .ExplicitColumns() .Column(t => t.KeyPart1) .Column(t => t.KeyPart2) .Column(t => t.Counter, map => map.AsCounter()) .PartitionKey(t => t.KeyPart1, t => t.KeyPart2) .TableName("linqcounter_batchtest_table") ); var counterTable = new Table<CounterEntityWithLinqAttributes>(Session, mappingConfig); counterTable.CreateIfNotExists(); var counter = new CounterEntityWithLinqAttributes { KeyPart1 = Guid.NewGuid(), KeyPart2 = 1, Counter = 1 }; var counter2 = new CounterEntityWithLinqAttributes { KeyPart1 = counter.KeyPart1, KeyPart2 = 2, Counter = 2 }; var batch = counterTable.GetSession().CreateBatch(BatchType.Counter); var update1 = counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = 1 }) .Update(); var update2 = counterTable .Where(t => t.KeyPart1 == counter2.KeyPart1 && t.KeyPart2 == counter2.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = 2 }) .Update(); batch.Append(update1); batch.Append(update2); batch.Execute(); VerifyBatchStatement( 1, new[] { "UPDATE linqcounter_batchtest_table SET Counter = Counter + ? WHERE KeyPart1 = ? AND KeyPart2 = ?", "UPDATE linqcounter_batchtest_table SET Counter = Counter + ? WHERE KeyPart1 = ? AND KeyPart2 = ?" }, new[] { new object[] { 1L, counter.KeyPart1, counter.KeyPart2 }, new object[] { 2L, counter2.KeyPart1, counter2.KeyPart2 } }); var expectedCounters = new[] { counter, counter2 }; PrimeLinqCounterRangeQuery(expectedCounters, "linqcounter_batchtest_table", false); var counters = counterTable.Execute().ToList(); Assert.AreEqual(2, counters.Count); Assert.IsTrue(counters.Contains(counter)); Assert.IsTrue(counters.Contains(counter2)); } [Cassandra.Data.Linq.Table] private class CounterEntityWithLinqAttributes { [Cassandra.Data.Linq.Counter] public long Counter; [Cassandra.Data.Linq.PartitionKey(1)] public Guid KeyPart1; [Cassandra.Data.Linq.PartitionKey(2)] public Decimal KeyPart2; public static IWhenQueryBuilder WithParams(IWhenQueryBuilder builder, params (string, CounterEntityWithLinqAttributes)[] parameters) { foreach (var (name, value) in parameters) { switch (name) { case nameof(CounterEntityWithLinqAttributes.Counter): builder = builder.WithParam(DataType.Counter, value.Counter); break; case nameof(CounterEntityWithLinqAttributes.KeyPart1): builder = builder.WithParam(DataType.Uuid, value.KeyPart1); break; case nameof(CounterEntityWithLinqAttributes.KeyPart2): builder = builder.WithParam(DataType.Decimal, value.KeyPart2); break; default: throw new ArgumentException("parameter not found"); } } return builder; } public IWhenQueryBuilder WithParams(IWhenQueryBuilder builder, params string[] parameters) { return WithParams(builder, parameters.Select(p => (p, this)).ToArray()); } public IWhenQueryBuilder WithParams(IWhenQueryBuilder builder) { return WithParams(builder, new string[0]); } public RowsResult CreateRowsResult() { return (RowsResult)AddRow(CounterEntityWithLinqAttributes.GetEmptyRowsResult()); } public static RowsResult GetEmptyRowsResult() { return new RowsResult( (nameof(CounterEntityWithLinqAttributes.Counter), DataType.Counter), (nameof(CounterEntityWithLinqAttributes.KeyPart1), DataType.Uuid), (nameof(CounterEntityWithLinqAttributes.KeyPart2), DataType.Decimal)); } public RowsResult AddRow(RowsResult rows) { return (RowsResult)rows.WithRow(Counter, KeyPart1, KeyPart2); } public override bool Equals(object obj) { if (obj == null) { return false; } var comp = (CounterEntityWithLinqAttributes)obj; return (this.Counter == comp.Counter && this.KeyPart1.Equals(comp.KeyPart1) && this.KeyPart2.Equals(comp.KeyPart2)); } public override int GetHashCode() { var hash = KeyPart1.GetHashCode(); hash += KeyPart2.GetHashCode() * 1000; hash += (int)Counter * 100000; return hash; } } } }
// SampSharp // Copyright 2017 Tim Potze // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using SampSharp.Core.CodePages; using SampSharp.Core.Communication.Clients; using SampSharp.Core.Logging; namespace SampSharp.Core { /// <summary> /// Represents a configuration build for running a SampSharp game mode. /// </summary> public sealed class GameModeBuilder { private ICommunicationClient _communicationClient; private GameModeExitBehaviour _exitBehaviour = GameModeExitBehaviour.ShutDown; private IGameModeProvider _gameModeProvider; private bool _redirectConsoleOutput; private GameModeStartBehaviour _startBehaviour = GameModeStartBehaviour.Gmx; private Encoding _encoding; private bool _hosted; private TextWriter _logWriter; private bool _logWriterSet; private const string DefaultUnixDomainSocketPath = "/tmp/SampSharp"; private const string DefaultPipeName = "SampSharp"; private const string DefaultTcpIp = "127.0.0.1"; private const int DefaultTcpPort = 8888; /// <summary> /// Initializes a new instance of the <see cref="GameModeBuilder"/> class. /// </summary> public GameModeBuilder() { ParseArguments(); } #region Communication /// <summary> /// Use the specified communication client to communicate with the SampSharp server. /// </summary> /// <param name="communicationClient">The communication client.</param> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release.")] public GameModeBuilder UseCommunicationClient(ICommunicationClient communicationClient) { _communicationClient = communicationClient ?? throw new ArgumentNullException(nameof(communicationClient)); return this; } /// <summary> /// Use a named pipe with the specified <paramref name="pipeName" /> to communicate with the SampSharp server. /// </summary> /// <param name="pipeName">Name of the pipe.</param> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release.")] public GameModeBuilder UsePipe(string pipeName) { if (pipeName == null) throw new ArgumentNullException(nameof(pipeName)); return UseCommunicationClient(new NamedPipeClient(pipeName)); } /// <summary> /// Use an unix domain socket with a file at the specified <paramref name="path" /> to communicate with the SampSharp /// server. /// </summary> /// <param name="path">The path to the domain socket file.</param> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release.")] public GameModeBuilder UseUnixDomainSocket(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return UseCommunicationClient(new UnixDomainSocketCommunicationClient(path)); } /// <summary> /// Use a TCP client to communicate with the SampSharp server on localhost. /// </summary> /// <param name="port">The port on which to connect.</param> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release.")] public GameModeBuilder UseTcpClient(int port) { return UseCommunicationClient(new TcpCommunicationClient(DefaultTcpIp, port)); } /// <summary> /// Use a TCP client to communicate with the SampSharp server. /// </summary> /// <param name="host">The host to which to connect.</param> /// <param name="port">The port on which to connect.</param> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release.")] public GameModeBuilder UseTcpClient(string host, int port) { if (host == null) throw new ArgumentNullException(nameof(host)); return UseCommunicationClient(new TcpCommunicationClient(host, port)); } #endregion #region Encoding /// <summary> /// Use the specified <paramref name="encoding"/> when en/decoding text messages sent to/from the server. /// </summary> /// <param name="encoding">The encoding to use when en/decoding text messages send to/from the server.</param> /// <returns>The updated game mode configuration builder.</returns> public GameModeBuilder UseEncoding(Encoding encoding) { _encoding = encoding ?? throw new ArgumentNullException(nameof(encoding)); return this; } /// <summary> /// Use the code page described by the file at the specified <paramref name="path"/> when en/decoding text messages sent to/from the server. /// </summary> /// <param name="path">The path to the code page file.</param> /// <returns>The updated game mode configuration builder.</returns> public GameModeBuilder UseEncoding(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return UseEncoding(CodePageEncoding.Load(path)); } /// <summary> /// Use the code page described by the specified <paramref name="stream"/> when en/decoding text messages sent to/from the server. /// </summary> /// <param name="stream">The stream containing the code page definition.</param> /// <returns>The updated game mode configuration builder.</returns> public GameModeBuilder UseEncoding(Stream stream) { return UseEncoding(CodePageEncoding.Load(stream)); } /// <summary> /// Uses the encoding code page. /// </summary> /// <param name="pageName">Name of the page.</param> /// <returns></returns> public GameModeBuilder UseEncodingCodePage(string pageName) { if (pageName == null) throw new ArgumentNullException(nameof(pageName)); var type = typeof(CodePageEncoding); var name = $"{type.Namespace}.data.{pageName.ToLowerInvariant()}.dat"; using var stream = type.Assembly.GetManifestResourceStream(name); if (stream == null) { throw new GameModeBuilderException($"Code page with name {pageName} is not available."); } var encoding = CodePageEncoding.Deserialize(stream); return UseEncoding(encoding); } #endregion #region Game Mode Provider /// <summary> /// Use the specified game mode. /// </summary> /// <param name="gameMode">The game mode to use.</param> /// <returns>The updated game mode configuration builder.</returns> public GameModeBuilder Use(IGameModeProvider gameMode) { _gameModeProvider = gameMode ?? throw new ArgumentNullException(nameof(gameMode)); return this; } /// <summary> /// Use the gamemode of the specified <typeparamref name="TGameMode" /> type. /// </summary> /// <typeparam name="TGameMode">The type of the game mode to use.</typeparam> /// <returns>The updated game mode configuration builder.</returns> public GameModeBuilder Use<TGameMode>() where TGameMode : IGameModeProvider { return Use(Activator.CreateInstance<TGameMode>()); } #endregion /// <summary> /// Redirect the console output to the server. /// </summary> /// <returns>The updated game mode configuration builder.</returns> public GameModeBuilder RedirectConsoleOutput() { _redirectConsoleOutput = true; return this; } #region Logging /// <summary> /// Uses the specified log level as the maximum level which is written to the log by SampSharp. /// </summary> /// <param name="logLevel">The log level.</param> /// <returns>The updated game mode configuration builder.</returns> public GameModeBuilder UseLogLevel(CoreLogLevel logLevel) { CoreLog.LogLevel = logLevel; return this; } /// <summary> /// Uses the specified text writer to log SampSharp log messages to. /// </summary> /// <param name="textWriter">The text writer to log SampSharp log messages to.</param> /// <remarks>If a null value is specified as text writer, no log messages will appear.</remarks> /// <returns>The updated game mode configuration builder.</returns> public GameModeBuilder UseLogWriter(TextWriter textWriter) { _logWriter = textWriter; _logWriterSet = true; return this; } #endregion /// <summary> /// Indicate the game mode will be hosted in the SA-MP server process. /// </summary> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release. There is no longer a need to call this method.")] public GameModeBuilder UseHosted() { _hosted = true; return this; } /// <summary> /// Sets the behaviour used once a OnGameModeExit call has been received. /// </summary> /// <param name="exitBehaviour">The exit behaviour.</param> /// <remarks>The exit behaviour is ignored when using a hosted game mode environment.</remarks> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release.")] public GameModeBuilder UseExitBehaviour(GameModeExitBehaviour exitBehaviour) { _exitBehaviour = exitBehaviour; return this; } /// <summary> /// Use the specified start method when attaching to the server. /// </summary> /// <param name="startBehaviour">The start behaviour.</param> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release.")] public GameModeBuilder UseStartBehaviour(GameModeStartBehaviour startBehaviour) { _startBehaviour = startBehaviour; return this; } /// <summary> /// Runs the specified <paramref name="action" /> if this game mode builder is configured to run in hosted mode either by /// calling <see cref="UseHosted" /> or by the SA-MP server having started this game mode process in hosted mode. /// </summary> /// <param name="action">The action to run if the game mode builder has been configured to run in hosted mode.</param> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release.")] public GameModeBuilder IfHosted(Action<GameModeBuilder> action) { if (_hosted) action?.Invoke(this); return this; } /// <summary> /// Runs the specified <paramref name="action" /> if this game mode builder is not configured to run in hosted mode either by /// calling <see cref="UseHosted" /> or by the SA-MP server having started this game mode process in hosted mode. /// </summary> /// <param name="action">The action to run if the game mode builder has been configured to run in multi process mode.</param> /// <returns>The updated game mode configuration builder.</returns> [Obsolete("Multi-process mode is deprecated and will be removed in a future release.")] public GameModeBuilder IfMultiProcess(Action<GameModeBuilder> action) { if (!_hosted) action?.Invoke(this); return this; } /// <summary> /// Run the game mode using the build configuration stored in this instance. /// </summary> public void Run() { ApplyDefaults(); if (!_hosted && _communicationClient == null) throw new GameModeBuilderException("No communication client has been specified"); if (_gameModeProvider == null) throw new GameModeBuilderException("No game mode provider has been specified"); var redirect = _redirectConsoleOutput; // Build the game mode runner var runner = Build(); if (runner == null) return; // Redirect console output ServerLogWriter redirectWriter = null; if (redirect) { redirectWriter = new ServerLogWriter(runner.Client); Console.SetOut(redirectWriter); } // Set framework log writer var logWriter = _logWriter; if (!_logWriterSet) logWriter = redirectWriter != null ? (TextWriter) redirectWriter : new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }; CoreLog.TextWriter = logWriter; // Run game mode runner if (_hosted) { // Ignore exit behaviours for hosted environments. runner.Run(); } else { do { // If true is returned, the runner wants to shut down. if (runner.Run()) break; } while (_exitBehaviour == GameModeExitBehaviour.Restart); if (redirect) Console.SetOut(new StreamWriter(Console.OpenStandardOutput())); } _gameModeProvider.Dispose(); } private void ParseArguments() { var args = Environment.GetCommandLineArgs(); if (args == null || args.Length == 0) { return; } for (int i = 0; i < args.Length; i++) { string option; string value; if (args[i].Length < 2 || !args[i].StartsWith("-")) continue; if (args[i].StartsWith("--")) { option = args[i]; value = args.Length > i + 1 ? args[i + 1] : null; } else { option = args[i].Substring(0, 2); value = args[i].Length > 2 ? args[i].Substring(2) : args.Length > i + 1 ? args[i + 1] : null; } switch (option) { case "--hosted": case "-h": UseHosted(); break; case "--redirect-console-output": case "-r": RedirectConsoleOutput(); break; case "--pipe": case "-p": if (value != null && !value.StartsWith("-")) { UsePipe(value); i++; } else { UsePipe(DefaultPipeName); } break; case "--unix": case "-u": if (value != null && !value.StartsWith("-")) { UseUnixDomainSocket(value); i++; } else { UseUnixDomainSocket(DefaultUnixDomainSocketPath); } break; case "--tcp": var ip = DefaultTcpIp; var port = DefaultTcpPort; if (value != null && !value.StartsWith("-")) { var colon = value.IndexOf(":", StringComparison.Ordinal); if (colon < 0) { if (IPAddress.TryParse(value.Substring(0, colon), out var addr) && addr.AddressFamily == AddressFamily.InterNetwork) ip = value.Substring(0, colon); int.TryParse(value.Substring(colon + 1), out port); } else { int.TryParse(value, out port); } i++; } UseTcpClient(ip, port); break; case "--log-level": case "-l": if (value == null) break; if (Enum.TryParse<CoreLogLevel>(value, out var level)) UseLogLevel(level); i++; break; case "--start-behaviour": case "-s": if (value == null) break; if (Enum.TryParse<GameModeStartBehaviour>(value, out var startBehaviour)) UseStartBehaviour(startBehaviour); i++; break; case "--exit-behaviour": case "-e": if (value == null) break; if (Enum.TryParse<GameModeExitBehaviour>(value, out var exitBehaviour)) UseExitBehaviour(exitBehaviour); i++; break; } } } private void ApplyDefaults() { if (_communicationClient == null && !_hosted) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) _communicationClient = new UnixDomainSocketCommunicationClient(DefaultUnixDomainSocketPath); else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) _communicationClient = new NamedPipeClient(DefaultPipeName); } } private IGameModeRunner Build() { if (_hosted) { return new HostedGameModeClient(_gameModeProvider, _encoding); } else { return new MultiProcessGameModeClient(_communicationClient, _startBehaviour, _gameModeProvider, _encoding); } } } }
using Lucene.Net.Index; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Lucene.Net.Documents { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Documents are the unit of indexing and search. /// <para/> /// A Document is a set of fields. Each field has a name and a textual value. /// A field may be stored (<see cref="IIndexableFieldType.IsStored"/>) with the document, in which /// case it is returned with search hits on the document. Thus each document /// should typically contain one or more stored fields which uniquely identify /// it. /// <para/> /// Note that fields which are <i>not</i> <see cref="Lucene.Net.Index.IIndexableFieldType.IsStored"/> are /// <i>not</i> available in documents retrieved from the index, e.g. with /// <see cref="Search.ScoreDoc.Doc"/> or <see cref="IndexReader.Document(int)"/>. /// </summary> public sealed class Document : IEnumerable<IIndexableField> { private readonly List<IIndexableField> fields = new List<IIndexableField>(); /// <summary> /// Constructs a new document with no fields. </summary> public Document() { } public IEnumerator<IIndexableField> GetEnumerator() { return fields.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// <para>Adds a field to a document. Several fields may be added with /// the same name. In this case, if the fields are indexed, their text is /// treated as though appended for the purposes of search.</para> /// <para> Note that add like the <see cref="RemoveField(string)"/> and <see cref="RemoveFields(string)"/> methods only makes sense /// prior to adding a document to an index. These methods cannot /// be used to change the content of an existing index! In order to achieve this, /// a document has to be deleted from an index and a new changed version of that /// document has to be added.</para> /// </summary> public void Add(IIndexableField field) { fields.Add(field); } /// <summary> /// <para>Removes field with the specified name from the document. /// If multiple fields exist with this name, this method removes the first field that has been added. /// If there is no field with the specified name, the document remains unchanged.</para> /// <para> Note that the <see cref="RemoveField(string)"/> and <see cref="RemoveFields(string)"/> methods like the add method only make sense /// prior to adding a document to an index. These methods cannot /// be used to change the content of an existing index! In order to achieve this, /// a document has to be deleted from an index and a new changed version of that /// document has to be added.</para> /// </summary> public void RemoveField(string name) { for (int i = 0; i < fields.Count; i++) { IIndexableField field = fields[i]; if (field.Name.Equals(name, StringComparison.Ordinal)) { fields.Remove(field); return; } } } /// <summary> /// <para>Removes all fields with the given name from the document. /// If there is no field with the specified name, the document remains unchanged.</para> /// <para> Note that the <see cref="RemoveField(string)"/> and <see cref="RemoveFields(string)"/> methods like the add method only make sense /// prior to adding a document to an index. These methods cannot /// be used to change the content of an existing index! In order to achieve this, /// a document has to be deleted from an index and a new changed version of that /// document has to be added.</para> /// </summary> public void RemoveFields(string name) { for (int i = fields.Count - 1; i >= 0; i--) { IIndexableField field = fields[i]; if (field.Name.Equals(name, StringComparison.Ordinal)) { fields.Remove(field); } } } /// <summary> /// Returns an array of byte arrays for of the fields that have the name specified /// as the method parameter. This method returns an empty /// array when there are no matching fields. It never /// returns <c>null</c>. /// </summary> /// <param name="name"> the name of the field </param> /// <returns> a <see cref="T:BytesRef[]"/> of binary field values </returns> public BytesRef[] GetBinaryValues(string name) { var result = new List<BytesRef>(); foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal)) { BytesRef bytes = field.GetBinaryValue(); if (bytes != null) { result.Add(bytes); } } } return result.ToArray(); } /// <summary> /// Returns an array of bytes for the first (or only) field that has the name /// specified as the method parameter. this method will return <c>null</c> /// if no binary fields with the specified name are available. /// There may be non-binary fields with the same name. /// </summary> /// <param name="name"> the name of the field. </param> /// <returns> a <see cref="BytesRef"/> containing the binary field value or <c>null</c> </returns> public BytesRef GetBinaryValue(string name) { foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal)) { BytesRef bytes = field.GetBinaryValue(); if (bytes != null) { return bytes; } } } return null; } /// <summary> /// Returns a field with the given name if any exist in this document, or /// <c>null</c>. If multiple fields exists with this name, this method returns the /// first value added. /// </summary> public IIndexableField GetField(string name) { foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal)) { return field; } } return null; } /// <summary> /// Returns an array of <see cref="IIndexableField"/>s with the given name. /// This method returns an empty array when there are no /// matching fields. It never returns <c>null</c>. /// </summary> /// <param name="name"> the name of the field </param> /// <returns> a <see cref="T:IndexableField[]"/> array </returns> public IIndexableField[] GetFields(string name) { var result = new List<IIndexableField>(); foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal)) { result.Add(field); } } return result.ToArray(); } /// <summary> /// Returns a List of all the fields in a document. /// <para>Note that fields which are <i>not</i> stored are /// <i>not</i> available in documents retrieved from the /// index, e.g. <see cref="Search.IndexSearcher.Doc(int)"/> or /// <see cref="IndexReader.Document(int)"/>. /// </para> /// </summary> public IList<IIndexableField> Fields => fields; private static readonly string[] NO_STRINGS = Arrays.Empty<string>(); /// <summary> /// Returns an array of values of the field specified as the method parameter. /// This method returns an empty array when there are no /// matching fields. It never returns <c>null</c>. /// For <see cref="Int32Field"/>, <see cref="Int64Field"/>, /// <see cref="SingleField"/> and <seealso cref="DoubleField"/> it returns the string value of the number. If you want /// the actual numeric field instances back, use <see cref="GetFields(string)"/>. </summary> /// <param name="name"> the name of the field </param> /// <returns> a <see cref="T:string[]"/> of field values </returns> public string[] GetValues(string name) { var result = new List<string>(); foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal) && field.GetStringValue() != null) { result.Add(field.GetStringValue()); } } if (result.Count == 0) { return NO_STRINGS; } return result.ToArray(); } /// <summary> /// Returns the string value of the field with the given name if any exist in /// this document, or <c>null</c>. If multiple fields exist with this name, this /// method returns the first value added. If only binary fields with this name /// exist, returns <c>null</c>. /// For <see cref="Int32Field"/>, <see cref="Int64Field"/>, /// <see cref="SingleField"/> and <seealso cref="DoubleField"/> it returns the string value of the number. If you want /// the actual numeric field instance back, use <see cref="GetField(string)"/>. /// </summary> public string Get(string name) { foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal) && field.GetStringValue() != null) { return field.GetStringValue(); } } return null; } /// <summary> /// Prints the fields of a document for human consumption. </summary> public override string ToString() { var buffer = new StringBuilder(); buffer.Append("Document<"); for (int i = 0; i < fields.Count; i++) { IIndexableField field = fields[i]; buffer.Append(field.ToString()); if (i != fields.Count - 1) { buffer.Append(" "); } } buffer.Append(">"); return buffer.ToString(); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesUpdateAliases2 { public partial class IndicesUpdateAliases2YamlTests { public class IndicesUpdateAliases220RoutingYamlBase : YamlTestsBase { public IndicesUpdateAliases220RoutingYamlBase() : base() { //do indices.create this.Do(()=> _client.IndicesCreate("test_index", null)); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class Routing2Tests : IndicesUpdateAliases220RoutingYamlBase { [Test] public void Routing2Test() { //do indices.update_aliases _body = new { actions= new [] { new { add= new { index= "test_index", alias= "test_alias", routing= "routing" } } } }; this.Do(()=> _client.IndicesUpdateAliasesForAll(_body)); //do indices.get_aliases this.Do(()=> _client.IndicesGetAliases("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new { index_routing= "routing", search_routing= "routing" }); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class IndexRouting3Tests : IndicesUpdateAliases220RoutingYamlBase { [Test] public void IndexRouting3Test() { //do indices.update_aliases _body = new { actions= new [] { new { add= new { index= "test_index", alias= "test_alias", index_routing= "index_routing" } } } }; this.Do(()=> _client.IndicesUpdateAliasesForAll(_body)); //do indices.get_aliases this.Do(()=> _client.IndicesGetAliases("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new { index_routing= "index_routing" }); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class SearchRouting4Tests : IndicesUpdateAliases220RoutingYamlBase { [Test] public void SearchRouting4Test() { //do indices.update_aliases _body = new { actions= new [] { new { add= new { index= "test_index", alias= "test_alias", search_routing= "search_routing" } } } }; this.Do(()=> _client.IndicesUpdateAliasesForAll(_body)); //do indices.get_aliases this.Do(()=> _client.IndicesGetAliases("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new { search_routing= "search_routing" }); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class IndexDefaultRouting5Tests : IndicesUpdateAliases220RoutingYamlBase { [Test] public void IndexDefaultRouting5Test() { //do indices.update_aliases _body = new { actions= new [] { new { add= new { index= "test_index", alias= "test_alias", index_routing= "index_routing", routing= "routing" } } } }; this.Do(()=> _client.IndicesUpdateAliasesForAll(_body)); //do indices.get_aliases this.Do(()=> _client.IndicesGetAliases("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new { index_routing= "index_routing", search_routing= "routing" }); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class SearchDefaultRouting6Tests : IndicesUpdateAliases220RoutingYamlBase { [Test] public void SearchDefaultRouting6Test() { //do indices.update_aliases _body = new { actions= new [] { new { add= new { index= "test_index", alias= "test_alias", search_routing= "search_routing", routing= "routing" } } } }; this.Do(()=> _client.IndicesUpdateAliasesForAll(_body)); //do indices.get_aliases this.Do(()=> _client.IndicesGetAliases("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new { index_routing= "routing", search_routing= "search_routing" }); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class IndexSearchDefaultRouting7Tests : IndicesUpdateAliases220RoutingYamlBase { [Test] public void IndexSearchDefaultRouting7Test() { //do indices.update_aliases _body = new { actions= new [] { new { add= new { index= "test_index", alias= "test_alias", index_routing= "index_routing", search_routing= "search_routing", routing= "routing" } } } }; this.Do(()=> _client.IndicesUpdateAliasesForAll(_body)); //do indices.get_aliases this.Do(()=> _client.IndicesGetAliases("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new { index_routing= "index_routing", search_routing= "search_routing" }); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class NumericRouting8Tests : IndicesUpdateAliases220RoutingYamlBase { [Test] public void NumericRouting8Test() { //do indices.update_aliases _body = new { actions= new [] { new { add= new { index= "test_index", alias= "test_alias", routing= "5" } } } }; this.Do(()=> _client.IndicesUpdateAliasesForAll(_body)); //do indices.get_aliases this.Do(()=> _client.IndicesGetAliases("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new { index_routing= "5", search_routing= "5" }); } } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using SharpDX.Collections; namespace SharpDX.Diagnostics { /// <summary> /// Event args for <see cref="ComObject"/> used by <see cref="ObjectTracker"/>. /// </summary> public class ComObjectEventArgs : EventArgs { /// <summary> /// The object being tracked/untracked. /// </summary> public ComObject Object; /// <summary> /// Initializes a new instance of the <see cref="ComObjectEventArgs"/> class. /// </summary> /// <param name="o">The o.</param> public ComObjectEventArgs(ComObject o) { Object = o; } } /// <summary> /// Track all allocated objects. /// </summary> public static class ObjectTracker { private static Dictionary<IntPtr, List<ObjectReference>> processGlobalObjectReferences; [ThreadStatic] private static Dictionary<IntPtr, List<ObjectReference>> threadStaticObjectReferences; /// <summary> /// Occurs when a ComObject is tracked. /// </summary> public static event EventHandler<ComObjectEventArgs> Tracked; /// <summary> /// Occurs when a ComObject is untracked. /// </summary> public static event EventHandler<ComObjectEventArgs> UnTracked; /// <summary> /// Function which provides stack trace for object tracking. /// </summary> public static Func<string> StackTraceProvider = GetStackTrace; private static Dictionary<IntPtr, List<ObjectReference>> ObjectReferences { get { Dictionary<IntPtr, List<ObjectReference>> objectReferences; if (Configuration.UseThreadStaticObjectTracking) { if (threadStaticObjectReferences == null) threadStaticObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = threadStaticObjectReferences; } else { if (processGlobalObjectReferences == null) processGlobalObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = processGlobalObjectReferences; } return objectReferences; } } /// <summary> /// Gets default stack trace. /// </summary> public static string GetStackTrace() { #if STORE_APP var stacktrace = "Stacktrace is not available on this platform"; // This code is a workaround to be able to get a full stacktrace on Windows Store App. // This is an unsafe code, that should not run on production. Only at dev time! // Make sure we are on a 32bit process if (IntPtr.Size == 4) { // Get an access to a restricted method try { var stackTraceGetMethod = typeof(Environment).GetRuntimeProperty("StackTrace").GetMethod; try { // First try to get the stacktrace stacktrace = (string)stackTraceGetMethod.Invoke(null, null); } catch (Exception ex) { // If we have an exception, it means that the access to the method is not possible // so we are going to patch the field RuntimeMethodInfo.m_invocationFlags that should contain // 0x41 (initialized + security), and replace it by 0x1 (initialized) // and then callback again the method unsafe { // unsafe code, the RuntimeMethodInfo could be relocated (is it a real managed GC object?), // but we don't have much choice var addr = *(int**)Interop.Fixed(ref stackTraceGetMethod); // offset to RuntimeMethodInfo.m_invocationFlags addr += 13; // Check if we have the expecting value if (*addr == 0x41) { // if yes, change it to 0x1 *addr = 0x1; try { // And try to callit again a second time // if it succeeds, first Invoke() should run on next call stacktrace = (string)stackTraceGetMethod.Invoke(null, null); } catch (Exception ex2) { // if it is still failing, we can't do anything } } } } } catch (Exception ex) { // can't do anything } } return stacktrace; #else // Another WTF: To get a stacktrace, we don't have other ways than throwing an exception on PCL. try { throw new GetStackTraceException(); } catch (GetStackTraceException ex) { return ex.StackTrace; } #endif } /// <summary> /// Tracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void Track(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (!ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { referenceList = new List<ObjectReference>(); ObjectReferences.Add(comObject.NativePointer, referenceList); } referenceList.Add(new ObjectReference(DateTime.Now, comObject, StackTraceProvider != null ? StackTraceProvider() : String.Empty)); // Fire Tracked event. OnTracked(comObject); } } /// <summary> /// Finds a list of object reference from a specified COM object pointer. /// </summary> /// <param name="comObjectPtr">The COM object pointer.</param> /// <returns>A list of object reference</returns> public static List<ObjectReference> Find(IntPtr comObjectPtr) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObjectPtr, out referenceList)) return new List<ObjectReference>(referenceList); } return new List<ObjectReference>(); } /// <summary> /// Finds the object reference for a specific COM object. /// </summary> /// <param name="comObject">The COM object.</param> /// <returns>An object reference</returns> public static ObjectReference Find(ComObject comObject) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { foreach (var objectReference in referenceList) { if (ReferenceEquals(objectReference.Object.Target, comObject)) return objectReference; } } } return null; } /// <summary> /// Untracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void UnTrack(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { for (int i = referenceList.Count-1; i >=0; i--) { var objectReference = referenceList[i]; if (ReferenceEquals(objectReference.Object.Target, comObject)) referenceList.RemoveAt(i); else if (!objectReference.IsAlive) referenceList.RemoveAt(i); } // Remove empty list if (referenceList.Count == 0) ObjectReferences.Remove(comObject.NativePointer); // Fire UnTracked event OnUnTracked(comObject); } } } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static List<ObjectReference> FindActiveObjects() { var activeObjects = new List<ObjectReference>(); lock (ObjectReferences) { foreach (var referenceList in ObjectReferences.Values) { foreach (var objectReference in referenceList) { if (objectReference.IsAlive) activeObjects.Add(objectReference); } } } return activeObjects; } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static string ReportActiveObjects() { var text = new StringBuilder(); int count = 0; var countPerType = new Dictionary<string, int>(); foreach (var findActiveObject in FindActiveObjects()) { var findActiveObjectStr = findActiveObject.ToString(); if (!string.IsNullOrEmpty(findActiveObjectStr)) { text.AppendFormat("[{0}]: {1}", count, findActiveObjectStr); var target = findActiveObject.Object.Target; if (target != null) { int typeCount; var targetType = target.GetType().Name; if (!countPerType.TryGetValue(targetType, out typeCount)) { countPerType[targetType] = 0; } else countPerType[targetType] = typeCount + 1; } } count++; } var keys = new List<string>(countPerType.Keys); keys.Sort(); text.AppendLine(); text.AppendLine("Count per Type:"); foreach (var key in keys) { text.AppendFormat("{0} : {1}", key, countPerType[key]); text.AppendLine(); } return text.ToString(); } private static void OnTracked(ComObject obj) { var handler = Tracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } private static void OnUnTracked(ComObject obj) { var handler = UnTracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } private class GetStackTraceException : Exception { } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors #if NASM using System; using System.Diagnostics; using System.Runtime.CompilerServices; using Iced.Intel.FormatterInternal; using Iced.Intel.NasmFormatterInternal; namespace Iced.Intel { /// <summary> /// Nasm formatter /// </summary> public sealed class NasmFormatter : Formatter { /// <summary> /// Gets the formatter options /// </summary> public override FormatterOptions Options => options; /// <summary> /// Gets the nasm formatter options /// </summary> [System.Obsolete("Use " + nameof(Options) + " instead of this property", true)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public FormatterOptions NasmOptions => options; readonly FormatterOptions options; readonly ISymbolResolver? symbolResolver; readonly IFormatterOptionsProvider? optionsProvider; readonly FormatterString[] allRegisters; readonly InstrInfo[] instrInfos; readonly MemorySizes.Info[] allMemorySizes; readonly NumberFormatter numberFormatter; readonly FormatterString[] opSizeStrings; readonly FormatterString[] addrSizeStrings; readonly FormatterString[]?[] branchInfos; readonly string[] scaleNumbers; readonly FormatterString[] memSizeInfos; readonly FormatterString[] farMemSizeInfos; /// <summary> /// Constructor /// </summary> public NasmFormatter() : this(null, null, null) { } /// <summary> /// Constructor /// </summary> /// <param name="symbolResolver">Symbol resolver or null</param> /// <param name="optionsProvider">Operand options provider or null</param> public NasmFormatter(ISymbolResolver? symbolResolver, IFormatterOptionsProvider? optionsProvider = null) : this(null, symbolResolver, optionsProvider) { } /// <summary> /// Constructor /// </summary> /// <param name="options">Formatter options or null</param> /// <param name="symbolResolver">Symbol resolver or null</param> /// <param name="optionsProvider">Operand options provider or null</param> public NasmFormatter(FormatterOptions? options, ISymbolResolver? symbolResolver = null, IFormatterOptionsProvider? optionsProvider = null) { this.options = options ?? FormatterOptions.CreateNasm(); this.symbolResolver = symbolResolver; this.optionsProvider = optionsProvider; allRegisters = Registers.AllRegisters; instrInfos = InstrInfos.AllInfos; allMemorySizes = MemorySizes.AllMemorySizes; numberFormatter = new NumberFormatter(true); opSizeStrings = s_opSizeStrings; addrSizeStrings = s_addrSizeStrings; branchInfos = s_branchInfos; scaleNumbers = s_scaleNumbers; memSizeInfos = s_memSizeInfos; farMemSizeInfos = s_farMemSizeInfos; } static readonly FormatterString str_bnd = new FormatterString("bnd"); static readonly FormatterString str_byte = new FormatterString("byte"); static readonly FormatterString str_dword = new FormatterString("dword"); static readonly FormatterString str_lock = new FormatterString("lock"); static readonly FormatterString str_notrack = new FormatterString("notrack"); static readonly FormatterString str_qword = new FormatterString("qword"); static readonly FormatterString str_rd_sae = new FormatterString("rd-sae"); static readonly FormatterString str_rel = new FormatterString("rel"); static readonly FormatterString str_rep = new FormatterString("rep"); static readonly FormatterString[] str_repe = new FormatterString[2] { new FormatterString("repe"), new FormatterString("repz"), }; static readonly FormatterString[] str_repne = new FormatterString[2] { new FormatterString("repne"), new FormatterString("repnz"), }; static readonly FormatterString str_rn_sae = new FormatterString("rn-sae"); static readonly FormatterString str_ru_sae = new FormatterString("ru-sae"); static readonly FormatterString str_rz_sae = new FormatterString("rz-sae"); static readonly FormatterString str_sae = new FormatterString("sae"); static readonly FormatterString str_to = new FormatterString("to"); static readonly FormatterString str_word = new FormatterString("word"); static readonly FormatterString str_xacquire = new FormatterString("xacquire"); static readonly FormatterString str_xrelease = new FormatterString("xrelease"); static readonly FormatterString str_z = new FormatterString("z"); static readonly FormatterString[] s_opSizeStrings = new FormatterString[(int)InstrOpInfoFlags.SizeOverrideMask + 1] { new FormatterString(""), new FormatterString("o16"), new FormatterString("o32"), new FormatterString("o64"), }; static readonly FormatterString[] s_addrSizeStrings = new FormatterString[(int)InstrOpInfoFlags.SizeOverrideMask + 1] { new FormatterString(""), new FormatterString("a16"), new FormatterString("a32"), new FormatterString("a64"), }; static readonly FormatterString[]?[] s_branchInfos = new FormatterString[]?[(int)InstrOpInfoFlags.BranchSizeInfoMask + 1] { null, new[] { new FormatterString("near") }, new[] { new FormatterString("near"), new FormatterString("word") }, new[] { new FormatterString("near"), new FormatterString("dword") }, new[] { new FormatterString("word") }, new[] { new FormatterString("dword") }, new[] { new FormatterString("short") }, null, }; static readonly FormatterString[] s_memSizeInfos = new FormatterString[(int)InstrOpInfoFlags.MemorySizeInfoMask + 1] { new FormatterString(""), new FormatterString("word"), new FormatterString("dword"), new FormatterString("qword"), }; static readonly FormatterString[] s_farMemSizeInfos = new FormatterString[(int)InstrOpInfoFlags.FarMemorySizeInfoMask + 1] { new FormatterString(""), new FormatterString("word"), new FormatterString("dword"), new FormatterString(""), }; static readonly string[] s_scaleNumbers = new string[4] { "1", "2", "4", "8", }; /// <summary> /// Formats the mnemonic and/or any prefixes /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> /// <param name="options">Options</param> public override void FormatMnemonic(in Instruction instruction, FormatterOutput output, FormatMnemonicOptions options) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(this.options, instruction, out var opInfo); int column = 0; FormatMnemonic(instruction, output, opInfo, ref column, options); } /// <summary> /// Gets the number of operands that will be formatted. A formatter can add and remove operands /// </summary> /// <param name="instruction">Instruction</param> /// <returns></returns> public override int GetOperandCount(in Instruction instruction) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); return opInfo.OpCount; } #if INSTR_INFO /// <summary> /// Returns the operand access but only if it's an operand added by the formatter. If it's an /// operand that is part of <see cref="Instruction"/>, you should call eg. <see cref="InstructionInfoFactory.GetInfo(in Instruction)"/>. /// </summary> /// <param name="instruction">Instruction</param> /// <param name="operand">Operand number, 0-based. This is a formatter operand and isn't necessarily the same as an instruction operand. /// See <see cref="GetOperandCount(in Instruction)"/></param> /// <param name="access">Updated with operand access if successful</param> /// <returns></returns> public override bool TryGetOpAccess(in Instruction instruction, int operand, out OpAccess access) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); // Although it's a TryXXX() method, it should only accept valid instruction operand indexes if ((uint)operand >= (uint)opInfo.OpCount) ThrowHelper.ThrowArgumentOutOfRangeException_operand(); return opInfo.TryGetOpAccess(operand, out access); } #endif /// <summary> /// Converts a formatter operand index to an instruction operand index. Returns -1 if it's an operand added by the formatter /// </summary> /// <param name="instruction">Instruction</param> /// <param name="operand">Operand number, 0-based. This is a formatter operand and isn't necessarily the same as an instruction operand. /// See <see cref="GetOperandCount(in Instruction)"/></param> /// <returns></returns> public override int GetInstructionOperand(in Instruction instruction, int operand) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); if ((uint)operand >= (uint)opInfo.OpCount) ThrowHelper.ThrowArgumentOutOfRangeException_operand(); return opInfo.GetInstructionIndex(operand); } /// <summary> /// Converts an instruction operand index to a formatter operand index. Returns -1 if the instruction operand isn't used by the formatter /// </summary> /// <param name="instruction">Instruction</param> /// <param name="instructionOperand">Instruction operand</param> /// <returns></returns> public override int GetFormatterOperand(in Instruction instruction, int instructionOperand) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); if ((uint)instructionOperand >= (uint)instruction.OpCount) ThrowHelper.ThrowArgumentOutOfRangeException_instructionOperand(); return opInfo.GetOperandIndex(instructionOperand); } /// <summary> /// Formats an operand. This is a formatter operand and not necessarily a real instruction operand. /// A formatter can add and remove operands. /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> /// <param name="operand">Operand number, 0-based. This is a formatter operand and isn't necessarily the same as an instruction operand. /// See <see cref="GetOperandCount(in Instruction)"/></param> public override void FormatOperand(in Instruction instruction, FormatterOutput output, int operand) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); if ((uint)operand >= (uint)opInfo.OpCount) ThrowHelper.ThrowArgumentOutOfRangeException_operand(); FormatOperand(instruction, output, opInfo, operand); } /// <summary> /// Formats an operand separator /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> public override void FormatOperandSeparator(in Instruction instruction, FormatterOutput output) { if (output is null) ThrowHelper.ThrowArgumentNullException_output(); output.Write(",", FormatterTextKind.Punctuation); if (options.SpaceAfterOperandSeparator) output.Write(" ", FormatterTextKind.Text); } /// <summary> /// Formats all operands /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> public override void FormatAllOperands(in Instruction instruction, FormatterOutput output) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); FormatOperands(instruction, output, opInfo); } /// <summary> /// Formats the whole instruction: prefixes, mnemonic, operands /// </summary> /// <param name="instruction">Instruction</param> /// <param name="output">Output</param> public override void Format(in Instruction instruction, FormatterOutput output) { Debug.Assert((uint)instruction.Code < (uint)instrInfos.Length); var instrInfo = instrInfos[(int)instruction.Code]; instrInfo.GetOpInfo(options, instruction, out var opInfo); int column = 0; FormatMnemonic(instruction, output, opInfo, ref column, FormatMnemonicOptions.None); if (opInfo.OpCount != 0) { FormatterUtils.AddTabs(output, column, options.FirstOperandCharIndex, options.TabSize); FormatOperands(instruction, output, opInfo); } } void FormatMnemonic(in Instruction instruction, FormatterOutput output, in InstrOpInfo opInfo, ref int column, FormatMnemonicOptions mnemonicOptions) { if (output is null) ThrowHelper.ThrowArgumentNullException_output(); bool needSpace = false; if ((mnemonicOptions & FormatMnemonicOptions.NoPrefixes) == 0 && (opInfo.Flags & InstrOpInfoFlags.MnemonicIsDirective) == 0) { var prefixSeg = instruction.SegmentPrefix; const uint PrefixFlags = ((uint)InstrOpInfoFlags.SizeOverrideMask << (int)InstrOpInfoFlags.OpSizeShift) | ((uint)InstrOpInfoFlags.SizeOverrideMask << (int)InstrOpInfoFlags.AddrSizeShift) | (uint)InstrOpInfoFlags.BndPrefix; if (((uint)prefixSeg | instruction.HasAnyOf_Xacquire_Xrelease_Lock_Rep_Repne_Prefix | ((uint)opInfo.Flags & PrefixFlags)) != 0) { FormatterString prefix; prefix = opSizeStrings[((int)opInfo.Flags >> (int)InstrOpInfoFlags.OpSizeShift) & (int)InstrOpInfoFlags.SizeOverrideMask]; if (prefix.Length != 0) FormatPrefix(output, instruction, ref column, prefix, PrefixKind.OperandSize, ref needSpace); prefix = addrSizeStrings[((int)opInfo.Flags >> (int)InstrOpInfoFlags.AddrSizeShift) & (int)InstrOpInfoFlags.SizeOverrideMask]; if (prefix.Length != 0) FormatPrefix(output, instruction, ref column, prefix, PrefixKind.AddressSize, ref needSpace); bool hasNoTrackPrefix = prefixSeg == Register.DS && FormatterUtils.IsNotrackPrefixBranch(instruction.Code); if (!hasNoTrackPrefix && prefixSeg != Register.None && ShowSegmentPrefix(instruction, opInfo)) FormatPrefix(output, instruction, ref column, allRegisters[(int)prefixSeg], FormatterUtils.GetSegmentRegisterPrefixKind(prefixSeg), ref needSpace); if (instruction.HasXacquirePrefix) FormatPrefix(output, instruction, ref column, str_xacquire, PrefixKind.Xacquire, ref needSpace); if (instruction.HasXreleasePrefix) FormatPrefix(output, instruction, ref column, str_xrelease, PrefixKind.Xrelease, ref needSpace); if (instruction.HasLockPrefix) FormatPrefix(output, instruction, ref column, str_lock, PrefixKind.Lock, ref needSpace); if (hasNoTrackPrefix) FormatPrefix(output, instruction, ref column, str_notrack, PrefixKind.Notrack, ref needSpace); bool hasBnd = (opInfo.Flags & InstrOpInfoFlags.BndPrefix) != 0; if (hasBnd) FormatPrefix(output, instruction, ref column, str_bnd, PrefixKind.Bnd, ref needSpace); if (instruction.HasRepePrefix && FormatterUtils.ShowRepOrRepePrefix(instruction.Code, options)) { if (FormatterUtils.IsRepeOrRepneInstruction(instruction.Code)) FormatPrefix(output, instruction, ref column, MnemonicCC.GetMnemonicCC(options, 4, str_repe), PrefixKind.Repe, ref needSpace); else FormatPrefix(output, instruction, ref column, str_rep, PrefixKind.Rep, ref needSpace); } if (instruction.HasRepnePrefix && !hasBnd && FormatterUtils.ShowRepnePrefix(instruction.Code, options)) FormatPrefix(output, instruction, ref column, MnemonicCC.GetMnemonicCC(options, 5, str_repne), PrefixKind.Repne, ref needSpace); } } if ((mnemonicOptions & FormatMnemonicOptions.NoMnemonic) == 0) { if (needSpace) { output.Write(" ", FormatterTextKind.Text); column++; } var mnemonic = opInfo.Mnemonic; if ((opInfo.Flags & InstrOpInfoFlags.MnemonicIsDirective) != 0) { output.Write(mnemonic.Get(options.UppercaseKeywords || options.UppercaseAll), FormatterTextKind.Directive); } else { output.WriteMnemonic(instruction, mnemonic.Get(options.UppercaseMnemonics || options.UppercaseAll)); } column += mnemonic.Length; } } bool ShowSegmentPrefix(in Instruction instruction, in InstrOpInfo opInfo) { if ((opInfo.Flags & (InstrOpInfoFlags.JccNotTaken | InstrOpInfoFlags.JccTaken)) != 0) return true; switch (instruction.Code) { case Code.Monitorw: case Code.Monitord: case Code.Monitorq: case Code.Monitorxw: case Code.Monitorxd: case Code.Monitorxq: case Code.Clzerow: case Code.Clzerod: case Code.Clzeroq: case Code.Umonitor_r16: case Code.Umonitor_r32: case Code.Umonitor_r64: case Code.Maskmovq_rDI_mm_mm: case Code.Maskmovdqu_rDI_xmm_xmm: #if !NO_VEX case Code.VEX_Vmaskmovdqu_rDI_xmm_xmm: #endif case Code.Xlat_m8: case Code.Outsb_DX_m8: case Code.Outsw_DX_m16: case Code.Outsd_DX_m32: case Code.Movsb_m8_m8: case Code.Movsw_m16_m16: case Code.Movsd_m32_m32: case Code.Movsq_m64_m64: case Code.Cmpsb_m8_m8: case Code.Cmpsw_m16_m16: case Code.Cmpsd_m32_m32: case Code.Cmpsq_m64_m64: case Code.Lodsb_AL_m8: case Code.Lodsw_AX_m16: case Code.Lodsd_EAX_m32: case Code.Lodsq_RAX_m64: return FormatterUtils.ShowSegmentPrefix(Register.DS, instruction, options); default: break; } for (int i = 0; i < opInfo.OpCount; i++) { switch (opInfo.GetOpKind(i)) { case InstrOpKind.Register: case InstrOpKind.NearBranch16: case InstrOpKind.NearBranch32: case InstrOpKind.NearBranch64: case InstrOpKind.FarBranch16: case InstrOpKind.FarBranch32: case InstrOpKind.Immediate8: case InstrOpKind.Immediate8_2nd: case InstrOpKind.Immediate16: case InstrOpKind.Immediate32: case InstrOpKind.Immediate64: case InstrOpKind.Immediate8to16: case InstrOpKind.Immediate8to32: case InstrOpKind.Immediate8to64: case InstrOpKind.Immediate32to64: case InstrOpKind.MemoryESDI: case InstrOpKind.MemoryESEDI: case InstrOpKind.MemoryESRDI: case InstrOpKind.Sae: case InstrOpKind.RnSae: case InstrOpKind.RdSae: case InstrOpKind.RuSae: case InstrOpKind.RzSae: case InstrOpKind.DeclareByte: case InstrOpKind.DeclareWord: case InstrOpKind.DeclareDword: case InstrOpKind.DeclareQword: break; case InstrOpKind.MemorySegSI: case InstrOpKind.MemorySegESI: case InstrOpKind.MemorySegRSI: case InstrOpKind.MemorySegDI: case InstrOpKind.MemorySegEDI: case InstrOpKind.MemorySegRDI: case InstrOpKind.Memory64: case InstrOpKind.Memory: return false; default: throw new InvalidOperationException(); } } return options.ShowUselessPrefixes; } void FormatPrefix(FormatterOutput output, in Instruction instruction, ref int column, FormatterString prefix, PrefixKind prefixKind, ref bool needSpace) { if (needSpace) { column++; output.Write(" ", FormatterTextKind.Text); } output.WritePrefix(instruction, prefix.Get(options.UppercasePrefixes || options.UppercaseAll), prefixKind); column += prefix.Length; needSpace = true; } void FormatOperands(in Instruction instruction, FormatterOutput output, in InstrOpInfo opInfo) { if (output is null) ThrowHelper.ThrowArgumentNullException_output(); for (int i = 0; i < opInfo.OpCount; i++) { if (i > 0) { output.Write(",", FormatterTextKind.Punctuation); if (options.SpaceAfterOperandSeparator) output.Write(" ", FormatterTextKind.Text); } FormatOperand(instruction, output, opInfo, i); } } void FormatOperand(in Instruction instruction, FormatterOutput output, in InstrOpInfo opInfo, int operand) { Debug.Assert((uint)operand < (uint)opInfo.OpCount); if (output is null) ThrowHelper.ThrowArgumentNullException_output(); int instructionOperand = opInfo.GetInstructionIndex(operand); string s; FormatterFlowControl flowControl; byte imm8; ushort imm16; uint imm32; ulong imm64, value64; int immSize; NumberFormattingOptions numberOptions; SymbolResult symbol; ISymbolResolver? symbolResolver; FormatterOperandOptions operandOptions; NumberKind numberKind; var opKind = opInfo.GetOpKind(operand); switch (opKind) { case InstrOpKind.Register: if ((opInfo.Flags & InstrOpInfoFlags.RegisterTo) != 0) { FormatKeyword(output, str_to); output.Write(" ", FormatterTextKind.Text); } FormatRegister(output, instruction, operand, instructionOperand, opInfo.GetOpRegister(operand)); break; case InstrOpKind.NearBranch16: case InstrOpKind.NearBranch32: case InstrOpKind.NearBranch64: if (opKind == InstrOpKind.NearBranch64) { immSize = 8; imm64 = instruction.NearBranch64; numberKind = NumberKind.UInt64; } else if (opKind == InstrOpKind.NearBranch32) { immSize = 4; imm64 = instruction.NearBranch32; numberKind = NumberKind.UInt32; } else { immSize = 2; imm64 = instruction.NearBranch16; numberKind = NumberKind.UInt16; } numberOptions = NumberFormattingOptions.CreateBranchInternal(options); operandOptions = new FormatterOperandOptions(options.ShowBranchSize ? FormatterOperandOptions.Flags.None : FormatterOperandOptions.Flags.NoBranchSize); optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm64, immSize, out symbol)) { FormatFlowControl(output, opInfo.Flags, operandOptions); output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm64, symbol, options.ShowSymbolAddress); } else { operandOptions = new FormatterOperandOptions(options.ShowBranchSize ? FormatterOperandOptions.Flags.None : FormatterOperandOptions.Flags.NoBranchSize); optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); flowControl = FormatterUtils.GetFlowControl(instruction); FormatFlowControl(output, opInfo.Flags, operandOptions); if (opKind == InstrOpKind.NearBranch32) s = numberFormatter.FormatUInt32(options, numberOptions, instruction.NearBranch32, numberOptions.LeadingZeroes); else if (opKind == InstrOpKind.NearBranch64) s = numberFormatter.FormatUInt64(options, numberOptions, instruction.NearBranch64, numberOptions.LeadingZeroes); else s = numberFormatter.FormatUInt16(options, numberOptions, instruction.NearBranch16, numberOptions.LeadingZeroes); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterUtils.IsCall(flowControl) ? FormatterTextKind.FunctionAddress : FormatterTextKind.LabelAddress); } break; case InstrOpKind.FarBranch16: case InstrOpKind.FarBranch32: if (opKind == InstrOpKind.FarBranch32) { immSize = 4; imm64 = instruction.FarBranch32; numberKind = NumberKind.UInt32; } else { immSize = 2; imm64 = instruction.FarBranch16; numberKind = NumberKind.UInt16; } numberOptions = NumberFormattingOptions.CreateBranchInternal(options); operandOptions = new FormatterOperandOptions(options.ShowBranchSize ? FormatterOperandOptions.Flags.None : FormatterOperandOptions.Flags.NoBranchSize); optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, (uint)imm64, immSize, out symbol)) { FormatFlowControl(output, opInfo.Flags, operandOptions); Debug.Assert(operand + 1 == 1); if (!symbolResolver.TryGetSymbol(instruction, operand + 1, instructionOperand, instruction.FarBranchSelector, 2, out var selectorSymbol)) { s = numberFormatter.FormatUInt16(options, numberOptions, instruction.FarBranchSelector, numberOptions.LeadingZeroes); output.WriteNumber(instruction, operand, instructionOperand, s, instruction.FarBranchSelector, NumberKind.UInt16, FormatterTextKind.SelectorValue); } else output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, instruction.FarBranchSelector, selectorSymbol, options.ShowSymbolAddress); output.Write(":", FormatterTextKind.Punctuation); output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm64, symbol, options.ShowSymbolAddress); } else { flowControl = FormatterUtils.GetFlowControl(instruction); FormatFlowControl(output, opInfo.Flags, operandOptions); s = numberFormatter.FormatUInt16(options, numberOptions, instruction.FarBranchSelector, numberOptions.LeadingZeroes); output.WriteNumber(instruction, operand, instructionOperand, s, instruction.FarBranchSelector, NumberKind.UInt16, FormatterTextKind.SelectorValue); output.Write(":", FormatterTextKind.Punctuation); if (opKind == InstrOpKind.FarBranch32) s = numberFormatter.FormatUInt32(options, numberOptions, instruction.FarBranch32, numberOptions.LeadingZeroes); else s = numberFormatter.FormatUInt16(options, numberOptions, instruction.FarBranch16, numberOptions.LeadingZeroes); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterUtils.IsCall(flowControl) ? FormatterTextKind.FunctionAddress : FormatterTextKind.LabelAddress); } break; case InstrOpKind.Immediate8: case InstrOpKind.Immediate8_2nd: case InstrOpKind.DeclareByte: if (opKind == InstrOpKind.Immediate8) imm8 = instruction.Immediate8; else if (opKind == InstrOpKind.Immediate8_2nd) imm8 = instruction.Immediate8_2nd; else imm8 = instruction.GetDeclareByteValue(operand); numberOptions = NumberFormattingOptions.CreateImmediateInternal(options); operandOptions = default; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm8, 1, out symbol)) output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm8, symbol, options.ShowSymbolAddress); else { if (numberOptions.SignedNumber) { imm64 = (ulong)(sbyte)imm8; numberKind = NumberKind.Int8; if ((sbyte)imm8 < 0) { output.Write("-", FormatterTextKind.Operator); imm8 = (byte)-(sbyte)imm8; } } else { imm64 = imm8; numberKind = NumberKind.UInt8; } s = numberFormatter.FormatUInt8(options, numberOptions, imm8); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterTextKind.Number); } break; case InstrOpKind.Immediate16: case InstrOpKind.Immediate8to16: case InstrOpKind.DeclareWord: ShowSignExtendInfo(output, opInfo.Flags); if (opKind == InstrOpKind.Immediate16) imm16 = instruction.Immediate16; else if (opKind == InstrOpKind.Immediate8to16) imm16 = (ushort)instruction.Immediate8to16; else imm16 = instruction.GetDeclareWordValue(operand); numberOptions = NumberFormattingOptions.CreateImmediateInternal(options); operandOptions = default; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm16, 2, out symbol)) output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm16, symbol, options.ShowSymbolAddress); else { if (numberOptions.SignedNumber) { imm64 = (ulong)(short)imm16; numberKind = NumberKind.Int16; if ((short)imm16 < 0) { output.Write("-", FormatterTextKind.Operator); imm16 = (ushort)-(short)imm16; } } else { imm64 = imm16; numberKind = NumberKind.UInt16; } s = numberFormatter.FormatUInt16(options, numberOptions, imm16); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterTextKind.Number); } break; case InstrOpKind.Immediate32: case InstrOpKind.Immediate8to32: case InstrOpKind.DeclareDword: ShowSignExtendInfo(output, opInfo.Flags); if (opKind == InstrOpKind.Immediate32) imm32 = instruction.Immediate32; else if (opKind == InstrOpKind.Immediate8to32) imm32 = (uint)instruction.Immediate8to32; else imm32 = instruction.GetDeclareDwordValue(operand); numberOptions = NumberFormattingOptions.CreateImmediateInternal(options); operandOptions = default; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm32, 4, out symbol)) output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm32, symbol, options.ShowSymbolAddress); else { if (numberOptions.SignedNumber) { imm64 = (ulong)(int)imm32; numberKind = NumberKind.Int32; if ((int)imm32 < 0) { output.Write("-", FormatterTextKind.Operator); imm32 = (uint)-(int)imm32; } } else { imm64 = imm32; numberKind = NumberKind.UInt32; } s = numberFormatter.FormatUInt32(options, numberOptions, imm32); output.WriteNumber(instruction, operand, instructionOperand, s, imm64, numberKind, FormatterTextKind.Number); } break; case InstrOpKind.Immediate64: case InstrOpKind.Immediate8to64: case InstrOpKind.Immediate32to64: case InstrOpKind.DeclareQword: ShowSignExtendInfo(output, opInfo.Flags); if (opKind == InstrOpKind.Immediate32to64) imm64 = (ulong)instruction.Immediate32to64; else if (opKind == InstrOpKind.Immediate8to64) imm64 = (ulong)instruction.Immediate8to64; else if (opKind == InstrOpKind.Immediate64) imm64 = instruction.Immediate64; else imm64 = instruction.GetDeclareQwordValue(operand); numberOptions = NumberFormattingOptions.CreateImmediateInternal(options); operandOptions = default; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); if ((symbolResolver = this.symbolResolver) is not null && symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, imm64, 8, out symbol)) output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, imm64, symbol, options.ShowSymbolAddress); else { value64 = imm64; if (numberOptions.SignedNumber) { numberKind = NumberKind.Int64; if ((long)imm64 < 0) { output.Write("-", FormatterTextKind.Operator); imm64 = (ulong)-(long)imm64; } } else numberKind = NumberKind.UInt64; s = numberFormatter.FormatUInt64(options, numberOptions, imm64); output.WriteNumber(instruction, operand, instructionOperand, s, value64, numberKind, FormatterTextKind.Number); } break; case InstrOpKind.MemorySegSI: FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, instruction.MemorySegment, Register.SI, Register.None, 0, 0, 0, 2, opInfo.Flags); break; case InstrOpKind.MemorySegESI: FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, instruction.MemorySegment, Register.ESI, Register.None, 0, 0, 0, 4, opInfo.Flags); break; case InstrOpKind.MemorySegRSI: FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, instruction.MemorySegment, Register.RSI, Register.None, 0, 0, 0, 8, opInfo.Flags); break; case InstrOpKind.MemorySegDI: FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, instruction.MemorySegment, Register.DI, Register.None, 0, 0, 0, 2, opInfo.Flags); break; case InstrOpKind.MemorySegEDI: FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, instruction.MemorySegment, Register.EDI, Register.None, 0, 0, 0, 4, opInfo.Flags); break; case InstrOpKind.MemorySegRDI: FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, instruction.MemorySegment, Register.RDI, Register.None, 0, 0, 0, 8, opInfo.Flags); break; case InstrOpKind.MemoryESDI: FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, Register.ES, Register.DI, Register.None, 0, 0, 0, 2, opInfo.Flags); break; case InstrOpKind.MemoryESEDI: FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, Register.ES, Register.EDI, Register.None, 0, 0, 0, 4, opInfo.Flags); break; case InstrOpKind.MemoryESRDI: FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, Register.ES, Register.RDI, Register.None, 0, 0, 0, 8, opInfo.Flags); break; case InstrOpKind.Memory64: break; case InstrOpKind.Memory: int displSize = instruction.MemoryDisplSize; var baseReg = instruction.MemoryBase; var indexReg = instruction.MemoryIndex; int addrSize = InstructionUtils.GetAddressSizeInBytes(baseReg, indexReg, displSize, instruction.CodeSize); long displ; if (addrSize == 8) displ = (long)instruction.MemoryDisplacement64; else displ = instruction.MemoryDisplacement32; FormatMemory(output, instruction, operand, instructionOperand, opInfo.MemorySize, instruction.MemorySegment, baseReg, indexReg, instruction.InternalMemoryIndexScale, displSize, displ, addrSize, opInfo.Flags); break; case InstrOpKind.Sae: FormatDecorator(output, instruction, operand, instructionOperand, str_sae, DecoratorKind.SuppressAllExceptions); break; case InstrOpKind.RnSae: FormatDecorator(output, instruction, operand, instructionOperand, str_rn_sae, DecoratorKind.RoundingControl); break; case InstrOpKind.RdSae: FormatDecorator(output, instruction, operand, instructionOperand, str_rd_sae, DecoratorKind.RoundingControl); break; case InstrOpKind.RuSae: FormatDecorator(output, instruction, operand, instructionOperand, str_ru_sae, DecoratorKind.RoundingControl); break; case InstrOpKind.RzSae: FormatDecorator(output, instruction, operand, instructionOperand, str_rz_sae, DecoratorKind.RoundingControl); break; default: throw new InvalidOperationException(); } if (operand == 0) { if (instruction.HasOpMask) { output.Write("{", FormatterTextKind.Punctuation); FormatRegister(output, instruction, operand, instructionOperand, (int)instruction.OpMask); output.Write("}", FormatterTextKind.Punctuation); } if (instruction.ZeroingMasking) FormatDecorator(output, instruction, operand, instructionOperand, str_z, DecoratorKind.ZeroingMasking); } } void ShowSignExtendInfo(FormatterOutput output, InstrOpInfoFlags flags) { if (!options.NasmShowSignExtendedImmediateSize) return; FormatterString keyword; switch ((SignExtendInfo)(((int)flags >> (int)InstrOpInfoFlags.SignExtendInfoShift) & (int)InstrOpInfoFlags.SignExtendInfoMask)) { case SignExtendInfo.None: return; case SignExtendInfo.Sex1to2: case SignExtendInfo.Sex1to4: case SignExtendInfo.Sex1to8: keyword = str_byte; break; case SignExtendInfo.Sex2: keyword = str_word; break; case SignExtendInfo.Sex4: keyword = str_dword; break; case SignExtendInfo.Sex4to8: keyword = str_qword; break; default: throw new InvalidOperationException(); } FormatKeyword(output, keyword); output.Write(" ", FormatterTextKind.Text); } void FormatFlowControl(FormatterOutput output, InstrOpInfoFlags flags, FormatterOperandOptions operandOptions) { if (!operandOptions.BranchSize) return; var keywords = branchInfos[((int)flags >> (int)InstrOpInfoFlags.BranchSizeInfoShift) & (int)InstrOpInfoFlags.BranchSizeInfoMask]; if (keywords is null) return; foreach (var keyword in keywords) { FormatKeyword(output, keyword); output.Write(" ", FormatterTextKind.Text); } } void FormatDecorator(FormatterOutput output, in Instruction instruction, int operand, int instructionOperand, FormatterString text, DecoratorKind decorator) { output.Write("{", FormatterTextKind.Punctuation); output.WriteDecorator(instruction, operand, instructionOperand, text.Get(options.UppercaseDecorators || options.UppercaseAll), decorator); output.Write("}", FormatterTextKind.Punctuation); } [MethodImpl(MethodImplOptions.AggressiveInlining)] string ToRegisterString(int regNum) { Debug.Assert((uint)regNum < (uint)allRegisters.Length); var regStr = allRegisters[(int)regNum]; return regStr.Get(options.UppercaseRegisters || options.UppercaseAll); } [MethodImpl(MethodImplOptions.NoInlining)] void FormatRegister(FormatterOutput output, in Instruction instruction, int operand, int instructionOperand, int regNum) { Static.Assert(Registers.ExtraRegisters == 0 ? 0 : -1); output.WriteRegister(instruction, operand, instructionOperand, ToRegisterString(regNum), (Register)regNum); } void FormatMemory(FormatterOutput output, in Instruction instruction, int operand, int instructionOperand, MemorySize memSize, Register segReg, Register baseReg, Register indexReg, int scale, int displSize, long displ, int addrSize, InstrOpInfoFlags flags) { Debug.Assert((uint)scale < (uint)scaleNumbers.Length); Debug.Assert(InstructionUtils.GetAddressSizeInBytes(baseReg, indexReg, displSize, instruction.CodeSize) == addrSize); var numberOptions = NumberFormattingOptions.CreateDisplacementInternal(options); SymbolResult symbol; bool useSymbol; var operandOptions = new FormatterOperandOptions(options.MemorySizeOptions); operandOptions.RipRelativeAddresses = options.RipRelativeAddresses; optionsProvider?.GetOperandOptions(instruction, operand, instructionOperand, ref operandOptions, ref numberOptions); ulong absAddr; bool addRelKeyword = false; if (baseReg == Register.RIP) { absAddr = (ulong)displ; if (options.RipRelativeAddresses) displ -= (long)instruction.NextIP; else { Debug.Assert(indexReg == Register.None); baseReg = Register.None; flags &= ~(InstrOpInfoFlags)((uint)InstrOpInfoFlags.MemorySizeInfoMask << (int)InstrOpInfoFlags.MemorySizeInfoShift); addRelKeyword = true; } displSize = 8; } else if (baseReg == Register.EIP) { absAddr = (uint)displ; if (options.RipRelativeAddresses) displ = (int)((uint)displ - instruction.NextIP32); else { Debug.Assert(indexReg == Register.None); baseReg = Register.None; flags = (flags & ~(InstrOpInfoFlags)((uint)InstrOpInfoFlags.MemorySizeInfoMask << (int)InstrOpInfoFlags.MemorySizeInfoShift)) | (InstrOpInfoFlags)((int)NasmFormatterInternal.MemorySizeInfo.Dword << (int)InstrOpInfoFlags.MemorySizeInfoShift); addRelKeyword = true; } displSize = 4; } else absAddr = (ulong)displ; if (this.symbolResolver is ISymbolResolver symbolResolver) useSymbol = symbolResolver.TryGetSymbol(instruction, operand, instructionOperand, absAddr, addrSize, out symbol); else { useSymbol = false; symbol = default; } bool useScale = scale != 0 || options.AlwaysShowScale; if (!useScale) { // [rsi] = base reg, [rsi*1] = index reg if (baseReg == Register.None) useScale = true; } if (addrSize == 2 || !FormatterUtils.ShowIndexScale(instruction, options)) useScale = false; FormatMemorySize(output, memSize, flags, operandOptions); output.Write("[", FormatterTextKind.Punctuation); if (options.SpaceAfterMemoryBracket) output.Write(" ", FormatterTextKind.Text); var memSizeName = memSizeInfos[((int)flags >> (int)InstrOpInfoFlags.MemorySizeInfoShift) & (int)InstrOpInfoFlags.MemorySizeInfoMask]; if (memSizeName.Length != 0) { FormatKeyword(output, memSizeName); output.Write(" ", FormatterTextKind.Text); } if (addRelKeyword) { FormatKeyword(output, str_rel); output.Write(" ", FormatterTextKind.Text); } var codeSize = instruction.CodeSize; var segOverride = instruction.SegmentPrefix; bool noTrackPrefix = segOverride == Register.DS && FormatterUtils.IsNotrackPrefixBranch(instruction.Code) && !((codeSize == CodeSize.Code16 || codeSize == CodeSize.Code32) && (baseReg == Register.BP || baseReg == Register.EBP || baseReg == Register.ESP)); if (options.AlwaysShowSegmentRegister || (segOverride != Register.None && !noTrackPrefix && FormatterUtils.ShowSegmentPrefix(Register.None, instruction, options))) { FormatRegister(output, instruction, operand, instructionOperand, (int)segReg); output.Write(":", FormatterTextKind.Punctuation); } bool needPlus = false; if (baseReg != Register.None) { FormatRegister(output, instruction, operand, instructionOperand, (int)baseReg); needPlus = true; } if (indexReg != Register.None) { if (needPlus) { if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); output.Write("+", FormatterTextKind.Operator); if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); } needPlus = true; if (!useScale) FormatRegister(output, instruction, operand, instructionOperand, (int)indexReg); else if (options.ScaleBeforeIndex) { output.WriteNumber(instruction, operand, instructionOperand, scaleNumbers[scale], 1U << scale, NumberKind.Int32, FormatterTextKind.Number); if (options.SpaceBetweenMemoryMulOperators) output.Write(" ", FormatterTextKind.Text); output.Write("*", FormatterTextKind.Operator); if (options.SpaceBetweenMemoryMulOperators) output.Write(" ", FormatterTextKind.Text); FormatRegister(output, instruction, operand, instructionOperand, (int)indexReg); } else { FormatRegister(output, instruction, operand, instructionOperand, (int)indexReg); if (options.SpaceBetweenMemoryMulOperators) output.Write(" ", FormatterTextKind.Text); output.Write("*", FormatterTextKind.Operator); if (options.SpaceBetweenMemoryMulOperators) output.Write(" ", FormatterTextKind.Text); output.WriteNumber(instruction, operand, instructionOperand, scaleNumbers[scale], 1U << scale, NumberKind.Int32, FormatterTextKind.Number); } } if (useSymbol) { if (needPlus) { if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); if ((symbol.Flags & SymbolFlags.Signed) != 0) output.Write("-", FormatterTextKind.Operator); else output.Write("+", FormatterTextKind.Operator); if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); } else if ((symbol.Flags & SymbolFlags.Signed) != 0) output.Write("-", FormatterTextKind.Operator); output.Write(instruction, operand, instructionOperand, options, numberFormatter, numberOptions, absAddr, symbol, options.ShowSymbolAddress, false, options.SpaceBetweenMemoryAddOperators); } else if (!needPlus || (displSize != 0 && (options.ShowZeroDisplacements || displ != 0))) { ulong origDispl = (ulong)displ; bool isSigned; if (needPlus) { isSigned = numberOptions.SignedNumber; if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); if (addrSize == 8) { if (!numberOptions.SignedNumber) output.Write("+", FormatterTextKind.Operator); else if (displ < 0) { displ = -displ; output.Write("-", FormatterTextKind.Operator); } else output.Write("+", FormatterTextKind.Operator); if (numberOptions.DisplacementLeadingZeroes) { Debug.Assert(displSize <= 8); displSize = 8; } } else if (addrSize == 4) { if (!numberOptions.SignedNumber) output.Write("+", FormatterTextKind.Operator); else if ((int)displ < 0) { displ = (uint)-(int)displ; output.Write("-", FormatterTextKind.Operator); } else output.Write("+", FormatterTextKind.Operator); if (numberOptions.DisplacementLeadingZeroes) { Debug.Assert(displSize <= 4); displSize = 4; } } else { Debug.Assert(addrSize == 2); if (!numberOptions.SignedNumber) output.Write("+", FormatterTextKind.Operator); else if ((short)displ < 0) { displ = (ushort)-(short)displ; output.Write("-", FormatterTextKind.Operator); } else output.Write("+", FormatterTextKind.Operator); if (numberOptions.DisplacementLeadingZeroes) { Debug.Assert(displSize <= 2); displSize = 2; } } if (options.SpaceBetweenMemoryAddOperators) output.Write(" ", FormatterTextKind.Text); } else isSigned = false; NumberKind displKind; string s; if (displSize <= 1 && (ulong)displ <= byte.MaxValue) { s = numberFormatter.FormatUInt8(options, numberOptions, (byte)displ); displKind = isSigned ? NumberKind.Int8 : NumberKind.UInt8; } else if (displSize <= 2 && (ulong)displ <= ushort.MaxValue) { s = numberFormatter.FormatUInt16(options, numberOptions, (ushort)displ); displKind = isSigned ? NumberKind.Int16 : NumberKind.UInt16; } else if (displSize <= 4 && (ulong)displ <= uint.MaxValue) { s = numberFormatter.FormatUInt32(options, numberOptions, (uint)displ); displKind = isSigned ? NumberKind.Int32 : NumberKind.UInt32; } else if (displSize <= 8) { s = numberFormatter.FormatUInt64(options, numberOptions, (ulong)displ); displKind = isSigned ? NumberKind.Int64 : NumberKind.UInt64; } else throw new InvalidOperationException(); output.WriteNumber(instruction, operand, instructionOperand, s, origDispl, displKind, FormatterTextKind.Number); } if (options.SpaceAfterMemoryBracket) output.Write(" ", FormatterTextKind.Text); output.Write("]", FormatterTextKind.Punctuation); Debug.Assert((uint)memSize < (uint)allMemorySizes.Length); var bcstTo = allMemorySizes[(int)memSize].bcstTo; if (bcstTo.Length != 0) FormatDecorator(output, instruction, operand, instructionOperand, bcstTo, DecoratorKind.Broadcast); } void FormatMemorySize(FormatterOutput output, MemorySize memSize, InstrOpInfoFlags flags, FormatterOperandOptions operandOptions) { var memSizeOptions = operandOptions.MemorySizeOptions; if (memSizeOptions == MemorySizeOptions.Never) return; if ((flags & InstrOpInfoFlags.MemSize_Nothing) != 0) return; Debug.Assert((uint)memSize < (uint)allMemorySizes.Length); var memInfo = allMemorySizes[(int)memSize]; var keyword = memInfo.keyword; if (keyword.Length == 0) return; if (memSizeOptions == MemorySizeOptions.Default) { if ((flags & InstrOpInfoFlags.ShowNoMemSize_ForceSize) == 0) return; } else if (memSizeOptions == MemorySizeOptions.Minimal) { if ((flags & InstrOpInfoFlags.ShowMinMemSize_ForceSize) == 0) return; } else Debug.Assert(memSizeOptions == MemorySizeOptions.Always); var farKind = farMemSizeInfos[((int)flags >> (int)InstrOpInfoFlags.FarMemorySizeInfoShift) & (int)InstrOpInfoFlags.FarMemorySizeInfoMask]; if (farKind.Length != 0) { FormatKeyword(output, farKind); output.Write(" ", FormatterTextKind.Text); } FormatKeyword(output, keyword); output.Write(" ", FormatterTextKind.Text); } void FormatKeyword(FormatterOutput output, FormatterString keyword) => output.Write(keyword.Get(options.UppercaseKeywords || options.UppercaseAll), FormatterTextKind.Keyword); /// <summary> /// Formats a register /// </summary> /// <param name="register">Register</param> /// <returns></returns> public override string Format(Register register) => ToRegisterString((int)register); /// <summary> /// Formats a <see cref="sbyte"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatInt8(sbyte value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatInt8(options, numberOptions, value); /// <summary> /// Formats a <see cref="short"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatInt16(short value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatInt16(options, numberOptions, value); /// <summary> /// Formats a <see cref="int"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatInt32(int value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatInt32(options, numberOptions, value); /// <summary> /// Formats a <see cref="long"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatInt64(long value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatInt64(options, numberOptions, value); /// <summary> /// Formats a <see cref="byte"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatUInt8(byte value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatUInt8(options, numberOptions, value); /// <summary> /// Formats a <see cref="ushort"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatUInt16(ushort value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatUInt16(options, numberOptions, value); /// <summary> /// Formats a <see cref="uint"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatUInt32(uint value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatUInt32(options, numberOptions, value); /// <summary> /// Formats a <see cref="ulong"/> /// </summary> /// <param name="value">Value</param> /// <param name="numberOptions">Options</param> /// <returns></returns> public override string FormatUInt64(ulong value, in NumberFormattingOptions numberOptions) => numberFormatter.FormatUInt64(options, numberOptions, value); } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond { using System; // Tag types used to annotate Bond schema types via Type attribute // ReSharper disable InconsistentNaming // ReSharper disable UnusedTypeParameter namespace Tag { /// <summary> /// Represents wstring Bond schema type /// </summary> public abstract class wstring { } /// <summary> /// Represents blob Bond schema type /// </summary> public abstract class blob { } /// <summary> /// Represents nullable&lt;T> Bond schema type /// </summary> public abstract class nullable<T> { } /// <summary> /// Represents bonded&lt;T> Bond schema type /// </summary> public abstract class bonded<T> { } /// <summary> /// Represents a type parameter constrained to value types /// </summary> public struct structT { } /// <summary> /// Represents unconstrained type parameter /// </summary> public abstract class classT { } } // ReSharper restore InconsistentNaming // ReSharper restore UnusedTypeParameter /// <summary> /// Specifies that a type represents Bond schema /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] public sealed class SchemaAttribute : Attribute { } /// <summary> /// Specifies namespace of the schema, required only if different than C# namespace of the class /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum, Inherited = false)] public sealed class NamespaceAttribute : Attribute { public NamespaceAttribute(string value) { Value = value; } internal string Value { get; private set; } } /// <summary> /// Specifies field identifier. Required for all Bond fields /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class IdAttribute : Attribute { public IdAttribute(ushort id) { Value = id; } internal ushort Value { get; private set; } } /// <summary> /// Specifies type of a field in Bond schema /// </summary> /// <remarks> /// If absent the type is inferred from C# type using the following rules: /// - numeric types map in the obvious way /// - IList, ICollection -> BT_LIST /// - IDictionary -> BT_MAP /// - ISet -> BT_SET /// - string -> BT_STRING (Utf8) /// - Bond struct fields initialized to null map to nullable /// - other fields initialized to null map to default of nothing /// The Type attribute is necessary in the following cases: /// - nullable types, e.g. Type[typeof(list&lt;nullable&lt;string>>)] /// - Utf16 string (BT_WSTRING), e.g. Type[typeof(wstring)] /// - user specified type aliases /// </remarks> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class TypeAttribute : Attribute { public TypeAttribute(Type type) { Value = type; } internal Type Value { get; private set; } } /// <summary> /// Specifies the default value of a field /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class DefaultAttribute : Attribute { public DefaultAttribute(object value) { Value = value; } public object Value { get; private set; } } /// <summary> /// Specifies that a field is required /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class RequiredAttribute : Attribute { } /// <summary> /// Specifies that a field is required_optional /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class RequiredOptionalAttribute : Attribute { } /// <summary> /// Specifies user defined schema attribute /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = false)] public sealed class AttributeAttribute : Attribute { public AttributeAttribute(string name, string value) { Name = name; Value = value; } public string Name { get; private set; } public string Value { get; private set; } } /// <summary> /// Applied to protocol readers to indicate the IParser implementation used for parsing the protocol /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class ParserAttribute : Attribute { public ParserAttribute(Type parserType) { ParserType = parserType; } internal Type ParserType { get; private set; } } /// <summary> /// Applied to protocol writers to indicate the reader type for the protocol /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class ReaderAttribute : Attribute { public ReaderAttribute(Type readerType) { ReaderType = readerType; } internal Type ReaderType { get; private set; } } /// <summary> /// Applied to protocol writers to indicate the implementation of ISerializerGenerator used to generate serializer /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class SerializerAttribute : Attribute { public SerializerAttribute(Type type) { Type = type; } internal Type Type { get; private set; } } /// <summary> /// Applied to 2-pass protocol writers to indicate the implementation of IProtocolWriter used to generate the first-pass serializer /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class FirstPassWriterAttribute : Attribute { public FirstPassWriterAttribute(Type type) { Type = type; } internal Type Type { get; private set; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { /// <summary> /// CA1019: Define accessors for attribute arguments /// /// Cause: /// In its constructor, an attribute defines arguments that do not have corresponding properties. /// </summary> public abstract class DefineAccessorsForAttributeArgumentsAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1019"; internal const string AddAccessorCase = "AddAccessor"; internal const string MakePublicCase = "MakePublic"; internal const string RemoveSetterCase = "RemoveSetter"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.DefineAccessorsForAttributeArgumentsTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_defaultRuleMessage = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.DefineAccessorsForAttributeArgumentsMessageDefault), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_increaseVisibilityMessage = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.DefineAccessorsForAttributeArgumentsMessageIncreaseVisibility), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_removeSetterMessage = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.DefineAccessorsForAttributeArgumentsMessageRemoveSetter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); internal static DiagnosticDescriptor DefaultRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_defaultRuleMessage, DiagnosticCategory.Design, RuleLevel.Disabled, description: null, isPortedFxCopRule: true, isDataflowRule: false, isEnabledByDefaultInFxCopAnalyzers: false); internal static DiagnosticDescriptor IncreaseVisibilityRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_increaseVisibilityMessage, DiagnosticCategory.Design, RuleLevel.Disabled, description: null, isPortedFxCopRule: true, isDataflowRule: false, isEnabledByDefaultInFxCopAnalyzers: false); internal static DiagnosticDescriptor RemoveSetterRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_removeSetterMessage, DiagnosticCategory.Design, RuleLevel.Disabled, description: null, isPortedFxCopRule: true, isDataflowRule: false, isEnabledByDefaultInFxCopAnalyzers: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule, IncreaseVisibilityRule, RemoveSetterRule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterCompilationStartAction(compilationContext => { INamedTypeSymbol? attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute); if (attributeType == null) { return; } compilationContext.RegisterSymbolAction(context => { AnalyzeSymbol((INamedTypeSymbol)context.Symbol, attributeType, context.Compilation, context.ReportDiagnostic); }, SymbolKind.NamedType); }); } private void AnalyzeSymbol(INamedTypeSymbol symbol, INamedTypeSymbol attributeType, Compilation compilation, Action<Diagnostic> addDiagnostic) { if (symbol != null && symbol.GetBaseTypesAndThis().Contains(attributeType) && symbol.DeclaredAccessibility != Accessibility.Private) { IEnumerable<IParameterSymbol> parametersToCheck = GetAllPublicConstructorParameters(symbol); if (parametersToCheck.Any()) { IDictionary<string, IPropertySymbol> propertiesMap = GetAllPropertiesInTypeChain(symbol); AnalyzeParameters(compilation, parametersToCheck, propertiesMap, symbol, addDiagnostic); } } } protected abstract bool IsAssignableTo( [NotNullWhen(returnValue: true)] ITypeSymbol? fromSymbol, [NotNullWhen(returnValue: true)] ITypeSymbol? toSymbol, Compilation compilation); private static IEnumerable<IParameterSymbol> GetAllPublicConstructorParameters(INamedTypeSymbol attributeType) { // FxCop compatibility: // Only examine parameters of public constructors. Can't use protected // constructors to define an attribute so this rule only applies to // public constructors. IEnumerable<IMethodSymbol> instanceConstructorsToCheck = attributeType.InstanceConstructors.Where(c => c.DeclaredAccessibility == Accessibility.Public); if (instanceConstructorsToCheck.Any()) { var uniqueParamNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (IMethodSymbol constructor in instanceConstructorsToCheck) { foreach (IParameterSymbol parameter in constructor.Parameters) { if (uniqueParamNames.Add(parameter.Name)) { yield return parameter; } } } } } private static IDictionary<string, IPropertySymbol> GetAllPropertiesInTypeChain(INamedTypeSymbol attributeType) { var propertiesMap = new Dictionary<string, IPropertySymbol>(StringComparer.OrdinalIgnoreCase); foreach (INamedTypeSymbol currentType in attributeType.GetBaseTypesAndThis()) { foreach (IPropertySymbol property in currentType.GetMembers().Where(m => m.Kind == SymbolKind.Property)) { if (!propertiesMap.ContainsKey(property.Name)) { propertiesMap.Add(property.Name, property); } } } return propertiesMap; } private void AnalyzeParameters(Compilation compilation, IEnumerable<IParameterSymbol> parameters, IDictionary<string, IPropertySymbol> propertiesMap, INamedTypeSymbol attributeType, Action<Diagnostic> addDiagnostic) { foreach (IParameterSymbol parameter in parameters) { if (parameter.Type.Kind != SymbolKind.ErrorType) { if (!propertiesMap.TryGetValue(parameter.Name, out IPropertySymbol property) || !IsAssignableTo(parameter.Type, property.Type, compilation)) { // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'. addDiagnostic(GetDefaultDiagnostic(parameter, attributeType)); } else { if (property.GetMethod == null) { // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'. addDiagnostic(GetDefaultDiagnostic(parameter, attributeType)); } else if (property.DeclaredAccessibility != Accessibility.Public || property.GetMethod.DeclaredAccessibility != Accessibility.Public) { if (!property.ContainingType.Equals(attributeType)) { // A non-public getter exists in one of the base types. // However, we cannot be sure if the user can modify the base type (it could be from a third party library). // So generate the default diagnostic instead of increase visibility here. // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'. addDiagnostic(GetDefaultDiagnostic(parameter, attributeType)); } else { // If '{0}' is the property accessor for positional argument '{1}', make it public. addDiagnostic(GetIncreaseVisibilityDiagnostic(parameter, property)); } } if (property.SetMethod != null && property.SetMethod.DeclaredAccessibility == Accessibility.Public && Equals(property.ContainingType, attributeType)) { // Remove the property setter from '{0}' or reduce its accessibility because it corresponds to positional argument '{1}'. addDiagnostic(GetRemoveSetterDiagnostic(parameter, property)); } } } } } private static Diagnostic GetDefaultDiagnostic(IParameterSymbol parameter, INamedTypeSymbol attributeType) { // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'. return parameter.Locations.CreateDiagnostic(DefaultRule, new Dictionary<string, string?> { { "case", AddAccessorCase } }.ToImmutableDictionary(), parameter.Name, attributeType.Name); } private static Diagnostic GetIncreaseVisibilityDiagnostic(IParameterSymbol parameter, IPropertySymbol property) { // If '{0}' is the property accessor for positional argument '{1}', make it public. return property.GetMethod.Locations.CreateDiagnostic(IncreaseVisibilityRule, new Dictionary<string, string?> { { "case", MakePublicCase } }.ToImmutableDictionary(), property.Name, parameter.Name); } private static Diagnostic GetRemoveSetterDiagnostic(IParameterSymbol parameter, IPropertySymbol property) { // Remove the property setter from '{0}' or reduce its accessibility because it corresponds to positional argument '{1}'. return property.SetMethod.Locations.CreateDiagnostic(RemoveSetterRule, new Dictionary<string, string?> { { "case", RemoveSetterCase } }.ToImmutableDictionary(), property.Name, parameter.Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; using System.Globalization; namespace System.Drawing { // Miscellaneous utilities internal static class ClientUtils { // ExecutionEngineException is obsolete and shouldn't be used (to catch, throw or reference) anymore. // Pragma added to prevent converting the "type is obsolete" warning into build error. // File owner should fix this. #pragma warning disable 618 public static bool IsCriticalException(Exception ex) { return ex is NullReferenceException || ex is StackOverflowException || ex is OutOfMemoryException || ex is System.Threading.ThreadAbortException || ex is ExecutionEngineException || ex is IndexOutOfRangeException || ex is AccessViolationException; } #pragma warning restore 618 public static bool IsSecurityOrCriticalException(Exception ex) { return (ex is System.Security.SecurityException) || IsCriticalException(ex); } public static int GetBitCount(uint x) { int count = 0; while (x > 0) { x &= x - 1; count++; } return count; } // Sequential version // assumes sequential enum members 0,1,2,3,4 -etc. // public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue) { bool valid = (value >= minValue) && (value <= maxValue); #if DEBUG Debug_SequentialEnumIsDefinedCheck(enumValue, minValue, maxValue); #endif return valid; } // Useful for sequential enum values which only use powers of two 0,1,2,4,8 etc: IsEnumValid(val, min, max, 1) // Valid example: TextImageRelation 0,1,2,4,8 - only one bit can ever be on, and the value is between 0 and 8. // // ClientUtils.IsEnumValid((int)(relation), /*min*/(int)TextImageRelation.None, (int)TextImageRelation.TextBeforeImage,1); // public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue, int maxNumberOfBitsOn) { System.Diagnostics.Debug.Assert(maxNumberOfBitsOn >= 0 && maxNumberOfBitsOn < 32, "expect this to be greater than zero and less than 32"); bool valid = (value >= minValue) && (value <= maxValue); //Note: if it's 0, it'll have no bits on. If it's a power of 2, it'll have 1. valid = (valid && GetBitCount((uint)value) <= maxNumberOfBitsOn); #if DEBUG Debug_NonSequentialEnumIsDefinedCheck(enumValue, minValue, maxValue, maxNumberOfBitsOn, valid); #endif return valid; } // Useful for enums that are a subset of a bitmask // Valid example: EdgeEffects 0, 0x800 (FillInterior), 0x1000 (Flat), 0x4000(Soft), 0x8000(Mono) // // ClientUtils.IsEnumValid((int)(effects), /*mask*/ FillInterior | Flat | Soft | Mono, // ,2); // public static bool IsEnumValid_Masked(Enum enumValue, int value, UInt32 mask) { bool valid = ((value & mask) == value); #if DEBUG Debug_ValidateMask(enumValue, mask); #endif return valid; } // Useful for cases where you have discontiguous members of the enum. // Valid example: AutoComplete source. // if (!ClientUtils.IsEnumValid(value, AutoCompleteSource.None, // AutoCompleteSource.AllSystemSources // AutoCompleteSource.AllUrl, // AutoCompleteSource.CustomSource, // AutoCompleteSource.FileSystem, // AutoCompleteSource.FileSystemDirectories, // AutoCompleteSource.HistoryList, // AutoCompleteSource.ListItems, // AutoCompleteSource.RecentlyUsedList)) // // PERF tip: put the default value in the enum towards the front of the argument list. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsEnumValid_NotSequential(System.Enum enumValue, int value, params int[] enumValues) { System.Diagnostics.Debug.Assert(Enum.GetValues(enumValue.GetType()).Length == enumValues.Length, "Not all the enum members were passed in."); for (int i = 0; i < enumValues.Length; i++) { if (enumValues[i] == value) { return true; } } return false; } #if DEBUG [ThreadStatic] private static Hashtable t_enumValueInfo; public const int MaxCache = 300; // we think we're going to get O(100) of these, put in a tripwire if it gets larger. private class SequentialEnumInfo { public SequentialEnumInfo(Type t) { int actualMinimum = int.MaxValue; int actualMaximum = int.MinValue; int countEnumVals = 0; foreach (int iVal in Enum.GetValues(t)) { actualMinimum = Math.Min(actualMinimum, iVal); actualMaximum = Math.Max(actualMaximum, iVal); countEnumVals++; } Debug.Assert(countEnumVals - 1 == actualMaximum - actualMinimum); MinValue = actualMinimum; MaxValue = actualMaximum; } public int MinValue; public int MaxValue; } private static void Debug_SequentialEnumIsDefinedCheck(Enum value, int minVal, int maxVal) { Type enumType = value.GetType(); if (t_enumValueInfo == null) { t_enumValueInfo = new Hashtable(); } SequentialEnumInfo sequentialEnumInfo = null; if (t_enumValueInfo.ContainsKey(enumType)) { sequentialEnumInfo = t_enumValueInfo[enumType] as SequentialEnumInfo; } if (sequentialEnumInfo == null) { sequentialEnumInfo = new SequentialEnumInfo(enumType); Debug.Assert(t_enumValueInfo.Count <= MaxCache); t_enumValueInfo[enumType] = sequentialEnumInfo; } Debug.Assert(minVal == sequentialEnumInfo.MinValue, "Minimum passed in is not the actual minimum for the enum. Consider changing the parameters or using a different function."); Debug.Assert(maxVal == sequentialEnumInfo.MaxValue, "Maximum passed in is not the actual maximum for the enum. Consider changing the parameters or using a different function."); } private static void Debug_ValidateMask(Enum value, uint mask) { Type enumType = value.GetType(); uint newMask = 0; foreach (int iVal in Enum.GetValues(enumType)) { newMask = newMask | (uint)iVal; } Debug.Assert(newMask == mask, "Mask not valid in IsEnumValid!"); } private static void Debug_NonSequentialEnumIsDefinedCheck(Enum value, int minVal, int maxVal, int maxBitsOn, bool isValid) { Type enumType = value.GetType(); int actualMinimum = int.MaxValue; int actualMaximum = int.MinValue; int checkedValue = Convert.ToInt32(value, CultureInfo.InvariantCulture); int maxBitsFound = 0; bool foundValue = false; foreach (int iVal in Enum.GetValues(enumType)) { actualMinimum = Math.Min(actualMinimum, iVal); actualMaximum = Math.Max(actualMaximum, iVal); maxBitsFound = Math.Max(maxBitsFound, GetBitCount((uint)iVal)); if (checkedValue == iVal) { foundValue = true; } } Debug.Assert(minVal == actualMinimum, "Minimum passed in is not the actual minimum for the enum. Consider changing the parameters or using a different function."); Debug.Assert(minVal == actualMinimum, "Maximum passed in is not the actual maximum for the enum. Consider changing the parameters or using a different function."); Debug.Assert(maxBitsFound == maxBitsOn, "Incorrect usage of IsEnumValid function. The bits set to 1 in this enum was found to be: " + maxBitsFound.ToString(CultureInfo.InvariantCulture) + "this does not match what's passed in: " + maxBitsOn.ToString(CultureInfo.InvariantCulture)); Debug.Assert(foundValue == isValid, string.Format(CultureInfo.InvariantCulture, "Returning {0} but we actually {1} found the value in the enum! Consider using a different overload to IsValidEnum.", isValid, ((foundValue) ? "have" : "have not"))); } #endif /// <summary> /// WeakRefCollection - a collection that holds onto weak references /// /// Essentially you pass in the object as it is, and under the covers /// we only hold a weak reference to the object. /// /// ----------------------------------------------------------------- /// !!!IMPORTANT USAGE NOTE!!! /// Users of this class should set the RefCheckThreshold property /// explicitly or call ScavengeReferences every once in a while to /// remove dead references. /// Also avoid calling Remove(item). Instead call RemoveByHashCode(item) /// to make sure dead refs are removed. /// ----------------------------------------------------------------- /// /// </summary> internal class WeakRefCollection : IList { private int _refCheckThreshold = Int32.MaxValue; // this means this is disabled by default. private ArrayList _innerList; internal WeakRefCollection() { _innerList = new ArrayList(4); } internal WeakRefCollection(int size) { _innerList = new ArrayList(size); } internal ArrayList InnerList { get { return _innerList; } } /// <summary> /// Indicates the value where the collection should check its items to remove dead weakref left over. /// Note: When GC collects weak refs from this collection the WeakRefObject identity changes since its /// Target becomes null. This makes the item unrecognizable by the collection and cannot be /// removed - Remove(item) and Contains(item) will not find it anymore. /// </summary> public int RefCheckThreshold { get { return _refCheckThreshold; } set { _refCheckThreshold = value; } } public object this[int index] { get { WeakRefObject weakRef = InnerList[index] as WeakRefObject; if ((weakRef != null) && (weakRef.IsAlive)) { return weakRef.Target; } return null; } set { InnerList[index] = CreateWeakRefObject(value); } } public void ScavengeReferences() { int currentIndex = 0; int currentCount = Count; for (int i = 0; i < currentCount; i++) { object item = this[currentIndex]; if (item == null) { InnerList.RemoveAt(currentIndex); } else { // only incriment if we have not removed the item currentIndex++; } } } public override bool Equals(object obj) { WeakRefCollection other = obj as WeakRefCollection; if (other == this) { return true; } if (other == null || Count != other.Count) { return false; } for (int i = 0; i < Count; i++) { if (InnerList[i] != other.InnerList[i]) { if (InnerList[i] == null || !InnerList[i].Equals(other.InnerList[i])) { return false; } } } return true; } public override int GetHashCode() { return base.GetHashCode(); } private WeakRefObject CreateWeakRefObject(object value) { if (value == null) { return null; } return new WeakRefObject(value); } private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefCollection destinationList, int destinationIndex, int length) { if (sourceIndex < destinationIndex) { // We need to copy from the back forward to prevent overwrite if source and // destination lists are the same, so we need to flip the source/dest indices // to point at the end of the spans to be copied. sourceIndex = sourceIndex + length; destinationIndex = destinationIndex + length; for (; length > 0; length--) { destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex]; } } else { for (; length > 0; length--) { destinationList.InnerList[destinationIndex++] = sourceList.InnerList[sourceIndex++]; } } } /// <summary> /// Removes the value using its hash code as its identity. /// This is needed because the underlying item in the collection may have already been collected changing /// the identity of the WeakRefObject making it impossible for the collection to identify it. /// See WeakRefObject for more info. /// </summary> public void RemoveByHashCode(object value) { if (value == null) { return; } int hash = value.GetHashCode(); for (int idx = 0; idx < InnerList.Count; idx++) { if (InnerList[idx] != null && InnerList[idx].GetHashCode() == hash) { RemoveAt(idx); return; } } } #region IList Members public void Clear() { InnerList.Clear(); } public bool IsFixedSize { get { return InnerList.IsFixedSize; } } public bool Contains(object value) { return InnerList.Contains(CreateWeakRefObject(value)); } public void RemoveAt(int index) { InnerList.RemoveAt(index); } public void Remove(object value) { InnerList.Remove(CreateWeakRefObject(value)); } public int IndexOf(object value) { return InnerList.IndexOf(CreateWeakRefObject(value)); } public void Insert(int index, object value) { InnerList.Insert(index, CreateWeakRefObject(value)); } public int Add(object value) { if (Count > RefCheckThreshold) { ScavengeReferences(); } return InnerList.Add(CreateWeakRefObject(value)); } #endregion #region ICollection Members public int Count { get { return InnerList.Count; } } object ICollection.SyncRoot { get { return InnerList.SyncRoot; } } public bool IsReadOnly { get { return InnerList.IsReadOnly; } } public void CopyTo(Array array, int index) { InnerList.CopyTo(array, index); } bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; } } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return InnerList.GetEnumerator(); } #endregion /// <summary> /// Wraps a weak ref object. /// WARNING: Use this class carefully! /// When the weak ref is collected, this object looses its identity. This is bad when the object has been /// added to a collection since Contains(WeakRef(item)) and Remove(WeakRef(item)) would not be able to /// identify the item. /// </summary> internal class WeakRefObject { private int _hash; private WeakReference _weakHolder; internal WeakRefObject(object obj) { Debug.Assert(obj != null, "Unexpected null object!"); _weakHolder = new WeakReference(obj); _hash = obj.GetHashCode(); } internal bool IsAlive { get { return _weakHolder.IsAlive; } } internal object Target { get { return _weakHolder.Target; } } public override int GetHashCode() { return _hash; } public override bool Equals(object obj) { WeakRefObject other = obj as WeakRefObject; if (other == this) { return true; } if (other == null) { return false; } if (other.Target != Target) { if (Target == null || !Target.Equals(other.Target)) { return false; } } return true; } } } } }
// 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.Text; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.InteropServices; namespace System.Reflection { // // Parses an assembly name. // [System.Runtime.CompilerServices.ReflectionBlocked] public static class AssemblyNameParser { public static void Parse(AssemblyName blank, String s) { if (s == null) throw new ArgumentNullException(nameof(s)); RuntimeAssemblyName runtimeAssemblyName = Parse(s); runtimeAssemblyName.CopyToAssemblyName(blank); } public static RuntimeAssemblyName Parse(String s) { Debug.Assert(s != null); int indexOfNul = s.IndexOf((char)0); if (indexOfNul != -1) s = s.Substring(0, indexOfNul); if (s.Length == 0) throw new ArgumentException(SR.Format_StringZeroLength); AssemblyNameLexer lexer = new AssemblyNameLexer(s); // Name must come first. String name; AssemblyNameLexer.Token token = lexer.GetNext(out name); if (token != AssemblyNameLexer.Token.String) throw new FileLoadException(SR.InvalidAssemblyName); if (name == String.Empty || name.IndexOfAny(s_illegalCharactersInSimpleName) != -1) throw new FileLoadException(SR.InvalidAssemblyName); Version version = null; String cultureName = null; byte[] pkt = null; AssemblyNameFlags flags = 0; LowLevelList<String> alreadySeen = new LowLevelList<String>(); token = lexer.GetNext(); while (token != AssemblyNameLexer.Token.End) { if (token != AssemblyNameLexer.Token.Comma) throw new FileLoadException(SR.InvalidAssemblyName); String attributeName; token = lexer.GetNext(out attributeName); if (token != AssemblyNameLexer.Token.String) throw new FileLoadException(SR.InvalidAssemblyName); token = lexer.GetNext(); // Compat note: Inside AppX apps, the desktop CLR's AssemblyName parser skips past any elements that don't follow the "<Something>=<Something>" pattern. // (when running classic Windows apps, such an illegal construction throws an exception as expected.) // Naturally, at least one app unwittingly takes advantage of this. if (token == AssemblyNameLexer.Token.Comma || token == AssemblyNameLexer.Token.End) continue; if (token != AssemblyNameLexer.Token.Equals) throw new FileLoadException(SR.InvalidAssemblyName); String attributeValue; token = lexer.GetNext(out attributeValue); if (token != AssemblyNameLexer.Token.String) throw new FileLoadException(SR.InvalidAssemblyName); if (attributeName == String.Empty) throw new FileLoadException(SR.InvalidAssemblyName); for (int i = 0; i < alreadySeen.Count; i++) { if (alreadySeen[i].Equals(attributeName, StringComparison.OrdinalIgnoreCase)) throw new FileLoadException(SR.InvalidAssemblyName); // Cannot specify the same attribute twice. } alreadySeen.Add(attributeName); if (attributeName.Equals("Version", StringComparison.OrdinalIgnoreCase)) { version = ParseVersion(attributeValue); } if (attributeName.Equals("Culture", StringComparison.OrdinalIgnoreCase)) { cultureName = ParseCulture(attributeValue); } if (attributeName.Equals("PublicKeyToken", StringComparison.OrdinalIgnoreCase)) { pkt = ParsePKT(attributeValue); } if (attributeName.Equals("ProcessorArchitecture", StringComparison.OrdinalIgnoreCase)) { flags |= (AssemblyNameFlags)(((int)ParseProcessorArchitecture(attributeValue)) << 4); } if (attributeName.Equals("Retargetable", StringComparison.OrdinalIgnoreCase)) { if (attributeValue.Equals("Yes", StringComparison.OrdinalIgnoreCase)) flags |= AssemblyNameFlags.Retargetable; else if (attributeValue.Equals("No", StringComparison.OrdinalIgnoreCase)) { // nothing to do } else throw new FileLoadException(SR.InvalidAssemblyName); } if (attributeName.Equals("ContentType", StringComparison.OrdinalIgnoreCase)) { if (attributeValue.Equals("WindowsRuntime", StringComparison.OrdinalIgnoreCase)) flags |= (AssemblyNameFlags)(((int)AssemblyContentType.WindowsRuntime) << 9); else throw new FileLoadException(SR.InvalidAssemblyName); } // Desktop compat: If we got here, the attribute name is unknown to us. Ignore it (as long it's not duplicated.) token = lexer.GetNext(); } return new RuntimeAssemblyName(name, version, cultureName, flags, pkt); } private static Version ParseVersion(String attributeValue) { String[] parts = attributeValue.Split('.'); if (parts.Length > 4) throw new FileLoadException(SR.InvalidAssemblyName); ushort[] versionNumbers = new ushort[4]; for (int i = 0; i < versionNumbers.Length; i++) { if (i >= parts.Length) versionNumbers[i] = ushort.MaxValue; else { // Desktop compat: TryParse is a little more forgiving than Fusion. for (int j = 0; j < parts[i].Length; j++) { if (!Char.IsDigit(parts[i][j])) throw new FileLoadException(SR.InvalidAssemblyName); } if (!(ushort.TryParse(parts[i], out versionNumbers[i]))) { throw new FileLoadException(SR.InvalidAssemblyName); } } } if (versionNumbers[0] == ushort.MaxValue || versionNumbers[1] == ushort.MaxValue) throw new FileLoadException(SR.InvalidAssemblyName); if (versionNumbers[2] == ushort.MaxValue) return new Version(versionNumbers[0], versionNumbers[1]); if (versionNumbers[3] == ushort.MaxValue) return new Version(versionNumbers[0], versionNumbers[1], versionNumbers[2]); return new Version(versionNumbers[0], versionNumbers[1], versionNumbers[2], versionNumbers[3]); } private static String ParseCulture(String attributeValue) { if (attributeValue.Equals("Neutral", StringComparison.OrdinalIgnoreCase)) { return ""; } else { CultureInfo culture = new CultureInfo(attributeValue); // Force a CultureNotFoundException if not a valid culture. return culture.Name; } } private static byte[] ParsePKT(String attributeValue) { if (attributeValue.Equals("null", StringComparison.OrdinalIgnoreCase) || attributeValue == String.Empty) return Array.Empty<byte>(); if (attributeValue.Length != 8 * 2) throw new FileLoadException(SR.InvalidAssemblyName); byte[] pkt = new byte[8]; int srcIndex = 0; for (int i = 0; i < 8; i++) { char hi = attributeValue[srcIndex++]; char lo = attributeValue[srcIndex++]; pkt[i] = (byte)((ParseHexNybble(hi) << 4) | ParseHexNybble(lo)); } return pkt; } private static ProcessorArchitecture ParseProcessorArchitecture(String attributeValue) { if (attributeValue.Equals("msil", StringComparison.OrdinalIgnoreCase)) return ProcessorArchitecture.MSIL; if (attributeValue.Equals("x86", StringComparison.OrdinalIgnoreCase)) return ProcessorArchitecture.X86; if (attributeValue.Equals("ia64", StringComparison.OrdinalIgnoreCase)) return ProcessorArchitecture.IA64; if (attributeValue.Equals("amd64", StringComparison.OrdinalIgnoreCase)) return ProcessorArchitecture.Amd64; if (attributeValue.Equals("arm", StringComparison.OrdinalIgnoreCase)) return ProcessorArchitecture.Arm; throw new FileLoadException(SR.InvalidAssemblyName); } private static byte ParseHexNybble(char c) { if (c >= '0' && c <= '9') return (byte)(c - '0'); if (c >= 'a' && c <= 'f') return (byte)(c - 'a' + 10); if (c >= 'A' && c <= 'F') return (byte)(c - 'A' + 10); throw new FileLoadException(SR.InvalidAssemblyName); } private static readonly char[] s_illegalCharactersInSimpleName = { '/', '\\', ':' }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Collections.Concurrent; using System.Runtime.InteropServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using Internal.Reflection.Tracing; namespace System.Reflection.Runtime.TypeInfos { // // The runtime's implementation of TypeInfo's for the "HasElement" subclass of types. // internal abstract partial class RuntimeHasElementTypeInfo : RuntimeTypeInfo, IKeyedItem<RuntimeHasElementTypeInfo.UnificationKey>, IRuntimeMemberInfoWithNoMetadataDefinition { protected RuntimeHasElementTypeInfo(UnificationKey key) : base() { _key = key; } public sealed override bool IsTypeDefinition => false; public sealed override bool IsGenericTypeDefinition => false; protected sealed override bool HasElementTypeImpl() => true; protected abstract override bool IsArrayImpl(); public abstract override bool IsSZArray { get; } public abstract override bool IsVariableBoundArray { get; } protected abstract override bool IsByRefImpl(); protected abstract override bool IsPointerImpl(); public sealed override bool IsConstructedGenericType => false; public sealed override bool IsGenericParameter => false; public sealed override bool IsGenericTypeParameter => false; public sealed override bool IsGenericMethodParameter => false; public sealed override bool IsByRefLike => false; // // Implements IKeyedItem.PrepareKey. // // This method is the keyed item's chance to do any lazy evaluation needed to produce the key quickly. // Concurrent unifiers are guaranteed to invoke this method at least once and wait for it // to complete before invoking the Key property. The unifier lock is NOT held across the call. // // PrepareKey() must be idempodent and thread-safe. It may be invoked multiple times and concurrently. // public void PrepareKey() { } // // Implements IKeyedItem.Key. // // Produce the key. This is a high-traffic property and is called while the hash table's lock is held. Thus, it should // return a precomputed stored value and refrain from invoking other methods. If the keyed item wishes to // do lazy evaluation of the key, it should do so in the PrepareKey() method. // public UnificationKey Key { get { return _key; } } public sealed override Assembly Assembly { get { return _key.ElementType.Assembly; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_CustomAttributes(this); #endif return Empty<CustomAttributeData>.Enumerable; } } public sealed override bool ContainsGenericParameters { get { return _key.ElementType.ContainsGenericParameters; } } public sealed override string FullName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_FullName(this); #endif string elementFullName = _key.ElementType.FullName; if (elementFullName == null) return null; return elementFullName + Suffix; } } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) { if (other == null) throw new ArgumentNullException(nameof(other)); // This logic is written to match CoreCLR's behavior. return other is Type && other is IRuntimeMemberInfoWithNoMetadataDefinition; } public sealed override string Namespace { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Namespace(this); #endif return _key.ElementType.Namespace; } } public sealed override StructLayoutAttribute StructLayoutAttribute { get { return null; } } public sealed override string ToString() { return _key.ElementType.ToString() + Suffix; } public sealed override int MetadataToken { get { return 0x02000000; // nil TypeDef token } } // // Left unsealed because this implemention is correct for ByRefs and Pointers but not Arrays. // protected override TypeAttributes GetAttributeFlagsImpl() { Debug.Assert(IsByRef || IsPointer); return TypeAttributes.AnsiClass; } protected sealed override int InternalGetHashCode() { return _key.ElementType.GetHashCode(); } internal sealed override bool CanBrowseWithoutMissingMetadataExceptions => true; internal sealed override Type InternalDeclaringType { get { return null; } } public sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure) { string elementTypeName = _key.ElementType.InternalGetNameIfAvailable(ref rootCauseForFailure); if (elementTypeName == null) { rootCauseForFailure = _key.ElementType; return null; } return elementTypeName + Suffix; } internal sealed override string InternalFullNameOfAssembly { get { return _key.ElementType.InternalFullNameOfAssembly; } } internal sealed override RuntimeTypeInfo InternalRuntimeElementType { get { return _key.ElementType; } } internal sealed override RuntimeTypeHandle InternalTypeHandleIfAvailable { get { return _key.TypeHandle; } } protected abstract string Suffix { get; } private readonly UnificationKey _key; } }
// // Authors: // Ben Motmans <ben.motmans@gmail.com> // Lucas Ontivero lucasontivero@gmail.com // // Copyright (C) 2007 Ben Motmans // Copyright (C) 2014 Lucas Ontivero // // 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.Linq; using System.Text; using System.Net; using System.Diagnostics; using System.Net.Sockets; using System.Threading; using System.Xml; namespace Open.Nat { internal class UpnpSearcher : Searcher { private readonly IIPAddressesProvider _ipprovider; private readonly IDictionary<Uri, NatDevice> _devices; private readonly Dictionary<IPAddress, DateTime> _lastFetched; private static readonly string[] ServiceTypes = new[]{ "WANIPConnection:2", "WANPPPConnection:2", "WANIPConnection:1", "WANPPPConnection:1" }; internal UpnpSearcher(IIPAddressesProvider ipprovider) { _ipprovider = ipprovider; Sockets = CreateSockets(); _devices = new Dictionary<Uri, NatDevice>(); _lastFetched = new Dictionary<IPAddress, DateTime>(); } private List<UdpClient> CreateSockets() { var clients = new List<UdpClient>(); try { var ips = _ipprovider.UnicastAddresses(); foreach (var ipAddress in ips) { try { clients.Add(new UdpClient(new IPEndPoint(ipAddress, 0))); } catch (Exception) { continue; // Move on to the next address. } } } catch (Exception) { clients.Add(new UdpClient(0)); } return clients; } protected override void Discover(UdpClient client, CancellationToken cancelationToken) { NextSearch = DateTime.UtcNow.AddSeconds(1); var searchEndpoint = new IPEndPoint( WellKnownConstants.IPv4MulticastAddress /*IPAddress.Broadcast*/ , 1900); foreach (var serviceType in ServiceTypes) { var datax = DiscoverDeviceMessage.Encode(serviceType); var data = Encoding.ASCII.GetBytes(datax); // UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2) // Yes, however it works perfectly well with just 1 request. for (var i = 0; i < 2; i++) { if (cancelationToken.IsCancellationRequested) return; client.Send(data, data.Length, searchEndpoint); } } } public override NatDevice AnalyseReceivedResponse(IPAddress localAddress, byte[] response, IPEndPoint endpoint) { // Convert it to a string for easy parsing string dataString = null; // No matter what, this method should never throw an exception. If something goes wrong // we should still be in a position to handle the next reply correctly. try { dataString = Encoding.UTF8.GetString(response); var message = new DiscoveryResponseMessage(dataString); var serviceType = message["ST"]; if (!IsValidControllerService(serviceType)) { NatDiscoverer.TraceSource.LogWarn("Invalid controller service. Ignoring."); return null; } NatDiscoverer.TraceSource.LogInfo("UPnP Response: Router advertised a '{0}' service!!!", serviceType); var location = message["Location"] ?? message["AL"]; var locationUri = new Uri(location); NatDiscoverer.TraceSource.LogInfo("Found device at: {0}", locationUri.ToString()); if (_devices.ContainsKey(locationUri)) { NatDiscoverer.TraceSource.LogInfo("Already found - Ignored"); _devices[locationUri].Touch(); return null; } // If we send 3 requests at a time, ensure we only fetch the services list once // even if three responses are received if (_lastFetched.ContainsKey(endpoint.Address)) { var last = _lastFetched[endpoint.Address]; if ((DateTime.Now - last) < TimeSpan.FromSeconds(20)) return null; } _lastFetched[endpoint.Address] = DateTime.Now; NatDiscoverer.TraceSource.LogInfo("{0}:{1}: Fetching service list", locationUri.Host, locationUri.Port ); var deviceInfo = BuildUpnpNatDeviceInfo(localAddress, locationUri); UpnpNatDevice device; lock (_devices) { device = new UpnpNatDevice(deviceInfo); if (!_devices.ContainsKey(locationUri)) { _devices.Add(locationUri, device); } } return device; } catch (Exception ex) { NatDiscoverer.TraceSource.LogError("Unhandled exception when trying to decode a device's response. "); NatDiscoverer.TraceSource.LogError("Report the issue in https://github.com/lontivero/Open.Nat/issues"); NatDiscoverer.TraceSource.LogError("Also copy and paste the following info:"); NatDiscoverer.TraceSource.LogError("-- beging ---------------------------------"); NatDiscoverer.TraceSource.LogError(ex.Message); NatDiscoverer.TraceSource.LogError("Data string:"); NatDiscoverer.TraceSource.LogError(dataString ?? "No data available"); NatDiscoverer.TraceSource.LogError("-- end ------------------------------------"); } return null; } private static bool IsValidControllerService(string serviceType) { var services = from serviceName in ServiceTypes let serviceUrn = string.Format("urn:schemas-upnp-org:service:{0}", serviceName) where serviceType.ContainsIgnoreCase(serviceUrn) select new {ServiceName = serviceName, ServiceUrn = serviceUrn}; return services.Any(); } private UpnpNatDeviceInfo BuildUpnpNatDeviceInfo(IPAddress localAddress, Uri location) { NatDiscoverer.TraceSource.LogInfo("Found device at: {0}", location.ToString()); var hostEndPoint = new IPEndPoint(IPAddress.Parse(location.Host), location.Port); WebResponse response = null; try { var request = WebRequest.CreateHttp(location); request.Headers.Add("ACCEPT-LANGUAGE", "en"); request.Method = "GET"; response = request.GetResponse(); var httpresponse = response as HttpWebResponse; if (httpresponse != null && httpresponse.StatusCode != HttpStatusCode.OK) { var message = string.Format("Couldn't get services list: {0} {1}", httpresponse.StatusCode, httpresponse.StatusDescription); throw new Exception(message); } var xmldoc = ReadXmlResponse(response); NatDiscoverer.TraceSource.LogInfo("{0}: Parsed services list", hostEndPoint); var ns = new XmlNamespaceManager(xmldoc.NameTable); ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0"); var services = xmldoc.SelectNodes("//ns:service", ns); foreach (XmlNode service in services) { var serviceType = service.GetXmlElementText("serviceType"); if (!IsValidControllerService(serviceType)) continue; NatDiscoverer.TraceSource.LogInfo("{0}: Found service: {1}", hostEndPoint, serviceType); var serviceControlUrl = service.GetXmlElementText("controlURL"); NatDiscoverer.TraceSource.LogInfo("{0}: Found upnp service at: {1}", hostEndPoint, serviceControlUrl); NatDiscoverer.TraceSource.LogInfo("{0}: Handshake Complete", hostEndPoint); return new UpnpNatDeviceInfo(localAddress, location, serviceControlUrl, serviceType); } throw new Exception("No valid control service was found in the service descriptor document"); } catch (WebException ex) { // Just drop the connection, FIXME: Should i retry? NatDiscoverer.TraceSource.LogError("{0}: Device denied the connection attempt: {1}", hostEndPoint, ex); var inner = ex.InnerException as SocketException; if (inner != null) { NatDiscoverer.TraceSource.LogError("{0}: ErrorCode:{1}", hostEndPoint, inner.ErrorCode); NatDiscoverer.TraceSource.LogError("Go to http://msdn.microsoft.com/en-us/library/system.net.sockets.socketerror.aspx"); NatDiscoverer.TraceSource.LogError("Usually this happens. Try resetting the device and try again. If you are in a VPN, disconnect and try again."); } throw; } finally { if (response != null) response.Close(); } } private static XmlDocument ReadXmlResponse(WebResponse response) { using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { var servicesXml = reader.ReadToEnd(); var xmldoc = new XmlDocument(); xmldoc.LoadXml(servicesXml); return xmldoc; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using NuGet.Resources; namespace NuGet { public class LocalPackageRepository : PackageRepositoryBase, IPackageLookup { private readonly ConcurrentDictionary<string, PackageCacheEntry> _packageCache = new ConcurrentDictionary<string, PackageCacheEntry>(StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary<PackageName, string> _packagePathLookup = new ConcurrentDictionary<PackageName, string>(); private readonly bool _enableCaching; public LocalPackageRepository(string physicalPath) : this(physicalPath, enableCaching: true) { } public LocalPackageRepository(string physicalPath, bool enableCaching) : this(new DefaultPackagePathResolver(physicalPath), new PhysicalFileSystem(physicalPath), enableCaching) { } public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem) : this(pathResolver, fileSystem, enableCaching: true) { } public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem, bool enableCaching) { if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } FileSystem = fileSystem; PathResolver = pathResolver; _enableCaching = enableCaching; } public override string Source { get { return FileSystem.Root; } } public IPackagePathResolver PathResolver { get; set; } public override bool SupportsPrereleasePackages { get { return true; } } protected IFileSystem FileSystem { get; private set; } public override IQueryable<IPackage> GetPackages() { return GetPackages(OpenPackage).AsQueryable(); } public override void AddPackage(IPackage package) { if (PackageSaveMode.HasFlag(PackageSaveModes.Nuspec)) { // Starting from 2.1, we save the nuspec file into the subdirectory with the name as <packageId>.<version> // for example, for jQuery version 1.0, it will be "jQuery.1.0\\jQuery.1.0.nuspec" string packageFilePath = GetManifestFilePath(package.Id, package.Version); Manifest manifest = Manifest.Create(package); // The IPackage object doesn't carry the References information. // Thus we set the References for the manifest to the set of all valid assembly references manifest.Metadata.ReferenceSets = package.AssemblyReferences .GroupBy(f => f.TargetFramework) .Select( g => new ManifestReferenceSet { TargetFramework = g.Key == null ? null : VersionUtility.GetFrameworkString(g.Key), References = g.Select(p => new ManifestReference { File = p.Name }).ToList() }) .ToList(); FileSystem.AddFileWithCheck(packageFilePath, manifest.Save); } if (PackageSaveMode.HasFlag(PackageSaveModes.Nupkg)) { string packageFilePath = GetPackageFilePath(package); FileSystem.AddFileWithCheck(packageFilePath, package.GetStream); } } public override void RemovePackage(IPackage package) { string manifestFilePath = GetManifestFilePath(package.Id, package.Version); if (FileSystem.FileExists(manifestFilePath)) { // delete .nuspec file FileSystem.DeleteFileSafe(manifestFilePath); } // Delete the package file string packageFilePath = GetPackageFilePath(package); FileSystem.DeleteFileSafe(packageFilePath); // Delete the package directory if any FileSystem.DeleteDirectorySafe(PathResolver.GetPackageDirectory(package), recursive: false); // If this is the last package delete the package directory if (!FileSystem.GetFilesSafe(String.Empty).Any() && !FileSystem.GetDirectoriesSafe(String.Empty).Any()) { FileSystem.DeleteDirectorySafe(String.Empty, recursive: false); } } public virtual IPackage FindPackage(string packageId, SemanticVersion version) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } if (version == null) { throw new ArgumentNullException("version"); } return FindPackage(OpenPackage, packageId, version); } public virtual IEnumerable<IPackage> FindPackagesById(string packageId) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } return FindPackagesById(OpenPackage, packageId); } public virtual bool Exists(string packageId, SemanticVersion version) { return FindPackage(packageId, version) != null; } public virtual IEnumerable<string> GetPackageLookupPaths(string packageId, SemanticVersion version) { // Files created by the path resolver. This would take into account the non-side-by-side scenario // and we do not need to match this for id and version. var packageFileName = PathResolver.GetPackageFileName(packageId, version); var manifestFileName = Path.ChangeExtension(packageFileName, Constants.ManifestExtension); var filesMatchingFullName = Enumerable.Concat( GetPackageFiles(packageFileName), GetPackageFiles(manifestFileName)); if (version != null && version.Version.Revision < 1) { // If the build or revision number is not set, we need to look for combinations of the format // * Foo.1.2.nupkg // * Foo.1.2.3.nupkg // * Foo.1.2.0.nupkg // * Foo.1.2.0.0.nupkg // To achieve this, we would look for files named 1.2*.nupkg if both build and revision are 0 and // 1.2.3*.nupkg if only the revision is set to 0. string partialName = version.Version.Build < 1 ? String.Join(".", packageId, version.Version.Major, version.Version.Minor) : String.Join(".", packageId, version.Version.Major, version.Version.Minor, version.Version.Build); string partialManifestName = partialName + "*" + Constants.ManifestExtension; partialName += "*" + Constants.PackageExtension; // Partial names would result is gathering package with matching major and minor but different build and revision. // Attempt to match the version in the path to the version we're interested in. var partialNameMatches = GetPackageFiles(partialName).Where(path => FileNameMatchesPattern(packageId, version, path)); var partialManifestNameMatches = GetPackageFiles(partialManifestName).Where( path => FileNameMatchesPattern(packageId, version, path)); return Enumerable.Concat(filesMatchingFullName, partialNameMatches).Concat(partialManifestNameMatches); } return filesMatchingFullName; } internal IPackage FindPackage(Func<string, IPackage> openPackage, string packageId, SemanticVersion version) { var lookupPackageName = new PackageName(packageId, version); string packagePath; // If caching is enabled, check if we have a cached path. Additionally, verify that the file actually exists on disk since it might have moved. if (_enableCaching && _packagePathLookup.TryGetValue(lookupPackageName, out packagePath) && FileSystem.FileExists(packagePath)) { // When depending on the cached path, verify the file exists on disk. return GetPackage(openPackage, packagePath); } // Lookup files which start with the name "<Id>." and attempt to match it with all possible version string combinations (e.g. 1.2.0, 1.2.0.0) // before opening the package. To avoid creating file name strings, we attempt to specifically match everything after the last path separator // which would be the file name and extension. return (from path in GetPackageLookupPaths(packageId, version) let package = GetPackage(openPackage, path) where lookupPackageName.Equals(new PackageName(package.Id, package.Version)) select package).FirstOrDefault(); } internal IEnumerable<IPackage> FindPackagesById(Func<string, IPackage> openPackage, string packageId) { Debug.Assert(!String.IsNullOrEmpty(packageId), "The caller has to ensure packageId is never null."); HashSet<IPackage> packages = new HashSet<IPackage>(PackageEqualityComparer.IdAndVersion); // get packages through nupkg files packages.AddRange( GetPackages( openPackage, packageId, GetPackageFiles(packageId + "*" + Constants.PackageExtension))); // then, get packages through nuspec files packages.AddRange( GetPackages( openPackage, packageId, GetPackageFiles(packageId + "*" + Constants.ManifestExtension))); return packages; } internal IEnumerable<IPackage> GetPackages(Func<string, IPackage> openPackage, string packageId, IEnumerable<string> packagePaths) { foreach (var path in packagePaths) { IPackage package = null; try { package = GetPackage(openPackage, path); } catch (InvalidOperationException) { // ignore error for unzipped packages (nuspec files). if (string.Equals( Constants.ManifestExtension, Path.GetExtension(path), StringComparison.OrdinalIgnoreCase)) { } else { throw; } } if (package != null && package.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)) { yield return package; } } } internal IEnumerable<IPackage> GetPackages(Func<string, IPackage> openPackage) { return from path in GetPackageFiles() select GetPackage(openPackage, path); } private IPackage GetPackage(Func<string, IPackage> openPackage, string path) { PackageCacheEntry cacheEntry; DateTimeOffset lastModified = FileSystem.GetLastModified(path); // If we never cached this file or we did and it's current last modified time is newer // create a new entry if (!_packageCache.TryGetValue(path, out cacheEntry) || (cacheEntry != null && lastModified > cacheEntry.LastModifiedTime)) { // We need to do this so we capture the correct loop variable string packagePath = path; // Create the package IPackage package = openPackage(packagePath); // create a cache entry with the last modified time cacheEntry = new PackageCacheEntry(package, lastModified); if (_enableCaching) { // Store the entry _packageCache[packagePath] = cacheEntry; _packagePathLookup.GetOrAdd(new PackageName(package.Id, package.Version), path); } } return cacheEntry.Package; } internal IEnumerable<string> GetPackageFiles(string filter = null) { filter = filter ?? "*" + Constants.PackageExtension; Debug.Assert( filter.EndsWith(Constants.PackageExtension, StringComparison.OrdinalIgnoreCase) || filter.EndsWith(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase)); // Check for package files one level deep. We use this at package install time // to determine the set of installed packages. Installed packages are copied to // {id}.{version}\{packagefile}.{extension}. foreach (var dir in FileSystem.GetDirectories(String.Empty)) { foreach (var path in FileSystem.GetFiles(dir, filter)) { yield return path; } } // Check top level directory foreach (var path in FileSystem.GetFiles(String.Empty, filter)) { yield return path; } } protected virtual IPackage OpenPackage(string path) { if (!FileSystem.FileExists(path)) { return null; } if (Path.GetExtension(path) == Constants.PackageExtension) { OptimizedZipPackage package; try { package = new OptimizedZipPackage(FileSystem, path); } catch (FileFormatException ex) { throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ErrorReadingPackage, path), ex); } // Set the last modified date on the package package.Published = FileSystem.GetLastModified(path); return package; } else if (Path.GetExtension(path) == Constants.ManifestExtension) { if (FileSystem.FileExists(path)) { return new UnzippedPackage(FileSystem, Path.GetFileNameWithoutExtension(path)); } } return null; } protected virtual string GetPackageFilePath(IPackage package) { return Path.Combine(PathResolver.GetPackageDirectory(package), PathResolver.GetPackageFileName(package)); } protected virtual string GetPackageFilePath(string id, SemanticVersion version) { return Path.Combine(PathResolver.GetPackageDirectory(id, version), PathResolver.GetPackageFileName(id, version)); } private static bool FileNameMatchesPattern(string packageId, SemanticVersion version, string path) { var name = Path.GetFileNameWithoutExtension(path); SemanticVersion parsedVersion; // When matching by pattern, we will always have a version token. Packages without versions would be matched early on by the version-less path resolver // when doing an exact match. return name.Length > packageId.Length && SemanticVersion.TryParse(name.Substring(packageId.Length + 1), out parsedVersion) && parsedVersion == version; } private string GetManifestFilePath(string packageId, SemanticVersion version) { string packageDirectory = PathResolver.GetPackageDirectory(packageId, version); string manifestFileName = packageDirectory + Constants.ManifestExtension; return Path.Combine(packageDirectory, manifestFileName); } private class PackageCacheEntry { public PackageCacheEntry(IPackage package, DateTimeOffset lastModifiedTime) { Package = package; LastModifiedTime = lastModifiedTime; } public IPackage Package { get; private set; } public DateTimeOffset LastModifiedTime { get; private set; } } } }
using System; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Runtime.Messaging; namespace Orleans.Messaging { // <summary> // This class is used on the client only. // It provides the client counterpart to the Gateway and GatewayAcceptor classes on the silo side. // // There is one ClientMessageCenter instance per OutsideRuntimeClient. There can be multiple ClientMessageCenter instances // in a single process, but because RuntimeClient keeps a static pointer to a single OutsideRuntimeClient instance, this is not // generally done in practice. // // Each ClientMessageCenter keeps a collection of GatewayConnection instances. Each of these represents a bidirectional connection // to a single gateway endpoint. Requests are assigned to a specific connection based on the target grain ID, so that requests to // the same grain will go to the same gateway, in sending order. To do this efficiently and scalably, we bucket grains together // based on their hash code mod a reasonably large number (currently 8192). // // When the first message is sent to a bucket, we assign a gateway to that bucket, selecting in round-robin fashion from the known // gateways. If this is the first message to be sent to the gateway, we will create a new connection for it and assign the bucket to // the new connection. Either way, all messages to grains in that bucket will be sent to the assigned connection as long as the // connection is live. // // Connections stay live as long as possible. If a socket error or other communications error occurs, then the client will try to // reconnect twice before giving up on the gateway. If the connection cannot be re-established, then the gateway is deemed (temporarily) // dead, and any buckets assigned to the connection are unassigned (so that the next message sent will cause a new gateway to be selected). // There is no assumption that this death is permanent; the system will try to reuse the gateway every 5 minutes. // // The list of known gateways is managed by the GatewayManager class. See comments there for details. // </summary> internal class ClientMessageCenter : IMessageCenter, IDisposable { private readonly object grainBucketUpdateLock = new object(); internal static readonly TimeSpan MINIMUM_INTERCONNECT_DELAY = TimeSpan.FromMilliseconds(100); // wait one tenth of a second between connect attempts internal const int CONNECT_RETRY_COUNT = 2; // Retry twice before giving up on a gateway server internal ClientGrainId ClientId { get; private set; } public IRuntimeClient RuntimeClient { get; } internal bool Running { get; private set; } private readonly GatewayManager gatewayManager; private Action<Message> messageHandler; private int numMessages; // The grainBuckets array is used to select the connection to use when sending an ordered message to a grain. // Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket. // Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used // if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is // false, then a new gateway is selected using the gateway manager, and a new connection established if necessary. private readonly WeakReference<Connection>[] grainBuckets; private readonly ILogger logger; public SiloAddress MyAddress { get; private set; } private readonly QueueTrackingStatistic queueTracking; private int numberOfConnectedGateways = 0; private readonly MessageFactory messageFactory; private readonly IClusterConnectionStatusListener connectionStatusListener; private readonly ConnectionManager connectionManager; private StatisticsLevel statisticsLevel; public ClientMessageCenter( IOptions<ClientMessagingOptions> clientMessagingOptions, IPAddress localAddress, int gen, ClientGrainId clientId, IRuntimeClient runtimeClient, MessageFactory messageFactory, IClusterConnectionStatusListener connectionStatusListener, ILoggerFactory loggerFactory, IOptions<StatisticsOptions> statisticsOptions, ConnectionManager connectionManager, GatewayManager gatewayManager) { this.connectionManager = connectionManager; MyAddress = SiloAddress.New(new IPEndPoint(localAddress, 0), gen); ClientId = clientId; this.RuntimeClient = runtimeClient; this.messageFactory = messageFactory; this.connectionStatusListener = connectionStatusListener; Running = false; this.gatewayManager = gatewayManager; numMessages = 0; this.grainBuckets = new WeakReference<Connection>[clientMessagingOptions.Value.ClientSenderBuckets]; logger = loggerFactory.CreateLogger<ClientMessageCenter>(); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Proxy grain client constructed"); IntValueStatistic.FindOrCreate( StatisticNames.CLIENT_CONNECTED_GATEWAY_COUNT, () => { return connectionManager.ConnectionCount; }); statisticsLevel = statisticsOptions.Value.CollectionLevel; if (statisticsLevel.CollectQueueStats()) { queueTracking = new QueueTrackingStatistic("ClientReceiver", statisticsOptions); } } public void Start() { Running = true; if (this.statisticsLevel.CollectQueueStats()) { queueTracking.OnStartExecution(); } if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Proxy grain client started"); } public void Stop() { Running = false; if (this.statisticsLevel.CollectQueueStats()) { queueTracking.OnStopExecution(); } gatewayManager.Stop(); } public void DispatchLocalMessage(Message message) { var handler = this.messageHandler; if (handler is null) { ThrowNullMessageHandler(); } else { handler(message); } static void ThrowNullMessageHandler() => throw new InvalidOperationException("MessageCenter does not have a message handler set"); } public void SendMessage(Message msg) { if (!Running) { this.logger.Error(ErrorCode.ProxyClient_MsgCtrNotRunning, $"Ignoring {msg} because the Client message center is not running"); return; } var connectionTask = this.GetGatewayConnection(msg); if (connectionTask.IsCompletedSuccessfully) { var connection = connectionTask.Result; if (connection is null) return; connection.Send(msg); if (this.logger.IsEnabled(LogLevel.Trace)) { this.logger.Trace( ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", msg, connection.RemoteEndPoint); } } else { _ = SendAsync(connectionTask, msg); async Task SendAsync(ValueTask<Connection> task, Message message) { try { var connection = await task; // If the connection returned is null then the message was already rejected due to a failure. if (connection is null) return; connection.Send(message); if (this.logger.IsEnabled(LogLevel.Trace)) { this.logger.Trace( ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", message, connection.RemoteEndPoint); } } catch (Exception exception) { if (message.RetryCount < MessagingOptions.DEFAULT_MAX_MESSAGE_SEND_RETRIES) { ++message.RetryCount; _ = Task.Factory.StartNew( state => this.SendMessage((Message)state), message, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { this.RejectMessage(message, $"Unable to send message due to exception {exception}", exception); } } } } } private ValueTask<Connection> GetGatewayConnection(Message msg) { // If there's a specific gateway specified, use it if (msg.TargetSilo != null && gatewayManager.IsGatewayAvailable(msg.TargetSilo)) { var siloAddress = SiloAddress.New(msg.TargetSilo.Endpoint, 0); var connectionTask = this.connectionManager.GetConnection(siloAddress); if (connectionTask.IsCompletedSuccessfully) return connectionTask; return ConnectAsync(msg.TargetSilo, connectionTask, msg, directGatewayMessage: true); } // For untargeted messages to system targets, and for unordered messages, pick a next connection in round robin fashion. if (msg.TargetGrain.IsSystemTarget() || msg.IsUnordered) { // Get the cached list of live gateways. // Pick a next gateway name in a round robin fashion. // See if we have a live connection to it. // If Yes, use it. // If not, create a new GatewayConnection and start it. // If start fails, we will mark this connection as dead and remove it from the GetCachedLiveGatewayNames. int msgNumber = Interlocked.Increment(ref numMessages); var gatewayAddresses = gatewayManager.GetLiveGateways(); int numGateways = gatewayAddresses.Count; if (numGateways == 0) { RejectMessage(msg, "No gateways available"); logger.Warn(ErrorCode.ProxyClient_CannotSend, "Unable to send message {0}; gateway manager state is {1}", msg, gatewayManager); return new ValueTask<Connection>(default(Connection)); } var gatewayAddress = gatewayAddresses[msgNumber % numGateways]; var connectionTask = this.connectionManager.GetConnection(gatewayAddress); if (connectionTask.IsCompletedSuccessfully) return connectionTask; return ConnectAsync(gatewayAddress, connectionTask, msg, directGatewayMessage: false); } // Otherwise, use the buckets to ensure ordering. var index = GetHashCodeModulo(msg.TargetGrain.GetHashCode(), (uint)grainBuckets.Length); // Repeated from above, at the declaration of the grainBuckets array: // Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket. // Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used // if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is // false, then a new gateway is selected using the gateway manager, and a new connection established if necessary. WeakReference<Connection> weakRef = grainBuckets[index]; if (weakRef != null && weakRef.TryGetTarget(out var existingConnection) && existingConnection.IsValid && gatewayManager.IsGatewayAvailable(msg.TargetSilo)) { return new ValueTask<Connection>(existingConnection); } var addr = gatewayManager.GetLiveGateway(); if (addr == null) { RejectMessage(msg, "No gateways available"); logger.Warn(ErrorCode.ProxyClient_CannotSend_NoGateway, "Unable to send message {0}; gateway manager state is {1}", msg, gatewayManager); return new ValueTask<Connection>(default(Connection)); } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.ProxyClient_NewBucketIndex, "Starting new bucket index {0} for ordered messages to grain {1}", index, msg.TargetGrain); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug( ErrorCode.ProxyClient_CreatedGatewayToGrain, "Creating gateway to {0} for message to grain {1}, bucket {2}, grain id hash code {3}X", addr, msg.TargetGrain, index, msg.TargetGrain.GetHashCode().ToString("x")); var gatewayConnection = this.connectionManager.GetConnection(addr); if (gatewayConnection.IsCompletedSuccessfully) { this.UpdateBucket(index, gatewayConnection.Result); return gatewayConnection; } return AddToBucketAsync(index, gatewayConnection, addr); async ValueTask<Connection> AddToBucketAsync( uint bucketIndex, ValueTask<Connection> connectionTask, SiloAddress gatewayAddress) { try { var connection = await connectionTask.ConfigureAwait(false); this.UpdateBucket(bucketIndex, connection); return connection; } catch { this.gatewayManager.MarkAsDead(gatewayAddress); this.UpdateBucket(bucketIndex, null); throw; } } async ValueTask<Connection> ConnectAsync( SiloAddress gateway, ValueTask<Connection> connectionTask, Message message, bool directGatewayMessage) { Connection result = default; try { return result = await connectionTask; } catch (Exception exception) when (directGatewayMessage) { RejectMessage(message, string.Format("Target silo {0} is unavailable", message.TargetSilo), exception); return null; } finally { if (result is null) this.gatewayManager.MarkAsDead(gateway); } } static uint GetHashCodeModulo(int key, uint umod) { int mod = (int)umod; key = ((key % mod) + mod) % mod; // key should be positive now. So assert with checked. return checked((uint)key); } } private void UpdateBucket(uint index, Connection connection) { lock (this.grainBucketUpdateLock) { var value = this.grainBuckets[index] ?? new WeakReference<Connection>(connection); value.SetTarget(connection); this.grainBuckets[index] = value; } } public void RegisterLocalMessageHandler(Action<Message> handler) { this.messageHandler = handler; } public void RejectMessage(Message msg, string reason, Exception exc = null) { if (!Running) return; if (msg.Direction != Message.Directions.Request) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason); } else { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnRejectedMessage(msg); var error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason, exc); DispatchLocalMessage(error); } } internal void OnGatewayConnectionOpen() { int newCount = Interlocked.Increment(ref numberOfConnectedGateways); this.connectionStatusListener.NotifyGatewayCountChanged(newCount, newCount - 1); } internal void OnGatewayConnectionClosed() { var gatewayCount = Interlocked.Decrement(ref numberOfConnectedGateways); if (gatewayCount == 0) { this.connectionStatusListener.NotifyClusterConnectionLost(); } this.connectionStatusListener.NotifyGatewayCountChanged(gatewayCount, gatewayCount + 1); } public void Dispose() { gatewayManager.Dispose(); } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Runtime.Remoting; using Common.Logging; using Spring.Core.TypeConversion; using Spring.Expressions; using Spring.Objects.Factory.Config; namespace Spring.Objects.Factory.Support { /// <summary> /// Helper class for use in object factory implementations, /// resolving values contained in object definition objects /// into the actual values applied to the target object instance. /// </summary> /// <remarks> /// Used by <see cref="AbstractAutowireCapableObjectFactory"/>. /// </remarks> /// <author>Juergen Hoeller</author> /// <author>Mark Pollack (.NET)</author> public class ObjectDefinitionValueResolver { private readonly ILog log; private readonly AbstractObjectFactory objectFactory; /// <summary> /// Initializes a new instance of the <see cref="ObjectDefinitionValueResolver"/> class. /// </summary> /// <param name="objectFactory">The object factory.</param> public ObjectDefinitionValueResolver(AbstractObjectFactory objectFactory) { this.log = LogManager.GetLogger(this.GetType()); this.objectFactory = objectFactory; } /// <summary> /// Given a property value, return a value, resolving any references to other /// objects in the factory if necessary. /// </summary> /// <remarks> /// <p> /// The value could be : /// <list type="bullet"> /// <item> /// <p> /// An <see cref="Spring.Objects.Factory.Config.IObjectDefinition"/>, /// which leads to the creation of a corresponding new object instance. /// Singleton flags and names of such "inner objects" are always ignored: inner objects /// are anonymous prototypes. /// </p> /// </item> /// <item> /// <p> /// A <see cref="Spring.Objects.Factory.Config.RuntimeObjectReference"/>, which must /// be resolved. /// </p> /// </item> /// <item> /// <p> /// An <see cref="Spring.Objects.Factory.Config.IManagedCollection"/>. This is a /// special placeholder collection that may contain /// <see cref="Spring.Objects.Factory.Config.RuntimeObjectReference"/>s or /// collections that will need to be resolved. /// </p> /// </item> /// <item> /// <p> /// An ordinary object or <see langword="null"/>, in which case it's left alone. /// </p> /// </item> /// </list> /// </p> /// </remarks> /// <param name="name"> /// The name of the object that is having the value of one of its properties resolved. /// </param> /// <param name="definition"> /// The definition of the named object. /// </param> /// <param name="argumentName"> /// The name of the property the value of which is being resolved. /// </param> /// <param name="argumentValue"> /// The value of the property that is being resolved. /// </param> public virtual object ResolveValueIfNecessary(string name, IObjectDefinition definition, string argumentName, object argumentValue) { object resolvedValue = null; resolvedValue = ResolvePropertyValue(name, definition, argumentName, argumentValue); return resolvedValue; } /// <summary> /// TODO /// </summary> /// <param name="name"> /// The name of the object that is having the value of one of its properties resolved. /// </param> /// <param name="definition"> /// The definition of the named object. /// </param> /// <param name="argumentName"> /// The name of the property the value of which is being resolved. /// </param> /// <param name="argumentValue"> /// The value of the property that is being resolved. /// </param> private object ResolvePropertyValue(string name, IObjectDefinition definition, string argumentName, object argumentValue) { object resolvedValue = null; // we must check the argument value to see whether it requires a runtime // reference to another object to be resolved. // if it does, we'll attempt to instantiate the object and set the reference. if (RemotingServices.IsTransparentProxy(argumentValue)) { resolvedValue = argumentValue; } else if (argumentValue is ICustomValueReferenceHolder) { resolvedValue = ((ICustomValueReferenceHolder) argumentValue).Resolve(objectFactory, name, definition, argumentName, argumentValue); } else if (argumentValue is ObjectDefinitionHolder) { // contains an IObjectDefinition with name and aliases... ObjectDefinitionHolder holder = (ObjectDefinitionHolder)argumentValue; resolvedValue = ResolveInnerObjectDefinition(name, holder.ObjectName, argumentName, holder.ObjectDefinition, definition.IsSingleton); } else if (argumentValue is IObjectDefinition) { // resolve plain IObjectDefinition, without contained name: use dummy name... IObjectDefinition def = (IObjectDefinition)argumentValue; resolvedValue = ResolveInnerObjectDefinition(name, "(inner object)", argumentName, def, definition.IsSingleton); } else if (argumentValue is RuntimeObjectReference) { RuntimeObjectReference roref = (RuntimeObjectReference)argumentValue; resolvedValue = ResolveReference(definition, name, argumentName, roref); } else if (argumentValue is ExpressionHolder) { ExpressionHolder expHolder = (ExpressionHolder)argumentValue; object context = null; IDictionary<string, object> variables = null; if (expHolder.Properties != null) { PropertyValue contextProperty = expHolder.Properties.GetPropertyValue("Context"); context = contextProperty == null ? null : ResolveValueIfNecessary(name, definition, "Context", contextProperty.Value); PropertyValue variablesProperty = expHolder.Properties.GetPropertyValue("Variables"); object vars = (variablesProperty == null ? null : ResolveValueIfNecessary(name, definition, "Variables", variablesProperty.Value)); if (vars is IDictionary<string, object>) { variables = (IDictionary<string, object>)vars; } if (vars is IDictionary) { IDictionary temp = (IDictionary) vars; variables = new Dictionary<string, object>(temp.Count); foreach (DictionaryEntry entry in temp) { variables.Add((string) entry.Key, entry.Value); } } else { if (vars != null) throw new ArgumentException("'Variables' must resolve to an IDictionary"); } } if (variables == null) variables = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); // add 'this' objectfactory reference to variables variables.Add(Expression.ReservedVariableNames.CurrentObjectFactory, objectFactory); resolvedValue = expHolder.Expression.GetValue(context, variables); } else if (argumentValue is IManagedCollection) { resolvedValue = ((IManagedCollection)argumentValue).Resolve(name, definition, argumentName, ResolveValueIfNecessary); } else if (argumentValue is TypedStringValue) { TypedStringValue tsv = (TypedStringValue)argumentValue; try { Type resolvedTargetType = ResolveTargetType(tsv); if (resolvedTargetType != null) { resolvedValue = TypeConversionUtils.ConvertValueIfNecessary(tsv.TargetType, tsv.Value, null); } else { resolvedValue = tsv.Value; } } catch (Exception ex) { throw new ObjectCreationException(definition.ResourceDescription, name, "Error converted typed String value for " + argumentName, ex); } } else { // no need to resolve value... resolvedValue = argumentValue; } return resolvedValue; } /// <summary> /// Resolve the target type of the passed <see cref="TypedStringValue"/>. /// </summary> /// <param name="value">The <see cref="TypedStringValue"/> who's target type is to be resolved</param> /// <returns>The resolved target type, if any. <see lang="null" /> otherwise.</returns> protected virtual Type ResolveTargetType(TypedStringValue value) { if (value.HasTargetType) { return value.TargetType; } return value.ResolveTargetType(); } /// <summary> /// Resolves an inner object definition. /// </summary> /// <param name="name"> /// The name of the object that surrounds this inner object definition. /// </param> /// <param name="innerObjectName"> /// The name of the inner object definition... note: this is a synthetic /// name assigned by the factory (since it makes no sense for inner object /// definitions to have names). /// </param> /// <param name="argumentName"> /// The name of the property the value of which is being resolved. /// </param> /// <param name="definition"> /// The definition of the inner object that is to be resolved. /// </param> /// <param name="singletonOwner"> /// <see langword="true"/> if the owner of the property is a singleton. /// </param> /// <returns> /// The resolved object as defined by the inner object definition. /// </returns> protected virtual object ResolveInnerObjectDefinition(string name, string innerObjectName, string argumentName, IObjectDefinition definition, bool singletonOwner) { RootObjectDefinition mod = objectFactory.GetMergedObjectDefinition(innerObjectName, definition); // Check given bean name whether it is unique. If not already unique, // add counter - increasing the counter until the name is unique. String actualInnerObjectName = innerObjectName; if (mod.IsSingleton) { actualInnerObjectName = AdaptInnerObjectName(innerObjectName); } mod.IsSingleton = singletonOwner; object instance; object result; try { //SPRNET-986 ObjectUtils.EmptyObjects -> null instance = objectFactory.InstantiateObject(actualInnerObjectName, mod, null, false, false); result = objectFactory.GetObjectForInstance(instance, actualInnerObjectName, actualInnerObjectName, mod); } catch (ObjectsException ex) { throw ObjectCreationException.GetObjectCreationException(ex, name, argumentName, definition.ResourceDescription, innerObjectName); } if (singletonOwner && instance is IDisposable) { // keep a reference to the inner object instance, to be able to destroy // it on factory shutdown... objectFactory.DisposableInnerObjects.Add(instance); } return result; } /// <summary> /// Checks the given bean name whether it is unique. If not already unique, /// a counter is added, increasing the counter until the name is unique. /// </summary> /// <param name="innerObjectName">Original Name of the inner object.</param> /// <returns>The Adapted name for the inner object</returns> private string AdaptInnerObjectName(string innerObjectName) { string actualInnerObjectName = innerObjectName; int counter = 0; while (this.objectFactory.IsObjectNameInUse(actualInnerObjectName)) { counter++; actualInnerObjectName = innerObjectName + ObjectFactoryUtils.GENERATED_OBJECT_NAME_SEPARATOR + counter; } return actualInnerObjectName; } /// <summary> /// Resolve a reference to another object in the factory. /// </summary> /// <param name="name"> /// The name of the object that is having the value of one of its properties resolved. /// </param> /// <param name="definition"> /// The definition of the named object. /// </param> /// <param name="argumentName"> /// The name of the property the value of which is being resolved. /// </param> /// <param name="reference"> /// The runtime reference containing the value of the property. /// </param> /// <returns>A reference to another object in the factory.</returns> protected virtual object ResolveReference(IObjectDefinition definition, string name, string argumentName, RuntimeObjectReference reference) { #region Instrumentation if (log.IsDebugEnabled) { log.Debug( string.Format(CultureInfo.InvariantCulture, "Resolving reference from property '{0}' in object '{1}' to object '{2}'.", argumentName, name, reference.ObjectName)); } #endregion try { if (reference.IsToParent) { if (null == objectFactory.ParentObjectFactory) { throw new ObjectCreationException(definition.ResourceDescription, name, string.Format( "Can't resolve reference to '{0}' in parent factory: " + "no parent factory available.", reference.ObjectName)); } return objectFactory.ParentObjectFactory.GetObject(reference.ObjectName); } return objectFactory.GetObject(reference.ObjectName); } catch (ObjectsException ex) { throw ObjectCreationException.GetObjectCreationException(ex, name, argumentName, definition.ResourceDescription, reference.ObjectName); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Test.ModuleCore; using System; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { public partial class ErrorConditions : BridgeHelpers { //[Variation(Desc = "Move to Attribute using []")] public void Variation1() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { TestLog.Compare(r[-100000], null, "Error"); TestLog.Compare(r[-1], null, "Error"); TestLog.Compare(r[0], null, "Error"); TestLog.Compare(r[100000], null, "Error"); TestLog.Compare(r[null], null, "Error"); TestLog.Compare(r[null, null], null, "Error"); TestLog.Compare(r[""], null, "Error"); TestLog.Compare(r["", ""], null, "Error"); } } } //[Variation(Desc = "GetAttribute")] public void Variation2() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { TestLog.Compare(r.GetAttribute(-100000), null, "Error"); TestLog.Compare(r.GetAttribute(-1), null, "Error"); TestLog.Compare(r.GetAttribute(0), null, "Error"); TestLog.Compare(r.GetAttribute(100000), null, "Error"); TestLog.Compare(r.GetAttribute(null), null, "Error"); TestLog.Compare(r.GetAttribute(null, null), null, "Error"); TestLog.Compare(r.GetAttribute(""), null, "Error"); TestLog.Compare(r.GetAttribute("", ""), null, "Error"); } } } //[Variation(Desc = "IsStartElement")] public void Variation3() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { TestLog.Compare(r.IsStartElement(null, null), false, "Error"); TestLog.Compare(r.IsStartElement(null), false, "Error"); TestLog.Compare(r.IsStartElement("", ""), false, "Error"); TestLog.Compare(r.IsStartElement(""), false, "Error"); } } } //[Variation(Desc = "LookupNamespace")] public void Variation4() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { TestLog.Compare(r.LookupNamespace(""), null, "Error"); TestLog.Compare(r.LookupNamespace(null), null, "Error"); } } } //[Variation(Desc = "MoveToAttribute")] public void Variation5() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToAttribute(-100000); r.MoveToAttribute(-1); r.MoveToAttribute(0); r.MoveToAttribute(100000); TestLog.Compare(r.MoveToAttribute(null), false, "Error"); TestLog.Compare(r.MoveToAttribute(null, null), false, "Error"); TestLog.Compare(r.MoveToAttribute(""), false, "Error"); TestLog.Compare(r.MoveToAttribute("", ""), false, "Error"); } } } //[Variation(Desc = "Other APIs")] public void Variation6() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); TestLog.Compare(r.MoveToElement(), false, "Error"); TestLog.Compare(r.MoveToFirstAttribute(), false, "Error"); TestLog.Compare(r.MoveToNextAttribute(), false, "Error"); TestLog.Compare(r.ReadAttributeValue(), false, "Error"); r.Read(); TestLog.Compare(r.ReadInnerXml(), "", "Error"); r.ReadOuterXml(); r.ResolveEntity(); r.Skip(); } } } //[Variation(Desc = "ReadContentAs(null, null)")] public void Variation7() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAs(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadContentAs(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } catch (InvalidOperationException) { } } catch (InvalidOperationException) { try { r.ReadContentAs(null, null); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadContentAsBase64")] public void Variation8() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAsBase64(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { try { r.ReadContentAsBase64(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { } } } } } //[Variation(Desc = "ReadContentAsBinHex")] public void Variation9() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAsBinHex(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { try { r.ReadContentAsBinHex(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { } } } } } //[Variation(Desc = "ReadContentAsBoolean")] public void Variation10() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAsBoolean(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { try { r.ReadContentAsBoolean(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (InvalidOperationException) { } } catch (InvalidOperationException) { try { r.ReadContentAsBoolean(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadContentAsDateTimeOffset")] public void Variation11b() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAsDateTimeOffset(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { try { r.ReadContentAsDateTimeOffset(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (InvalidOperationException) { } } catch (InvalidOperationException) { try { r.ReadContentAsDateTimeOffset(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadContentAsDecimal")] public void Variation12() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAsDecimal(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { try { r.ReadContentAsDecimal(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (InvalidOperationException) { } } catch (InvalidOperationException) { try { r.ReadContentAsDecimal(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadContentAsDouble")] public void Variation13() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAsDouble(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { try { r.ReadContentAsDouble(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (InvalidOperationException) { } } catch (InvalidOperationException) { try { r.ReadContentAsDouble(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadContentAsFloat")] public void Variation14() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAsFloat(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { try { r.ReadContentAsFloat(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (InvalidOperationException) { } } catch (InvalidOperationException) { try { r.ReadContentAsFloat(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadContentAsInt")] public void Variation15() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAsInt(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { try { r.ReadContentAsInt(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (InvalidOperationException) { } } catch (InvalidOperationException) { try { r.ReadContentAsInt(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadContentAsLong")] public void Variation16() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.MoveToContent(); try { r.ReadContentAsLong(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { try { r.ReadContentAsLong(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (InvalidOperationException) { } } catch (InvalidOperationException) { try { r.ReadContentAsLong(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadElementContentAs(null, null)")] public void Variation17() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAs(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadElementContentAs(null, null, null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } catch (InvalidOperationException) { try { r.ReadElementContentAs(null, null, null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } } } } //[Variation(Desc = "ReadElementContentAsBase64")] public void Variation18() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsBase64(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { try { r.ReadElementContentAsBase64(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { } } } } } //[Variation(Desc = "ReadElementContentAsBinHex")] public void Variation19() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsBinHex(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { try { r.ReadElementContentAsBinHex(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { } } } } } //[Variation(Desc = "ReadElementContentAsBoolean")] public void Variation20() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsBoolean(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadElementContentAsBoolean(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (FormatException) { } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadElementContentAsDecimal")] public void Variation22() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsDecimal(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadElementContentAsDecimal(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (FormatException) { } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadElementContentAsDouble")] public void Variation23() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsDouble(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadElementContentAsDouble(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (FormatException) { } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadElementContentAsFloat")] public void Variation24() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsFloat(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadElementContentAsFloat(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (FormatException) { } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadElementContentAsInt")] public void Variation25() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsInt(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadElementContentAsInt(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (FormatException) { } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadElementContentAsLong")] public void Variation26() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsLong(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadElementContentAsLong(); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } catch (FormatException) { } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadElementContentAsObject")] public void Variation27() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsLong(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadElementContentAsLong(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } } } } //[Variation(Desc = "ReadElementContentAsString")] public void Variation28() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadElementContentAsString(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { r.ReadElementContentAsString(null, null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } } } } //[Variation(Desc = "ReadStartElement")] public void Variation30() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadStartElement(null, null); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { try { r.ReadStartElement(null); throw new TestException(TestResult.Failed, ""); } catch (XmlException) { } } } } } //[Variation(Desc = "ReadToDescendant(null)")] public void Variation31() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); TestLog.Compare(r.ReadToDescendant(null, null), false, "Incorrect value returned"); } } } //[Variation(Desc = "ReadToDescendant(String.Empty)")] public void Variation32() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); TestLog.Compare(r.ReadToDescendant("", ""), false, "Incorrect value returned"); } } } //[Variation(Desc = "ReadToFollowing(null)")] public void Variation33() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); TestLog.Compare(r.ReadToFollowing(null, null), false, "Incorrect value returned"); } } } //[Variation(Desc = "ReadToFollowing(String.Empty)")] public void Variation34() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); TestLog.Compare(r.ReadToFollowing("", ""), false, "Incorrect value returned"); } } } //[Variation(Desc = "ReadToNextSibling(null)")] public void Variation35() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); TestLog.Compare(r.ReadToNextSibling(null, null), false, "Incorrect value returned"); } } } //[Variation(Desc = "ReadToNextSibling(String.Empty)")] public void Variation36() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); TestLog.Compare(r.ReadToNextSibling("", ""), false, "Incorrect value returned"); } } } //[Variation(Desc = "ReadValueChunk")] public void Variation37() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { r.Read(); try { r.ReadValueChunk(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { try { r.ReadValueChunk(null, 0, 0); throw new TestException(TestResult.Failed, ""); } catch (NotSupportedException) { } } } } } //[Variation(Desc = "ReadElementContentAsObject")] public void Variation38() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { while (r.Read()) ; try { r.ReadElementContentAsObject(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { try { r.ReadElementContentAsObject(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //[Variation(Desc = "ReadElementContentAsString")] public void Variation39() { foreach (XNode n in GetXNodeR()) { using (XmlReader r = n.CreateReader()) { while (r.Read()) ; try { r.ReadElementContentAsString(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { try { r.ReadElementContentAsString(); throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } } } } //GetXNode List public List<XNode> GetXNodeR() { List<XNode> xNode = new List<XNode>(); xNode.Add(new XDocument(new XDocumentType("root", "", "", "<!ELEMENT root ANY>"), new XElement("root"))); xNode.Add(new XElement("elem1")); xNode.Add(new XText("text1")); xNode.Add(new XComment("comment1")); xNode.Add(new XProcessingInstruction("pi1", "pi1pi1pi1pi1pi1")); xNode.Add(new XCData("cdata cdata")); xNode.Add(new XDocumentType("dtd1", "dtd1dtd1dtd1", "dtd1dtd1", "dtd1dtd1dtd1dtd1")); return xNode; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.WebSites { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// AppServicePlansOperations operations. /// </summary> public partial interface IAppServicePlansOperations { /// <summary> /// Gets all App Service Plans for a subcription /// </summary> /// Gets all App Service Plans for a subcription /// <param name='detailed'> /// False to return a subset of App Service Plan properties, true to /// return all of the properties. /// Retrieval of all properties may increase the API /// latency. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<AppServicePlan>>> ListWithHttpMessagesAsync(bool? detailed = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets collection of App Service Plans in a resource group for a /// given subscription. /// </summary> /// Gets collection of App Service Plans in a resource group for a /// given subscription. /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<AppServicePlan>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets specified App Service Plan in a resource group /// </summary> /// Gets specified App Service Plan in a resource group /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<AppServicePlan>> GetWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an App Service Plan /// </summary> /// Creates or updates an App Service Plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='appServicePlan'> /// Details of App Service Plan /// </param> /// <param name='allowPendingState'> /// OBSOLETE: If true, allow pending state for App Service Plan /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<AppServicePlan>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, AppServicePlan appServicePlan, bool? allowPendingState = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an App Service Plan /// </summary> /// Creates or updates an App Service Plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='appServicePlan'> /// Details of App Service Plan /// </param> /// <param name='allowPendingState'> /// OBSOLETE: If true, allow pending state for App Service Plan /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<AppServicePlan>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, AppServicePlan appServicePlan, bool? allowPendingState = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a App Service Plan /// </summary> /// Deletes a App Service Plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<object>> DeleteWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List serverfarm capabilities /// </summary> /// List serverfarm capabilities /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='name'> /// The name of the App Service Plan /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IList<Capability>>> ListCapabilitiesWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieves a specific Service Bus Hybrid Connection in use on this /// App Service Plan. /// </summary> /// Retrieves a specific Service Bus Hybrid Connection in use on this /// App Service Plan. /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='name'> /// The name of the App Service Plan /// </param> /// <param name='namespaceName'> /// The name of the Service Bus Namespace /// </param> /// <param name='relayName'> /// The name of the Service Bus Relay /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<HybridConnection>> GetHybridConnectionWithHttpMessagesAsync(string resourceGroupName, string name, string namespaceName, string relayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates an existing Service Bus Hybrid Connection in use on this /// App Service Plan. This will fail if the Hybrid Connection does /// not already exist. /// </summary> /// Updates an existing Service Bus Hybrid Connection in use on this /// App Service Plan. This will fail if the Hybrid Connection does /// not already exist. /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='name'> /// The name of the App Service Plan /// </param> /// <param name='namespaceName'> /// The name of the Service Bus Namespace /// </param> /// <param name='relayName'> /// The name of the Service Bus Relay /// </param> /// <param name='connection'> /// The hybrid connection entity /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<HybridConnection>> UpdateHybridConnectionWithHttpMessagesAsync(string resourceGroupName, string name, string namespaceName, string relayName, HybridConnection connection, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing Service Bus Hybrid Connection in use on this /// App Service Plan. /// </summary> /// Deletes an existing Service Bus Hybrid Connection in use on this /// App Service Plan. /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='name'> /// The name of the App Service Plan /// </param> /// <param name='namespaceName'> /// The name of the Service Bus Namespace /// </param> /// <param name='relayName'> /// The name of the Service Bus Relay /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<object>> DeleteHybridConnectionWithHttpMessagesAsync(string resourceGroupName, string name, string namespaceName, string relayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the send key name and value for this Hybrid Connection /// </summary> /// Gets the send key name and value for this Hybrid Connection /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='name'> /// The name of the App Service Plan /// </param> /// <param name='namespaceName'> /// The name of the Service Bus Namespace /// </param> /// <param name='relayName'> /// The name of the Service Bus Relay /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<HybridConnectionKey>> ListHybridConnectionKeysWithHttpMessagesAsync(string resourceGroupName, string name, string namespaceName, string relayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of sites that are using a particular Hybrid Connection /// on an App Service Plan /// </summary> /// Gets a list of sites that are using a particular Hybrid Connection /// on an App Service Plan /// <param name='resourceGroupName'> /// The resource group /// </param> /// <param name='name'> /// The name of the App Service Plan /// </param> /// <param name='namespaceName'> /// The Hybrid Connection namespace /// </param> /// <param name='relayName'> /// The Hybrid Connection relay name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<object>> ListHybridConnectionWebAppsWithHttpMessagesAsync(string resourceGroupName, string name, string namespaceName, string relayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the maximum number of Hybrid Connections allowed on a /// specified App Service Plan /// </summary> /// Gets the maximum number of Hybrid Connections allowed on a /// specified App Service Plan /// <param name='resourceGroupName'> /// The resource group /// </param> /// <param name='name'> /// The name of the App Service Plan /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<object>> GetHybridConnectionPlanLimitWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieves all Service Bus Hybrid Connections in use on this App /// Service Plan /// </summary> /// Retrieves all Service Bus Hybrid Connections in use on this App /// Service Plan /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='name'> /// The name of the App Service Plan /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<HybridConnection>> ListHybridConnectionsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List of metrics that can be queried for an App Service Plan /// </summary> /// List of metrics that can be queried for an App Service Plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<MetricDefinition>>> ListMetricDefintionsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Queries for App Serice Plan metrics /// </summary> /// Queries for App Serice Plan metrics /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='details'> /// If true, metrics are broken down per App Service Plan instance /// </param> /// <param name='filter'> /// Return only usages/metrics specified in the filter. Filter /// conforms to odata syntax. Example: $filter=(name.value eq /// 'Metric1' or name.value eq 'Metric2') and startTime eq /// '2014-01-01T00:00:00Z' and endTime eq '2014-12-31T23:59:59Z' and /// timeGrain eq duration'[Hour|Minute|Day]'. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ResourceMetric>>> ListMetricsWithHttpMessagesAsync(string resourceGroupName, string name, bool? details = default(bool?), string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a server farm operation /// </summary> /// Gets a server farm operation /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of server farm /// </param> /// <param name='operationId'> /// Id of Server farm operation"&amp;gt; /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<AppServicePlan>> GetOperationWithHttpMessagesAsync(string resourceGroupName, string name, string operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Restarts web apps in a specified App Service Plan /// </summary> /// Restarts web apps in a specified App Service Plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='softRestart'> /// Soft restart applies the configuration settings and restarts the /// apps if necessary. Hard restart always restarts and reprovisions /// the apps /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<object>> RestartWebAppsWithHttpMessagesAsync(string resourceGroupName, string name, bool? softRestart = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets list of Apps associated with an App Service Plan /// </summary> /// Gets list of Apps associated with an App Service Plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='skipToken'> /// Skip to of web apps in a list. If specified, the resulting list /// will contain web apps starting from (including) the skipToken. /// Else, the resulting list contains web apps from the start of the /// list /// </param> /// <param name='filter'> /// Supported filter: $filter=state eq running. Returns only web apps /// that are currently running /// </param> /// <param name='top'> /// List page size. If specified, results are paged. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Site>>> ListWebAppsWithHttpMessagesAsync(string resourceGroupName, string name, string skipToken = default(string), string filter = default(string), string top = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets list of vnets associated with App Service Plan /// </summary> /// Gets list of vnets associated with App Service Plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IList<VnetInfo>>> ListVnetsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a vnet associated with an App Service Plan /// </summary> /// Gets a vnet associated with an App Service Plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='vnetName'> /// Name of virtual network /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VnetInfo>> GetVnetFromServerFarmWithHttpMessagesAsync(string resourceGroupName, string name, string vnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the vnet gateway. /// </summary> /// Gets the vnet gateway. /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of the App Service Plan /// </param> /// <param name='vnetName'> /// Name of the virtual network /// </param> /// <param name='gatewayName'> /// Name of the gateway. Only the 'primary' gateway is supported. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VnetGateway>> GetVnetGatewayWithHttpMessagesAsync(string resourceGroupName, string name, string vnetName, string gatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the vnet gateway /// </summary> /// Updates the vnet gateway /// <param name='resourceGroupName'> /// The resource group /// </param> /// <param name='name'> /// The name of the App Service Plan /// </param> /// <param name='vnetName'> /// The name of the virtual network /// </param> /// <param name='gatewayName'> /// The name of the gateway. Only 'primary' is supported. /// </param> /// <param name='connectionEnvelope'> /// The gateway entity. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VnetGateway>> UpdateVnetGatewayWithHttpMessagesAsync(string resourceGroupName, string name, string vnetName, string gatewayName, VnetGateway connectionEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of all routes associated with a vnet, in an app /// service plan /// </summary> /// Gets a list of all routes associated with a vnet, in an app /// service plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='vnetName'> /// Name of virtual network /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IList<VnetRoute>>> ListtRoutesForVnetWithHttpMessagesAsync(string resourceGroupName, string name, string vnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a specific route associated with a vnet, in an app service /// plan /// </summary> /// Gets a specific route associated with a vnet, in an app service /// plan /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='vnetName'> /// Name of virtual network /// </param> /// <param name='routeName'> /// Name of the virtual network route /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IList<VnetRoute>>> GetRouteForVnetWithHttpMessagesAsync(string resourceGroupName, string name, string vnetName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a new route or updates an existing route for a vnet in an /// app service plan. /// </summary> /// Creates a new route or updates an existing route for a vnet in an /// app service plan. /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='vnetName'> /// Name of virtual network /// </param> /// <param name='routeName'> /// Name of the virtual network route /// </param> /// <param name='route'> /// The route object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VnetRoute>> CreateOrUpdateVnetRouteWithHttpMessagesAsync(string resourceGroupName, string name, string vnetName, string routeName, VnetRoute route, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing route for a vnet in an app service plan. /// </summary> /// Deletes an existing route for a vnet in an app service plan. /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='vnetName'> /// Name of virtual network /// </param> /// <param name='routeName'> /// Name of the virtual network route /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<object>> DeleteVnetRouteWithHttpMessagesAsync(string resourceGroupName, string name, string vnetName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a new route or updates an existing route for a vnet in an /// app service plan. /// </summary> /// Creates a new route or updates an existing route for a vnet in an /// app service plan. /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of App Service Plan /// </param> /// <param name='vnetName'> /// Name of virtual network /// </param> /// <param name='routeName'> /// Name of the virtual network route /// </param> /// <param name='route'> /// The route object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VnetRoute>> UpdateVnetRouteWithHttpMessagesAsync(string resourceGroupName, string name, string vnetName, string routeName, VnetRoute route, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Submit a reboot request for a worker machine in the specified /// server farm /// </summary> /// Submit a reboot request for a worker machine in the specified /// server farm /// <param name='resourceGroupName'> /// Name of resource group /// </param> /// <param name='name'> /// Name of server farm /// </param> /// <param name='workerName'> /// Name of worker machine, typically starts with RD /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<object>> RebootWorkerWithHttpMessagesAsync(string resourceGroupName, string name, string workerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all App Service Plans for a subcription /// </summary> /// Gets all App Service Plans for a subcription /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<AppServicePlan>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets collection of App Service Plans in a resource group for a /// given subscription. /// </summary> /// Gets collection of App Service Plans in a resource group for a /// given subscription. /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<AppServicePlan>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List of metrics that can be queried for an App Service Plan /// </summary> /// List of metrics that can be queried for an App Service Plan /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<MetricDefinition>>> ListMetricDefintionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Queries for App Serice Plan metrics /// </summary> /// Queries for App Serice Plan metrics /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ResourceMetric>>> ListMetricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets list of Apps associated with an App Service Plan /// </summary> /// Gets list of Apps associated with an App Service Plan /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Site>>> ListWebAppsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Thrift.Protocol; using Thrift.Processor; using Thrift.Transport; namespace Thrift.Server { //TODO: unhandled exceptions, etc. // ReSharper disable once InconsistentNaming public class TSimpleAsyncServer : TServer { private readonly int _clientWaitingDelay; private volatile Task _serverTask; public TSimpleAsyncServer(ITProcessorFactory itProcessorFactory, TServerTransport serverTransport, TTransportFactory inputTransportFactory, TTransportFactory outputTransportFactory, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, ILogger logger, int clientWaitingDelay = 10) : base(itProcessorFactory, serverTransport, inputTransportFactory, outputTransportFactory, inputProtocolFactory, outputProtocolFactory, logger) { _clientWaitingDelay = clientWaitingDelay; } public TSimpleAsyncServer(ITProcessorFactory itProcessorFactory, TServerTransport serverTransport, TTransportFactory inputTransportFactory, TTransportFactory outputTransportFactory, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, ILoggerFactory loggerFactory, int clientWaitingDelay = 10) : this(itProcessorFactory, serverTransport, inputTransportFactory, outputTransportFactory, inputProtocolFactory, outputProtocolFactory, loggerFactory.CreateLogger<TSimpleAsyncServer>(), clientWaitingDelay) { } public TSimpleAsyncServer(ITAsyncProcessor processor, TServerTransport serverTransport, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, ILoggerFactory loggerFactory, int clientWaitingDelay = 10) : this(new TSingletonProcessorFactory(processor), serverTransport, null, // defaults to TTransportFactory() null, // defaults to TTransportFactory() inputProtocolFactory, outputProtocolFactory, loggerFactory.CreateLogger(nameof(TSimpleAsyncServer)), clientWaitingDelay) { } public override async Task ServeAsync(CancellationToken cancellationToken) { try { // cancelation token _serverTask = Task.Factory.StartNew(() => StartListening(cancellationToken), TaskCreationOptions.LongRunning); await _serverTask; } catch (Exception ex) { Logger.LogError(ex.ToString()); } } private async Task StartListening(CancellationToken cancellationToken) { ServerTransport.Listen(); Logger.LogTrace("Started listening at server"); if (ServerEventHandler != null) { await ServerEventHandler.PreServeAsync(cancellationToken); } while (!cancellationToken.IsCancellationRequested) { if (ServerTransport.IsClientPending()) { Logger.LogTrace("Waiting for client connection"); try { var client = await ServerTransport.AcceptAsync(cancellationToken); await Task.Factory.StartNew(() => Execute(client, cancellationToken), cancellationToken); } catch (TTransportException ttx) { Logger.LogTrace($"Transport exception: {ttx}"); if (ttx.Type != TTransportException.ExceptionType.Interrupted) { Logger.LogError(ttx.ToString()); } } } else { try { await Task.Delay(TimeSpan.FromMilliseconds(_clientWaitingDelay), cancellationToken); } catch (TaskCanceledException) { } } } ServerTransport.Close(); Logger.LogTrace("Completed listening at server"); } public override void Stop() { } private async Task Execute(TTransport client, CancellationToken cancellationToken) { Logger.LogTrace("Started client request processing"); var processor = ProcessorFactory.GetAsyncProcessor(client, this); TTransport inputTransport = null; TTransport outputTransport = null; TProtocol inputProtocol = null; TProtocol outputProtocol = null; object connectionContext = null; try { try { inputTransport = InputTransportFactory.GetTransport(client); outputTransport = OutputTransportFactory.GetTransport(client); inputProtocol = InputProtocolFactory.GetProtocol(inputTransport); outputProtocol = OutputProtocolFactory.GetProtocol(outputTransport); if (ServerEventHandler != null) { connectionContext = await ServerEventHandler.CreateContextAsync(inputProtocol, outputProtocol, cancellationToken); } while (!cancellationToken.IsCancellationRequested) { if (!await inputTransport.PeekAsync(cancellationToken)) { break; } if (ServerEventHandler != null) { await ServerEventHandler.ProcessContextAsync(connectionContext, inputTransport, cancellationToken); } if (!await processor.ProcessAsync(inputProtocol, outputProtocol, cancellationToken)) { break; } } } catch (TTransportException ttx) { Logger.LogTrace($"Transport exception: {ttx}"); } catch (Exception x) { Logger.LogError($"Error: {x}"); } if (ServerEventHandler != null) { await ServerEventHandler.DeleteContextAsync(connectionContext, inputProtocol, outputProtocol, cancellationToken); } } finally { //Close transports inputTransport?.Close(); outputTransport?.Close(); // disposable stuff should be disposed inputProtocol?.Dispose(); outputProtocol?.Dispose(); inputTransport?.Dispose(); outputTransport?.Dispose(); } Logger.LogTrace("Completed client request processing"); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell.Interop; using NuGet.VisualStudio; using Roslyn.Utilities; using SVsServiceProvider = Microsoft.VisualStudio.Shell.SVsServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Packaging { /// <summary> /// Free threaded wrapper around the NuGet.VisualStudio STA package installer interfaces. /// We want to be able to make queries about packages from any thread. For example, the /// add-nuget-reference feature wants to know what packages a project already has /// references to. NuGet.VisualStudio provides this information, but only in a COM STA /// manner. As we don't want our background work to bounce and block on the UI thread /// we have this helper class which queries the information on the UI thread and caches /// the data so it can be read from the background. /// </summary> [ExportWorkspaceService(typeof(IPackageInstallerService)), Shared] internal partial class PackageInstallerService : AbstractDelayStartedService, IPackageInstallerService, IVsSearchProviderCallback { private readonly object _gate = new object(); private readonly VisualStudioWorkspaceImpl _workspace; private readonly SVsServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; // We refer to the package services through proxy types so that we can // delay loading their DLLs until we actually need them. private IPackageServicesProxy _packageServices; private CancellationTokenSource _tokenSource = new CancellationTokenSource(); // We keep track of what types of changes we've seen so we can then determine what to // refresh on the UI thread. If we hear about project changes, we only refresh that // project. If we hear about a solution level change, we'll refresh all projects. private bool _solutionChanged; private HashSet<ProjectId> _changedProjects = new HashSet<ProjectId>(); private readonly ConcurrentDictionary<ProjectId, Dictionary<string, string>> _projectToInstalledPackageAndVersion = new ConcurrentDictionary<ProjectId, Dictionary<string, string>>(); [ImportingConstructor] public PackageInstallerService( VisualStudioWorkspaceImpl workspace, SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) : base(workspace, SymbolSearchOptions.Enabled, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInNuGetPackages) { _workspace = workspace; _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; } public ImmutableArray<PackageSource> PackageSources { get; private set; } = ImmutableArray<PackageSource>.Empty; public event EventHandler PackageSourcesChanged; public bool IsEnabled => _packageServices != null; protected override void EnableService() { // Our service has been enabled. Now load the VS package dlls. var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var packageInstallerServices = componentModel.GetExtensions<IVsPackageInstallerServices>().FirstOrDefault(); var packageInstaller = componentModel.GetExtensions<IVsPackageInstaller2>().FirstOrDefault(); var packageUninstaller = componentModel.GetExtensions<IVsPackageUninstaller>().FirstOrDefault(); var packageSourceProvider = componentModel.GetExtensions<IVsPackageSourceProvider>().FirstOrDefault(); if (packageInstallerServices == null || packageInstaller == null || packageUninstaller == null || packageSourceProvider == null) { return; } _packageServices = new PackageServicesProxy( packageInstallerServices, packageInstaller, packageUninstaller, packageSourceProvider); // Start listening to additional events workspace changes. _workspace.WorkspaceChanged += OnWorkspaceChanged; _packageServices.SourcesChanged += OnSourceProviderSourcesChanged; } protected override void StartWorking() { this.AssertIsForeground(); if (!this.IsEnabled) { return; } OnSourceProviderSourcesChanged(this, EventArgs.Empty); OnWorkspaceChanged(null, new WorkspaceChangeEventArgs( WorkspaceChangeKind.SolutionAdded, null, null)); } private void OnSourceProviderSourcesChanged(object sender, EventArgs e) { if (!this.IsForeground()) { this.InvokeBelowInputPriority(() => OnSourceProviderSourcesChanged(sender, e)); return; } this.AssertIsForeground(); PackageSources = _packageServices.GetSources(includeUnOfficial: true, includeDisabled: false) .Select(r => new PackageSource(r.Key, r.Value)) .ToImmutableArrayOrEmpty(); PackageSourcesChanged?.Invoke(this, EventArgs.Empty); } public bool TryInstallPackage( Workspace workspace, DocumentId documentId, string source, string packageName, string versionOpt, bool includePrerelease, CancellationToken cancellationToken) { this.AssertIsForeground(); // The 'workspace == _workspace' line is probably not necessary. However, we include // it just to make sure that someone isn't trying to install a package into a workspace // other than the VisualStudioWorkspace. if (workspace == _workspace && _workspace != null && _packageServices != null) { var projectId = documentId.ProjectId; var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(SDTE)); var dteProject = _workspace.TryGetDTEProject(projectId); if (dteProject != null) { var description = string.Format(ServicesVSResources.Install_0, packageName); var undoManager = _editorAdaptersFactoryService.TryGetUndoManager( workspace, documentId, cancellationToken); return TryInstallAndAddUndoAction( source, packageName, versionOpt, includePrerelease, dte, dteProject, undoManager); } } return false; } private bool TryInstallPackage( string source, string packageName, string versionOpt, bool includePrerelease, EnvDTE.DTE dte, EnvDTE.Project dteProject) { try { if (!_packageServices.IsPackageInstalled(dteProject, packageName)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0, packageName); if (versionOpt == null) { _packageServices.InstallLatestPackage( source, dteProject, packageName, includePrerelease, ignoreDependencies: false); } else { _packageServices.InstallPackage( source, dteProject, packageName, versionOpt, ignoreDependencies: false); } var installedVersion = GetInstalledVersion(packageName, dteProject); dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0_completed, GetStatusBarText(packageName, installedVersion)); return true; } // fall through. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Package_install_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Installing_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); // fall through. } return false; } private static string GetStatusBarText(string packageName, string installedVersion) { return installedVersion == null ? packageName : $"{packageName} - {installedVersion}"; } private bool TryUninstallPackage( string packageName, EnvDTE.DTE dte, EnvDTE.Project dteProject) { this.AssertIsForeground(); try { if (_packageServices.IsPackageInstalled(dteProject, packageName)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0, packageName); var installedVersion = GetInstalledVersion(packageName, dteProject); _packageServices.UninstallPackage(dteProject, packageName, removeDependencies: true); dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0_completed, GetStatusBarText(packageName, installedVersion)); return true; } // fall through. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Package_uninstall_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Uninstalling_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); // fall through. } return false; } private string GetInstalledVersion(string packageName, EnvDTE.Project dteProject) { this.AssertIsForeground(); try { var installedPackages = _packageServices.GetInstalledPackages(dteProject); var metadata = installedPackages.FirstOrDefault(m => m.Id == packageName); return metadata?.VersionString; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return null; } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { ThisCanBeCalledOnAnyThread(); bool localSolutionChanged = false; ProjectId localChangedProject = null; switch (e.Kind) { default: // Nothing to do for any other events. return; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: localChangedProject = e.ProjectId; break; case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: localSolutionChanged = true; break; } lock (_gate) { // Augment the data that the foreground thread will process. _solutionChanged |= localSolutionChanged; if (localChangedProject != null) { _changedProjects.Add(localChangedProject); } // Now cancel any inflight work that is processing the data. _tokenSource.Cancel(); _tokenSource = new CancellationTokenSource(); // And enqueue a new job to process things. Wait one second before starting. // That way if we get a flurry of events we'll end up processing them after // they've all come in. var cancellationToken = _tokenSource.Token; Task.Delay(TimeSpan.FromSeconds(1), cancellationToken) .ContinueWith(_ => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundTaskScheduler); } } private void ProcessBatchedChangesOnForeground(CancellationToken cancellationToken) { this.AssertIsForeground(); // If we've been asked to stop, then there's no point proceeding. if (cancellationToken.IsCancellationRequested) { return; } // If we've been disconnected, then there's no point proceeding. if (_workspace == null || _packageServices == null) { return; } // Get a project to process. var solution = _workspace.CurrentSolution; var projectId = DequeueNextProject(solution); if (projectId == null) { // No project to process, nothing to do. return; } // Process this single project. ProcessProjectChange(solution, projectId); // After processing this single project, yield so the foreground thread // can do more work. Then go and loop again so we can process the // rest of the projects. Task.Factory.SafeStartNew( () => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, ForegroundTaskScheduler); } private ProjectId DequeueNextProject(Solution solution) { this.AssertIsForeground(); lock (_gate) { // If we detected a solution change, then we need to process all projects. // This includes all the projects that we already know about, as well as // all the projects in the current workspace solution. if (_solutionChanged) { _changedProjects.AddRange(solution.ProjectIds); _changedProjects.AddRange(_projectToInstalledPackageAndVersion.Keys); } _solutionChanged = false; // Remove and return the first project in the list. var projectId = _changedProjects.FirstOrDefault(); _changedProjects.Remove(projectId); return projectId; } } private void ProcessProjectChange(Solution solution, ProjectId projectId) { this.AssertIsForeground(); // Remove anything we have associated with this project. _projectToInstalledPackageAndVersion.TryRemove(projectId, out var installedPackages); if (!solution.ContainsProject(projectId)) { // Project was removed. Nothing needs to be done. return; } // Project was changed in some way. Let's go find the set of installed packages for it. var dteProject = _workspace.TryGetDTEProject(projectId); if (dteProject == null) { // Don't have a DTE project for this project ID. not something we can query nuget for. return; } installedPackages = new Dictionary<string, string>(); // Calling into nuget. Assume they may fail for any reason. try { var installedPackageMetadata = _packageServices.GetInstalledPackages(dteProject); installedPackages.AddRange(installedPackageMetadata.Select(m => new KeyValuePair<string, string>(m.Id, m.VersionString))); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } _projectToInstalledPackageAndVersion.AddOrUpdate(projectId, installedPackages, (_1, _2) => installedPackages); } public bool IsInstalled(Workspace workspace, ProjectId projectId, string packageName) { ThisCanBeCalledOnAnyThread(); return _projectToInstalledPackageAndVersion.TryGetValue(projectId, out var installedPackages) && installedPackages.ContainsKey(packageName); } public ImmutableArray<string> GetInstalledVersions(string packageName) { ThisCanBeCalledOnAnyThread(); var installedVersions = new HashSet<string>(); foreach (var installedPackages in _projectToInstalledPackageAndVersion.Values) { string version = null; if (installedPackages?.TryGetValue(packageName, out version) == true && version != null) { installedVersions.Add(version); } } // Order the versions with a weak heuristic so that 'newer' versions come first. // Essentially, we try to break the version on dots, and then we use a LogicalComparer // to try to more naturally order the things we see between the dots. var versionsAndSplits = installedVersions.Select(v => new { Version = v, Split = v.Split('.') }).ToList(); versionsAndSplits.Sort((v1, v2) => { var diff = CompareSplit(v1.Split, v2.Split); return diff != 0 ? diff : -v1.Version.CompareTo(v2.Version); }); return versionsAndSplits.Select(v => v.Version).ToImmutableArray(); } private int CompareSplit(string[] split1, string[] split2) { ThisCanBeCalledOnAnyThread(); for (int i = 0, n = Math.Min(split1.Length, split2.Length); i < n; i++) { // Prefer things that look larger. i.e. 7 should come before 6. // Use a logical string comparer so that 10 is understood to be // greater than 3. var diff = -LogicalStringComparer.Instance.Compare(split1[i], split2[i]); if (diff != 0) { return diff; } } // Choose the one with more parts. return split2.Length - split1.Length; } public IEnumerable<Project> GetProjectsWithInstalledPackage(Solution solution, string packageName, string version) { ThisCanBeCalledOnAnyThread(); var result = new List<Project>(); foreach (var kvp in this._projectToInstalledPackageAndVersion) { var installedPackageAndVersion = kvp.Value; if (installedPackageAndVersion != null) { if (installedPackageAndVersion.TryGetValue(packageName, out var installedVersion) && installedVersion == version) { var project = solution.GetProject(kvp.Key); if (project != null) { result.Add(project); } } } } return result; } public void ShowManagePackagesDialog(string packageName) { this.AssertIsForeground(); var shell = (IVsShell)_serviceProvider.GetService(typeof(SVsShell)); if (shell == null) { return; } var nugetGuid = new Guid("5fcc8577-4feb-4d04-ad72-d6c629b083cc"); shell.LoadPackage(ref nugetGuid, out var nugetPackage); if (nugetPackage == null) { return; } // We're able to launch the package manager (with an item in its search box) by // using the IVsSearchProvider API that the nuget package exposes. // // We get that interface for it and then pass it a SearchQuery that effectively // wraps the package name we're looking for. The NuGet package will then read // out that string and populate their search box with it. var extensionProvider = (IVsPackageExtensionProvider)nugetPackage; var extensionGuid = new Guid("042C2B4B-C7F7-49DB-B7A2-402EB8DC7892"); var emptyGuid = Guid.Empty; var searchProvider = (IVsSearchProvider)extensionProvider.CreateExtensionInstance(ref emptyGuid, ref extensionGuid); var task = searchProvider.CreateSearch(dwCookie: 1, pSearchQuery: new SearchQuery(packageName), pSearchCallback: this); task.Start(); } public void ReportProgress(IVsSearchTask pTask, uint dwProgress, uint dwMaxProgress) { } public void ReportComplete(IVsSearchTask pTask, uint dwResultsFound) { } public void ReportResult(IVsSearchTask pTask, IVsSearchItemResult pSearchItemResult) { pSearchItemResult.InvokeAction(); } public void ReportResults(IVsSearchTask pTask, uint dwResults, IVsSearchItemResult[] pSearchItemResults) { } private class SearchQuery : IVsSearchQuery { public SearchQuery(string packageName) { this.SearchString = packageName; } public string SearchString { get; } public uint ParseError => 0; public uint GetTokens(uint dwMaxTokens, IVsSearchToken[] rgpSearchTokens) { return 0; } } private class PackageServicesProxy : IPackageServicesProxy { private readonly IVsPackageInstaller2 _packageInstaller; private readonly IVsPackageInstallerServices _packageInstallerServices; private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly IVsPackageUninstaller _packageUninstaller; public PackageServicesProxy( IVsPackageInstallerServices packageInstallerServices, IVsPackageInstaller2 packageInstaller, IVsPackageUninstaller packageUninstaller, IVsPackageSourceProvider packageSourceProvider) { _packageInstallerServices = packageInstallerServices; _packageInstaller = packageInstaller; _packageUninstaller = packageUninstaller; _packageSourceProvider = packageSourceProvider; } public event EventHandler SourcesChanged { add { _packageSourceProvider.SourcesChanged += value; } remove { _packageSourceProvider.SourcesChanged -= value; } } public IEnumerable<PackageMetadata> GetInstalledPackages(EnvDTE.Project project) { return _packageInstallerServices.GetInstalledPackages(project) .Select(m => new PackageMetadata(m.Id, m.VersionString)) .ToList(); } public bool IsPackageInstalled(EnvDTE.Project project, string id) => _packageInstallerServices.IsPackageInstalled(project, id); public void InstallPackage(string source, EnvDTE.Project project, string packageId, string version, bool ignoreDependencies) => _packageInstaller.InstallPackage(source, project, packageId, version, ignoreDependencies); public void InstallLatestPackage(string source, EnvDTE.Project project, string packageId, bool includePrerelease, bool ignoreDependencies) => _packageInstaller.InstallLatestPackage(source, project, packageId, includePrerelease, ignoreDependencies); public IEnumerable<KeyValuePair<string, string>> GetSources(bool includeUnOfficial, bool includeDisabled) => _packageSourceProvider.GetSources(includeUnOfficial, includeDisabled); public void UninstallPackage(EnvDTE.Project project, string packageId, bool removeDependencies) => _packageUninstaller.UninstallPackage(project, packageId, removeDependencies); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public class zip_ReadTests { [Fact] public static async Task ReadNormal() { await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("normal.zip"), ZipTest.zfolder("normal"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("fake64.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("empty.zip"), ZipTest.zfolder("empty"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("appended.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("prepended.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("emptydir.zip"), ZipTest.zfolder("emptydir"), ZipArchiveMode.Read); await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("small.zip"), ZipTest.zfolder("small"), ZipArchiveMode.Read); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)] { await ZipTest.IsZipSameAsDirAsync( ZipTest.zfile("unicode.zip"), ZipTest.zfolder("unicode"), ZipArchiveMode.Read); } } [Fact] public static async Task ReadStreaming() { //don't include large, because that means loading the whole thing in memory await TestStreamingRead(ZipTest.zfile("normal.zip"), ZipTest.zfolder("normal")); await TestStreamingRead(ZipTest.zfile("fake64.zip"), ZipTest.zfolder("small")); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(846, PlatformID.AnyUnix)] { await TestStreamingRead(ZipTest.zfile("unicode.zip"), ZipTest.zfolder("unicode")); } await TestStreamingRead(ZipTest.zfile("empty.zip"), ZipTest.zfolder("empty")); await TestStreamingRead(ZipTest.zfile("appended.zip"), ZipTest.zfolder("small")); await TestStreamingRead(ZipTest.zfile("prepended.zip"), ZipTest.zfolder("small")); await TestStreamingRead(ZipTest.zfile("emptydir.zip"), ZipTest.zfolder("emptydir")); } private static async Task TestStreamingRead(String zipFile, String directory) { using (var stream = await StreamHelpers.CreateTempCopyStream(zipFile)) { Stream wrapped = new WrappedStream(stream, true, false, false, null); ZipTest.IsZipSameAsDir(wrapped, directory, ZipArchiveMode.Read, false, false); Assert.False(wrapped.CanRead, "Wrapped stream should be closed at this point"); //check that it was closed } } [Fact] public static async Task ReadStreamOps() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")), ZipArchiveMode.Read)) { foreach (ZipArchiveEntry e in archive.Entries) { using (Stream s = e.Open()) { Assert.True(s.CanRead, "Can read to read archive"); Assert.False(s.CanWrite, "Can't write to read archive"); Assert.False(s.CanSeek, "Can't seek on archive"); Assert.Equal(ZipTest.LengthOfUnseekableStream(s), e.Length); //"Length is not correct on unseekable stream" } } } } [Fact] public static async Task ReadInterleaved() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")))) { ZipArchiveEntry e1 = archive.GetEntry("first.txt"); ZipArchiveEntry e2 = archive.GetEntry("notempty/second.txt"); //read all of e1 and e2's contents Byte[] e1readnormal = new Byte[e1.Length]; Byte[] e2readnormal = new Byte[e2.Length]; Byte[] e1interleaved = new Byte[e1.Length]; Byte[] e2interleaved = new Byte[e2.Length]; using (Stream e1s = e1.Open()) { ZipTest.ReadBytes(e1s, e1readnormal, e1.Length); } using (Stream e2s = e2.Open()) { ZipTest.ReadBytes(e2s, e2readnormal, e2.Length); } //now read interleaved, assume we are working with < 4gb files const Int32 bytesAtATime = 15; using (Stream e1s = e1.Open(), e2s = e2.Open()) { Int32 e1pos = 0; Int32 e2pos = 0; while (e1pos < e1.Length || e2pos < e2.Length) { if (e1pos < e1.Length) { Int32 e1bytesRead = e1s.Read(e1interleaved, e1pos, bytesAtATime + e1pos > e1.Length ? (Int32)e1.Length - e1pos : bytesAtATime); e1pos += e1bytesRead; } if (e2pos < e2.Length) { Int32 e2bytesRead = e2s.Read(e2interleaved, e2pos, bytesAtATime + e2pos > e2.Length ? (Int32)e2.Length - e2pos : bytesAtATime); e2pos += e2bytesRead; } } } //now compare to original read ZipTest.ArraysEqual<Byte>(e1readnormal, e1interleaved, e1readnormal.Length); ZipTest.ArraysEqual<Byte>(e2readnormal, e2interleaved, e2readnormal.Length); //now read one entry interleaved Byte[] e1selfInterleaved1 = new Byte[e1.Length]; Byte[] e1selfInterleaved2 = new Byte[e2.Length]; using (Stream s1 = e1.Open(), s2 = e1.Open()) { Int32 s1pos = 0; Int32 s2pos = 0; while (s1pos < e1.Length || s2pos < e1.Length) { if (s1pos < e1.Length) { Int32 s1bytesRead = s1.Read(e1interleaved, s1pos, bytesAtATime + s1pos > e1.Length ? (Int32)e1.Length - s1pos : bytesAtATime); s1pos += s1bytesRead; } if (s2pos < e1.Length) { Int32 s2bytesRead = s2.Read(e2interleaved, s2pos, bytesAtATime + s2pos > e1.Length ? (Int32)e1.Length - s2pos : bytesAtATime); s2pos += s2bytesRead; } } } //now compare to original read ZipTest.ArraysEqual<Byte>(e1readnormal, e1selfInterleaved1, e1readnormal.Length); ZipTest.ArraysEqual<Byte>(e1readnormal, e1selfInterleaved2, e1readnormal.Length); } } [Fact] public static async Task ReadModeInvalidOpsTest() { ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")), ZipArchiveMode.Read); ZipArchiveEntry e = archive.GetEntry("first.txt"); //should also do it on deflated stream //on archive Assert.Throws<NotSupportedException>(() => archive.CreateEntry("hi there")); //"Should not be able to create entry" //on entry Assert.Throws<NotSupportedException>(() => e.Delete()); //"Should not be able to delete entry" //Throws<NotSupportedException>(() => e.MoveTo("dirka")); Assert.Throws<NotSupportedException>(() => e.LastWriteTime = new DateTimeOffset()); //"Should not be able to update time" //on stream Stream s = e.Open(); Assert.Throws<NotSupportedException>(() => s.Flush()); //"Should not be able to flush on read stream" Assert.Throws<NotSupportedException>(() => s.WriteByte(25)); //"should not be able to write to read stream" Assert.Throws<NotSupportedException>(() => s.Position = 4); //"should not be able to seek on read stream" Assert.Throws<NotSupportedException>(() => s.Seek(0, SeekOrigin.Begin)); //"should not be able to seek on read stream" Assert.Throws<NotSupportedException>(() => s.SetLength(0)); //"should not be able to resize read stream" archive.Dispose(); //after disposed Assert.Throws<ObjectDisposedException>(() => { var x = archive.Entries; }); //"Should not be able to get entries on disposed archive" Assert.Throws<NotSupportedException>(() => archive.CreateEntry("dirka")); //"should not be able to create on disposed archive" Assert.Throws<ObjectDisposedException>(() => e.Open()); //"should not be able to open on disposed archive" Assert.Throws<NotSupportedException>(() => e.Delete()); //"should not be able to delete on disposed archive" Assert.Throws<ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); }); //"Should not be able to update on disposed archive" Assert.Throws<NotSupportedException>(() => s.ReadByte()); //"should not be able to read on disposed archive" s.Dispose(); } } }
using System; using System.Collections.Generic; using System.Composition; using System.IO; using System.Linq; using System.Net.WebSockets; using System.Reflection; using System.Security.Claims; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.FeatureModel; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Core; using Microsoft.CodeAnalysis; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.Logging; using Microsoft.Framework.Runtime; using Newtonsoft.Json; using OmniSharp.Mef; using OmniSharp.Middleware; using OmniSharp.Models; using OmniSharp.Models.v1; using OmniSharp.Roslyn.CSharp.Services; using OmniSharp.Services; using Xunit; namespace OmniSharp.Tests { public class EndpointMiddlewareFacts { [OmniSharpHandler(OmnisharpEndpoints.GotoDefinition, LanguageNames.CSharp)] public class GotoDefinitionService : RequestHandler<GotoDefinitionRequest, GotoDefinitionResponse> { [Import] public OmnisharpWorkspace Workspace { get; set; } public Task<GotoDefinitionResponse> Handle(GotoDefinitionRequest request) { return Task.FromResult<GotoDefinitionResponse>(null); } } [OmniSharpHandler(OmnisharpEndpoints.FindSymbols, LanguageNames.CSharp)] public class FindSymbolsService : RequestHandler<FindSymbolsRequest, QuickFixResponse> { [Import] public OmnisharpWorkspace Workspace { get; set; } public Task<QuickFixResponse> Handle(FindSymbolsRequest request) { return Task.FromResult<QuickFixResponse>(null); } } [OmniSharpHandler(OmnisharpEndpoints.UpdateBuffer, LanguageNames.CSharp)] public class UpdateBufferService : RequestHandler<UpdateBufferRequest, object> { [Import] public OmnisharpWorkspace Workspace { get; set; } public Task<object> Handle(UpdateBufferRequest request) { return Task.FromResult<object>(null); } } class Response { } [Export(typeof(IProjectSystem))] class FakeProjectSystem : IProjectSystem { public string Key { get { return "Fake"; } } public string Language { get { return LanguageNames.CSharp; } } public IEnumerable<string> Extensions { get; } = new[] { ".cs" }; public Task<object> GetInformationModel(WorkspaceInformationRequest request) { throw new NotImplementedException(); } public Task<object> GetProjectModel(string path) { throw new NotImplementedException(); } public void Initalize(IConfiguration configuration) { } } class LoggerFactory : ILoggerFactory { public LogLevel MinimumLevel { get; set; } public void AddProvider(ILoggerProvider provider) { } public ILogger CreateLogger(string categoryName) { return new Logger(); } } class Disposable : IDisposable { public void Dispose() { } } class Logger : ILogger { public IDisposable BeginScope(object state) { return new Disposable(); } public bool IsEnabled(LogLevel logLevel) { return true; } public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter) { } } [Fact] public async Task Passes_through_for_invalid_path() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/notvalid"); await Assert.ThrowsAsync<NotImplementedException>(() => middleware.Invoke(context)); } [Fact] public async Task Does_not_throw_for_valid_path() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly, typeof(EndpointDescriptor).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/gotodefinition"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new GotoDefinitionRequest { FileName = "bar.cs", Line = 2, Column = 14, Timeout = 60000 }) ) ); await middleware.Invoke(context); Assert.True(true); } [Fact] public async Task Passes_through_to_services() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly, typeof(EndpointDescriptor).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/gotodefinition"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new GotoDefinitionRequest { FileName = "bar.cs", Line = 2, Column = 14, Timeout = 60000 }) ) ); await middleware.Invoke(context); Assert.True(true); } [Fact] public async Task Passes_through_to_all_services_with_delegate() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly, typeof(EndpointDescriptor).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/findsymbols"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new FindSymbolsRequest { }) ) ); await middleware.Invoke(context); Assert.True(true); } [Fact] public async Task Passes_through_to_specific_service_with_delegate() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly, typeof(EndpointDescriptor).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/findsymbols"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new FindSymbolsRequest { Language = LanguageNames.CSharp }) ) ); await middleware.Invoke(context); Assert.True(true); } public Func<ThrowRequest, Task<ThrowResponse>> ThrowDelegate = (request) => { return Task.FromResult<ThrowResponse>(null); }; [OmniSharpEndpoint("/throw", typeof(ThrowRequest), typeof(ThrowResponse))] public class ThrowRequest : IRequest { } public class ThrowResponse { } [Fact] public async Task Should_throw_if_type_is_not_mergeable() { RequestDelegate _next = async (ctx) => await Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/throw"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new ThrowRequest()) ) ); await Assert.ThrowsAsync<NotSupportedException>(async () => await middleware.Invoke(context)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.MachineLearning.CommitmentPlans { using Microsoft.Rest.Azure; using Models; /// <summary> /// CommitmentPlansOperations operations. /// </summary> public partial interface ICommitmentPlansOperations { /// <summary> /// Retrieve an Azure ML commitment plan by its subscription, resource /// group and name. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='commitmentPlanName'> /// The Azure ML commitment plan name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CommitmentPlan>> GetWithHttpMessagesAsync(string resourceGroupName, string commitmentPlanName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates a new Azure ML commitment plan resource or updates an /// existing one. /// </summary> /// <param name='createOrUpdatePayload'> /// The payload to create or update the Azure ML commitment plan. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='commitmentPlanName'> /// The Azure ML commitment plan name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CommitmentPlan>> CreateOrUpdateWithHttpMessagesAsync(CommitmentPlan createOrUpdatePayload, string resourceGroupName, string commitmentPlanName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Remove an existing Azure ML commitment plan. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='commitmentPlanName'> /// The Azure ML commitment plan name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> RemoveWithHttpMessagesAsync(string resourceGroupName, string commitmentPlanName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Patch an existing Azure ML commitment plan resource. /// </summary> /// <param name='patchPayload'> /// The payload to patch the Azure ML commitment plan with. Only tags /// and SKU may be modified on an existing commitment plan. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='commitmentPlanName'> /// The Azure ML commitment plan name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CommitmentPlan>> PatchWithHttpMessagesAsync(CommitmentPlanPatchPayload patchPayload, string resourceGroupName, string commitmentPlanName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Retrieve all Azure ML commitment plans in a subscription. /// </summary> /// <param name='skipToken'> /// Continuation token for pagination. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>> ListWithHttpMessagesAsync(string skipToken = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Retrieve all Azure ML commitment plans in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='skipToken'> /// Continuation token for pagination. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>> ListInResourceGroupWithHttpMessagesAsync(string resourceGroupName, string skipToken = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Retrieve all Azure ML commitment plans in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Retrieve all Azure ML commitment plans in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CommitmentPlan>>> ListInResourceGroupNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Hosting; using OrchardCore.DisplayManagement.Events; using OrchardCore.DisplayManagement.Extensions; using OrchardCore.Environment.Extensions; using OrchardCore.Environment.Extensions.Features; using OrchardCore.Modules; using OrchardCore.Tests.Stubs; using Xunit; namespace OrchardCore.Tests.Extensions { public class ExtensionManagerTests { private static IHostEnvironment HostingEnvironment = new StubHostingEnvironment(); private static IApplicationContext ApplicationContext = new ModularApplicationContext(HostingEnvironment, new List<IModuleNamesProvider>() { new ModuleNamesProvider() }); private static IFeaturesProvider ModuleFeatureProvider = new FeaturesProvider(new[] { new ThemeFeatureBuilderEvents() }); private static IFeaturesProvider ThemeFeatureProvider = new FeaturesProvider(new[] { new ThemeFeatureBuilderEvents() }); private IExtensionManager ModuleScopedExtensionManager; private IExtensionManager ThemeScopedExtensionManager; private IExtensionManager ModuleThemeScopedExtensionManager; public ExtensionManagerTests() { ModuleScopedExtensionManager = new ExtensionManager( ApplicationContext, new[] { new ExtensionDependencyStrategy() }, new[] { new ExtensionPriorityStrategy() }, new TypeFeatureProvider(), ModuleFeatureProvider, new NullLogger<ExtensionManager>() ); ThemeScopedExtensionManager = new ExtensionManager( ApplicationContext, new[] { new ExtensionDependencyStrategy() }, new[] { new ExtensionPriorityStrategy() }, new TypeFeatureProvider(), ThemeFeatureProvider, new NullLogger<ExtensionManager>() ); ModuleThemeScopedExtensionManager = new ExtensionManager( ApplicationContext, new IExtensionDependencyStrategy[] { new ExtensionDependencyStrategy(), new ThemeExtensionDependencyStrategy() }, new[] { new ExtensionPriorityStrategy() }, new TypeFeatureProvider(), ThemeFeatureProvider, new NullLogger<ExtensionManager>() ); } private class ModuleNamesProvider : IModuleNamesProvider { private readonly string[] _moduleNames; public ModuleNamesProvider() { _moduleNames = new[] { "BaseThemeSample", "BaseThemeSample2", "DerivedThemeSample", "DerivedThemeSample2", "ModuleSample" }; } public IEnumerable<string> GetModuleNames() { return _moduleNames; } } [Fact] public void ShouldReturnExtension() { var extensions = ModuleThemeScopedExtensionManager.GetExtensions() .Where(e => e.Manifest.ModuleInfo.Category == "Test"); Assert.Equal(5, extensions.Count()); } [Fact] public void ShouldReturnAllDependenciesIncludingFeatureForAGivenFeatureOrdered() { var features = ModuleScopedExtensionManager.GetFeatureDependencies("Sample3"); Assert.Equal(3, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); } [Fact] public void ShouldNotReturnFeaturesNotDependentOn() { var features = ModuleScopedExtensionManager.GetFeatureDependencies("Sample2"); Assert.Equal(2, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); } [Fact] public void GetDependentFeaturesShouldReturnAllFeaturesThatHaveADependencyOnAFeature() { var features = ModuleScopedExtensionManager.GetDependentFeatures("Sample1"); Assert.Equal(4, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("Sample4", features.ElementAt(3).Id); } [Fact] public void GetFeaturesShouldReturnAllFeaturesOrderedByDependency() { var features = ModuleScopedExtensionManager.GetFeatures() .Where(f => f.Category == "Test" && !f.Extension.IsTheme()); Assert.Equal(4, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("Sample4", features.ElementAt(3).Id); } [Fact] public void GetFeaturesWithAIdShouldReturnThatFeatureWithDependenciesOrdered() { var features = ModuleScopedExtensionManager.GetFeatures(new[] { "Sample2" }); Assert.Equal(2, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); } [Fact] public void GetFeaturesWithAIdShouldReturnThatFeatureWithDependenciesOrderedWithNoDuplicates() { var features = ModuleScopedExtensionManager.GetFeatures(new[] { "Sample2", "Sample3" }); Assert.Equal(3, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); } [Fact] public void GetFeaturesWithAIdShouldNotReturnFeaturesTheHaveADependencyOutsideOfGraph() { var features = ModuleScopedExtensionManager.GetFeatures(new[] { "Sample4" }); Assert.Equal(3, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample4", features.ElementAt(2).Id); } /* Theme Base Theme Dependencies */ [Fact] public void GetFeaturesShouldReturnCorrectThemeHeirarchy() { var features = ThemeScopedExtensionManager.GetFeatures(new[] { "DerivedThemeSample" }); Assert.Equal(2, features.Count()); Assert.Equal("BaseThemeSample", features.ElementAt(0).Id); Assert.Equal("DerivedThemeSample", features.ElementAt(1).Id); } /* Theme and Module Dependencies */ [Fact] public void GetFeaturesShouldReturnBothThemesAndModules() { var features = ModuleThemeScopedExtensionManager.GetFeatures() .Where(f => f.Category == "Test"); Assert.Equal(8, features.Count()); } [Fact] public void GetFeaturesShouldReturnThemesAfterModules() { var features = ModuleThemeScopedExtensionManager.GetFeatures() .Where(f => f.Category == "Test"); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("Sample4", features.ElementAt(3).Id); Assert.Equal("BaseThemeSample", features.ElementAt(4).Id); Assert.Equal("BaseThemeSample2", features.ElementAt(5).Id); Assert.Equal("DerivedThemeSample", features.ElementAt(6).Id); Assert.Equal("DerivedThemeSample2", features.ElementAt(7).Id); } [Fact] public void GetFeaturesShouldReturnThemesAfterModulesWhenRequestingBoth() { var features = ModuleThemeScopedExtensionManager.GetFeatures(new[] { "DerivedThemeSample", "Sample3" }); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("BaseThemeSample", features.ElementAt(3).Id); Assert.Equal("DerivedThemeSample", features.ElementAt(4).Id); } [Fact] public void ShouldReturnNotFoundExtensionInfoWhenNotFound() { var extension = ModuleThemeScopedExtensionManager.GetExtension("NotFound"); Assert.False(extension.Exists); } } }
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; // <auto-generated /> namespace SAEON.Observations.Data { /// <summary> /// Strongly-typed collection for the Site class. /// </summary> [Serializable] public partial class SiteCollection : ActiveList<Site, SiteCollection> { public SiteCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SiteCollection</returns> public SiteCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Site 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 Site table. /// </summary> [Serializable] public partial class Site : ActiveRecord<Site>, IActiveRecord { #region .ctors and Default Settings public Site() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Site(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Site(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Site(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("Site", TableType.Table, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @"(newid())"; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarCode = new TableSchema.TableColumn(schema); colvarCode.ColumnName = "Code"; colvarCode.DataType = DbType.AnsiString; colvarCode.MaxLength = 50; colvarCode.AutoIncrement = false; colvarCode.IsNullable = false; colvarCode.IsPrimaryKey = false; colvarCode.IsForeignKey = false; colvarCode.IsReadOnly = false; colvarCode.DefaultSetting = @""; colvarCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarCode); TableSchema.TableColumn colvarName = new TableSchema.TableColumn(schema); colvarName.ColumnName = "Name"; colvarName.DataType = DbType.AnsiString; colvarName.MaxLength = 150; colvarName.AutoIncrement = false; colvarName.IsNullable = false; colvarName.IsPrimaryKey = false; colvarName.IsForeignKey = false; colvarName.IsReadOnly = false; colvarName.DefaultSetting = @""; colvarName.ForeignKeyTableName = ""; schema.Columns.Add(colvarName); TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema); colvarDescription.ColumnName = "Description"; colvarDescription.DataType = DbType.AnsiString; colvarDescription.MaxLength = 5000; colvarDescription.AutoIncrement = false; colvarDescription.IsNullable = true; colvarDescription.IsPrimaryKey = false; colvarDescription.IsForeignKey = false; colvarDescription.IsReadOnly = false; colvarDescription.DefaultSetting = @""; colvarDescription.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescription); TableSchema.TableColumn colvarUrl = new TableSchema.TableColumn(schema); colvarUrl.ColumnName = "Url"; colvarUrl.DataType = DbType.AnsiString; colvarUrl.MaxLength = 250; colvarUrl.AutoIncrement = false; colvarUrl.IsNullable = true; colvarUrl.IsPrimaryKey = false; colvarUrl.IsForeignKey = false; colvarUrl.IsReadOnly = false; colvarUrl.DefaultSetting = @""; colvarUrl.ForeignKeyTableName = ""; schema.Columns.Add(colvarUrl); TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema); colvarStartDate.ColumnName = "StartDate"; colvarStartDate.DataType = DbType.Date; colvarStartDate.MaxLength = 0; colvarStartDate.AutoIncrement = false; colvarStartDate.IsNullable = true; colvarStartDate.IsPrimaryKey = false; colvarStartDate.IsForeignKey = false; colvarStartDate.IsReadOnly = false; colvarStartDate.DefaultSetting = @""; colvarStartDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarStartDate); TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema); colvarEndDate.ColumnName = "EndDate"; colvarEndDate.DataType = DbType.Date; colvarEndDate.MaxLength = 0; colvarEndDate.AutoIncrement = false; colvarEndDate.IsNullable = true; colvarEndDate.IsPrimaryKey = false; colvarEndDate.IsForeignKey = false; colvarEndDate.IsReadOnly = false; colvarEndDate.DefaultSetting = @""; colvarEndDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarEndDate); TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema); colvarUserId.ColumnName = "UserId"; colvarUserId.DataType = DbType.Guid; colvarUserId.MaxLength = 0; colvarUserId.AutoIncrement = false; colvarUserId.IsNullable = false; colvarUserId.IsPrimaryKey = false; colvarUserId.IsForeignKey = true; colvarUserId.IsReadOnly = false; colvarUserId.DefaultSetting = @""; colvarUserId.ForeignKeyTableName = "aspnet_Users"; schema.Columns.Add(colvarUserId); TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema); colvarAddedAt.ColumnName = "AddedAt"; colvarAddedAt.DataType = DbType.DateTime; colvarAddedAt.MaxLength = 0; colvarAddedAt.AutoIncrement = false; colvarAddedAt.IsNullable = true; colvarAddedAt.IsPrimaryKey = false; colvarAddedAt.IsForeignKey = false; colvarAddedAt.IsReadOnly = false; colvarAddedAt.DefaultSetting = @"(getdate())"; colvarAddedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddedAt); TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema); colvarUpdatedAt.ColumnName = "UpdatedAt"; colvarUpdatedAt.DataType = DbType.DateTime; colvarUpdatedAt.MaxLength = 0; colvarUpdatedAt.AutoIncrement = false; colvarUpdatedAt.IsNullable = true; colvarUpdatedAt.IsPrimaryKey = false; colvarUpdatedAt.IsForeignKey = false; colvarUpdatedAt.IsReadOnly = false; colvarUpdatedAt.DefaultSetting = @"(getdate())"; colvarUpdatedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarUpdatedAt); TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema); colvarRowVersion.ColumnName = "RowVersion"; colvarRowVersion.DataType = DbType.Binary; colvarRowVersion.MaxLength = 0; colvarRowVersion.AutoIncrement = false; colvarRowVersion.IsNullable = false; colvarRowVersion.IsPrimaryKey = false; colvarRowVersion.IsForeignKey = false; colvarRowVersion.IsReadOnly = true; colvarRowVersion.DefaultSetting = @""; colvarRowVersion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRowVersion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("Site",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Code")] [Bindable(true)] public string Code { get { return GetColumnValue<string>(Columns.Code); } set { SetColumnValue(Columns.Code, value); } } [XmlAttribute("Name")] [Bindable(true)] public string Name { get { return GetColumnValue<string>(Columns.Name); } set { SetColumnValue(Columns.Name, value); } } [XmlAttribute("Description")] [Bindable(true)] public string Description { get { return GetColumnValue<string>(Columns.Description); } set { SetColumnValue(Columns.Description, value); } } [XmlAttribute("Url")] [Bindable(true)] public string Url { get { return GetColumnValue<string>(Columns.Url); } set { SetColumnValue(Columns.Url, value); } } [XmlAttribute("StartDate")] [Bindable(true)] public DateTime? StartDate { get { return GetColumnValue<DateTime?>(Columns.StartDate); } set { SetColumnValue(Columns.StartDate, value); } } [XmlAttribute("EndDate")] [Bindable(true)] public DateTime? EndDate { get { return GetColumnValue<DateTime?>(Columns.EndDate); } set { SetColumnValue(Columns.EndDate, value); } } [XmlAttribute("UserId")] [Bindable(true)] public Guid UserId { get { return GetColumnValue<Guid>(Columns.UserId); } set { SetColumnValue(Columns.UserId, value); } } [XmlAttribute("AddedAt")] [Bindable(true)] public DateTime? AddedAt { get { return GetColumnValue<DateTime?>(Columns.AddedAt); } set { SetColumnValue(Columns.AddedAt, value); } } [XmlAttribute("UpdatedAt")] [Bindable(true)] public DateTime? UpdatedAt { get { return GetColumnValue<DateTime?>(Columns.UpdatedAt); } set { SetColumnValue(Columns.UpdatedAt, value); } } [XmlAttribute("RowVersion")] [Bindable(true)] public byte[] RowVersion { get { return GetColumnValue<byte[]>(Columns.RowVersion); } set { SetColumnValue(Columns.RowVersion, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public SAEON.Observations.Data.ImportBatchSummaryCollection ImportBatchSummaryRecords() { return new SAEON.Observations.Data.ImportBatchSummaryCollection().Where(ImportBatchSummary.Columns.SiteID, Id).Load(); } public SAEON.Observations.Data.OrganisationSiteCollection OrganisationSiteRecords() { return new SAEON.Observations.Data.OrganisationSiteCollection().Where(OrganisationSite.Columns.SiteID, Id).Load(); } public SAEON.Observations.Data.StationCollection StationRecords() { return new SAEON.Observations.Data.StationCollection().Where(Station.Columns.SiteID, Id).Load(); } #endregion #region ForeignKey Properties private SAEON.Observations.Data.AspnetUser _AspnetUser = null; /// <summary> /// Returns a AspnetUser ActiveRecord object related to this Site /// /// </summary> public SAEON.Observations.Data.AspnetUser AspnetUser { // get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); } get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); } set { SetColumnValue("UserId", value.UserId); } } #endregion //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(Guid varId,string varCode,string varName,string varDescription,string varUrl,DateTime? varStartDate,DateTime? varEndDate,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { Site item = new Site(); item.Id = varId; item.Code = varCode; item.Name = varName; item.Description = varDescription; item.Url = varUrl; item.StartDate = varStartDate; item.EndDate = varEndDate; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; 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(Guid varId,string varCode,string varName,string varDescription,string varUrl,DateTime? varStartDate,DateTime? varEndDate,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { Site item = new Site(); item.Id = varId; item.Code = varCode; item.Name = varName; item.Description = varDescription; item.Url = varUrl; item.StartDate = varStartDate; item.EndDate = varEndDate; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; 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 IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CodeColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn NameColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn DescriptionColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn UrlColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn StartDateColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn EndDateColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn UserIdColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn AddedAtColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn UpdatedAtColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn RowVersionColumn { get { return Schema.Columns[10]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string Code = @"Code"; public static string Name = @"Name"; public static string Description = @"Description"; public static string Url = @"Url"; public static string StartDate = @"StartDate"; public static string EndDate = @"EndDate"; public static string UserId = @"UserId"; public static string AddedAt = @"AddedAt"; public static string UpdatedAt = @"UpdatedAt"; public static string RowVersion = @"RowVersion"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
/* * Copyright (c) 2021 Algolia * http://www.algolia.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Algolia.Search.Http; using Algolia.Search.Models.Common; using Algolia.Search.Models.Dictionary; using Algolia.Search.Models.Search; namespace Algolia.Search.Clients { /// <summary> /// Search Client Dictionary interface /// </summary> public interface IDictionaryClient { /// <summary> /// Save dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="dictionaryEntries">Dictionary entries to be saved. entries from the dictionary.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <returns></returns> DictionaryResponse SaveDictionaryEntries(AlgoliaDictionary dictionary, List<DictionaryEntry> dictionaryEntries, RequestOptions requestOptions = null); /// <summary> /// Save dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="dictionaryEntries">Dictionary entries to be saved. entries from the dictionary.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <param name="ct">Cancelation token.</param> /// <returns></returns> Task<DictionaryResponse> SaveDictionaryEntriesAsync(AlgoliaDictionary dictionary, List<DictionaryEntry> dictionaryEntries, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Replace dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="dictionaryEntries">Dictionary entries to be saved. entries from the dictionary.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <returns></returns> DictionaryResponse ReplaceDictionaryEntries(AlgoliaDictionary dictionary, List<DictionaryEntry> dictionaryEntries, RequestOptions requestOptions = null); /// <summary> /// Replace dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="dictionaryEntries">Dictionary entries to be saved. entries from the dictionary.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <param name="ct">Cancelation token.</param> /// <returns></returns> Task<DictionaryResponse> ReplaceDictionaryEntriesAsync(AlgoliaDictionary dictionary, List<DictionaryEntry> dictionaryEntries, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Delete dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="ObjectIDs">List of entries' IDs to delete</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <returns></returns> DictionaryResponse DeleteDictionaryEntries(AlgoliaDictionary dictionary, List<String> ObjectIDs, RequestOptions requestOptions = null); /// <summary> /// Delete dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="ObjectIDs">List of entries' IDs to delete</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <param name="ct">Cancelation token.</param> /// <returns></returns> Task<DictionaryResponse> DeleteDictionaryEntriesAsync(AlgoliaDictionary dictionary, List<String> ObjectIDs, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Clear all dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <returns></returns> DictionaryResponse ClearDictionaryEntries(AlgoliaDictionary dictionary, RequestOptions requestOptions = null); /// <summary> /// Clear all dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <param name="ct">Cancelation token.</param> /// <returns></returns> Task<DictionaryResponse> ClearDictionaryEntriesAsync(AlgoliaDictionary dictionary, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Search the dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="query">The Query used to search.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <typeparam name="T">Type of the data to send/retrieve</typeparam> /// <returns></returns> SearchResponse<T> SearchDictionaryEntries<T>(AlgoliaDictionary dictionary, Query query, RequestOptions requestOptions = null) where T : class; /// <summary> /// Search the dictionary entries. /// </summary> /// <param name="dictionary">Target dictionary.</param> /// <param name="query">The Query used to search.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <param name="ct">Cancelation token.</param> /// <typeparam name="T">Type of the data to send/retrieve</typeparam> /// <returns></returns> Task<SearchResponse<T>> SearchDictionaryEntriesAsync<T>(AlgoliaDictionary dictionary, Query query, RequestOptions requestOptions = null, CancellationToken ct = default) where T : class; /// <summary> /// Update dictionary settings. Only specified settings are overridden; unspecified settings are /// left unchanged. Specifying `null` for a setting resets it to its default value. /// </summary> /// <param name="dictionarySettings">Settings to be applied.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <returns></returns> DictionaryResponse SetDictionarySettings(DictionarySettings dictionarySettings, RequestOptions requestOptions = null); /// <summary> /// Update dictionary settings. Only specified settings are overridden; unspecified settings are /// left unchanged. Specifying `null` for a setting resets it to its default value. /// </summary> /// <param name="dictionarySettings">Settings to be applied.</param> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <param name="ct">Cancelation token.</param> /// <returns></returns> Task<DictionaryResponse> SetDictionarySettingsAsync(DictionarySettings dictionarySettings, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Retrieve dictionaries settings. /// </summary> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <returns></returns> DictionarySettings GetDictionarySettings(RequestOptions requestOptions = null); /// <summary> /// Retrieve dictionaries settings. /// </summary> /// <param name="requestOptions">Configure request locally with RequestOptions.</param> /// <param name="ct">Cancelation token.</param> /// <returns></returns> Task<DictionarySettings> GetDictionarySettingsAsync(RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Wait for a dictionary task to complete before executing the next line of code. All write /// operations in Algolia are asynchronous by design. /// </summary> /// <param name="taskId">taskID returned by Algolia API</param> /// <param name="timeToWait"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> void WaitAppTask(long taskId, int timeToWait = 100, RequestOptions requestOptions = null); /// <summary> /// Wait for a dictionary task to complete before executing the next line of code. All write /// operations in Algolia are asynchronous by design. /// </summary> /// <param name="taskId">taskID returned by Algolia API</param> /// <param name="timeToWait"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Cancelation token.</param> Task WaitAppTaskAsync(long taskId, int timeToWait = 100, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Get the status of the given dictionary task. /// </summary> /// <param name="taskId">taskID returned by Algolia API</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> TaskStatusResponse GetAppTask(long taskId, RequestOptions requestOptions = null); /// <summary> /// Get the status of the given dictionary task. /// </summary> /// <param name="taskId">taskID returned by Algolia API</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Cancelation token.</param> Task<TaskStatusResponse> GetAppTaskAsync(long taskId, RequestOptions requestOptions = null, CancellationToken ct = default); } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; namespace com.adjust.sdk { #if UNITY_IOS public class AdjustiOS { private const string sdkPrefix = "unity4.29.7"; [DllImport("__Internal")] private static extern void _AdjustLaunchApp( string appToken, string environment, string sdkPrefix, string userAgent, string defaultTracker, string extenralDeviceId, string urlStrategy, string sceneName, int allowSuppressLogLevel, int logLevel, int isDeviceKnown, int eventBuffering, int sendInBackground, int allowiAdInfoReading, int allowAdServicesInfoReading, int allowIdfaReading, int deactivateSkAdNetworkHandling, int needsCost, long secretId, long info1, long info2, long info3, long info4, double delayStart, int launchDeferredDeeplink, int isAttributionCallbackImplemented, int isEventSuccessCallbackImplemented, int isEventFailureCallbackImplemented, int isSessionSuccessCallbackImplemented, int isSessionFailureCallbackImplemented, int isDeferredDeeplinkCallbackImplemented, int isConversionValueUpdatedCallbackImplemented); [DllImport("__Internal")] private static extern void _AdjustTrackEvent( string eventToken, double revenue, string currency, string receipt, string transactionId, string callbackId, int isReceiptSet, string jsonCallbackParameters, string jsonPartnerParameters); [DllImport("__Internal")] private static extern void _AdjustSetEnabled(int enabled); [DllImport("__Internal")] private static extern int _AdjustIsEnabled(); [DllImport("__Internal")] private static extern void _AdjustSetOfflineMode(int enabled); [DllImport("__Internal")] private static extern void _AdjustSetDeviceToken(string deviceToken); [DllImport("__Internal")] private static extern void _AdjustAppWillOpenUrl(string url); [DllImport("__Internal")] private static extern string _AdjustGetIdfa(); [DllImport("__Internal")] private static extern string _AdjustGetAdid(); [DllImport("__Internal")] private static extern string _AdjustGetSdkVersion(); [DllImport("__Internal")] private static extern void _AdjustGdprForgetMe(); [DllImport("__Internal")] private static extern void _AdjustDisableThirdPartySharing(); [DllImport("__Internal")] private static extern string _AdjustGetAttribution(); [DllImport("__Internal")] private static extern void _AdjustSendFirstPackages(); [DllImport("__Internal")] private static extern void _AdjustAddSessionPartnerParameter(string key, string value); [DllImport("__Internal")] private static extern void _AdjustAddSessionCallbackParameter(string key, string value); [DllImport("__Internal")] private static extern void _AdjustRemoveSessionPartnerParameter(string key); [DllImport("__Internal")] private static extern void _AdjustRemoveSessionCallbackParameter(string key); [DllImport("__Internal")] private static extern void _AdjustResetSessionPartnerParameters(); [DllImport("__Internal")] private static extern void _AdjustResetSessionCallbackParameters(); [DllImport("__Internal")] private static extern void _AdjustTrackAdRevenue(string source, string payload); [DllImport("__Internal")] private static extern void _AdjustTrackAdRevenueNew( string source, double revenue, string currency, int adImpressionsCount, string adRevenueNetwork, string adRevenueUnit, string adRevenuePlacement, string jsonCallbackParameters, string jsonPartnerParameters); [DllImport("__Internal")] private static extern void _AdjustTrackAppStoreSubscription( string price, string currency, string transactionId, string receipt, string billingStore, string transactionDate, string salesRegion, string jsonCallbackParameters, string jsonPartnerParameters); [DllImport("__Internal")] private static extern void _AdjustTrackThirdPartySharing(int enabled, string jsonGranularOptions); [DllImport("__Internal")] private static extern void _AdjustTrackMeasurementConsent(int enabled); [DllImport("__Internal")] private static extern void _AdjustSetTestOptions( string baseUrl, string gdprUrl, string subscriptionUrl, string extraPath, long timerIntervalInMilliseconds, long timerStartInMilliseconds, long sessionIntervalInMilliseconds, long subsessionIntervalInMilliseconds, int teardown, int deleteState, int noBackoffWait, int iAdFrameworkEnabled, int adServicesFrameworkEnabled); [DllImport("__Internal")] private static extern void _AdjustRequestTrackingAuthorizationWithCompletionHandler(string sceneName); [DllImport("__Internal")] private static extern void _AdjustUpdateConversionValue(int conversionValue); [DllImport("__Internal")] private static extern int _AdjustGetAppTrackingAuthorizationStatus(); [DllImport("__Internal")] private static extern void _AdjustTrackSubsessionStart(); [DllImport("__Internal")] private static extern void _AdjustTrackSubsessionEnd(); public AdjustiOS() {} public static void Start(AdjustConfig adjustConfig) { string appToken = adjustConfig.appToken != null ? adjustConfig.appToken : "ADJ_INVALID"; string sceneName = adjustConfig.sceneName != null ? adjustConfig.sceneName : "ADJ_INVALID"; string userAgent = adjustConfig.userAgent != null ? adjustConfig.userAgent : "ADJ_INVALID"; string defaultTracker = adjustConfig.defaultTracker != null ? adjustConfig.defaultTracker : "ADJ_INVALID"; string externalDeviceId = adjustConfig.externalDeviceId != null ? adjustConfig.externalDeviceId : "ADJ_INVALID"; string urlStrategy = adjustConfig.urlStrategy != null ? adjustConfig.urlStrategy : "ADJ_INVALID"; string environment = adjustConfig.environment.ToLowercaseString(); long info1 = AdjustUtils.ConvertLong(adjustConfig.info1); long info2 = AdjustUtils.ConvertLong(adjustConfig.info2); long info3 = AdjustUtils.ConvertLong(adjustConfig.info3); long info4 = AdjustUtils.ConvertLong(adjustConfig.info4); long secretId = AdjustUtils.ConvertLong(adjustConfig.secretId); double delayStart = AdjustUtils.ConvertDouble(adjustConfig.delayStart); int logLevel = AdjustUtils.ConvertLogLevel(adjustConfig.logLevel); int isDeviceKnown = AdjustUtils.ConvertBool(adjustConfig.isDeviceKnown); int sendInBackground = AdjustUtils.ConvertBool(adjustConfig.sendInBackground); int eventBufferingEnabled = AdjustUtils.ConvertBool(adjustConfig.eventBufferingEnabled); int allowiAdInfoReading = AdjustUtils.ConvertBool(adjustConfig.allowiAdInfoReading); int allowAdServicesInfoReading = AdjustUtils.ConvertBool(adjustConfig.allowAdServicesInfoReading); int allowIdfaReading = AdjustUtils.ConvertBool(adjustConfig.allowIdfaReading); int allowSuppressLogLevel = AdjustUtils.ConvertBool(adjustConfig.allowSuppressLogLevel); int launchDeferredDeeplink = AdjustUtils.ConvertBool(adjustConfig.launchDeferredDeeplink); int deactivateSkAdNetworkHandling = AdjustUtils.ConvertBool(adjustConfig.skAdNetworkHandling); int needsCost = AdjustUtils.ConvertBool(adjustConfig.needsCost); int isAttributionCallbackImplemented = AdjustUtils.ConvertBool(adjustConfig.getAttributionChangedDelegate() != null); int isEventSuccessCallbackImplemented = AdjustUtils.ConvertBool(adjustConfig.getEventSuccessDelegate() != null); int isEventFailureCallbackImplemented = AdjustUtils.ConvertBool(adjustConfig.getEventFailureDelegate() != null); int isSessionSuccessCallbackImplemented = AdjustUtils.ConvertBool(adjustConfig.getSessionSuccessDelegate() != null); int isSessionFailureCallbackImplemented = AdjustUtils.ConvertBool(adjustConfig.getSessionFailureDelegate() != null); int isDeferredDeeplinkCallbackImplemented = AdjustUtils.ConvertBool(adjustConfig.getDeferredDeeplinkDelegate() != null); int isConversionValueUpdatedCallbackImplemented = AdjustUtils.ConvertBool(adjustConfig.getConversionValueUpdatedDelegate() != null); _AdjustLaunchApp( appToken, environment, sdkPrefix, userAgent, defaultTracker, externalDeviceId, urlStrategy, sceneName, allowSuppressLogLevel, logLevel, isDeviceKnown, eventBufferingEnabled, sendInBackground, allowiAdInfoReading, allowAdServicesInfoReading, allowIdfaReading, deactivateSkAdNetworkHandling, needsCost, secretId, info1, info2, info3, info4, delayStart, launchDeferredDeeplink, isAttributionCallbackImplemented, isEventSuccessCallbackImplemented, isEventFailureCallbackImplemented, isSessionSuccessCallbackImplemented, isSessionFailureCallbackImplemented, isDeferredDeeplinkCallbackImplemented, isConversionValueUpdatedCallbackImplemented); } public static void TrackEvent(AdjustEvent adjustEvent) { int isReceiptSet = AdjustUtils.ConvertBool(adjustEvent.isReceiptSet); double revenue = AdjustUtils.ConvertDouble(adjustEvent.revenue); string eventToken = adjustEvent.eventToken; string currency = adjustEvent.currency; string receipt = adjustEvent.receipt; string transactionId = adjustEvent.transactionId; string callbackId = adjustEvent.callbackId; string stringJsonCallbackParameters = AdjustUtils.ConvertListToJson(adjustEvent.callbackList); string stringJsonPartnerParameters = AdjustUtils.ConvertListToJson(adjustEvent.partnerList); _AdjustTrackEvent(eventToken, revenue, currency, receipt, transactionId, callbackId, isReceiptSet, stringJsonCallbackParameters, stringJsonPartnerParameters); } public static void SetEnabled(bool enabled) { _AdjustSetEnabled(AdjustUtils.ConvertBool(enabled)); } public static bool IsEnabled() { var iIsEnabled = _AdjustIsEnabled(); return Convert.ToBoolean(iIsEnabled); } public static void SetOfflineMode(bool enabled) { _AdjustSetOfflineMode(AdjustUtils.ConvertBool(enabled)); } public static void SendFirstPackages() { _AdjustSendFirstPackages(); } public static void AppWillOpenUrl(string url) { _AdjustAppWillOpenUrl(url); } public static void AddSessionPartnerParameter(string key, string value) { _AdjustAddSessionPartnerParameter(key, value); } public static void AddSessionCallbackParameter(string key, string value) { _AdjustAddSessionCallbackParameter(key, value); } public static void RemoveSessionPartnerParameter(string key) { _AdjustRemoveSessionPartnerParameter(key); } public static void RemoveSessionCallbackParameter(string key) { _AdjustRemoveSessionCallbackParameter(key); } public static void ResetSessionPartnerParameters() { _AdjustResetSessionPartnerParameters(); } public static void ResetSessionCallbackParameters() { _AdjustResetSessionCallbackParameters(); } public static void TrackAdRevenue(string source, string payload) { _AdjustTrackAdRevenue(source, payload); } public static void TrackAdRevenue(AdjustAdRevenue adRevenue) { string source = adRevenue.source; double revenue = AdjustUtils.ConvertDouble(adRevenue.revenue); string currency = adRevenue.currency; int adImpressionsCount = AdjustUtils.ConvertInt(adRevenue.adImpressionsCount); string adRevenueNetwork = adRevenue.adRevenueNetwork; string adRevenueUnit = adRevenue.adRevenueUnit; string adRevenuePlacement = adRevenue.adRevenuePlacement; string stringJsonCallbackParameters = AdjustUtils.ConvertListToJson(adRevenue.callbackList); string stringJsonPartnerParameters = AdjustUtils.ConvertListToJson(adRevenue.partnerList); _AdjustTrackAdRevenueNew( source, revenue, currency, adImpressionsCount, adRevenueNetwork, adRevenueUnit, adRevenuePlacement, stringJsonCallbackParameters, stringJsonPartnerParameters); } public static void TrackAppStoreSubscription(AdjustAppStoreSubscription subscription) { string price = subscription.price; string currency = subscription.currency; string transactionId = subscription.transactionId; string receipt = subscription.receipt; string billingStore = subscription.billingStore; string transactionDate = subscription.transactionDate; string salesRegion = subscription.salesRegion; string stringJsonCallbackParameters = AdjustUtils.ConvertListToJson(subscription.callbackList); string stringJsonPartnerParameters = AdjustUtils.ConvertListToJson(subscription.partnerList); _AdjustTrackAppStoreSubscription( price, currency, transactionId, receipt, billingStore, transactionDate, salesRegion, stringJsonCallbackParameters, stringJsonPartnerParameters); } public static void TrackThirdPartySharing(AdjustThirdPartySharing thirdPartySharing) { int enabled = AdjustUtils.ConvertBool(thirdPartySharing.isEnabled); List<string> jsonGranularOptions = new List<string>(); foreach (KeyValuePair<string, List<string>> entry in thirdPartySharing.granularOptions) { jsonGranularOptions.Add(entry.Key); jsonGranularOptions.Add(AdjustUtils.ConvertListToJson(entry.Value)); } _AdjustTrackThirdPartySharing(enabled, AdjustUtils.ConvertListToJson(jsonGranularOptions)); } public static void TrackMeasurementConsent(bool enabled) { _AdjustTrackMeasurementConsent(AdjustUtils.ConvertBool(enabled)); } public static void RequestTrackingAuthorizationWithCompletionHandler(string sceneName) { string cSceneName = sceneName != null ? sceneName : "ADJ_INVALID"; _AdjustRequestTrackingAuthorizationWithCompletionHandler(cSceneName); } public static void UpdateConversionValue(int conversionValue) { _AdjustUpdateConversionValue(conversionValue); } public static int GetAppTrackingAuthorizationStatus() { return _AdjustGetAppTrackingAuthorizationStatus(); } public static void SetDeviceToken(string deviceToken) { _AdjustSetDeviceToken(deviceToken); } public static string GetIdfa() { return _AdjustGetIdfa(); } public static string GetAdid() { return _AdjustGetAdid(); } public static string GetSdkVersion() { return sdkPrefix + "@" + _AdjustGetSdkVersion(); } public static void GdprForgetMe() { _AdjustGdprForgetMe(); } public static void DisableThirdPartySharing() { _AdjustDisableThirdPartySharing(); } public static AdjustAttribution GetAttribution() { string attributionString = _AdjustGetAttribution(); if (null == attributionString) { return null; } var attribution = new AdjustAttribution(attributionString); return attribution; } // Used for testing only. public static void SetTestOptions(Dictionary<string, string> testOptions) { string baseUrl = testOptions[AdjustUtils.KeyTestOptionsBaseUrl]; string gdprUrl = testOptions[AdjustUtils.KeyTestOptionsGdprUrl]; string subscriptionUrl = testOptions[AdjustUtils.KeyTestOptionsSubscriptionUrl]; string extraPath = testOptions.ContainsKey(AdjustUtils.KeyTestOptionsExtraPath) ? testOptions[AdjustUtils.KeyTestOptionsExtraPath] : null; long timerIntervalMilis = -1; long timerStartMilis = -1; long sessionIntMilis = -1; long subsessionIntMilis = -1; bool teardown = false; bool deleteState = false; bool noBackoffWait = false; bool iAdFrameworkEnabled = false; bool adServicesFrameworkEnabled = false; if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsTimerIntervalInMilliseconds)) { timerIntervalMilis = long.Parse(testOptions[AdjustUtils.KeyTestOptionsTimerIntervalInMilliseconds]); } if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsTimerStartInMilliseconds)) { timerStartMilis = long.Parse(testOptions[AdjustUtils.KeyTestOptionsTimerStartInMilliseconds]); } if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsSessionIntervalInMilliseconds)) { sessionIntMilis = long.Parse(testOptions[AdjustUtils.KeyTestOptionsSessionIntervalInMilliseconds]); } if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsSubsessionIntervalInMilliseconds)) { subsessionIntMilis = long.Parse(testOptions[AdjustUtils.KeyTestOptionsSubsessionIntervalInMilliseconds]); } if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsTeardown)) { teardown = testOptions[AdjustUtils.KeyTestOptionsTeardown].ToLower() == "true"; } if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsDeleteState)) { deleteState = testOptions[AdjustUtils.KeyTestOptionsDeleteState].ToLower() == "true"; } if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsNoBackoffWait)) { noBackoffWait = testOptions[AdjustUtils.KeyTestOptionsNoBackoffWait].ToLower() == "true"; } if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsiAdFrameworkEnabled)) { iAdFrameworkEnabled = testOptions[AdjustUtils.KeyTestOptionsiAdFrameworkEnabled].ToLower() == "true"; } if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsAdServicesFrameworkEnabled)) { adServicesFrameworkEnabled = testOptions[AdjustUtils.KeyTestOptionsAdServicesFrameworkEnabled].ToLower() == "true"; } _AdjustSetTestOptions( baseUrl, gdprUrl, subscriptionUrl, extraPath, timerIntervalMilis, timerStartMilis, sessionIntMilis, subsessionIntMilis, AdjustUtils.ConvertBool(teardown), AdjustUtils.ConvertBool(deleteState), AdjustUtils.ConvertBool(noBackoffWait), AdjustUtils.ConvertBool(iAdFrameworkEnabled), AdjustUtils.ConvertBool(adServicesFrameworkEnabled)); } public static void TrackSubsessionStart(string testingArgument = null) { if (testingArgument == "test") { _AdjustTrackSubsessionStart(); } } public static void TrackSubsessionEnd(string testingArgument = null) { if (testingArgument == "test") { _AdjustTrackSubsessionEnd(); } } } #endif }
#region License // // HttpListenerRequest.cs // Copied from System.Net.HttpListenerRequest.cs // // Author: // Gonzalo Paniagua Javier (gonzalo@novell.com) // // Copyright (c) 2005 Novell, Inc. (http://www.novell.com) // Copyright (c) 2012-2013 sta.blockhead // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; namespace WebSocketSharp.Net { /// <summary> /// Provides access to a request to a <see cref="HttpListener"/> instance. /// </summary> /// <remarks> /// The HttpListenerRequest class cannot be inherited. /// </remarks> public sealed class HttpListenerRequest { #region Private Static Fields private static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n"); #endregion #region Private Fields private string [] _acceptTypes; private bool _chunked; private Encoding _contentEncoding; private long _contentLength; private bool _contentLengthWasSet; private HttpListenerContext _context; private CookieCollection _cookies; private WebHeaderCollection _headers; private Guid _identifier; private Stream _inputStream; private bool _keepAlive; private bool _keepAliveWasSet; private string _method; private NameValueCollection _queryString; private string _rawUrl; private Uri _referer; private Uri _url; private string [] _userLanguages; private Version _version; #endregion #region Internal Constructors internal HttpListenerRequest (HttpListenerContext context) { _context = context; _contentLength = -1; _headers = new WebHeaderCollection (); _identifier = Guid.NewGuid (); _version = HttpVersion.Version10; } #endregion #region Public Properties /// <summary> /// Gets the media types which are acceptable for the response. /// </summary> /// <value> /// An array of <see cref="string"/> that contains the media type names in the Accept request-header /// or <see langword="null"/> if the request did not include an Accept header. /// </value> public string [] AcceptTypes { get { return _acceptTypes; } } /// <summary> /// Gets an error code that identifies a problem with the client's certificate. /// </summary> /// <value> /// Always returns <c>0</c>. /// </value> public int ClientCertificateError { get { // TODO: Always returns 0. /* if (no_get_certificate) throw new InvalidOperationException ( "Call GetClientCertificate method before accessing this property."); return client_cert_error; */ return 0; } } /// <summary> /// Gets the encoding used with the entity body data included in the request. /// </summary> /// <value> /// A <see cref="Encoding"/> that indicates the encoding used with the entity body data /// or <see cref="Encoding.Default"/> if the request did not include the information about the encoding. /// </value> public Encoding ContentEncoding { get { if (_contentEncoding == null) _contentEncoding = Encoding.Default; return _contentEncoding; } } /// <summary> /// Gets the size of the entity body data included in the request. /// </summary> /// <value> /// A <see cref="long"/> that contains the value of the Content-Length entity-header. /// The value is a number of bytes in the entity body data. <c>-1</c> if the size is not known. /// </value> public long ContentLength64 { get { return _contentLength; } } /// <summary> /// Gets the media type of the entity body included in the request. /// </summary> /// <value> /// A <see cref="string"/> that contains the value of the Content-Type entity-header. /// </value> public string ContentType { get { return _headers ["Content-Type"]; } } /// <summary> /// Gets the cookies included in the request. /// </summary> /// <value> /// A <see cref="CookieCollection"/> that contains the cookies included in the request. /// </value> public CookieCollection Cookies { get { if (_cookies == null) _cookies = _headers.GetCookies (false); return _cookies; } } /// <summary> /// Gets a value indicating whether the request has the entity body. /// </summary> /// <value> /// <c>true</c> if the request has the entity body; otherwise, <c>false</c>. /// </value> public bool HasEntityBody { get { return _contentLength > 0 || _chunked; } } /// <summary> /// Gets the HTTP headers used in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the HTTP headers used in the request. /// </value> public NameValueCollection Headers { get { return _headers; } } /// <summary> /// Gets the HTTP method used in the request. /// </summary> /// <value> /// A <see cref="string"/> that contains the HTTP method used in the request. /// </value> public string HttpMethod { get { return _method; } } /// <summary> /// Gets a <see cref="Stream"/> that contains the entity body data included in the request. /// </summary> /// <value> /// A <see cref="Stream"/> that contains the entity body data included in the request. /// </value> public Stream InputStream { get { if (_inputStream == null) _inputStream = HasEntityBody ? _context.Connection.GetRequestStream (_chunked, _contentLength) : Stream.Null; return _inputStream; } } /// <summary> /// Gets a value indicating whether the client that sent the request is authenticated. /// </summary> /// <value> /// Always returns <c>false</c>. /// </value> public bool IsAuthenticated { get { // TODO: Always returns false. return false; } } /// <summary> /// Gets a value indicating whether the request is sent from the local computer. /// </summary> /// <value> /// <c>true</c> if the request is sent from the local computer; otherwise, <c>false</c>. /// </value> public bool IsLocal { get { return RemoteEndPoint.Address.IsLocal (); } } /// <summary> /// Gets a value indicating whether the HTTP connection is secured using the SSL protocol. /// </summary> /// <value> /// <c>true</c> if the HTTP connection is secured; otherwise, <c>false</c>. /// </value> public bool IsSecureConnection { get { return _context.Connection.IsSecure; } } /// <summary> /// Gets a value indicating whether the request is a WebSocket connection request. /// </summary> /// <value> /// <c>true</c> if the request is a WebSocket connection request; otherwise, <c>false</c>. /// </value> public bool IsWebSocketRequest { get { return _method == "GET" && _version >= HttpVersion.Version11 && _headers.Contains ("Upgrade", "websocket") && _headers.Contains ("Connection", "Upgrade"); } } /// <summary> /// Gets a value indicating whether the client requests a persistent connection. /// </summary> /// <value> /// <c>true</c> if the client requests a persistent connection; otherwise, <c>false</c>. /// </value> public bool KeepAlive { get { if (!_keepAliveWasSet) { _keepAlive = _headers.Contains ("Connection", "keep-alive") || _version == HttpVersion.Version11 ? true : _headers.Contains ("Keep-Alive") ? !_headers.Contains ("Keep-Alive", "closed") : false; _keepAliveWasSet = true; } return _keepAlive; } } /// <summary> /// Gets the server endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="IPEndPoint"/> that contains the server endpoint. /// </value> public IPEndPoint LocalEndPoint { get { return _context.Connection.LocalEndPoint; } } /// <summary> /// Gets the HTTP version used in the request. /// </summary> /// <value> /// A <see cref="Version"/> that contains the HTTP version used in the request. /// </value> public Version ProtocolVersion { get { return _version; } } /// <summary> /// Gets the collection of query string variables used in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the collection of query string variables used in the request. /// </value> public NameValueCollection QueryString { get { return _queryString; } } /// <summary> /// Gets the raw URL (without the scheme, host and port) requested by the client. /// </summary> /// <value> /// A <see cref="string"/> that contains the raw URL requested by the client. /// </value> public string RawUrl { get { return _rawUrl; } } /// <summary> /// Gets the client endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="IPEndPoint"/> that contains the client endpoint. /// </value> public IPEndPoint RemoteEndPoint { get { return _context.Connection.RemoteEndPoint; } } /// <summary> /// Gets the request identifier of a incoming HTTP request. /// </summary> /// <value> /// A <see cref="Guid"/> that contains the identifier of a request. /// </value> public Guid RequestTraceIdentifier { get { return _identifier; } } /// <summary> /// Gets the URL requested by the client. /// </summary> /// <value> /// A <see cref="Uri"/> that contains the URL requested by the client. /// </value> public Uri Url { get { return _url; } } /// <summary> /// Gets the URL of the resource from which the requested URL was obtained. /// </summary> /// <value> /// A <see cref="Uri"/> that contains the value of the Referer request-header /// or <see langword="null"/> if the request did not include an Referer header. /// </value> public Uri UrlReferrer { get { return _referer; } } /// <summary> /// Gets the information about the user agent originating the request. /// </summary> /// <value> /// A <see cref="string"/> that contains the value of the User-Agent request-header. /// </value> public string UserAgent { get { return _headers ["User-Agent"]; } } /// <summary> /// Gets the server endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="string"/> that contains the server endpoint. /// </value> public string UserHostAddress { get { return LocalEndPoint.ToString (); } } /// <summary> /// Gets the internet host name and port number (if present) specified by the client. /// </summary> /// <value> /// A <see cref="string"/> that contains the value of the Host request-header. /// </value> public string UserHostName { get { return _headers ["Host"]; } } /// <summary> /// Gets the natural languages which are preferred for the response. /// </summary> /// <value> /// An array of <see cref="string"/> that contains the natural language names in the Accept-Language request-header /// or <see langword="null"/> if the request did not include an Accept-Language header. /// </value> public string [] UserLanguages { get { return _userLanguages; } } #endregion #region Private Methods private void CreateQueryString (string query) { if (query == null || query.Length == 0) { _queryString = new NameValueCollection (1); return; } _queryString = new NameValueCollection (); if (query [0] == '?') query = query.Substring (1); var components = query.Split ('&'); foreach (var kv in components) { var pos = kv.IndexOf ('='); if (pos == -1) { _queryString.Add (null, HttpUtility.UrlDecode (kv)); } else { var key = HttpUtility.UrlDecode (kv.Substring (0, pos)); var val = HttpUtility.UrlDecode (kv.Substring (pos + 1)); _queryString.Add (key, val); } } } #endregion #region Internal Methods internal void AddHeader (string header) { var colon = header.IndexOf (':'); if (colon <= 0) { _context.ErrorMessage = "Invalid header"; return; } var name = header.Substring (0, colon).Trim (); var val = header.Substring (colon + 1).Trim (); var lower = name.ToLower (CultureInfo.InvariantCulture); _headers.SetInternal (name, val, false); if (lower == "accept") { _acceptTypes = val.SplitHeaderValue (',').ToArray (); return; } if (lower == "accept-language") { _userLanguages = val.Split (','); return; } if (lower == "content-length") { long length; if (Int64.TryParse (val, out length) && length >= 0) { _contentLength = length; _contentLengthWasSet = true; } else { _context.ErrorMessage = "Invalid Content-Length header"; } return; } if (lower == "content-type") { var contents = val.Split (';'); foreach (var content in contents) { var tmp = content.Trim (); if (tmp.StartsWith ("charset")) { var charset = tmp.GetValue ("="); if (!charset.IsNullOrEmpty ()) { try { _contentEncoding = Encoding.GetEncoding (charset); } catch { _context.ErrorMessage = "Invalid Content-Type header"; } } break; } } return; } if (lower == "referer") _referer = val.ToUri (); } internal void FinishInitialization () { var host = UserHostName; if (_version > HttpVersion.Version10 && host.IsNullOrEmpty ()) { _context.ErrorMessage = "Invalid Host header"; return; } Uri rawUri = null; var path = _rawUrl.MaybeUri () && Uri.TryCreate (_rawUrl, UriKind.Absolute, out rawUri) ? rawUri.PathAndQuery : HttpUtility.UrlDecode (_rawUrl); if (host.IsNullOrEmpty ()) host = UserHostAddress; if (rawUri != null) host = rawUri.Host; var colon = host.IndexOf (':'); if (colon >= 0) host = host.Substring (0, colon); var baseUri = String.Format ("{0}://{1}:{2}", IsSecureConnection ? "https" : "http", host, LocalEndPoint.Port); if (!Uri.TryCreate (baseUri + path, UriKind.Absolute, out _url)) { _context.ErrorMessage = "Invalid request url: " + baseUri + path; return; } CreateQueryString (_url.Query); var encoding = Headers ["Transfer-Encoding"]; if (_version >= HttpVersion.Version11 && !encoding.IsNullOrEmpty ()) { _chunked = encoding.ToLower () == "chunked"; // 'identity' is not valid! if (!_chunked) { _context.ErrorMessage = String.Empty; _context.ErrorStatus = 501; return; } } if (!_chunked && !_contentLengthWasSet) { var method = _method.ToLower (); if (method == "post" || method == "put") { _context.ErrorMessage = String.Empty; _context.ErrorStatus = 411; return; } } var expect = Headers ["Expect"]; if (!expect.IsNullOrEmpty () && expect.ToLower () == "100-continue") { var output = _context.Connection.GetResponseStream (); output.InternalWrite (_100continue, 0, _100continue.Length); } } // Returns true is the stream could be reused. internal bool FlushInput () { if (!HasEntityBody) return true; var length = 2048; if (_contentLength > 0) length = (int) Math.Min (_contentLength, (long) length); var buffer = new byte [length]; while (true) { // TODO: Test if MS has a timeout when doing this. try { var ares = InputStream.BeginRead (buffer, 0, length, null, null); if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100)) return false; if (InputStream.EndRead (ares) <= 0) return true; } catch { return false; } } } internal void SetRequestLine (string requestLine) { var parts = requestLine.Split (new char [] { ' ' }, 3); if (parts.Length != 3) { _context.ErrorMessage = "Invalid request line (parts)"; return; } _method = parts [0]; if (!_method.IsToken ()) { _context.ErrorMessage = "Invalid request line (method)"; return; } _rawUrl = parts [1]; if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) { _context.ErrorMessage = "Invalid request line (version)"; return; } try { _version = new Version (parts [2].Substring (5)); if (_version.Major < 1) throw new Exception (); } catch { _context.ErrorMessage = "Invalid request line (version)"; } } #endregion #region Public Methods /// <summary> /// Begins getting the client's X.509 v.3 certificate asynchronously. /// </summary> /// <remarks> /// This asynchronous operation must be completed by calling the <see cref="EndGetClientCertificate"/> method. /// Typically, the method is invoked by the <paramref name="requestCallback"/> delegate. /// </remarks> /// <returns> /// An <see cref="IAsyncResult"/> that contains the status of the asynchronous operation. /// </returns> /// <param name="requestCallback"> /// An <see cref="AsyncCallback"/> delegate that references the method(s) /// called when the asynchronous operation completes. /// </param> /// <param name="state"> /// An <see cref="object"/> that contains a user defined object to pass to the <paramref name="requestCallback"/> delegate. /// </param> /// <exception cref="NotImplementedException"> /// This method is not implemented. /// </exception> public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state) { // TODO: Not Implemented. throw new NotImplementedException (); } /// <summary> /// Ends an asynchronous operation to get the client's X.509 v.3 certificate. /// </summary> /// <remarks> /// This method completes an asynchronous operation started by calling the <see cref="BeginGetClientCertificate"/> method. /// </remarks> /// <returns> /// A <see cref="X509Certificate2"/> that contains the client's X.509 v.3 certificate. /// </returns> /// <param name="asyncResult"> /// An <see cref="IAsyncResult"/> obtained by calling the <see cref="BeginGetClientCertificate"/> method. /// </param> /// <exception cref="NotImplementedException"> /// This method is not implemented. /// </exception> public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult) { // TODO: Not Implemented. throw new NotImplementedException (); } /// <summary> /// Gets the client's X.509 v.3 certificate. /// </summary> /// <returns> /// A <see cref="X509Certificate2"/> that contains the client's X.509 v.3 certificate. /// </returns> /// <exception cref="NotImplementedException"> /// This method is not implemented. /// </exception> public X509Certificate2 GetClientCertificate () { // TODO: Not Implemented. throw new NotImplementedException (); } /// <summary> /// Returns a <see cref="string"/> that represents the current <see cref="HttpListenerRequest"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents the current <see cref="HttpListenerRequest"/>. /// </returns> public override string ToString () { var buffer = new StringBuilder (64); buffer.AppendFormat ("{0} {1} HTTP/{2}\r\n", _method, _rawUrl, _version); foreach (string key in _headers.AllKeys) buffer.AppendFormat ("{0}: {1}\r\n", key, _headers [key]); buffer.Append ("\r\n"); return buffer.ToString (); } #endregion } }
/* * daap-sharp * Copyright (C) 2005 James Willcox <snorp@snorp.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Runtime.InteropServices; using System.Threading; using System.IO; using System.Web; using System.Net; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Daap { public class Client : IDisposable { private const int UpdateSleepInterval = 2 * 60 * 1000; // 2 minutes private IPAddress address; private UInt16 port; private ContentCodeBag bag; private ServerInfo serverInfo; private List<Database> databases = new List<Database> (); private ContentFetcher fetcher; private int revision; private bool updateRunning; public event EventHandler Updated; internal int Revision { get { return revision; } } public string Name { get { return serverInfo.Name; } } public IPAddress Address { get { return address; } } public ushort Port { get { return port; } } public AuthenticationMethod AuthenticationMethod { get { return serverInfo.AuthenticationMethod; } } public IList<Database> Databases { get { return new ReadOnlyCollection<Database> (databases); } } internal ContentCodeBag Bag { get { return bag; } } internal ContentFetcher Fetcher { get { return fetcher; } } public Client (Service service) : this (service.Address, service.Port) { } public Client (string host, UInt16 port) : this (Dns.GetHostEntry (host).AddressList[0], port) { } public Client (IPAddress address, UInt16 port) { this.address = address; this.port = port; fetcher = new ContentFetcher (address, port); bag = ContentCodeBag.ParseCodes (fetcher.Fetch ("/content-codes")); ContentNode node = ContentParser.Parse (ContentCodeBag.Default, fetcher.Fetch ("/server-info")); serverInfo = ServerInfo.FromNode (node); } ~Client () { Dispose (); } public void Dispose () { updateRunning = false; if (fetcher != null) { fetcher.Dispose (); fetcher = null; } } private void ParseSessionId (ContentNode node) { fetcher.SessionId = (int) node.GetChild ("dmap.sessionid").Value; } public void Login () { Login (null, null); } public void Login (string password) { Login (null, password); } public void Login (string username, string password) { fetcher.Username = username; fetcher.Password = password; try { ContentNode node = ContentParser.Parse (bag, fetcher.Fetch ("/login")); ParseSessionId (node); FetchDatabases (); Refresh (); if (serverInfo.SupportsUpdate) { updateRunning = true; Thread thread = new Thread (UpdateLoop); thread.Name = "DAAP"; thread.IsBackground = true; thread.Start (); } } catch (WebException e) { if (e.Response != null && (e.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized) throw new AuthenticationException ("Username or password incorrect"); else throw new LoginException ("Failed to login", e); } catch (Exception e) { throw new LoginException ("Failed to login", e); } } public void Logout () { try { updateRunning = false; fetcher.KillAll (); fetcher.Fetch ("/logout"); } catch (WebException) { // some servers don't implement this, etc. } fetcher.SessionId = 0; } private void FetchDatabases () { ContentNode dbnode = ContentParser.Parse (bag, fetcher.Fetch ("/databases")); foreach (ContentNode child in (ContentNode[]) dbnode.Value) { if (child.Name != "dmap.listing") continue; foreach (ContentNode item in (ContentNode[]) child.Value) { Database db = new Database (this, item); databases.Add (db); } } } private int GetCurrentRevision () { ContentNode revNode = ContentParser.Parse (bag, fetcher.Fetch ("/update"), "dmap.serverrevision"); return (int) revNode.Value; } private int WaitForRevision (int currentRevision) { ContentNode revNode = ContentParser.Parse (bag, fetcher.Fetch ("/update", "revision-number=" + currentRevision)); return (int) revNode.GetChild ("dmap.serverrevision").Value; } private void Refresh () { int newrev = revision; if (serverInfo.SupportsUpdate) { if (revision == 0) newrev = GetCurrentRevision (); else newrev = WaitForRevision (revision); if (newrev == revision) return; } // Console.WriteLine ("Got new revision: " + newrev); foreach (Database db in databases) { db.Refresh (newrev); } revision = newrev; if (Updated != null) Updated (this, new EventArgs ()); } private void UpdateLoop () { while (true) { try { if (!updateRunning) break; Refresh (); } catch (WebException) { if (!updateRunning) break; // chill out for a while, maybe the server went down // temporarily or something. Thread.Sleep (UpdateSleepInterval); } catch (Exception e) { if (!updateRunning) break; Console.Error.WriteLine ("Exception in update loop: " + e); Thread.Sleep (UpdateSleepInterval); } } } } }
//----------------------------------------------------------------------- // Copyright 2014 Tobii Technology AB. All rights reserved. //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using Tobii.EyeX.Client; using Tobii.EyeX.Framework; using UnityEngine; using Rect = UnityEngine.Rect; using Environment = Tobii.EyeX.Client.Environment; /// <summary> /// Provides the main point of contact with the EyeX Engine. /// Hosts an EyeX context and responds to engine queries using a repository of interactors. /// </summary> [AddComponentMenu("")] public partial class EyeXHost : MonoBehaviour { /// <summary> /// If set to true, it will automatically initialize the EyeX Engine on Start(). /// </summary> public bool initializeOnStart = true; /// <summary> /// Special interactor ID indicating that an interactor doesn't have a parent. /// </summary> public const string NoParent = Literals.RootId; private static EyeXHost _instance; private readonly object _lock = new object(); private readonly Dictionary<string, IEyeXGlobalInteractor> _globalInteractors = new Dictionary<string, IEyeXGlobalInteractor>(); private readonly Dictionary<string, EyeXInteractor> _interactors = new Dictionary<string, EyeXInteractor>(); private readonly EyeXActivationHub _activationHub = new EyeXActivationHub(); private readonly EyeXPanningHub _pannableHub = new EyeXPanningHub(); private Environment _environment; private Context _context; private Vector2 _viewportPosition = new Vector2(float.NaN, float.NaN); private Vector2 _viewportPixelsPerDesktopPixel = Vector2.one; private bool _isConnected; private bool _isPaused; private bool _isFocused; private bool _runInBackground; private EyeXViewportBoundsProvider _viewportBoundsProvider; private Version _engineVersion; // Engine state accessors private EyeXEngineStateAccessor<Tobii.EyeX.Client.Rect> _screenBoundsStateAccessor; private EyeXEngineStateAccessor<Size2> _displaySizeStateAccessor; private EyeXEngineStateAccessor<EyeTrackingDeviceStatus> _eyeTrackingDeviceStatusStateAccessor; private EyeXEngineStateAccessor<UserPresence> _userPresenceStateAccessor; private EyeXEngineStateAccessor<GazeTracking> _gazeTracking; /// <summary> /// Gets the engine state: Screen bounds in pixels. /// </summary> public EyeXEngineStateValue<Tobii.EyeX.Client.Rect> ScreenBounds { get { return _screenBoundsStateAccessor.GetCurrentValue(_context); } } /// <summary> /// Gets the engine state: Display size, width and height, in millimeters. /// </summary> public EyeXEngineStateValue<Size2> DisplaySize { get { return _displaySizeStateAccessor.GetCurrentValue(_context); } } /// <summary> /// Gets the engine state: Eye tracking status. /// </summary> public EyeXDeviceStatus EyeTrackingDeviceStatus { get { return EnumHelpers.ConvertToEyeXDeviceStatus( _eyeTrackingDeviceStatusStateAccessor.GetCurrentValue(_context)); } } /// <summary> /// Gets the engine state: User presence. /// </summary> public EyeXUserPresence UserPresence { get { return EnumHelpers.ConvertToEyeXUserPresence( _userPresenceStateAccessor.GetCurrentValue(_context)); } } /// <summary> /// Gets the engine state: Gaze tracking. /// </summary> /// <value>The gaze tracking.</value> public EyeXGazeTracking GazeTracking { get { return EnumHelpers.ConvertToEyeXGazeTracking( this, _gazeTracking.GetCurrentValue(_context)); } } /// <summary> /// Gets the engine version. /// </summary> public Version EngineVersion { get { return _engineVersion; } } /// <summary> /// Gets the shared <see cref="IEyeXActivationHub"/> used for synchronizing activation events across interactors and frames. /// Use this object when creating <see cref="EyeXActivatable"/> behaviors. /// </summary> public IEyeXActivationHub ActivationHub { get { return _activationHub; } } /// <summary> /// Gets the shared <see cref="EyeXPannableHub"/> used for synchronizing activation events across interactors and frames. /// Use this object when creating <see cref="EyeXPannable"/> behaviors. /// </summary> public EyeXPanningHub PannableHub { get { return _pannableHub; } } /// <summary> /// Returns a value indicating whether The EyeX Engine has been initialized /// </summary> public bool IsInitialized { get { return _context != null; } } /// <summary> /// Gets a value indicating whether the host is running. /// </summary> /// <value><c>true</c> if the host is running; otherwise, <c>false</c>.</value> private bool IsRunning { get { return !_isPaused && (_isFocused || _runInBackground); } } /// <summary> /// Gets the singleton EyeXHost instance. /// Users of this class should store a reference to the singleton instance in their Awake() method, or similar, /// to ensure that the EyeX host instance stays alive at least as long as the user object. Otherwise the /// EyeXHost might be garbage collected and replaced with a new, uninitialized instance during application /// shutdown, and that would lead to unexpected behavior. /// </summary> /// <returns>The instance.</returns> public static EyeXHost GetInstance() { if (_instance == null) { // create a game object with a new instance of this class attached as a component. // (there's no need to keep a reference to the game object, because game objects are not garbage collected.) var container = new GameObject(); container.name = "EyeXHostContainer"; DontDestroyOnLoad(container); _instance = (EyeXHost)container.AddComponent(typeof(EyeXHost)); } return _instance; } /// <summary> /// Initialize helper classes and state accessors on Awake /// </summary> void Awake() { _runInBackground = Application.runInBackground; #if UNITY_EDITOR _viewportBoundsProvider = CreateEditorScreenHelper(); #else _viewportBoundsProvider = new UnityPlayerViewportBoundsProvider(); #endif _screenBoundsStateAccessor = new EyeXEngineStateAccessor<Tobii.EyeX.Client.Rect>(StatePaths.EyeTrackingScreenBounds); _displaySizeStateAccessor = new EyeXEngineStateAccessor<Size2>(StatePaths.EyeTrackingDisplaySize); _eyeTrackingDeviceStatusStateAccessor = new EyeXEngineStateAccessor<EyeTrackingDeviceStatus>(StatePaths.EyeTrackingState); _userPresenceStateAccessor = new EyeXEngineStateAccessor<UserPresence>(StatePaths.UserPresence); _userProfileNameStateAccessor = new EyeXEngineStateAccessor<string>(StatePaths.ProfileName); _userProfileNamesStateAccessor = new EyeXEngineEnumerableStateAccessor<string>(StatePaths.EyeTrackingProfiles); _gazeTracking = new EyeXEngineStateAccessor<GazeTracking>(StatePaths.GazeTracking); } #if UNITY_EDITOR private static EyeXViewportBoundsProvider CreateEditorScreenHelper() { #if UNITY_4_5 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 return new LegacyEditorViewportBoundsProvider(); #else return new EditorViewportBoundsProvider(); #endif } #endif /// <summary> /// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time. /// </summary> public void Start() { if (initializeOnStart) { InitializeEyeX(); } } /// <summary> /// Update is called every frame, if the MonoBehaviour is enabled. /// </summary> public void Update() { if (_engineVersion == null && IsInitialized && _isConnected) { _engineVersion = GetEngineVersion(); } // update the viewport position, in case the game window has been moved or resized. var viewportBounds = _viewportBoundsProvider.GetViewportPhysicalBounds(); _viewportPosition = new Vector2(viewportBounds.x, viewportBounds.y); _viewportPixelsPerDesktopPixel = new Vector2(Screen.width / viewportBounds.width, Screen.height / viewportBounds.height); StartCoroutine(DoEndOfFrameCleanup()); } private IEnumerator DoEndOfFrameCleanup() { yield return new WaitForEndOfFrame(); _activationHub.EndFrame(); _pannableHub.EndFrame(); } /// <summary> /// Sent to all game objects when the player gets or loses focus. /// </summary> /// <param name="focusStatus">Gets a value indicating whether the player is focused.</param> public void OnApplicationFocus(bool focusStatus) { var wasRunning = IsRunning; _isFocused = focusStatus; // make sure that data streams are disabled while the game is paused. if (wasRunning != IsRunning && _isConnected) { CommitAllGlobalInteractors(); } } /// <summary> /// Sent to all game objects when the player pauses. /// </summary> /// <param name="pauseStatus">Gets a value indicating whether the player is paused.</param> public void OnApplicationPause(bool pauseStatus) { var wasRunning = IsRunning; _isPaused = pauseStatus; // make sure that data streams are disabled while the game is paused. if (wasRunning != IsRunning && _isConnected) { CommitAllGlobalInteractors(); } } /// <summary> /// Sent to all game objects before the application is quit. /// </summary> public void OnApplicationQuit() { ShutdownEyeX(); } /// <summary> /// Registers an interactor with the repository. /// </summary> /// <param name="interactor">The interactor.</param> public void RegisterInteractor(EyeXInteractor interactor) { lock (_lock) { _interactors[interactor.Id] = interactor; } } /// <summary> /// Gets an interactor from the repository. /// </summary> /// <param name="interactorId">ID of the interactor.</param> /// <returns>Interactor, or null if not found.</returns> public EyeXInteractor GetInteractor(string interactorId) { lock (_lock) { EyeXInteractor interactor = null; _interactors.TryGetValue(interactorId, out interactor); return interactor; } } /// <summary> /// Removes an interactor from the repository. /// </summary> /// <param name="interactorId">ID of the interactor.</param> public void UnregisterInteractor(string interactorId) { lock (_lock) { _interactors.Remove(interactorId); } } /// <summary> /// Gets a provider of gaze point data. /// See <see cref="IEyeXDataProvider{T}"/>. /// </summary> /// <param name="mode">Specifies the kind of data processing to be applied by the EyeX Engine.</param> /// <returns>The data provider.</returns> public IEyeXDataProvider<EyeXGazePoint> GetGazePointDataProvider(GazePointDataMode mode) { var dataStream = new EyeXGazePointDataStream(mode); return GetDataProviderForDataStream<EyeXGazePoint>(dataStream); } /// <summary> /// Gets a provider of fixation data. /// See <see cref="IEyeXDataProvider{T}"/>. /// </summary> /// <param name="mode">Specifies the kind of data processing to be applied by the EyeX Engine.</param> /// <returns>The data provider.</returns> public IEyeXDataProvider<EyeXFixationPoint> GetFixationDataProvider(FixationDataMode mode) { var dataStream = new EyeXFixationDataStream(mode); return GetDataProviderForDataStream<EyeXFixationPoint>(dataStream); } /// <summary> /// Gets a provider of eye position data. /// See <see cref="IEyeXDataProvider{T}"/>. /// </summary> /// <returns>The data provider.</returns> public IEyeXDataProvider<EyeXEyePosition> GetEyePositionDataProvider() { var dataStream = new EyeXEyePositionDataStream(); return GetDataProviderForDataStream<EyeXEyePosition>(dataStream); } /// <summary> /// Trigger an activation ("direct click"). /// <remarks>This will also cause the EyeX Engine to switch off any ongoing activation mode.</remarks> /// </summary> public void TriggerActivation() { _context.CreateActionCommand(ActionType.Activate) .ExecuteAsync(null); } /// <summary> /// Send a reguest to the EyeX Engine to switch activation mode on. /// <remarks>This request will be ignored if the EyeX Engine is in panning mode.</remarks> /// </summary> public void TriggerActivationModeOn() { _context.CreateActionCommand(ActionType.ActivationModeOn) .ExecuteAsync(null); } /// <summary> /// Send a reguest to the EyeX Engine to switch activation mode off. /// <remarks>This request is not needed if <see cref="TriggerActivation"/> has been /// called since the engine switched the activation mode on.</remarks> /// </summary> public void TriggerActivationModeOff() { _context.CreateActionCommand(ActionType.ActivationModeOff) .ExecuteAsync(null); } /// <summary> /// Trigger panning to begin. /// <remark>This will put the EyeX Engine in panning mode until panning end is triggered.</remark> /// </summary> public void TriggerPanningBegin() { _context.CreateActionCommand(ActionType.PanningBegin) .ExecuteAsync(null); } /// <summary> /// Trigger panning to end. /// <remarks>If the EyeX Engine was in activaion mode when panning mode was entered, /// ending the panning mode will cause the engine to return to activation mode.</remarks> /// </summary> public void TriggerPanningEnd() { _context.CreateActionCommand(ActionType.PanningEnd) .ExecuteAsync(null); } /// <summary> /// Gets a data provider for a given data stream: preferably an existing one /// in the _globalInteractors collection, or, failing that, the one passed /// in as a parameter. /// </summary> /// <typeparam name="T">Type of the provided data value object.</typeparam> /// <param name="dataStream">Data stream to be added.</param> /// <returns>A data provider.</returns> private IEyeXDataProvider<T> GetDataProviderForDataStream<T>(EyeXDataStreamBase<T> dataStream) { lock (_lock) { IEyeXGlobalInteractor existing; if (_globalInteractors.TryGetValue(dataStream.Id, out existing)) { return (IEyeXDataProvider<T>)existing; } _globalInteractors.Add(dataStream.Id, dataStream); dataStream.Updated += OnGlobalInteractorUpdated; return dataStream; } } /// <summary> /// Gets an interactor from the repository. /// </summary> /// <param name="interactorId">ID of the interactor.</param> /// <returns>Interactor, or null if not found.</returns> private IEyeXGlobalInteractor GetGlobalInteractor(string interactorId) { lock (_lock) { IEyeXGlobalInteractor interactor = null; _globalInteractors.TryGetValue(interactorId, out interactor); return interactor; } } /// <summary> /// Initializes the EyeX engine. /// </summary> public void InitializeEyeX() { if (IsInitialized) return; try { Tobii.EyeX.Client.Interop.EyeX.EnableMonoCallbacks("mono"); _environment = Environment.Initialize(); } catch (InteractionApiException ex) { Debug.LogError("EyeX initialization failed: " + ex.Message); } catch (DllNotFoundException) { #if UNITY_EDITOR Debug.LogError("EyeX initialization failed because the client access library 'Tobii.EyeX.Client.dll' could not be loaded. " + "Please make sure that it is present in the Unity project directory. " + "You can find it in the SDK package, in the lib/x86 directory. (Currently only Windows is supported.)"); #else Debug.LogError("EyeX initialization failed because the client access library 'Tobii.EyeX.Client.dll' could not be loaded. " + "Please make sure that it is present in the root directory of the game/application."); #endif return; } try { _context = new Context(false); _context.RegisterQueryHandlerForCurrentProcess(HandleQuery); _context.RegisterEventHandler(HandleEvent); _context.ConnectionStateChanged += OnConnectionStateChanged; _context.EnableConnection(); print("EyeX is running."); } catch (InteractionApiException ex) { Debug.LogError("EyeX context initialization failed: " + ex.Message); } } /// <summary> /// Shuts down the eyeX engine. /// </summary> public void ShutdownEyeX() { if (!IsInitialized) return; print("EyeX is shutting down."); if (_context != null) { // The context must be shut down before disposing. try { _context.Shutdown(1000, false); } catch (InteractionApiException ex) { Debug.LogError("EyeX context shutdown failed: " + ex.Message); } _context.Dispose(); _context = null; } if (_environment != null) { _environment.Dispose(); _environment = null; } } private void OnConnectionStateChanged(object sender, ConnectionStateChangedEventArgs e) { if (e.State == ConnectionState.Connected) { _isConnected = true; // commit the snapshot with the global interactor as soon as the connection to the engine is established. // (it cannot be done earlier because committing means "send to the engine".) CommitAllGlobalInteractors(); _screenBoundsStateAccessor.OnConnected(_context); _displaySizeStateAccessor.OnConnected(_context); _eyeTrackingDeviceStatusStateAccessor.OnConnected(_context); _userPresenceStateAccessor.OnConnected(_context); _userProfileNameStateAccessor.OnConnected(_context); _userProfileNamesStateAccessor.OnConnected(_context); _gazeTracking.OnConnected(_context); } else { _isConnected = false; _screenBoundsStateAccessor.OnDisconnected(); _displaySizeStateAccessor.OnDisconnected(); _eyeTrackingDeviceStatusStateAccessor.OnDisconnected(); _userPresenceStateAccessor.OnDisconnected(); _userProfileNameStateAccessor.OnDisconnected(); _userProfileNamesStateAccessor.OnDisconnected(); _gazeTracking.OnDisconnected(); } } private void HandleQuery(Query query) { // NOTE: this method is called from a worker thread, so it must not access any game objects. using (query) { try { Rect queryRectInGuiCoordinates; if (!TryGetQueryRectangle(query, out queryRectInGuiCoordinates)) { return; } // Make a copy of the collection of interactors to avoid race conditions. List<EyeXInteractor> interactorsCopy; lock (_lock) { interactorsCopy = new List<EyeXInteractor>(_interactors.Values); } // Create the snapshot and add the interactors that intersect with the query bounds. using (var snapshot = _context.CreateSnapshotWithQueryBounds(query)) { snapshot.AddWindowId(_viewportBoundsProvider.GameWindowId); foreach (var interactor in interactorsCopy) { if (interactor.IntersectsWith(queryRectInGuiCoordinates)) { interactor.AddToSnapshot( snapshot, _viewportBoundsProvider.GameWindowId, _viewportPosition, _viewportPixelsPerDesktopPixel); } } CommitSnapshot(snapshot); } } catch (InteractionApiException ex) { print("EyeX query handler failed: " + ex.Message); } } } private bool TryGetQueryRectangle(Query query, out Rect queryRectInGuiCoordinates) { if (float.IsNaN(_viewportPosition.x)) { // We don't have a valid game window position, so we cannot respond to any queries at this time. queryRectInGuiCoordinates = new Rect(); return false; } double boundsX, boundsY, boundsWidth, boundsHeight; // desktop pixels using (var bounds = query.Bounds) { if (!bounds.TryGetRectangularData(out boundsX, out boundsY, out boundsWidth, out boundsHeight)) { queryRectInGuiCoordinates = new Rect(); return false; } } queryRectInGuiCoordinates = new Rect( (float)((boundsX - _viewportPosition.x) * _viewportPixelsPerDesktopPixel.x), (float)((boundsY - _viewportPosition.y) * _viewportPixelsPerDesktopPixel.y), (float)(boundsWidth * _viewportPixelsPerDesktopPixel.x), (float)(boundsHeight * _viewportPixelsPerDesktopPixel.y)); return true; } private void HandleEvent(InteractionEvent event_) { // NOTE: this method is called from a worker thread, so it must not access any game objects. using (event_) { try { // Route the event to the appropriate interactor, if any. var interactorId = event_.InteractorId; var globalInteractor = GetGlobalInteractor(interactorId); if (globalInteractor != null) { globalInteractor.HandleEvent(event_, _viewportPosition, _viewportPixelsPerDesktopPixel); } else { var interactor = GetInteractor(interactorId); if (interactor != null) { interactor.HandleEvent(event_); } } } catch (InteractionApiException ex) { print("EyeX event handler failed: " + ex.Message); } } } private void OnGlobalInteractorUpdated(object sender, EventArgs e) { var globalInteractor = (IEyeXGlobalInteractor)sender; if (_isConnected) { CommitGlobalInteractors(new[] { globalInteractor }); } } private void CommitAllGlobalInteractors() { // make a copy of the collection of interactors to avoid race conditions. List<IEyeXGlobalInteractor> globalInteractorsCopy; lock (_lock) { if (_globalInteractors.Count == 0) { return; } globalInteractorsCopy = new List<IEyeXGlobalInteractor>(_globalInteractors.Values); } CommitGlobalInteractors(globalInteractorsCopy); } private void CommitGlobalInteractors(IEnumerable<IEyeXGlobalInteractor> globalInteractors) { try { var snapshot = CreateGlobalInteractorSnapshot(); var forceDeletion = !IsRunning; foreach (var globalInteractor in globalInteractors) { globalInteractor.AddToSnapshot(snapshot, forceDeletion); } CommitSnapshot(snapshot); } catch (InteractionApiException ex) { print("EyeX operation failed: " + ex.Message); } } private Snapshot CreateGlobalInteractorSnapshot() { var snapshot = _context.CreateSnapshot(); snapshot.CreateBounds(BoundsType.None); snapshot.AddWindowId(Literals.GlobalInteractorWindowId); return snapshot; } private void CommitSnapshot(Snapshot snapshot) { #if DEVELOPMENT_BUILD snapshot.CommitAsync(OnSnapshotCommitted); #else snapshot.CommitAsync(null); #endif } #if DEVELOPMENT_BUILD private static void OnSnapshotCommitted(AsyncData asyncData) { try { ResultCode resultCode; if (!asyncData.TryGetResultCode(out resultCode)) { return; } if (resultCode == ResultCode.InvalidSnapshot) { print("Snapshot validation failed: " + GetErrorMessage(asyncData)); } else if (resultCode != ResultCode.Ok && resultCode != ResultCode.Cancelled) { print("Could not commit snapshot: " + GetErrorMessage(asyncData)); } } catch (InteractionApiException ex) { print("EyeX operation failed: " + ex.Message); } asyncData.Dispose(); } private static string GetErrorMessage(AsyncData asyncData) { string errorMessage; if (asyncData.Data.TryGetPropertyValue<string>(Literals.ErrorMessage, out errorMessage)) { return errorMessage; } else { return "Unspecified error."; } } #endif public Version GetEngineVersion() { if (_context == null) { throw new InvalidOperationException("The EyeX host has not been started."); } if(_engineVersion != null) { return _engineVersion; } var stateBag = _context.GetState(StatePaths.EngineVersion); string value; if (!stateBag.TryGetStateValue(out value, StatePaths.EngineVersion)) { throw new InvalidOperationException("Could not get engine version."); } return new Version(value); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace Microsoft.VisualStudioTools { internal static class CommonUtils { private static readonly char[] InvalidPathChars = GetInvalidPathChars(); private static readonly char[] DirectorySeparators = new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; private static char[] GetInvalidPathChars() { return Path.GetInvalidPathChars().Concat(new[] { '*', '?' }).ToArray(); } internal static bool TryMakeUri(string path, bool isDirectory, UriKind kind, out Uri uri) { if (isDirectory && !string.IsNullOrEmpty(path) && !HasEndSeparator(path)) { path += Path.DirectorySeparatorChar; } return Uri.TryCreate(path, kind, out uri); } internal static Uri MakeUri(string path, bool isDirectory, UriKind kind, string throwParameterName = "path") { try { if (isDirectory && !string.IsNullOrEmpty(path) && !HasEndSeparator(path)) { path += Path.DirectorySeparatorChar; } return new Uri(path, kind); } catch (UriFormatException ex) { throw new ArgumentException("Path was invalid", throwParameterName, ex); } catch (ArgumentException ex) { throw new ArgumentException("Path was invalid", throwParameterName, ex); } } /// <summary> /// Normalizes and returns the provided path. /// </summary> public static string NormalizePath(string path) { if (string.IsNullOrEmpty(path)) { return null; } const string MdhaPrefix = "mdha:"; // webkit debugger prepends with 'mdha' if (path.StartsWith(MdhaPrefix, StringComparison.OrdinalIgnoreCase)) { path = path.Substring(MdhaPrefix.Length); } return !HasStartSeparator(path) && Path.IsPathRooted(path) ? Path.GetFullPath(path) : path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); } /// <summary> /// Normalizes and returns the provided directory path, always /// ending with '/'. /// </summary> public static string NormalizeDirectoryPath(string path) { var normalizedPath = NormalizePath(path); return EnsureEndSeparator(normalizedPath); } /// <summary> /// Return true if both paths represent the same directory. /// </summary> public static bool IsSameDirectory(string path1, string path2) { if (StringComparer.Ordinal.Equals(path1, path2)) { // Quick return, but will only work where the paths are already normalized and // have matching case. return true; } return TryMakeUri(path1, true, UriKind.Absolute, out Uri uri1) && TryMakeUri(path2, true, UriKind.Absolute, out Uri uri2) && uri1 == uri2; } /// <summary> /// Return true if both paths represent the same location. /// </summary> public static bool IsSamePath(string file1, string file2) { if (StringComparer.Ordinal.Equals(file1, file2)) { // Quick return, but will only work where the paths are already normalized and // have matching case. return true; } return TryMakeUri(file1, false, UriKind.Absolute, out Uri uri1) && TryMakeUri(file2, false, UriKind.Absolute, out Uri uri2) && uri1 == uri2; } /// <summary> /// Return true if the path represents a file or directory contained in /// root or a subdirectory of root. /// </summary> public static bool IsSubpathOf(string root, string path) { if (HasEndSeparator(root) && !path.Contains("..") && path.StartsWith(root, StringComparison.Ordinal)) { // Quick return, but only where the paths are already normalized and // have matching case. return true; } var uriRoot = MakeUri(root, true, UriKind.Absolute, "root"); var uriPath = MakeUri(path, false, UriKind.Absolute, "path"); if (uriRoot.Equals(uriPath) || uriRoot.IsBaseOf(uriPath)) { return true; } // Special case where root and path are the same, but path was provided // without a terminating separator. var uriDirectoryPath = MakeUri(path, true, UriKind.Absolute, "path"); if (uriRoot.Equals(uriDirectoryPath)) { return true; } return false; } /// <summary> /// Returns a normalized directory path created by joining relativePath to root. /// The result is guaranteed to end with a backslash. /// </summary> /// <exception cref="ArgumentException">root is not an absolute path, or /// either path is invalid.</exception> /// <exception cref="InvalidOperationException">An absolute path cannot be /// created.</exception> public static string GetAbsoluteDirectoryPath(string root, string relativePath) { var absolutePath = GetAbsoluteFilePath(root, relativePath); return EnsureEndSeparator(absolutePath); } /// <summary> /// Returns a normalized file path created by joining relativePath to root. /// The result is not guaranteed to end with a backslash. /// </summary> /// <exception cref="ArgumentException">root is not an absolute path, or /// either path is invalid.</exception> public static string GetAbsoluteFilePath(string root, string relativePath) { var absolutePath = HasStartSeparator(relativePath) ? Path.GetFullPath(relativePath) : Path.Combine(root, relativePath); var split = absolutePath.Split(DirectorySeparators); var segments = new LinkedList<string>(); for (var i = split.Length - 1; i >= 0; i--) { var segment = split[i]; if (segment == "..") { i--; } else if (segment != ".") { segments.AddFirst(segment); } } // Cannot use Path.Combine because the result will not return an absolute path. // This happens because the root has missing the trailing slash. return string.Join(Path.DirectorySeparatorChar.ToString(), segments); } /// <summary> /// Returns a relative path from the base path to the other path. This is /// intended for serialization rather than UI. See CreateFriendlyDirectoryPath /// for UI strings. /// </summary> /// <exception cref="ArgumentException">Either parameter was an invalid or a /// relative path.</exception> public static string GetRelativeDirectoryPath(string fromDirectory, string toDirectory) { var relativePath = GetRelativeFilePath(fromDirectory, toDirectory); return EnsureEndSeparator(relativePath); } /// <summary> /// Returns a relative path from the base path to the file. This is /// intended for serialization rather than UI. See CreateFriendlyFilePath /// for UI strings. /// Retunrs the file fullpath if the roots are different. /// </summary> public static string GetRelativeFilePath(string fromDirectory, string toFile) { var dirFullPath = Path.GetFullPath(TrimEndSeparator(fromDirectory)); var fileFullPath = Path.GetFullPath(toFile); // If the root paths doesn't match return the file full path. if (!string.Equals(Path.GetPathRoot(dirFullPath), Path.GetPathRoot(fileFullPath), StringComparison.OrdinalIgnoreCase)) { return fileFullPath; } var splitDirectory = dirFullPath.Split(DirectorySeparators); var splitFile = fileFullPath.Split(DirectorySeparators); var relativePath = new List<string>(); var dirIndex = 0; var minLegth = Math.Min(splitDirectory.Length, splitFile.Length); while (dirIndex < minLegth && string.Equals(splitDirectory[dirIndex], splitFile[dirIndex], StringComparison.OrdinalIgnoreCase)) { dirIndex++; } for (var i = splitDirectory.Length; i > dirIndex; i--) { relativePath.Add(".."); } for (var i = dirIndex; i < splitFile.Length; i++) { relativePath.Add(splitFile[i]); } return string.Join(Path.DirectorySeparatorChar.ToString(), relativePath); } /// <summary> /// Tries to create a friendly directory path: '.' if the same as base path, /// relative path if short, absolute path otherwise. /// </summary> public static string CreateFriendlyDirectoryPath(string basePath, string path) { var relativePath = GetRelativeDirectoryPath(basePath, path); if (relativePath.Length > 1) { relativePath = TrimEndSeparator(relativePath); } if (string.IsNullOrEmpty(relativePath)) { relativePath = "."; } return relativePath; } /// <summary> /// Tries to create a friendly file path. /// </summary> public static string CreateFriendlyFilePath(string basePath, string path) { return GetRelativeFilePath(basePath, path); } /// <summary> /// Returns the last directory segment of a path. The last segment is /// assumed to be the string between the second-last and last directory /// separator characters in the path. If there is no suitable substring, /// the empty string is returned. /// /// The first segment of the path is only returned if it does not /// contain a colon. Segments equal to "." are ignored and the preceding /// segment is used. /// </summary> /// <remarks> /// This should be used in place of: /// <c>Path.GetFileName(CommonUtils.TrimEndSeparator(Path.GetDirectoryName(path)))</c> /// </remarks> public static string GetLastDirectoryName(string path) { if (string.IsNullOrEmpty(path)) { return string.Empty; } var last = path.LastIndexOfAny(DirectorySeparators); var result = string.Empty; while (last > 1) { var first = path.LastIndexOfAny(DirectorySeparators, last - 1); if (first < 0) { if (path.IndexOf(':') < last) { // Don't want to return scheme/drive as a directory return string.Empty; } first = -1; } if (first == 1 && path[0] == path[1]) { // Don't return computer name in UNC path return string.Empty; } result = path.Substring(first + 1, last - (first + 1)); if (!string.IsNullOrEmpty(result) && result != ".") { // Result is valid break; } last = first; } return result; } /// <summary> /// Returns the path to the parent directory segment of a path. If the /// last character of the path is a directory separator, the segment /// prior to that character is removed. Otherwise, the segment following /// the last directory separator is removed. /// </summary> /// <remarks> /// This should be used in place of: /// <c>Path.GetDirectoryName(CommonUtils.TrimEndSeparator(path)) + Path.DirectorySeparatorChar</c> /// </remarks> public static string GetParent(string path) { if (string.IsNullOrEmpty(path)) { return string.Empty; } var last = path.Length - 1; if (DirectorySeparators.Contains(path[last])) { last -= 1; } if (last <= 0) { return string.Empty; } last = path.LastIndexOfAny(DirectorySeparators, last); if (last < 0) { return string.Empty; } return path.Remove(last + 1); } /// <summary> /// Returns the last segment of the path. If the last character is a /// directory separator, this will be the segment preceding the /// separator. Otherwise, it will be the segment following the last /// separator. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetFileOrDirectoryName(string path) { if (string.IsNullOrEmpty(path)) { return string.Empty; } var last = path.Length - 1; if (DirectorySeparators.Contains(path[last])) { last -= 1; } if (last < 0) { return string.Empty; } var start = path.LastIndexOfAny(DirectorySeparators, last); return path.Substring(start + 1, last - start); } /// <summary> /// Returns true if the path has a directory separator character at the end. /// </summary> public static bool HasEndSeparator(string path) { return !string.IsNullOrEmpty(path) && DirectorySeparators.Contains(path[path.Length - 1]); } public static bool HasStartSeparator(string path) { return !string.IsNullOrEmpty(path) && DirectorySeparators.Contains(path[0]); } /// <summary> /// Removes up to one directory separator character from the end of path. /// </summary> public static string TrimEndSeparator(string path) { if (HasEndSeparator(path)) { if (path.Length > 2 && path[path.Length - 2] == ':') { // The slash at the end of a drive specifier is not actually // a separator. return path; } else if (path.Length > 3 && path[path.Length - 2] == path[path.Length - 1] && path[path.Length - 3] == ':') { // The double slash at the end of a schema is not actually a // separator. return path; } return path.Remove(path.Length - 1); } else { return path; } } /// <summary> /// Adds a directory separator character to the end of path if required. /// </summary> public static string EnsureEndSeparator(string path) { if (string.IsNullOrEmpty(path)) { return path; } else if (!HasEndSeparator(path)) { return path + Path.DirectorySeparatorChar; } else { return path; } } /// <summary> /// Removes leading @"..\" segments from a path. /// </summary> private static string TrimUpPaths(string path) { var actualStart = 0; while (actualStart + 2 < path.Length) { if (path[actualStart] == '.' && path[actualStart + 1] == '.' && (path[actualStart + 2] == Path.DirectorySeparatorChar || path[actualStart + 2] == Path.AltDirectorySeparatorChar)) { actualStart += 3; } else { break; } } return (actualStart > 0) ? path.Substring(actualStart) : path; } /// <summary> /// Remove first and last quotes from path /// </summary> /// <param name="path"></param> /// <returns></returns> public static string UnquotePath(string path) { if (path.StartsWith("\"") && path.EndsWith("\"")) { return path.Substring(1, path.Length - 2); } return path; } /// <summary> /// Returns true if the path is a valid path, regardless of whether the /// file exists or not. /// </summary> public static bool IsValidPath(string path) { return !string.IsNullOrEmpty(path) && path.IndexOfAny(InvalidPathChars) < 0; } /// <summary> /// Gets a filename in the specified location with the specified name and extension. /// If the file already exist it will calculate a name with a number in it. /// </summary> public static string GetAvailableFilename(string location, string basename, string extension) { var newPath = Path.Combine(location, basename); var index = 0; if (File.Exists(newPath + extension)) { string candidateNewPath; do { candidateNewPath = string.Format("{0}{1}", newPath, ++index); } while (File.Exists(candidateNewPath + extension)); newPath = candidateNewPath; } var final = newPath + extension; return final; } } }
// 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 ConvertToInt64WithTruncationVector128Single() { var test = new SimdScalarUnaryOpConvertTest__ConvertToInt64WithTruncationVector128Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.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 (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 SimdScalarUnaryOpConvertTest__ConvertToInt64WithTruncationVector128Single { private struct TestStruct { public Vector128<Single> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimdScalarUnaryOpConvertTest__ConvertToInt64WithTruncationVector128Single testClass) { var result = Sse.X64.ConvertToInt64WithTruncation(_fld); testClass.ValidateResult(_fld, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar; private Vector128<Single> _fld; private SimdScalarUnaryOpTest__DataTable<Single> _dataTable; static SimdScalarUnaryOpConvertTest__ConvertToInt64WithTruncationVector128Single() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimdScalarUnaryOpConvertTest__ConvertToInt64WithTruncationVector128Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new SimdScalarUnaryOpTest__DataTable<Single>(_data, LargestVectorSize); } public bool IsSupported => Sse.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.X64.ConvertToInt64WithTruncation( Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.X64.ConvertToInt64WithTruncation( Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.X64.ConvertToInt64WithTruncation( Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse.X64).GetMethod(nameof(Sse.X64.ConvertToInt64WithTruncation), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) }); ValidateResult(_dataTable.inArrayPtr, (Int64)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse.X64).GetMethod(nameof(Sse.X64.ConvertToInt64WithTruncation), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) }); ValidateResult(_dataTable.inArrayPtr, (Int64)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse.X64).GetMethod(nameof(Sse.X64.ConvertToInt64WithTruncation), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) }); ValidateResult(_dataTable.inArrayPtr, (Int64)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.X64.ConvertToInt64WithTruncation( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr); var result = Sse.X64.ConvertToInt64WithTruncation(firstOp); ValidateResult(firstOp, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)); var result = Sse.X64.ConvertToInt64WithTruncation(firstOp); ValidateResult(firstOp, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)); var result = Sse.X64.ConvertToInt64WithTruncation(firstOp); ValidateResult(firstOp, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimdScalarUnaryOpConvertTest__ConvertToInt64WithTruncationVector128Single(); var result = Sse.X64.ConvertToInt64WithTruncation(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.X64.ConvertToInt64WithTruncation(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.X64.ConvertToInt64WithTruncation(test._fld); ValidateResult(test._fld, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> firstOp, Int64 result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp); ValidateResult(inArray, result, method); } private void ValidateResult(void* firstOp, Int64 result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray, result, method); } private void ValidateResult(Single[] firstOp, Int64 result, [CallerMemberName] string method = "") { bool succeeded = true; if ((long) firstOp[0] != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse.X64)}.{nameof(Sse.X64.ConvertToInt64WithTruncation)}<Int64>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: result"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Xml; using SIL.Annotations; using SIL.DictionaryServices.Model; using SIL.Extensions; using SIL.Lift; using SIL.Lift.Options; using SIL.Lift.Validation; using SIL.Text; using SIL.Xml; namespace SIL.DictionaryServices.Lift { public class LiftWriter : ILiftWriter<LexEntry> { private readonly XmlWriter _writer; private readonly Dictionary<string, int> _allIdsExportedSoFar; #if DEBUG [CLSCompliant(false)] protected StackTrace _constructionStack; #endif private LiftWriter() { #if DEBUG _constructionStack = new StackTrace(); #endif _allIdsExportedSoFar = new Dictionary<string, int>(); } public enum ByteOrderStyle { BOM, NoBOM } ; /// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="includeByteOrderMark">PrinceXML (at least v7 chokes if given a BOM, Lexique Pro chokes without it) </param> public LiftWriter(string path, ByteOrderStyle byteOrderStyle) : this() { _disposed = true; // Just in case we throw in the constructor var settings = CanonicalXmlSettings.CreateXmlWriterSettings(); settings.Encoding = new UTF8Encoding(byteOrderStyle == ByteOrderStyle.BOM); _writer = XmlWriter.Create(path, settings); Start(); _disposed = false; } public LiftWriter(StringBuilder builder, bool produceFragmentOnly): this() { _writer = XmlWriter.Create(builder, CanonicalXmlSettings.CreateXmlWriterSettings( produceFragmentOnly ? ConformanceLevel.Fragment : ConformanceLevel.Document) ); if (!produceFragmentOnly) { Start(); } } private void Start() { Writer.WriteStartDocument(); Writer.WriteStartElement("lift"); Writer.WriteAttributeString("version", Validator.LiftVersion); Writer.WriteAttributeString("producer", ProducerString); // _writer.WriteAttributeString("xmlns", "flex", null, "http://fieldworks.sil.org"); } public void WriteHeader(string headerConentsNotIncludingHeaderElement) { Writer.WriteStartElement("header"); Writer.WriteRaw(headerConentsNotIncludingHeaderElement); Writer.WriteEndElement(); } public static string ProducerString { get { return "Palaso.DictionaryServices.LiftWriter " + Assembly.GetExecutingAssembly().GetName().Version; } } protected XmlWriter Writer { get { return _writer; } } public void End() { if (Writer.Settings.ConformanceLevel != ConformanceLevel.Fragment) { #if MONO // If there are no open elements and you try to WriteEndElement then mono throws a // InvalidOperationException: There is no more open element // WriteEndDocument will close any open elements anyway // // If you try to WriteEndDocument on a closed writer then mono throws a // InvalidOperationException: This XmlWriter does not accept EndDocument at this state Closed if (Writer.WriteState != WriteState.Closed) Writer.WriteEndDocument(); #else Writer.WriteEndElement(); //lift Writer.WriteEndDocument(); #endif } Writer.Flush(); Writer.Close(); } public virtual void Add(LexEntry entry) { Add(entry, 0); } public void Add(LexEntry entry, int order) { List<string> propertiesAlreadyOutput = new List<string>(); Writer.WriteStartElement("entry"); Writer.WriteAttributeString("id", GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, _allIdsExportedSoFar)); if (order > 0) { Writer.WriteAttributeString("order", order.ToString()); } Debug.Assert(entry.CreationTime.Kind == DateTimeKind.Utc); Writer.WriteAttributeString("dateCreated", entry.CreationTime.ToLiftDateTimeFormat()); Debug.Assert(entry.ModificationTime.Kind == DateTimeKind.Utc); Writer.WriteAttributeString("dateModified", entry.ModificationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("guid", entry.Guid.ToString()); // _writer.WriteAttributeString("flex", "id", "http://fieldworks.sil.org", entry.Guid.ToString()); WriteMultiWithWrapperIfNonEmpty(LexEntry.WellKnownProperties.LexicalUnit, "lexical-unit", entry.LexicalForm); WriteHeadword(entry); WriteWellKnownCustomMultiText(entry, LexEntry.WellKnownProperties.Citation, propertiesAlreadyOutput); WriteWellKnownCustomMultiText(entry, PalasoDataObject.WellKnownProperties.Note, propertiesAlreadyOutput); WriteCustomProperties(entry, propertiesAlreadyOutput); InsertPronunciationIfNeeded(entry, propertiesAlreadyOutput); foreach (LexSense sense in entry.Senses) { Add(sense); } foreach (var variant in entry.Variants) { AddVariant(variant); } foreach (var phonetic in entry.Pronunciations) { AddPronunciation(phonetic); } foreach (var etymology in entry.Etymologies) { AddEtymology(etymology); } foreach (var note in entry.Notes) { AddNote(note); } Writer.WriteEndElement(); } private void AddEtymology(LexEtymology etymology) { // ok if no form is given if (!MultiTextBase.IsEmpty(etymology)) // { Writer.WriteStartElement("etymology"); //type is required, so add the attribute even if it's emtpy Writer.WriteAttributeString("type", etymology.Type.Trim()); //source is required, so add the attribute even if it's emtpy Writer.WriteAttributeString("source", etymology.Source.Trim()); AddMultitextGlosses(string.Empty, etymology.Gloss); WriteCustomMultiTextField("comment", etymology.Comment); AddMultitextForms(string.Empty, etymology); Writer.WriteEndElement(); // } } private void AddPronunciation(LexPhonetic phonetic) { WriteMultiWithWrapperIfNonEmpty(string.Empty, "pronunciation", phonetic); } public void AddVariant(LexVariant variant) { WriteMultiWithWrapperIfNonEmpty(string.Empty, "variant", variant); } public void AddNote(LexNote note) { if (!MultiTextBase.IsEmpty(note)) { Writer.WriteStartElement("note"); if(!string.IsNullOrEmpty(note.Type)) { Writer.WriteAttributeString("type", note.Type.Trim()); } AddMultitextForms(string.Empty, note); Writer.WriteEndElement(); } } public void AddReversal(LexReversal reversal) { if (!MultiTextBase.IsEmpty(reversal)) { Writer.WriteStartElement("reversal"); if (!string.IsNullOrEmpty(reversal.Type)) { Writer.WriteAttributeString("type", reversal.Type.Trim()); } AddMultitextForms(string.Empty, reversal); Writer.WriteEndElement(); } } /// <summary> /// in the plift subclass, we add a pronounciation if we have an audio writing system alternative on the lexical unit /// </summary> protected virtual void InsertPronunciationIfNeeded(LexEntry entry, List<string> propertiesAlreadyOutput) { } protected virtual void WriteHeadword(LexEntry entry) {} /// <summary> /// Get a human readable identifier for this entry taking into account all the rest of the /// identifiers that this has seen /// </summary> /// <param name="entry">the entry to </param> /// <param name="idsAndCounts">the base ids that have been used so far and how many times</param> /// <remarks>This function alters the idsAndCounts and thus is not stable if the entry /// does not already have an id and the same idsAndCounts dictionary is provided. /// A second call to this function with the same entry that lacks an id and the same /// idsAndCounts will produce different results each time it runs /// </remarks> /// <returns>A base id composed with its count</returns> public static string GetHumanReadableIdWithAnyIllegalUnicodeEscaped(LexEntry entry, Dictionary<string, int> idsAndCounts) { string id = entry.GetOrCreateId(true); /* if (id == null || id.Length == 0) // if the entry doesn't claim to have an id { id = entry.LexicalForm.GetFirstAlternative().Trim().Normalize(NormalizationForm.FormD); // use the first form as an id if (id == "") { id = "NoForm"; //review } } id = id.Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' '); //make this id unique int count; if (idsAndCounts.TryGetValue(id, out count)) { ++count; idsAndCounts.Remove(id); idsAndCounts.Add(id, count); id = string.Format("{0}_{1}", id, count); } else { idsAndCounts.Add(id, 1); } */ return id.EscapeAnyUnicodeCharactersIllegalInXml(); } public void Add(LexSense sense) { List<string> propertiesAlreadyOutput = new List<string>(); Writer.WriteStartElement("sense"); Writer.WriteAttributeString("id", sense.GetOrCreateId()); if (ShouldOutputProperty(LexSense.WellKnownProperties.PartOfSpeech)) { WriteGrammi(sense); propertiesAlreadyOutput.Add(LexSense.WellKnownProperties.PartOfSpeech); } if (ShouldOutputProperty(LexSense.WellKnownProperties.Gloss)) { // review: I (cp) don't think this has the same checking for round tripping that AddMultiText... methods have. WriteGlossOneElementPerFormIfNonEmpty(sense.Gloss); propertiesAlreadyOutput.Add(LexSense.WellKnownProperties.Gloss); } WriteWellKnownCustomMultiText(sense, LexSense.WellKnownProperties.Definition, propertiesAlreadyOutput); foreach (LexExampleSentence example in sense.ExampleSentences) { Add(example); } foreach (var reversal in sense.Reversals) { AddReversal(reversal); } foreach (var note in sense.Notes) { AddNote(note); } WriteWellKnownCustomMultiText(sense, PalasoDataObject.WellKnownProperties.Note, propertiesAlreadyOutput); // WriteWellKnownUnimplementedProperty(sense, LexSense.WellKnownProperties.Note, propertiesAlreadyOutput); WriteCustomProperties(sense, propertiesAlreadyOutput); Writer.WriteEndElement(); } private void WriteGrammi(LexSense sense) { if (!ShouldOutputProperty(LexSense.WellKnownProperties.PartOfSpeech)) { return; } OptionRef pos = sense.GetProperty<OptionRef>(LexSense.WellKnownProperties.PartOfSpeech); if (pos != null && !pos.IsEmpty) { WritePosCore(pos); } } protected virtual void WritePosCore(OptionRef pos) { Writer.WriteStartElement("grammatical-info"); Writer.WriteAttributeString("value", pos.Value); WriteFlags(pos); foreach (string rawXml in pos.EmbeddedXmlElements) { Writer.WriteRaw(rawXml); } Writer.WriteEndElement(); } private void WriteWellKnownCustomMultiText(PalasoDataObject item, string property, ICollection<string> propertiesAlreadyOutput) { if (ShouldOutputProperty(property)) { MultiText m = item.GetProperty<MultiText>(property); if (WriteMultiWithWrapperIfNonEmpty(property, property, m)) { propertiesAlreadyOutput.Add(property); } } } /// <summary> /// this base implementationg is for when we're just exporting to lift, and dont' want to filter or order. /// It is overridden in a child class for writing presentation-ready lift, when /// we do want to filter and order /// </summary> /// <param name="text"></param> /// <param name="propertyName"></param> /// <returns></returns> protected virtual LanguageForm[] GetOrderedAndFilteredForms(MultiTextBase text, string propertyName) { return text.Forms; } private void WriteCustomProperties(PalasoDataObject item, ICollection<string> propertiesAlreadyOutput) { foreach (KeyValuePair<string, IPalasoDataObjectProperty> pair in item.Properties) { if (propertiesAlreadyOutput.Contains(pair.Key)) { continue; } if (!ShouldOutputProperty(pair.Key)) { continue; } if (pair.Value is EmbeddedXmlCollection) { WriteEmbeddedXmlCollection(pair.Value as EmbeddedXmlCollection); continue; } if (pair.Value is MultiText) { WriteCustomMultiTextField(pair.Key, pair.Value as MultiText); continue; } if (pair.Value is OptionRef) { WriteOptionRef(pair.Key, pair.Value as OptionRef); continue; } if (pair.Value is OptionRefCollection) { WriteOptionRefCollection(pair.Key, pair.Value as OptionRefCollection); continue; } if (pair.Value is LexRelationCollection) { WriteRelationCollection(pair.Key, pair.Value as LexRelationCollection); continue; } if (pair.Value is FlagState) { WriteFlagState(pair.Key, pair.Value as FlagState); continue; } PictureRef pictureRef = pair.Value as PictureRef; if (pictureRef != null) { WriteIllustrationElement(pictureRef); continue; } throw new ApplicationException( string.Format( "The LIFT exporter was surprised to find a property '{0}' of type: {1}", pair.Key, pair.Value.GetType())); } } protected virtual void WriteIllustrationElement(PictureRef pictureRef) { WriteURLRef("illustration", pictureRef.Value, pictureRef.Caption); } protected virtual bool ShouldOutputProperty(string key) { return true; } private void WriteEmbeddedXmlCollection(EmbeddedXmlCollection collection) { foreach (string rawXml in collection.Values) { Writer.WriteRaw(rawXml); } } protected void WriteURLRef(string key, string href, MultiText caption) { if (!string.IsNullOrEmpty(href)) { Writer.WriteStartElement(key); Writer.WriteAttributeString("href", href); WriteMultiWithWrapperIfNonEmpty(key, "label", caption); Writer.WriteEndElement(); } } private void WriteFlagState(string key, FlagState state) { if (state.Value) //skip it if it's not set { Writer.WriteStartElement("trait"); Writer.WriteAttributeString("name", key); Writer.WriteAttributeString("value", "set"); //this attr required by lift schema, though we don't use it Writer.WriteEndElement(); } } private void WriteRelationCollection(string key, LexRelationCollection collection) { if (!ShouldOutputProperty(key)) { return; } foreach (LexRelation relation in collection.Relations) { if(string.IsNullOrEmpty(relation.Key)) continue; if(!EntryDoesExist(relation.TargetId)) continue; Writer.WriteStartElement("relation"); Writer.WriteAttributeString("type", GetOutputRelationName(relation)); Writer.WriteAttributeString("ref", relation.Key); WriteRelationTarget(relation); WriteExtensible(relation); foreach (string rawXml in relation.EmbeddedXmlElements) { Writer.WriteRaw(rawXml); } Writer.WriteEndElement(); } } protected virtual bool EntryDoesExist(string id) { return true;// real implementations would check } protected virtual string GetOutputRelationName(LexRelation relation) { return relation.FieldId; } /// <summary> /// allows subclass to output a dereferenced target name, e.g., for plift /// </summary> protected virtual void WriteRelationTarget(LexRelation relation) {} private void WriteOptionRefCollection(string traitName, OptionRefCollection collection) { if (!ShouldOutputProperty(traitName)) { return; } foreach (string key in collection.Keys) { Writer.WriteStartElement("trait"); Writer.WriteAttributeString("name", traitName); Writer.WriteAttributeString("value", key); //yes, the 'value' here is an option key Writer.WriteEndElement(); } } private void WriteCustomMultiTextField(string type, MultiText text) // review cp see WriteEmbeddedXmlCollection { if (!MultiTextBase.IsEmpty(text)) { Writer.WriteStartElement("field"); Writer.WriteAttributeString("type", type); WriteMultiTextNoWrapper(type, text); Writer.WriteEndElement(); } } protected virtual void WriteOptionRef(string key, OptionRef optionRef) { if (optionRef.Value.Length > 0) { Writer.WriteStartElement("trait"); Writer.WriteAttributeString("name", key); Writer.WriteAttributeString("value", optionRef.Value); foreach (string rawXml in optionRef.EmbeddedXmlElements) { Writer.WriteRaw(rawXml); } Writer.WriteEndElement(); } } public void Add(LexExampleSentence example) { if (!ShouldOutputProperty(LexExampleSentence.WellKnownProperties.ExampleSentence)) { return; } List<string> propertiesAlreadyOutput = new List<string>(); Writer.WriteStartElement("example"); OptionRef source = example.GetProperty<OptionRef>(LexExampleSentence.WellKnownProperties.Source); if (source != null && source.Value.Length > 0) { if (ShouldOutputProperty(LexExampleSentence.WellKnownProperties.Source)) { Writer.WriteAttributeString("source", source.Value); propertiesAlreadyOutput.Add("source"); } } WriteMultiTextNoWrapper(LexExampleSentence.WellKnownProperties.ExampleSentence, example.Sentence); propertiesAlreadyOutput.Add(LexExampleSentence.WellKnownProperties.ExampleSentence); // WriteMultiWithWrapperIfNonEmpty(LexExampleSentence.WellKnownProperties.Translation, "translation", example.Translation); if (!MultiTextBase.IsEmpty(example.Translation)) { Writer.WriteStartElement("translation"); if (!string.IsNullOrEmpty(example.TranslationType)) { Writer.WriteAttributeString("type", example.TranslationType); propertiesAlreadyOutput.Add("type"); } AddMultitextForms(LexExampleSentence.WellKnownProperties.Translation, example.Translation); Writer.WriteEndElement(); propertiesAlreadyOutput.Add(LexExampleSentence.WellKnownProperties.Translation); } if (ShouldOutputProperty(LexExampleSentence.WellKnownProperties.ExampleSentence)) { WriteWellKnownCustomMultiText(example, PalasoDataObject.WellKnownProperties.Note, propertiesAlreadyOutput); } WriteCustomProperties(example, propertiesAlreadyOutput); Writer.WriteEndElement(); } public void AddMultitextGlosses(string propertyName, MultiText text) // review cp see WriteEmbeddedXmlCollection { WriteLanguageFormsInWrapper(GetOrderedAndFilteredForms(text, propertyName), "gloss", false); WriteFormsThatNeedToBeTheirOwnFields(text, propertyName); WriteEmbeddedXmlCollection(text); } public void AddMultitextForms(string propertyName, MultiText text) // review cp see WriteEmbeddedXmlCollection { WriteLanguageFormsInWrapper(GetOrderedAndFilteredForms(text, propertyName), "form", false); WriteFormsThatNeedToBeTheirOwnFields(text, propertyName); WriteEmbeddedXmlCollection(text); } private void WriteExtensible(IExtensible extensible) { foreach (var trait in extensible.Traits) { WriteTrait(trait); } foreach (var field in extensible.Fields) { Writer.WriteStartElement("field"); Writer.WriteAttributeString("type", field.Type); WriteMultiTextNoWrapper(string.Empty /*what's this for*/ , field); foreach (var trait in field.Traits) { WriteTrait(trait); } Writer.WriteEndElement(); } } private void WriteTrait(LexTrait trait) { Writer.WriteStartElement("trait"); Writer.WriteAttributeString("name", trait.Name); Writer.WriteAttributeString("value", trait.Value.Trim()); Writer.WriteEndElement(); } private void WriteEmbeddedXmlCollection(MultiText text) { foreach (string rawXml in text.EmbeddedXmlElements) // todo cp Promote roundtripping to Palaso.Lift / Palaso.Data also then can use MultiTextBase here (or a better interface). { Writer.WriteRaw(rawXml); } } protected virtual void WriteFormsThatNeedToBeTheirOwnFields(MultiText text, string name) // review cp For PLiftExporter GetAudioForms { } protected void WriteLanguageFormsInWrapper(IEnumerable<LanguageForm> forms, string wrapper, bool doMarkTheFirst) { foreach (LanguageForm form in forms) { var spans = form.Spans; Writer.WriteStartElement(wrapper); Writer.WriteAttributeString("lang", form.WritingSystemId); if (doMarkTheFirst) { doMarkTheFirst = false; Writer.WriteAttributeString("first", "true"); //useful for headword } // string wrappedTextToExport = "<text>" + form.Form + "</text>"; // string wrappedTextToExport = form.Form; XmlReaderSettings fragmentReaderSettings = new XmlReaderSettings(); fragmentReaderSettings.ConformanceLevel = ConformanceLevel.Fragment; string scaryUnicodeEscaped = form.Form.EscapeAnyUnicodeCharactersIllegalInXml(); string safeFromScaryUnicodeSoItStaysEscaped = scaryUnicodeEscaped.Replace("&#x", ""); XmlReader testerForWellFormedness = XmlReader.Create(new StringReader("<temp>" + safeFromScaryUnicodeSoItStaysEscaped + "</temp>")); bool isTextWellFormedXml = true; try { while (testerForWellFormedness.Read()) { //Just checking for well formed XML } } catch { isTextWellFormedXml = false; } if(isTextWellFormedXml) { Writer.WriteStartElement("text"); if (spans.Count > 0) { Writer.WriteString(""); // trick writer into knowing this is "mixed mode". int index = 0; int count; foreach (var span in spans) { // User edits may have effectively deleted the text of this span. if (span.Length <= 0) continue; if (index < span.Index) { count = span.Index - index; string txtBefore = String.Empty; if (index + count <= form.Form.Length) txtBefore = form.Form.Substring(index, count); else if (index < form.Form.Length) txtBefore = form.Form.Substring(index); Writer.WriteRaw(txtBefore.EscapeAnyUnicodeCharactersIllegalInXml()); } var txtInner = WriteSpanStartElementAndGetText(form, span); Writer.WriteRaw(txtInner.EscapeAnyUnicodeCharactersIllegalInXml()); Writer.WriteEndElement(); index = span.Index + span.Length; } if (index < form.Form.Length) { var txtAfter = form.Form.Substring(index); Writer.WriteRaw(txtAfter.EscapeAnyUnicodeCharactersIllegalInXml()); } } else { Writer.WriteRaw(form.Form.EscapeAnyUnicodeCharactersIllegalInXml()); } Writer.WriteEndElement(); } else { Writer.WriteStartElement("text"); if (spans.Count > 0) { Writer.WriteString(""); // trick writer into knowing this is "mixed mode". int index = 0; int count; foreach (var span in spans) { // User edits may have effectively deleted the text of this span. if (span.Length <= 0) continue; if (index < span.Index) { count = span.Index - index; string txtBefore = String.Empty; if (index + count <= form.Form.Length) txtBefore = form.Form.Substring(index, count); else if (index < form.Form.Length) txtBefore = form.Form.Substring(index); Writer.WriteRaw(txtBefore.EscapeSoXmlSeesAsPureTextAndEscapeCharactersIllegalInXml()); } var txtInner = WriteSpanStartElementAndGetText(form, span); Writer.WriteRaw(txtInner.EscapeSoXmlSeesAsPureTextAndEscapeCharactersIllegalInXml()); Writer.WriteEndElement(); index = span.Index + span.Length; } if (index < form.Form.Length) { var txtAfter = form.Form.Substring(index); Writer.WriteRaw(txtAfter.EscapeSoXmlSeesAsPureTextAndEscapeCharactersIllegalInXml()); } } else { Writer.WriteRaw(form.Form.EscapeSoXmlSeesAsPureTextAndEscapeCharactersIllegalInXml()); } Writer.WriteEndElement(); } WriteFlags(form); Writer.WriteEndElement(); } } string WriteSpanStartElementAndGetText(LanguageForm form, LanguageForm.FormatSpan span) { Writer.WriteStartElement("span"); if (!String.IsNullOrEmpty(span.Lang)) Writer.WriteAttributeString("lang", span.Lang); if (!String.IsNullOrEmpty(span.Class)) Writer.WriteAttributeString("class", span.Class); if (!String.IsNullOrEmpty(span.LinkURL)) Writer.WriteAttributeString("href", span.LinkURL); if (span.Index + span.Length <= form.Form.Length) return form.Form.Substring(span.Index, span.Length); else if (span.Index < form.Form.Length) return form.Form.Substring(span.Index); else return String.Empty; } private void WriteFlags(IAnnotatable thing) { if (thing.IsStarred) { Writer.WriteStartElement("annotation"); Writer.WriteAttributeString("name", "flag"); Writer.WriteAttributeString("value", "1"); Writer.WriteEndElement(); } } private void WriteMultiTextNoWrapper(string propertyName, MultiText text) // review cp see WriteEmbeddedXmlCollection { if (!MultiTextBase.IsEmpty(text)) { AddMultitextForms(propertyName, text); } } private void WriteGlossOneElementPerFormIfNonEmpty(MultiTextBase text) { if (MultiTextBase.IsEmpty(text)) { return; } foreach (var form in GetOrderedAndFilteredForms(text, LexSense.WellKnownProperties.Gloss)) { if (string.IsNullOrEmpty(form.Form)) { continue; } Writer.WriteStartElement("gloss"); Writer.WriteAttributeString("lang", form.WritingSystemId); Writer.WriteStartElement("text"); Writer.WriteString(form.Form); Writer.WriteEndElement(); WriteFlags(form); Writer.WriteEndElement(); } } private bool WriteMultiWithWrapperIfNonEmpty(string propertyName, string wrapperName, MultiText text) // review cp see WriteEmbeddedXmlCollection { if (!MultiTextBase.IsEmpty(text)) { Writer.WriteStartElement(wrapperName); AddMultitextForms(propertyName, text); // review cp see WriteEmbeddedXmlCollection if (text is IExtensible) { WriteExtensible((IExtensible)text); } Writer.WriteEndElement(); return true; } return false; } public void AddNewEntry(LexEntry entry) { Writer.WriteStartElement("entry"); Writer.WriteAttributeString("dateCreated", entry.CreationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("dateModified", entry.ModificationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("guid", entry.Guid.ToString()); Writer.WriteEndElement(); } public void AddDeletedEntry(LexEntry entry) { Writer.WriteStartElement("entry"); Writer.WriteAttributeString("id", GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, _allIdsExportedSoFar)); Writer.WriteAttributeString("dateCreated", entry.CreationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("dateModified", entry.ModificationTime.ToLiftDateTimeFormat()); Writer.WriteAttributeString("guid", entry.Guid.ToString()); Writer.WriteAttributeString("dateDeleted", DateTime.UtcNow.ToLiftDateTimeFormat()); Writer.WriteEndElement(); } #region IDisposable Members #if DEBUG ~LiftWriter() { if (!_disposed) { throw new ApplicationException("Disposed not explicitly called on LiftWriter." + "\n" + _constructionStack); } } #endif [CLSCompliant(false)] protected bool _disposed; public virtual void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // dispose-only, i.e. non-finalizable logic if(_writer !=null) _writer.Close(); } // shared (dispose and finalizable) cleanup logic _disposed = true; } } protected void VerifyNotDisposed() { if (!_disposed) { throw new ObjectDisposedException("WeSayLiftWriter"); } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Net; using System.Net.Sockets; using System.Text; using log4net; using Gearman.Packets.Client; using Gearman.Packets.Worker; namespace Gearman { /// <summary> /// This class represents a client connecting to the Gearman network. The client can connect to one or more /// manager daemons, and submit jobs to the network. The jobs are sent as <see cref="System.byte[]"/> arrays /// containing the data to work on, a string to identify the type of work to be done, a unique job id, and an /// an optional priority (for background jobs) /// </summary> public class Client { // A list of managers to cycle through private List<Connection> managers; // Which connection private int connectionIndex; // log4net log instance private static readonly ILog Log = LogManager.GetLogger(typeof(Client)); /// <summary> /// Public enum describing the priority of the job /// </summary> public enum JobPriority { HIGH = 1, NORMAL, LOW }; /// <summary> /// Constructor (default), initializes an empty list of managers /// </summary> private Client() { managers = new List<Connection>(); } /// <summary> /// Constructor connecting to a specific host / port combination. Adds the connection to the managers list /// </summary> /// <param name="host"> /// A <see cref="System.String"/> /// </param> /// <param name="port"> /// A <see cref="System.Int32"/> /// </param> public Client (string host, int port) : this() { Connection c = new Connection(host, port); managers.Add(c); } /// <summary> /// Constructor connecting to a specific host, on the default port TCP 4730 /// </summary> /// <param name="host"> /// A <see cref="System.String"/> representing the host to connect to. /// </param> public Client (string host) : this(host, 4730) { } /// <summary> /// Add a new host to the list of hosts to try connecting to, taking both a hostname and a port /// </summary> /// <param name="host"> /// A <see cref="System.String"/> representing the hostname /// </param> /// <param name="port"> /// A <see cref="System.Int32"/> representing the port to connect on /// </param> public void addHostToList(string host, int port) { managers.Add(new Connection(host, port)); } /// <summary> /// Add a new host to the list of hosts to try connecting to, taking only a hostname, using default port 4730 /// </summary> /// <param name="host"> /// A <see cref="System.String"/> /// </param> public void addHostToList(string host) { this.addHostToList(host, 4730); } /// <summary> /// Submit a job to a job server for processing. The callback string is used as the /// task for the manager to hand off the job to a worker. /// </summary> /// <param name="callback"> /// A string containing the name of the operation to ask the manager to find a worker for /// </param> /// <param name="data"> /// A byte array containing the data to be worked on. This data is passed to the worker who can /// work on a job of the requested type. /// </param> /// <returns> /// A byte array containing the response from the worker that completed the task /// </returns> /// <example> /// <code> /// Client c = new Client("localhost"); /// byte[] data = new ASCIIEncoding().GetBytes("foo\nbar\nquiddle\n"); /// byte[] result = c.submitJob("wc", data); /// </code> /// </example> public byte[] submitJob(string callback, byte[] data) { try { Packet result = null; bool submitted = false; Connection c = null; string jobid = System.Guid.NewGuid().ToString(); SubmitJob p = new SubmitJob(callback, jobid, data, false); while(!submitted) { // Simple round-robin submission for now c = managers[connectionIndex++ % managers.Count]; c.sendPacket(p); Log.DebugFormat("Sent job request to {0}...", c); // We need to get back a JOB_CREATED packet result = c.getNextPacket(); // If we get back a JOB_CREATED packet, we can continue // otherwise try the next job manager if (result.Type == PacketType.JOB_CREATED) { submitted = true; Log.DebugFormat("Created job {0}", ((JobCreated)result).jobhandle); } } // This method handles synchronous requests, so we wait // until we get a work complete packet while(true) { result = c.getNextPacket(); if(result.Type == PacketType.WORK_COMPLETE) { WorkComplete wc = (WorkComplete)result; Log.DebugFormat("Completed job {0}", wc.jobhandle); return wc.data; } } } catch (Exception e) { Log.DebugFormat("Error submitting job: {0}", e.ToString()); return null; } } /// <summary>Submit a job to the job server in the background, with a particular priority</summary> /// <example> /// <code> /// </code> /// </example> public string submitJobInBackground(string callback, byte[] data, JobPriority priority) { try { Connection c = null; string jobid = System.Guid.NewGuid().ToString(); SubmitJob p = new SubmitJob(callback, jobid, data, true, priority); Packet result; while(true) { // Simple round-robin submission for now c = managers[connectionIndex++ % managers.Count]; c.sendPacket(p); Log.DebugFormat("Sent background job request to {0}...", c); // We need to get back a JOB_CREATED packet result = c.getNextPacket(); // If we get back a JOB_CREATED packet, we can continue, // otherwise try the next job manager if (result.Type == PacketType.JOB_CREATED) { Log.DebugFormat("Created background job {0}, with priority {1}", ((JobCreated)result).jobhandle, priority.ToString()); return ((JobCreated)result).jobhandle; } } } catch (Exception e) { Log.DebugFormat("Error submitting job: {0}", e.ToString()); return null; } } // TODO: Implement a percentage done feedback in the future? /// <summary> /// Query the manager to determine if a job with the unique job handle provided is done or not. The server returns /// a "percentage" done, if that's 100%, then the job is complete. This is mainly used for background jobs, in case /// the progress needs to be reported. /// </summary> /// <param name="jobHandle"> /// A <see cref="System.String"/> containing the unique job ID to query /// </param> /// <returns> /// True if complete, False otherwise /// </returns> public bool checkIsDone(string jobHandle) { GetStatus statusPkt = new GetStatus(jobHandle); Packet result = null; foreach (Connection conn in managers) { Log.DebugFormat("Checking for status on {0} on {1}", jobHandle, conn); conn.sendPacket(statusPkt); result = conn.getNextPacket(); if(result.Type == PacketType.STATUS_RES) { StatusRes statusResult = (StatusRes)result; if(statusResult.jobhandle != jobHandle) { Log.DebugFormat("Wrong job!!"); } else { Log.DebugFormat("Hooray, this is my job!!"); float percentdone = 0; if(statusResult.pctCompleteDenominator != 0) { percentdone = statusResult.pctCompleteNumerator / statusResult.pctCompleteDenominator; } // Check to see if this response has a known status // and if it's running if(statusResult.knownstatus && statusResult.running) { Log.DebugFormat("{0}% done!", percentdone * 100); } else { if (!statusResult.knownstatus) Log.DebugFormat("Status of job not known!"); if (!statusResult.running) Log.DebugFormat("Job not running!"); } return (percentdone == 1); } } } return false; } public List<Connection> HostList { get { return this.managers; } set { } } } }
using System; using Microsoft.Office.Core; using Microsoft.Office.Interop.Excel; using Microsoft.Vbe.Interop; using Application = Microsoft.Office.Interop.Excel.Application; using Window = Microsoft.Office.Interop.Excel.Window; using Windows = Microsoft.Office.Interop.Excel.Windows; namespace Excel.TestDoubles { #pragma warning disable 0067 public class WorkbookTestDouble : Workbook { public WorkbookTestDouble(ApplicationTestDouble application, WindowTestDouble window) { Application = application; Windows = new WindowsTestDouble(application) { window }; } void _Workbook.Activate() { throw new NotImplementedException(); } public void ChangeFileAccess(XlFileAccess mode, object writePassword, object notify) { throw new NotImplementedException(); } public void ChangeLink(string name, string newName, XlLinkType type = XlLinkType.xlLinkTypeExcelLinks) { throw new NotImplementedException(); } public void Close(object saveChanges, object filename, object routeWorkbook) { var applicationTestDouble = ((ApplicationTestDouble)Application); ((WorkbooksTestDouble)applicationTestDouble.Workbooks).Remove(this); applicationTestDouble.RaiseWorkbookBeforeClose(this); applicationTestDouble.RaiseWorkbookDeactivate(this); } public void DeleteNumberFormat(string numberFormat) { throw new NotImplementedException(); } public bool ExclusiveAccess() { throw new NotImplementedException(); } public void ForwardMailer() { throw new NotImplementedException(); } public object LinkInfo(string name, XlLinkInfo linkInfo, object type, object editionRef) { throw new NotImplementedException(); } public object LinkSources(object type) { throw new NotImplementedException(); } public void MergeWorkbook(object filename) { throw new NotImplementedException(); } public Window NewWindow() { throw new NotImplementedException(); } public void OpenLinks(string name, object readOnly, object type) { throw new NotImplementedException(); } public PivotCaches PivotCaches() { throw new NotImplementedException(); } public void Post(object destName) { throw new NotImplementedException(); } public void _PrintOut(object @from, object to, object copies, object preview, object activePrinter, object printToFile, object collate) { throw new NotImplementedException(); } public void PrintPreview(object enableChanges) { throw new NotImplementedException(); } public void _Protect(object password, object structure, object windows) { throw new NotImplementedException(); } public void ProtectSharing(object filename, object password, object writeResPassword, object readOnlyRecommended, object createBackup, object sharingPassword) { throw new NotImplementedException(); } public void RefreshAll() { throw new NotImplementedException(); } public void Reply() { throw new NotImplementedException(); } public void ReplyAll() { throw new NotImplementedException(); } public void RemoveUser(int index) { throw new NotImplementedException(); } public void Route() { throw new NotImplementedException(); } public void RunAutoMacros(XlRunAutoMacro which) { throw new NotImplementedException(); } public void Save() { throw new NotImplementedException(); } public void _SaveAs(object filename, object fileFormat, object password, object writeResPassword, object readOnlyRecommended, object createBackup, XlSaveAsAccessMode accessMode, object conflictResolution, object addToMru, object textCodepage, object textVisualLayout) { throw new NotImplementedException(); } public void SaveCopyAs(object filename) { throw new NotImplementedException(); } public void SendMail(object recipients, object subject, object returnReceipt) { throw new NotImplementedException(); } public void SendMailer(object fileFormat, XlPriority priority = XlPriority.xlPriorityNormal) { throw new NotImplementedException(); } public void SetLinkOnData(string name, object procedure) { throw new NotImplementedException(); } public void Unprotect(object password) { throw new NotImplementedException(); } public void UnprotectSharing(object sharingPassword) { throw new NotImplementedException(); } public void UpdateFromFile() { throw new NotImplementedException(); } public void UpdateLink(object name, object type) { throw new NotImplementedException(); } public void HighlightChangesOptions(object when, object who, object where) { throw new NotImplementedException(); } public void PurgeChangeHistoryNow(int days, object sharingPassword) { throw new NotImplementedException(); } public void AcceptAllChanges(object when, object who, object where) { throw new NotImplementedException(); } public void RejectAllChanges(object when, object who, object where) { throw new NotImplementedException(); } public void PivotTableWizard(object sourceType, object sourceData, object tableDestination, object tableName, object rowGrand, object columnGrand, object saveData, object hasAutoFormat, object autoPage, object reserved, object backgroundQuery, object optimizeCache, object pageFieldOrder, object pageFieldWrapCount, object readData, object connection) { throw new NotImplementedException(); } public void ResetColors() { throw new NotImplementedException(); } public void FollowHyperlink(string address, object subAddress, object newWindow, object addHistory, object extraInfo, object method, object headerInfo) { throw new NotImplementedException(); } public void AddToFavorites() { throw new NotImplementedException(); } public void PrintOut(object @from, object to, object copies, object preview, object activePrinter, object printToFile, object collate, object prToFileName) { throw new NotImplementedException(); } public void WebPagePreview() { throw new NotImplementedException(); } public void ReloadAs(MsoEncoding encoding) { throw new NotImplementedException(); } public void Dummy17(int calcid) { throw new NotImplementedException(); } public void sblt(string s) { throw new NotImplementedException(); } public void BreakLink(string name, XlLinkType type) { throw new NotImplementedException(); } public void Dummy16() { throw new NotImplementedException(); } public void SaveAs(object filename, object fileFormat, object password, object writeResPassword, object readOnlyRecommended, object createBackup, XlSaveAsAccessMode accessMode, object conflictResolution, object addToMru, object textCodepage, object textVisualLayout, object local) { throw new NotImplementedException(); } public void CheckIn(object saveChanges, object comments, object makePublic) { throw new NotImplementedException(); } public bool CanCheckIn() { throw new NotImplementedException(); } public void SendForReview(object recipients, object subject, object showMessage, object includeAttachment) { throw new NotImplementedException(); } public void ReplyWithChanges(object showMessage) { throw new NotImplementedException(); } public void EndReview() { throw new NotImplementedException(); } public void SetPasswordEncryptionOptions(object passwordEncryptionProvider, object passwordEncryptionAlgorithm, object passwordEncryptionKeyLength, object passwordEncryptionFileProperties) { throw new NotImplementedException(); } public void Protect(object password, object structure, object windows) { throw new NotImplementedException(); } public void RecheckSmartTags() { throw new NotImplementedException(); } public void SendFaxOverInternet(object recipients, object subject, object showMessage) { throw new NotImplementedException(); } public XlXmlImportResult XmlImport(string url, out XmlMap importMap, object overwrite, object destination) { throw new NotImplementedException(); } public XlXmlImportResult XmlImportXml(string data, out XmlMap importMap, object overwrite, object destination) { throw new NotImplementedException(); } public void SaveAsXMLData(string filename, XmlMap map) { throw new NotImplementedException(); } public void ToggleFormsDesign() { throw new NotImplementedException(); } public void RemoveDocumentInformation(XlRemoveDocInfoType removeDocInfoType) { throw new NotImplementedException(); } public void CheckInWithVersion(object saveChanges, object comments, object makePublic, object versionType) { throw new NotImplementedException(); } public void LockServerFile() { throw new NotImplementedException(); } public WorkflowTasks GetWorkflowTasks() { throw new NotImplementedException(); } public WorkflowTemplates GetWorkflowTemplates() { throw new NotImplementedException(); } public void PrintOutEx(object @from, object to, object copies, object preview, object activePrinter, object printToFile, object collate, object prToFileName, object ignorePrintAreas) { throw new NotImplementedException(); } public void ApplyTheme(string filename) { throw new NotImplementedException(); } public void EnableConnections() { throw new NotImplementedException(); } public void ExportAsFixedFormat(XlFixedFormatType type, object filename, object quality, object includeDocProperties, object ignorePrintAreas, object from, object to, object openAfterPublish, object fixedFormatExtClassPtr) { throw new NotImplementedException(); } public void ProtectSharingEx(object filename, object password, object writeResPassword, object readOnlyRecommended, object createBackup, object sharingPassword, object fileFormat) { throw new NotImplementedException(); } public void Dummy26() { throw new NotImplementedException(); } public void Dummy27() { throw new NotImplementedException(); } public Application Application { get; private set; } public XlCreator Creator { get; private set; } public object Parent { get; private set; } public bool AcceptLabelsInFormulas { get; set; } public Chart ActiveChart { get; private set; } public object ActiveSheet { get; private set; } public string Author { get; set; } public int AutoUpdateFrequency { get; set; } public bool AutoUpdateSaveChanges { get; set; } public int ChangeHistoryDuration { get; set; } public object BuiltinDocumentProperties { get; private set; } public Sheets Charts { get; private set; } public string CodeName { get; private set; } public string _CodeName { get; set; } public object get_Colors(object index) { throw new NotImplementedException(); } public void set_Colors(object index, object rhs) { throw new NotImplementedException(); } public CommandBars CommandBars { get; private set; } public string Comments { get; set; } public XlSaveConflictResolution ConflictResolution { get; set; } public object Container { get; private set; } public bool CreateBackup { get; private set; } public object CustomDocumentProperties { get; private set; } public bool Date1904 { get; set; } public Sheets DialogSheets { get; private set; } public XlDisplayDrawingObjects DisplayDrawingObjects { get; set; } public XlFileFormat FileFormat { get; private set; } public string FullName { get; private set; } public bool HasMailer { get; set; } public bool HasPassword { get; private set; } public bool HasRoutingSlip { get; set; } public bool IsAddin { get; set; } public string Keywords { get; set; } public Mailer Mailer { get; private set; } public Sheets Modules { get; private set; } public bool MultiUserEditing { get; private set; } public string Name { get; private set; } public Names Names { get; private set; } public string OnSave { get; set; } public string OnSheetActivate { get; set; } public string OnSheetDeactivate { get; set; } public string Path { get; private set; } public bool PersonalViewListSettings { get; set; } public bool PersonalViewPrintSettings { get; set; } public bool PrecisionAsDisplayed { get; set; } public bool ProtectStructure { get; private set; } public bool ProtectWindows { get; private set; } public bool ReadOnly { get; private set; } public bool _ReadOnlyRecommended { get; private set; } public int RevisionNumber { get; private set; } public bool Routed { get; private set; } public RoutingSlip RoutingSlip { get; private set; } public bool Saved { get; set; } public bool SaveLinkValues { get; set; } public Sheets Sheets { get; private set; } public bool ShowConflictHistory { get; set; } public Styles Styles { get; private set; } public string Subject { get; set; } public string Title { get; set; } public bool UpdateRemoteReferences { get; set; } public bool UserControl { get; set; } public object UserStatus { get; private set; } public CustomViews CustomViews { get; private set; } public Windows Windows { get; private set; } public Sheets Worksheets { get; private set; } public bool WriteReserved { get; private set; } public string WriteReservedBy { get; private set; } public Sheets Excel4IntlMacroSheets { get; private set; } public Sheets Excel4MacroSheets { get; private set; } public bool TemplateRemoveExtData { get; set; } public bool HighlightChangesOnScreen { get; set; } public bool KeepChangeHistory { get; set; } public bool ListChangesOnNewSheet { get; set; } public VBProject VBProject { get; private set; } public bool IsInplace { get; private set; } public PublishObjects PublishObjects { get; private set; } public WebOptions WebOptions { get; private set; } public HTMLProject HTMLProject { get; private set; } public bool EnvelopeVisible { get; set; } public int CalculationVersion { get; private set; } public bool VBASigned { get; private set; } public bool ShowPivotTableFieldList { get; set; } public XlUpdateLinks UpdateLinks { get; set; } public bool EnableAutoRecover { get; set; } public bool RemovePersonalInformation { get; set; } public string FullNameURLEncoded { get; private set; } public string Password { get; set; } public string WritePassword { get; set; } public string PasswordEncryptionProvider { get; private set; } public string PasswordEncryptionAlgorithm { get; private set; } public int PasswordEncryptionKeyLength { get; private set; } public bool PasswordEncryptionFileProperties { get; private set; } public bool ReadOnlyRecommended { get; set; } public SmartTagOptions SmartTagOptions { get; private set; } public Permission Permission { get; private set; } public SharedWorkspace SharedWorkspace { get; private set; } Sync _Workbook.Sync { get { throw new NotImplementedException();} } public XmlNamespaces XmlNamespaces { get; private set; } public XmlMaps XmlMaps { get; private set; } public SmartDocument SmartDocument { get; private set; } public DocumentLibraryVersions DocumentLibraryVersions { get; private set; } public bool InactiveListBorderVisible { get; set; } public bool DisplayInkComments { get; set; } public MetaProperties ContentTypeProperties { get; private set; } public Connections Connections { get; private set; } public SignatureSet Signatures { get; private set; } public ServerPolicy ServerPolicy { get; private set; } public DocumentInspectors DocumentInspectors { get; private set; } public ServerViewableItems ServerViewableItems { get; private set; } public TableStyles TableStyles { get; private set; } public object DefaultTableStyle { get; set; } public object DefaultPivotTableStyle { get; set; } public bool CheckCompatibility { get; set; } public bool HasVBProject { get; private set; } public CustomXMLParts CustomXMLParts { get; private set; } public bool Final { get; set; } public Research Research { get; private set; } public OfficeTheme Theme { get; private set; } public bool Excel8CompatibilityMode { get; private set; } public bool ConnectionsDisabled { get; private set; } public bool ShowPivotChartActiveFields { get; set; } public IconSets IconSets { get; private set; } public string EncryptionProvider { get; set; } public bool DoNotPromptForConvert { get; set; } public bool ForceFullCalculation { get; set; } public SlicerCaches SlicerCaches { get; private set; } public Slicer ActiveSlicer { get; private set; } public object DefaultSlicerStyle { get; set; } public int AccuracyVersion { get; set; } public bool CaseSensitive { get; private set; } public bool UseWholeCellCriteria { get; private set; } public bool UseWildcards { get; private set; } public object PivotTables { get; private set; } public Model Model { get; private set; } public bool ChartDataPointTrack { get; set; } public object DefaultTimelineStyle { get; set; } public event WorkbookEvents_OpenEventHandler Open; public event WorkbookEvents_ActivateEventHandler Activate; public event WorkbookEvents_DeactivateEventHandler Deactivate; public event WorkbookEvents_BeforeCloseEventHandler BeforeClose; public event WorkbookEvents_BeforeSaveEventHandler BeforeSave; public event WorkbookEvents_BeforePrintEventHandler BeforePrint; public event WorkbookEvents_NewSheetEventHandler NewSheet; public event WorkbookEvents_AddinInstallEventHandler AddinInstall; public event WorkbookEvents_AddinUninstallEventHandler AddinUninstall; public event WorkbookEvents_WindowResizeEventHandler WindowResize; public event WorkbookEvents_WindowActivateEventHandler WindowActivate; public event WorkbookEvents_WindowDeactivateEventHandler WindowDeactivate; public event WorkbookEvents_SheetSelectionChangeEventHandler SheetSelectionChange; public event WorkbookEvents_SheetBeforeDoubleClickEventHandler SheetBeforeDoubleClick; public event WorkbookEvents_SheetBeforeRightClickEventHandler SheetBeforeRightClick; public event WorkbookEvents_SheetActivateEventHandler SheetActivate; public event WorkbookEvents_SheetDeactivateEventHandler SheetDeactivate; public event WorkbookEvents_SheetCalculateEventHandler SheetCalculate; public event WorkbookEvents_SheetChangeEventHandler SheetChange; public event WorkbookEvents_SheetFollowHyperlinkEventHandler SheetFollowHyperlink; public event WorkbookEvents_SheetPivotTableUpdateEventHandler SheetPivotTableUpdate; public event WorkbookEvents_PivotTableCloseConnectionEventHandler PivotTableCloseConnection; public event WorkbookEvents_PivotTableOpenConnectionEventHandler PivotTableOpenConnection; event WorkbookEvents_SyncEventHandler WorkbookEvents_Event.Sync { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } public event WorkbookEvents_BeforeXmlImportEventHandler BeforeXmlImport; public event WorkbookEvents_AfterXmlImportEventHandler AfterXmlImport; public event WorkbookEvents_BeforeXmlExportEventHandler BeforeXmlExport; public event WorkbookEvents_AfterXmlExportEventHandler AfterXmlExport; public event WorkbookEvents_RowsetCompleteEventHandler RowsetComplete; public event WorkbookEvents_SheetPivotTableAfterValueChangeEventHandler SheetPivotTableAfterValueChange; public event WorkbookEvents_SheetPivotTableBeforeAllocateChangesEventHandler SheetPivotTableBeforeAllocateChanges; public event WorkbookEvents_SheetPivotTableBeforeCommitChangesEventHandler SheetPivotTableBeforeCommitChanges; public event WorkbookEvents_SheetPivotTableBeforeDiscardChangesEventHandler SheetPivotTableBeforeDiscardChanges; public event WorkbookEvents_SheetPivotTableChangeSyncEventHandler SheetPivotTableChangeSync; public event WorkbookEvents_AfterSaveEventHandler AfterSave; public event WorkbookEvents_NewChartEventHandler NewChart; public event WorkbookEvents_SheetLensGalleryRenderCompleteEventHandler SheetLensGalleryRenderComplete; public event WorkbookEvents_SheetTableUpdateEventHandler SheetTableUpdate; public event WorkbookEvents_ModelChangeEventHandler ModelChange; public event WorkbookEvents_SheetBeforeDeleteEventHandler SheetBeforeDelete; } }
#region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Input; #endregion namespace Pinball { /// <summary> /// Base class for screens that contain a menu of options. The user can /// move up and down to select an entry, or cancel to back out of the screen. /// </summary> public abstract class MenuScreen : GameScreen { #region Fields // the number of pixels to pad above and below menu entries for touch input const int menuEntryPadding = 10; List<MenuEntry> menuEntries = new List<MenuEntry>(); int selectedEntry = 0; string menuTitle; #endregion #region Properties /// <summary> /// Gets the list of menu entries, so derived classes can add /// or change the menu contents. /// </summary> protected IList<MenuEntry> MenuEntries { get { return menuEntries; } } public string MenuTitle { get; set; } #endregion #region Initialization /// <summary> /// Constructor. /// </summary> public MenuScreen(string menuTitle) { // menus generally only need Tap for menu selection EnabledGestures = GestureType.Tap; this.menuTitle = menuTitle; TransitionOnTime = TimeSpan.FromSeconds(0.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); } #endregion #region Handle Input /// <summary> /// Allows the screen to create the hit bounds for a particular menu entry. /// </summary> protected virtual Rectangle GetMenuEntryHitBounds(MenuEntry entry) { // the hit bounds are the entire width of the screen, and the height of the entry // with some additional padding above and below. return new Rectangle( 0, (int)entry.Position.Y - menuEntryPadding, ScreenManager.GraphicsDevice.Viewport.Width, entry.GetHeight(this) + (menuEntryPadding * 2)); } /// <summary> /// Responds to user input, changing the selected entry and accepting /// or cancelling the menu. /// </summary> public override void HandleInput(InputState input) { // we cancel the current menu screen if the user presses the back button PlayerIndex player; if (input.IsNewButtonPress(Buttons.Back, ControllingPlayer, out player)) { OnCancel(player); } // look for any taps that occurred and select any entries that were tapped foreach (GestureSample gesture in input.Gestures) { if (gesture.GestureType == GestureType.Tap) { // convert the position to a Point that we can test against a Rectangle Point tapLocation = new Point((int)gesture.Position.X, (int)gesture.Position.Y); // iterate the entries to see if any were tapped for (int i = 0; i < menuEntries.Count; i++) { MenuEntry menuEntry = menuEntries[i]; if (GetMenuEntryHitBounds(menuEntry).Contains(tapLocation)) { // select the entry. since gestures are only available on Windows Phone, // we can safely pass PlayerIndex.One to all entries since there is only // one player on Windows Phone. OnSelectEntry(i, PlayerIndex.One); } } } } } /// <summary> /// Handler for when the user has chosen a menu entry. /// </summary> protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex) { menuEntries[entryIndex].OnSelectEntry(playerIndex); } /// <summary> /// Handler for when the user has cancelled the menu. /// </summary> protected virtual void OnCancel(PlayerIndex playerIndex) { ExitScreen(); } /// <summary> /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler. /// </summary> protected void OnCancel(object sender, PlayerIndexEventArgs e) { OnCancel(e.PlayerIndex); } #endregion #region Update and Draw /// <summary> /// Allows the screen the chance to position the menu entries. By default /// all menu entries are lined up in a vertical list, centered on the screen. /// </summary> protected virtual void UpdateMenuEntryLocations() { // Make the menu slide into place during transitions, using a // power curve to make things look more interesting (this makes // the movement slow down as it nears the end). float transitionOffset = (float)Math.Pow(TransitionPosition, 2); // start at Y = 175; each X value is generated per entry Vector2 position = new Vector2(0f, 175f); // update each menu entry's location in turn for (int i = 0; i < menuEntries.Count; i++) { MenuEntry menuEntry = menuEntries[i]; // each entry is to be centered horizontally position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2; if (ScreenState == ScreenState.TransitionOn) position.X -= transitionOffset * 256; else position.X += transitionOffset * 512; // set the entry's position menuEntry.Position = position; // move down for the next entry the size of this entry plus our padding position.Y += menuEntry.GetHeight(this) + (menuEntryPadding * 2); } } /// <summary> /// Updates the menu. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); // Update each nested MenuEntry object. for (int i = 0; i < menuEntries.Count; i++) { bool isSelected = IsActive && (i == selectedEntry); menuEntries[i].Update(this, isSelected, gameTime); } } /// <summary> /// Draws the menu. /// </summary> public override void Draw(GameTime gameTime) { // make sure our entries are in the right place before we draw them UpdateMenuEntryLocations(); GraphicsDevice graphics = ScreenManager.GraphicsDevice; SpriteBatch spriteBatch = ScreenManager.SpriteBatch; SpriteFont font = ScreenManager.Font; spriteBatch.Begin(); // Draw each menu entry in turn. for (int i = 0; i < menuEntries.Count; i++) { MenuEntry menuEntry = menuEntries[i]; bool isSelected = IsActive && (i == selectedEntry); menuEntry.Draw(this, isSelected, gameTime); } // Make the menu slide into place during transitions, using a // power curve to make things look more interesting (this makes // the movement slow down as it nears the end). float transitionOffset = (float)Math.Pow(TransitionPosition, 2); // Draw the menu title centered on the screen Vector2 titlePosition = new Vector2(graphics.Viewport.Width / 2, 80); Vector2 titleOrigin = font.MeasureString(menuTitle) / 2; Color titleColor = new Color(192, 192, 192) * TransitionAlpha; float titleScale = 1.25f; titlePosition.Y -= transitionOffset * 100; spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0, titleOrigin, titleScale, SpriteEffects.None, 0); spriteBatch.End(); } #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. // /* unboxing where a parameter is types as object and then is unboxed to its scalar type */ using System; using System.Reflection; using System.Runtime.CompilerServices; class X { public static int x_count = 1; public virtual void incCount() { x_count *= 2; } } class A : X { public static int a_count = 1; public override void incCount() { a_count *= 17; } } class B : X { public static int b_count = 1; public override void incCount() { b_count *= 19; } } class C : A { public static int c_count = 1; public override void incCount() { c_count *= 23; } } class D : B { public static int d_count = 1; public override void incCount() { d_count *= 31; } } sealed class CS : A { public static int cs_count = 1; public override void incCount() { cs_count *= 37; } } sealed class DS : B { public static int ds_count = 1; public override void incCount() { ds_count *= 41; } } class mainMethod { public static bool failed = false; public static void checkGetType(System.Object x) { if (x.GetType() == typeof(DS)) (new DS()).incCount(); if (x.GetType() == typeof(CS)) (new CS()).incCount(); if (x.GetType() == typeof(D)) (new D()).incCount(); if (x.GetType() == typeof(C)) (new C()).incCount(); if (x.GetType() == typeof(B)) (new B()).incCount(); if (x.GetType() == typeof(A)) (new A()).incCount(); if (x.GetType() == typeof(X)) (new X()).incCount(); if (x.GetType() == null) (new X()).incCount(); } public static void checkIs(System.Object x) { if (x is X) (new X()).incCount(); if (x is A) (new A()).incCount(); if (x is B) (new B()).incCount(); if (x is C) (new C()).incCount(); if (x is D) (new D()).incCount(); if (x is CS) (new CS()).incCount(); if (x is DS) (new DS()).incCount(); } public static void checkAs(System.Object x) { X x1 = x as X; if (x1 != null) (new X()).incCount(); A a = x as A; if (a != null) (new A()).incCount(); B b = x as B; if (b != null) (new B()).incCount(); C c = x as C; if (c != null) (new C()).incCount(); D d = x as D; if (d != null) (new D()).incCount(); CS cs = x as CS; if (cs != null) (new CS()).incCount(); DS ds = x as DS; if (ds != null) (new DS()).incCount(); } public static void checkGetTypeObjectCast(System.Object x) { if (x.GetType() == typeof(DS)) ((DS)x).incCount(); if (x.GetType() == typeof(CS)) ((CS)x).incCount(); if (x.GetType() == typeof(D)) ((D)x).incCount(); if (x.GetType() == typeof(C)) ((C)x).incCount(); if (x.GetType() == typeof(B)) ((B)x).incCount(); if (x.GetType() == typeof(A)) ((A)x).incCount(); if (x.GetType() == typeof(X)) ((X)x).incCount(); if (x.GetType() == null) ((X)x).incCount(); } public static void checkIsObjectCast(System.Object x) { if (x is X) ((X)x).incCount(); if (x is A) ((A)x).incCount(); if (x is B) ((B)x).incCount(); if (x is C) ((C)x).incCount(); if (x is D) ((D)x).incCount(); if (x is CS) ((CS)x).incCount(); if (x is DS) ((DS)x).incCount(); } public static void checkAsObjectCast(System.Object x) { X x2 = x as X; if (x2 != null) ((X)x).incCount(); A a = x as A; if (a != null) ((A)x).incCount(); B b = x as B; if (b != null) ((B)x).incCount(); C c = x as C; if (c != null) ((C)x).incCount(); D d = x as D; if (d != null) ((D)x).incCount(); CS cs = x as CS; if (cs != null) ((CS)x).incCount(); DS ds = x as DS; if (ds != null) ((DS)x).incCount(); } public static void checkCount(ref int actual, int expected, string message) { if (actual != expected) { Console.WriteLine("FAILED: {0}", message); failed = true; } actual = 1; } public static void checkAllCounts(ref int x_actual, int ds, int cs, int d, int c, int b, int a, int x, string dsm, string csm, string dm, string cm, string bm, string am, string xm) { /* printCount(ref DS.ds_count, ds, dsm); printCount(ref CS.cs_count, cs, csm); printCount(ref D.d_count, d, dm); printCount(ref C.c_count, c, cm); printCount(ref B.b_count, b, bm); printCount(ref A.a_count, a, am); printCount(ref x_actual, x, xm); */ checkCount(ref DS.ds_count, ds, dsm); checkCount(ref CS.cs_count, cs, csm); checkCount(ref D.d_count, d, dm); checkCount(ref C.c_count, c, cm); checkCount(ref B.b_count, b, bm); checkCount(ref A.a_count, a, am); checkCount(ref x_actual, x, xm); } public static void printCount(ref int actual, int expected, string message) { Console.Write("{0}, ", actual); actual = 1; } public static void callCheckGetType() { int i = 0; checkGetType(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 17, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 19, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 23, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new D()); checkAllCounts(ref X.x_count, 1, 1, 31, 1, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new CS()); checkAllCounts(ref X.x_count, 1, 37, 1, 1, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); checkGetType(new DS()); checkAllCounts(ref X.x_count, 41, 1, 1, 1, 1, 1, 1, "DS Count after GetType and typeof", "CS Count after GetType and typeof", "D Count after GetType and typeof", "C Count after GetType and typeof", "B Count after GetType and typeof", "A Count after GetType and typeof", "X Count after GetType and typeof"); Console.WriteLine("-----------{0}", i++); } public static void callCheckIs() { int i = 0; checkIs(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 17, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 19, 1, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 23, 1, 17, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new D()); checkAllCounts(ref X.x_count, 1, 1, 31, 1, 19, 1, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new CS()); checkAllCounts(ref X.x_count, 1, 37, 1, 1, 1, 17, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); checkIs(new DS()); checkAllCounts(ref X.x_count, 41, 1, 1, 1, 19, 1, 2, "DS Count after checking is", "CS Count after checking is", "D Count after checking is", "C Count after checking is", "B Count after checking is", "A Count after checking is", "X Count after checking is"); Console.WriteLine("-----------{0}", i++); } public static void callCheckAs() { int i = 0; checkAs(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 17, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 19, 1, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 23, 1, 17, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new D()); checkAllCounts(ref X.x_count, 1, 1, 31, 1, 19, 1, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new CS()); checkAllCounts(ref X.x_count, 1, 37, 1, 1, 1, 17, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); checkAs(new DS()); checkAllCounts(ref X.x_count, 41, 1, 1, 1, 19, 1, 2, "DS Count after checking as", "CS Count after checking as", "D Count after checking as", "C Count after checking as", "B Count after checking as", "A Count after checking as", "X Count after checking as"); Console.WriteLine("-----------{0}", i++); } public static void callCheckGetTypeObjectCast() { int i = 0; checkGetTypeObjectCast(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 17, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 19, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 23, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new D()); checkAllCounts(ref X.x_count, 1, 1, 31, 1, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new CS()); checkAllCounts(ref X.x_count, 1, 37, 1, 1, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); checkGetTypeObjectCast(new DS()); checkAllCounts(ref X.x_count, 41, 1, 1, 1, 1, 1, 1, "DS Count after GetType and typeof string cast", "CS Count after GetType and typeof string cast", "D Count after GetType and typeof string cast", "C Count after GetType and typeof string cast", "B Count after GetType and typeof string cast", "A Count after GetType and typeof string cast", "X Count after GetType and typeof string cast"); Console.WriteLine("-----------{0}", i++); } public static void callCheckIsObjectCast() { int i = 0; checkIsObjectCast(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 289, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 361, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 12167, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new D()); checkAllCounts(ref X.x_count, 1, 1, 29791, 1, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new CS()); checkAllCounts(ref X.x_count, 1, 50653, 1, 1, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); checkIsObjectCast(new DS()); checkAllCounts(ref X.x_count, 68921, 1, 1, 1, 1, 1, 1, "DS Count after check is string cast ", "CS Count after check is string cast ", "D Count after check is string cast ", "C Count after check is string cast ", "B Count after check is string cast ", "A Count after check is string cast ", "X Count after check is string cast "); Console.WriteLine("-----------{0}", i++); } public static void callCheckAsObjectCast() { int i = 0; checkAsObjectCast(new System.Object()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new X()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 1, 2, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new A()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 1, 289, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new B()); checkAllCounts(ref X.x_count, 1, 1, 1, 1, 361, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new C()); checkAllCounts(ref X.x_count, 1, 1, 1, 12167, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new D()); checkAllCounts(ref X.x_count, 1, 1, 29791, 1, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new CS()); checkAllCounts(ref X.x_count, 1, 50653, 1, 1, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); checkAsObjectCast(new DS()); checkAllCounts(ref X.x_count, 68921, 1, 1, 1, 1, 1, 1, "DS Count after check as string cast ", "CS Count after check as string cast ", "D Count after check as string cast ", "C Count after check as string cast ", "B Count after check as string cast ", "A Count after check as string cast ", "X Count after check as string cast "); Console.WriteLine("-----------{0}", i++); } public static int Main() { callCheckGetType(); callCheckIs(); callCheckAs(); callCheckGetTypeObjectCast(); callCheckIsObjectCast(); callCheckAsObjectCast(); if (failed) return 101; else return 100; } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the logs-2014-03-28.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.CloudWatchLogs.Model; namespace Amazon.CloudWatchLogs { /// <summary> /// Interface for accessing CloudWatchLogs /// /// Amazon CloudWatch Logs API Reference /// <para> /// This is the <i>Amazon CloudWatch Logs API Reference</i>. Amazon CloudWatch Logs enables /// you to monitor, store, and access your system, application, and custom log files. /// This guide provides detailed information about Amazon CloudWatch Logs actions, data /// types, parameters, and errors. For detailed information about Amazon CloudWatch Logs /// features and their associated API calls, go to the <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide">Amazon /// CloudWatch Developer Guide</a>. /// </para> /// /// <para> /// Use the following links to get started using the <i>Amazon CloudWatch Logs API Reference</i>: /// </para> /// <ul> <li> <a href="http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_Operations.html">Actions</a>: /// An alphabetical list of all Amazon CloudWatch Logs actions.</li> <li> <a href="http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_Types.html">Data /// Types</a>: An alphabetical list of all Amazon CloudWatch Logs data types.</li> <li> /// <a href="http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/CommonParameters.html">Common /// Parameters</a>: Parameters that all Query actions can use.</li> <li> <a href="http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/CommonErrors.html">Common /// Errors</a>: Client and server errors that all actions can return.</li> <li> <a href="http://docs.aws.amazon.com/general/latest/gr/index.html?rande.html">Regions /// and Endpoints</a>: Itemized regions and endpoints for all AWS products.</li> </ul> /// /// <para> /// In addition to using the Amazon CloudWatch Logs API, you can also use the following /// SDKs and third-party libraries to access Amazon CloudWatch Logs programmatically. /// </para> /// <ul> <li><a href="http://aws.amazon.com/documentation/sdkforjava/">AWS SDK for Java /// Documentation</a></li> <li><a href="http://aws.amazon.com/documentation/sdkfornet/">AWS /// SDK for .NET Documentation</a></li> <li><a href="http://aws.amazon.com/documentation/sdkforphp/">AWS /// SDK for PHP Documentation</a></li> <li><a href="http://aws.amazon.com/documentation/sdkforruby/">AWS /// SDK for Ruby Documentation</a></li> </ul> /// <para> /// Developers in the AWS developer community also provide their own libraries, which /// you can find at the following AWS developer centers: /// </para> /// <ul> <li><a href="http://aws.amazon.com/java/">AWS Java Developer Center</a></li> /// <li><a href="http://aws.amazon.com/php/">AWS PHP Developer Center</a></li> <li><a /// href="http://aws.amazon.com/python/">AWS Python Developer Center</a></li> <li><a href="http://aws.amazon.com/ruby/">AWS /// Ruby Developer Center</a></li> <li><a href="http://aws.amazon.com/net/">AWS Windows /// and .NET Developer Center</a></li> </ul> /// </summary> public partial interface IAmazonCloudWatchLogs : IDisposable { #region CancelExportTask /// <summary> /// Initiates the asynchronous execution of the CancelExportTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CancelExportTask operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CancelExportTaskResponse> CancelExportTaskAsync(CancelExportTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateExportTask /// <summary> /// Initiates the asynchronous execution of the CreateExportTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateExportTask operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateExportTaskResponse> CreateExportTaskAsync(CreateExportTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateLogGroup /// <summary> /// Initiates the asynchronous execution of the CreateLogGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateLogGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateLogGroupResponse> CreateLogGroupAsync(CreateLogGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateLogStream /// <summary> /// Initiates the asynchronous execution of the CreateLogStream operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateLogStream operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateLogStreamResponse> CreateLogStreamAsync(CreateLogStreamRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteDestination /// <summary> /// Initiates the asynchronous execution of the DeleteDestination operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDestination operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteDestinationResponse> DeleteDestinationAsync(DeleteDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteLogGroup /// <summary> /// Initiates the asynchronous execution of the DeleteLogGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteLogGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteLogGroupResponse> DeleteLogGroupAsync(DeleteLogGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteLogStream /// <summary> /// Initiates the asynchronous execution of the DeleteLogStream operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteLogStream operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteLogStreamResponse> DeleteLogStreamAsync(DeleteLogStreamRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteMetricFilter /// <summary> /// Initiates the asynchronous execution of the DeleteMetricFilter operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteMetricFilter operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteMetricFilterResponse> DeleteMetricFilterAsync(DeleteMetricFilterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteRetentionPolicy /// <summary> /// Initiates the asynchronous execution of the DeleteRetentionPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteRetentionPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteRetentionPolicyResponse> DeleteRetentionPolicyAsync(DeleteRetentionPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteSubscriptionFilter /// <summary> /// Initiates the asynchronous execution of the DeleteSubscriptionFilter operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteSubscriptionFilter operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteSubscriptionFilterResponse> DeleteSubscriptionFilterAsync(DeleteSubscriptionFilterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeDestinations /// <summary> /// Initiates the asynchronous execution of the DescribeDestinations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDestinations operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeDestinationsResponse> DescribeDestinationsAsync(DescribeDestinationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeExportTasks /// <summary> /// Initiates the asynchronous execution of the DescribeExportTasks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeExportTasks operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeExportTasksResponse> DescribeExportTasksAsync(DescribeExportTasksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeLogGroups /// <summary> /// Returns all the log groups that are associated with the AWS account making the request. /// The list returned in the response is ASCII-sorted by log group name. /// /// /// <para> /// By default, this operation returns up to 50 log groups. If there are more log groups /// to list, the response would contain a <code class="code">nextToken</code> value in /// the response body. You can also limit the number of log groups returned in the response /// by specifying the <code class="code">limit</code> parameter in the request. /// </para> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeLogGroups service method, as returned by CloudWatchLogs.</returns> /// <exception cref="Amazon.CloudWatchLogs.Model.InvalidParameterException"> /// Returned if a parameter of the request is incorrectly specified. /// </exception> /// <exception cref="Amazon.CloudWatchLogs.Model.ServiceUnavailableException"> /// Returned if the service cannot complete the request. /// </exception> Task<DescribeLogGroupsResponse> DescribeLogGroupsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeLogGroups operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeLogGroups operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeLogGroupsResponse> DescribeLogGroupsAsync(DescribeLogGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeLogStreams /// <summary> /// Initiates the asynchronous execution of the DescribeLogStreams operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeLogStreams operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeLogStreamsResponse> DescribeLogStreamsAsync(DescribeLogStreamsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeMetricFilters /// <summary> /// Initiates the asynchronous execution of the DescribeMetricFilters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeMetricFilters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeMetricFiltersResponse> DescribeMetricFiltersAsync(DescribeMetricFiltersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeSubscriptionFilters /// <summary> /// Initiates the asynchronous execution of the DescribeSubscriptionFilters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSubscriptionFilters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeSubscriptionFiltersResponse> DescribeSubscriptionFiltersAsync(DescribeSubscriptionFiltersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region FilterLogEvents /// <summary> /// Initiates the asynchronous execution of the FilterLogEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the FilterLogEvents operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<FilterLogEventsResponse> FilterLogEventsAsync(FilterLogEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetLogEvents /// <summary> /// Initiates the asynchronous execution of the GetLogEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetLogEvents operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetLogEventsResponse> GetLogEventsAsync(GetLogEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutDestination /// <summary> /// Initiates the asynchronous execution of the PutDestination operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutDestination operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutDestinationResponse> PutDestinationAsync(PutDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutDestinationPolicy /// <summary> /// Initiates the asynchronous execution of the PutDestinationPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutDestinationPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutDestinationPolicyResponse> PutDestinationPolicyAsync(PutDestinationPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutLogEvents /// <summary> /// Initiates the asynchronous execution of the PutLogEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutLogEvents operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutLogEventsResponse> PutLogEventsAsync(PutLogEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutMetricFilter /// <summary> /// Initiates the asynchronous execution of the PutMetricFilter operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutMetricFilter operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutMetricFilterResponse> PutMetricFilterAsync(PutMetricFilterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutRetentionPolicy /// <summary> /// Initiates the asynchronous execution of the PutRetentionPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutRetentionPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutRetentionPolicyResponse> PutRetentionPolicyAsync(PutRetentionPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutSubscriptionFilter /// <summary> /// Initiates the asynchronous execution of the PutSubscriptionFilter operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutSubscriptionFilter operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutSubscriptionFilterResponse> PutSubscriptionFilterAsync(PutSubscriptionFilterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region TestMetricFilter /// <summary> /// Initiates the asynchronous execution of the TestMetricFilter operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TestMetricFilter operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<TestMetricFilterResponse> TestMetricFilterAsync(TestMetricFilterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Diagnostics; using System.Runtime; using System.Security.Principal; using System.ServiceModel; using System.ServiceModel.Diagnostics; abstract class NamedPipeChannelListener<TChannel, TChannelAcceptor> : NamedPipeChannelListener, IChannelListener<TChannel> where TChannel : class, IChannel where TChannelAcceptor : ChannelAcceptor<TChannel> { protected NamedPipeChannelListener(NamedPipeTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context) { } protected abstract TChannelAcceptor ChannelAcceptor { get; } protected override void OnOpen(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnOpen(timeoutHelper.RemainingTime()); ChannelAcceptor.Open(timeoutHelper.RemainingTime()); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedOpenAsyncResult(timeout, callback, state, base.OnBeginOpen, base.OnEndOpen, ChannelAcceptor); } protected override void OnEndOpen(IAsyncResult result) { ChainedOpenAsyncResult.End(result); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); ChannelAcceptor.Close(timeoutHelper.RemainingTime()); base.OnClose(timeoutHelper.RemainingTime()); } protected override void OnAbort() { this.ChannelAcceptor.Abort(); base.OnAbort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedCloseAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, ChannelAcceptor); } protected override void OnEndClose(IAsyncResult result) { ChainedCloseAsyncResult.End(result); } public TChannel AcceptChannel() { return this.AcceptChannel(this.DefaultReceiveTimeout); } public IAsyncResult BeginAcceptChannel(AsyncCallback callback, object state) { return this.BeginAcceptChannel(this.DefaultReceiveTimeout, callback, state); } public TChannel AcceptChannel(TimeSpan timeout) { base.ThrowIfNotOpened(); return ChannelAcceptor.AcceptChannel(timeout); } public IAsyncResult BeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state) { base.ThrowIfNotOpened(); return ChannelAcceptor.BeginAcceptChannel(timeout, callback, state); } public TChannel EndAcceptChannel(IAsyncResult result) { base.ThrowPending(); return ChannelAcceptor.EndAcceptChannel(result); } protected override bool OnWaitForChannel(TimeSpan timeout) { return ChannelAcceptor.WaitForChannel(timeout); } protected override IAsyncResult OnBeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state) { return ChannelAcceptor.BeginWaitForChannel(timeout, callback, state); } protected override bool OnEndWaitForChannel(IAsyncResult result) { return ChannelAcceptor.EndWaitForChannel(result); } } class NamedPipeReplyChannelListener : NamedPipeChannelListener<IReplyChannel, ReplyChannelAcceptor>, ISingletonChannelListener { ReplyChannelAcceptor replyAcceptor; public NamedPipeReplyChannelListener(NamedPipeTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context) { this.replyAcceptor = new ConnectionOrientedTransportReplyChannelAcceptor(this); } protected override ReplyChannelAcceptor ChannelAcceptor { get { return this.replyAcceptor; } } TimeSpan ISingletonChannelListener.ReceiveTimeout { get { return this.InternalReceiveTimeout; } } void ISingletonChannelListener.ReceiveRequest(RequestContext requestContext, Action callback, bool canDispatchOnThisThread) { if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.NamedPipeChannelMessageReceived, SR.GetString(SR.TraceCodeNamedPipeChannelMessageReceived), requestContext.RequestMessage); } replyAcceptor.Enqueue(requestContext, callback, canDispatchOnThisThread); } } class NamedPipeDuplexChannelListener : NamedPipeChannelListener<IDuplexSessionChannel, InputQueueChannelAcceptor<IDuplexSessionChannel>>, ISessionPreambleHandler { InputQueueChannelAcceptor<IDuplexSessionChannel> duplexAcceptor; public NamedPipeDuplexChannelListener(NamedPipeTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context) { this.duplexAcceptor = new InputQueueChannelAcceptor<IDuplexSessionChannel>(this); } protected override InputQueueChannelAcceptor<IDuplexSessionChannel> ChannelAcceptor { get { return this.duplexAcceptor; } } void ISessionPreambleHandler.HandleServerSessionPreamble(ServerSessionPreambleConnectionReader preambleReader, ConnectionDemuxer connectionDemuxer) { IDuplexSessionChannel channel = preambleReader.CreateDuplexSessionChannel( this, new EndpointAddress(this.Uri), ExposeConnectionProperty, connectionDemuxer); duplexAcceptor.EnqueueAndDispatch(channel, preambleReader.ConnectionDequeuedCallback); } } abstract class NamedPipeChannelListener : ConnectionOrientedTransportChannelListener { List<SecurityIdentifier> allowedUsers; protected NamedPipeChannelListener(NamedPipeTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context) { SetIdleTimeout(bindingElement.ConnectionPoolSettings.IdleTimeout); InitializeMaxPooledConnections(bindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint); } static UriPrefixTable<ITransportManagerRegistration> transportManagerTable = new UriPrefixTable<ITransportManagerRegistration>(); public override string Scheme { get { return Uri.UriSchemeNetPipe; } } internal List<SecurityIdentifier> AllowedUsers { get { return allowedUsers; } set { lock (ThisLock) { ThrowIfDisposedOrImmutable(); this.allowedUsers = value; } } } internal static UriPrefixTable<ITransportManagerRegistration> StaticTransportManagerTable { get { return transportManagerTable; } } internal override UriPrefixTable<ITransportManagerRegistration> TransportManagerTable { get { return transportManagerTable; } } internal override ITransportManagerRegistration CreateTransportManagerRegistration(Uri listenUri) { return new ExclusiveNamedPipeTransportManager(listenUri, this); } protected override bool SupportsUpgrade(StreamUpgradeBindingElement upgradeBindingElement) { return !(upgradeBindingElement is SslStreamSecurityBindingElement); } } }
using System; using System.Collections.Generic; using System.Linq; namespace NGraphics { public interface ICanvas { void SaveState (); void Transform (Transform transform); void RestoreState (); TextMetrics MeasureText (string text, Font font); void DrawText (string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, Brush brush = null); void DrawPath (IEnumerable<PathOp> ops, Pen pen = null, Brush brush = null); void DrawRectangle (Rect frame, Size corner, Pen pen = null, Brush brush = null); void DrawEllipse (Rect frame, Pen pen = null, Brush brush = null); void DrawImage (IImage image, Rect frame, double alpha = 1.0); } public static class CanvasEx { public static void Translate (this ICanvas canvas, double dx, double dy) { canvas.Transform (Transform.Translate (dx, dy)); } public static void Translate (this ICanvas canvas, Size translation) { canvas.Transform (Transform.Translate (translation)); } public static void Translate (this ICanvas canvas, Point translation) { canvas.Transform (Transform.Translate (translation)); } /// <summary> /// Rotate the specified canvas by the given angle (in degrees). /// </summary> /// <param name="canvas">The canvas to rotate.</param> /// <param name="angle">Angle in degrees.</param> public static void Rotate (this ICanvas canvas, double angle) { if (angle != 0) { canvas.Transform (Transform.Rotate (angle)); } } /// <param name="canvas">The canvas to rotate.</param> /// <param name="angle">Angle in degrees.</param> /// <param name="point">The translation point.</param> public static void Rotate (this ICanvas canvas, double angle, Point point) { if (angle != 0) { canvas.Translate (point); canvas.Rotate (angle); canvas.Translate (-point); } } /// <param name="canvas">The canvas to rotate.</param> /// <param name="angle">Angle in degrees.</param> /// <param name="x">The x coordinate of the translation point.</param> /// <param name="y">The y coordinate of the translation point.</param> public static void Rotate (this ICanvas canvas, double angle, double x, double y) { if (angle != 0) { canvas.Rotate (angle, new Point (x, y)); } } public static void Scale (this ICanvas canvas, double sx, double sy) { if (sx != 1 || sy != 1) { canvas.Transform (Transform.Scale (sx, sy)); } } public static void Scale (this ICanvas canvas, double scale) { if (scale != 1) { canvas.Transform (Transform.Scale (scale, scale)); } } public static void Scale (this ICanvas canvas, Size scale) { if (scale.Width != 1 || scale.Height != 1) { canvas.Transform (Transform.Scale (scale)); } } public static void Scale (this ICanvas canvas, Size scale, Point point) { if (scale.Width != 1 || scale.Height != 1) { canvas.Translate (point); canvas.Scale (scale); canvas.Translate (-point); } } public static void Scale (this ICanvas canvas, double scale, Point point) { if (scale != 1) { canvas.Scale (new Size (scale), point); } } public static void Scale (this ICanvas canvas, double sx, double sy, double x, double y) { if (sx != 1 || sy != 1) { canvas.Scale (new Size (sx, sy), new Point (x, y)); } } public static void Scale (this ICanvas canvas, double scale, double x, double y) { if (scale != 1) { canvas.Scale (new Size (scale), new Point (x, y)); } } public static void DrawRectangle (this ICanvas canvas, Rect frame, Color color, double width = 1) { canvas.DrawRectangle (frame, Size.Zero, new Pen (color, width), null); } public static void DrawRectangle (this ICanvas canvas, Rect frame, Size corner, Color color, double width = 1) { canvas.DrawRectangle (frame, corner, new Pen (color, width), null); } public static void DrawRectangle (this ICanvas canvas, Rect frame, Pen pen = null, Brush brush = null) { canvas.DrawRectangle (frame, Size.Zero, pen, brush); } public static void DrawRectangle (this ICanvas canvas, double x, double y, double width, double height, Pen pen = null, Brush brush = null) { canvas.DrawRectangle (new Rect (x, y, width, height), Size.Zero, pen, brush); } public static void DrawRectangle (this ICanvas canvas, double x, double y, double width, double height, double rx, double ry, Pen pen = null, Brush brush = null) { canvas.DrawRectangle (new Rect (x, y, width, height), new Size (rx, ry), pen, brush); } public static void DrawRectangle (this ICanvas canvas, double x, double y, double width, double height, double rx, double ry, Color color, double penWidth = 1) { canvas.DrawRectangle (new Rect (x, y, width, height), new Size (rx, ry), pen: new Pen (color, penWidth)); } public static void DrawRectangle (this ICanvas canvas, Point position, Size size, Pen pen = null, Brush brush = null) { canvas.DrawRectangle (new Rect (position, size), pen, brush); } public static void FillRectangle (this ICanvas canvas, Rect frame, Color color) { canvas.DrawRectangle (frame, brush: new SolidBrush (color)); } public static void FillRectangle (this ICanvas canvas, Rect frame, Size corner, Color color) { canvas.DrawRectangle (frame, corner, brush: new SolidBrush (color)); } public static void FillRectangle (this ICanvas canvas, double x, double y, double width, double height, Color color) { canvas.DrawRectangle (new Rect (x, y, width, height), brush: new SolidBrush (color)); } public static void FillRectangle (this ICanvas canvas, double x, double y, double width, double height, double rx, double ry, Color color) { canvas.DrawRectangle (new Rect (x, y, width, height), new Size (rx, ry), brush: new SolidBrush (color)); } public static void FillRectangle (this ICanvas canvas, double x, double y, double width, double height, Brush brush) { canvas.DrawRectangle (new Rect (x, y, width, height), brush: brush); } public static void FillRectangle (this ICanvas canvas, Rect frame, Brush brush) { canvas.DrawRectangle (frame, brush: brush); } public static void FillRectangle (this ICanvas canvas, Rect frame, Size corner, Brush brush) { canvas.DrawRectangle (frame, corner, brush: brush); } public static void DrawEllipse (this ICanvas canvas, Rect frame, Color color, double width = 1) { canvas.DrawEllipse (frame, new Pen (color, width), null); } public static void DrawEllipse (this ICanvas canvas, double x, double y, double width, double height, Pen pen = null, Brush brush = null) { canvas.DrawEllipse (new Rect (x, y, width, height), pen, brush); } public static void DrawEllipse (this ICanvas canvas, Point position, Size size, Pen pen = null, Brush brush = null) { canvas.DrawEllipse (new Rect (position, size), pen, brush); } public static void FillEllipse (this ICanvas canvas, Point position, Size size, Brush brush) { canvas.DrawEllipse (new Rect (position, size), null, brush); } public static void FillEllipse (this ICanvas canvas, Point position, Size size, Color color) { canvas.DrawEllipse (new Rect (position, size), null, new SolidBrush (color)); } public static void FillEllipse (this ICanvas canvas, double x, double y, double width, double height, Color color) { canvas.DrawEllipse (new Rect (x, y, width, height), brush: new SolidBrush (color)); } public static void FillEllipse (this ICanvas canvas, double x, double y, double width, double height, Brush brush) { canvas.DrawEllipse (new Rect (x, y, width, height), brush: brush); } public static void FillEllipse (this ICanvas canvas, Rect frame, Color color) { canvas.DrawEllipse (frame, brush: new SolidBrush (color)); } public static void FillEllipse (this ICanvas canvas, Rect frame, Brush brush) { canvas.DrawEllipse (frame, brush: brush); } public static void StrokeEllipse (this ICanvas canvas, Rect frame, Color color, double width = 1.0) { canvas.DrawEllipse (frame, pen: new Pen (color, width)); } public static void StrokeEllipse (this ICanvas canvas, Point position, Size size, Color color, double width = 1.0) { canvas.DrawEllipse (new Rect (position, size), new Pen (color, width), null); } public static void DrawPath (this ICanvas canvas, Action<Path> draw, Pen pen = null, Brush brush = null) { var p = new Path (pen, brush); draw (p); p.Draw (canvas); } public static void FillPath (this ICanvas canvas, IEnumerable<PathOp> ops, Brush brush) { canvas.DrawPath (ops, brush: brush); } public static void FillPath (this ICanvas canvas, IEnumerable<PathOp> ops, Color color) { canvas.DrawPath (ops, brush: new SolidBrush (color)); } public static void FillPath (this ICanvas canvas, Action<Path> draw, Brush brush) { var p = new Path (null, brush); draw (p); p.Draw (canvas); } public static void FillPath (this ICanvas canvas, Action<Path> draw, Color color) { FillPath (canvas, draw, new SolidBrush (color)); } public static void DrawLine (this ICanvas canvas, Point start, Point end, Pen pen) { var p = new Path { Pen = pen }; p.MoveTo (start); p.LineTo (end); p.Draw (canvas); } public static void DrawLine (this ICanvas canvas, Point start, Point end, Color color, double width = 1.0) { var p = new Path { Pen = new Pen (color, width) }; p.MoveTo (start); p.LineTo (end); p.Draw (canvas); } public static void DrawLine (this ICanvas canvas, double x1, double y1, double x2, double y2, Color color, double width = 1.0) { var p = new Path { Pen = new Pen (color, width) }; p.MoveTo (x1, y1); p.LineTo (x2, y2); p.Draw (canvas); } public static void DrawImage (this ICanvas canvas, IImage image) { canvas.DrawImage (image, new Rect (image.Size)); } public static void DrawImage (this ICanvas canvas, IImage image, double x, double y, double width, double height, double alpha = 1.0) { canvas.DrawImage (image, new Rect (x, y, width, height), alpha); } public static void DrawText (this ICanvas canvas, string text, Point point, Font font, Brush brush) { canvas.DrawText (text, new Rect (point, Size.MaxValue), font, brush: brush); } public static void DrawText (this ICanvas canvas, string text, Point point, Font font, Color color) { canvas.DrawText (text, new Rect (point, Size.MaxValue), font, brush: new SolidBrush (color)); } public static void DrawText (this ICanvas canvas, string text, Rect frame, Font font, TextAlignment alignment, Color color) { canvas.DrawText (text, frame, font, alignment, brush: new SolidBrush (color)); } } }
// // Image.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using Xwt.Backends; using System.Reflection; using System.IO; using System.Collections.Generic; namespace Xwt.Drawing { public class Image: XwtObject, IDisposable { internal Size requestedSize; internal NativeImageRef NativeRef; internal double requestedAlpha = 1; internal StyleSet styles; internal static int[] SupportedScales = { 2 }; internal Image () { } internal Image (object backend): base (backend) { Init (); } internal Image (object backend, Toolkit toolkit): base (backend, toolkit) { Init (); } /// <summary> /// Creates a new image that is a copy of another image /// </summary> /// <param name="image">Image.</param> public Image (Image image): base (image.Backend, image.ToolkitEngine) { NativeRef = image.NativeRef; requestedSize = image.requestedSize; requestedAlpha = image.requestedAlpha; styles = image.styles; Init (); } internal void Init () { if (NativeRef == null) { NativeRef = new NativeImageRef (Backend, ToolkitEngine); } else NativeRef.AddReference (); } ~Image () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (NativeRef != null) NativeRef.ReleaseReference (disposing); } internal ImageDescription GetImageDescription (Toolkit toolkit) { InitForToolkit (toolkit); return new ImageDescription () { Alpha = requestedAlpha, Size = Size, Backend = Backend, Styles = styles }; } internal void InitForToolkit (Toolkit t) { if (ToolkitEngine != t && NativeRef != null) { var nr = NativeRef.LoadForToolkit (t); ToolkitEngine = t; Backend = nr.Backend; } } /// <summary> /// Loads an image from a resource /// </summary> /// <returns>An image</returns> /// <param name="resource">Resource name</param> /// <remarks> /// This method will look for alternative versions of the image with different resolutions. /// For example, if a resource is named "foo.png", this method will load /// other resources with the name "foo@XXX.png", where XXX can be any arbitrary string. For example "foo@2x.png". /// Each of those resources will be considered different versions of the same image. /// </remarks> public static Image FromResource (string resource) { if (resource == null) throw new ArgumentNullException ("resource"); return FromResource (Assembly.GetCallingAssembly (), resource); } /// <summary> /// Loads an image from a resource /// </summary> /// <returns>An image</returns> /// <param name="type">Type which identifies the assembly from which to load the image</param> /// <param name="resource">Resource name</param> /// <remarks> /// This method will look for alternative versions of the image with different resolutions. /// For example, if a resource is named "foo.png", this method will load /// other resources with the name "foo@XXX.png", where XXX can be any arbitrary string. For example "foo@2x.png". /// Each of those resources will be considered different versions of the same image. /// </remarks> public static Image FromResource (Type type, string resource) { if (type == null) throw new ArgumentNullException ("type"); if (resource == null) throw new ArgumentNullException ("resource"); return FromResource (type.Assembly, resource); } /// <summary> /// Loads an image from a resource /// </summary> /// <returns>An image</returns> /// <param name="assembly">The assembly from which to load the image</param> /// <param name="resource">Resource name</param> /// <remarks> /// This method will look for alternative versions of the image with different resolutions. /// For example, if a resource is named "foo.png", this method will load /// other resources with the name "foo@XXX.png", where XXX can be any arbitrary string. For example "foo@2x.png". /// Each of those resources will be considered different versions of the same image. /// </remarks> public static Image FromResource (Assembly assembly, string resource) { if (assembly == null) throw new ArgumentNullException ("assembly"); if (resource == null) throw new ArgumentNullException ("resource"); var toolkit = Toolkit.CurrentEngine; if (toolkit == null) throw new ToolkitNotInitializedException (); var loader = new ResourceImageLoader (toolkit, assembly); return LoadImage (loader, resource, null); } static Image LoadImage (ImageLoader loader, string fileName, ImageTagSet tagFilter) { var toolkit = Toolkit.CurrentEngine; if (toolkit == null) throw new ToolkitNotInitializedException (); var img = loader.LoadImage (fileName); var reqSize = toolkit.ImageBackendHandler.GetSize (img); var ext = GetExtension (fileName); var name = fileName.Substring (0, fileName.Length - ext.Length); var altImages = new List<Tuple<string,ImageTagSet,bool,object>> (); var tags = Context.RegisteredStyles; foreach (var r in loader.GetAlternativeFiles (fileName, name, ext)) { int scale; ImageTagSet fileTags; if (ParseImageHints (name, r, ext, out scale, out fileTags) && (tagFilter == null || tagFilter.Equals (fileTags))) { var rim = loader.LoadImage (r); if (rim != null) altImages.Add (new Tuple<string, ImageTagSet, bool, object> (r, fileTags, scale > 1, rim)); } } if (altImages.Count > 0) { altImages.Insert (0, new Tuple<string, ImageTagSet, bool, object> (fileName, ImageTagSet.Empty, false, img)); var list = new List<Tuple<Image,string[]>> (); foreach (var imageGroup in altImages.GroupBy (t => t.Item2)) { Image altImg; if (ext == ".9.png") altImg = CreateComposedNinePatch (toolkit, imageGroup); else { var ib = toolkit.ImageBackendHandler.CreateMultiResolutionImage (imageGroup.Select (i => i.Item4)); altImg = loader.WrapImage (fileName, imageGroup.Key, ib, reqSize); } list.Add (new Tuple<Image,string[]> (altImg, imageGroup.Key.AsArray)); } if (list.Count == 1) return list [0].Item1; else { return new ThemedImage (list, reqSize); } } else { var res = loader.WrapImage (fileName, ImageTagSet.Empty, img, reqSize); if (ext == ".9.png") res = new NinePatchImage (res.ToBitmap ()); return res; } } static bool ParseImageHints (string baseName, string fileName, string ext, out int scale, out ImageTagSet tags) { scale = 1; tags = ImageTagSet.Empty; if (!fileName.StartsWith (baseName, StringComparison.Ordinal) || fileName.Length <= baseName.Length + 1 || (fileName [baseName.Length] != '@' && fileName [baseName.Length] != '~')) return false; fileName = fileName.Substring (0, fileName.Length - ext.Length); int i = baseName.Length; if (fileName [i] == '~') { // For example: foo~dark@2x i++; var i2 = fileName.IndexOf ('@', i); if (i2 != -1) { int i3 = fileName.IndexOf ('x', i2 + 2); if (i3 == -1 || !int.TryParse (fileName.Substring (i2 + 1, i3 - i2 - 1), out scale)) return false; } else i2 = fileName.Length; tags = new ImageTagSet (fileName.Substring (i, i2 - i)); return true; } else { // For example: foo@2x~dark i++; var i2 = fileName.IndexOf ('~', i + 1); if (i2 == -1) i2 = fileName.Length; i2--; if (i2 < 0 || fileName [i2] != 'x') return false; var s = fileName.Substring (i, i2 - i); if (!int.TryParse (s, out scale)) { tags = null; return false; } if (i2 + 2 < fileName.Length) tags = new ImageTagSet (fileName.Substring (i2 + 2)); return true; } } public static Image CreateMultiSizeIcon (IEnumerable<Image> images) { if (Toolkit.CurrentEngine == null) throw new ToolkitNotInitializedException (); var allImages = images.ToArray (); if (allImages.Length == 1) return allImages [0]; if (allImages.Any (i => i is ThemedImage)) { // If one of the images is themed, then the whole resulting image will be themed. // To create the new image, we group images with the same theme but different size, and we create a multi-size icon for those. // The resulting image is the combination of those multi-size icons. var allThemes = allImages.OfType<ThemedImage> ().SelectMany (i => i.Images).Select (i => new ImageTagSet (i.Item2)).Distinct ().ToArray (); List<Tuple<Image, string []>> newImages = new List<Tuple<Image, string []>> (); foreach (var ts in allThemes) { List<Image> multiSizeImages = new List<Image> (); foreach (var i in allImages) { if (i is ThemedImage) multiSizeImages.Add (((ThemedImage)i).GetImage (ts.AsArray)); else multiSizeImages.Add (i); } var img = CreateMultiSizeIcon (multiSizeImages); newImages.Add (new Tuple<Image, string []> (img, ts.AsArray)); } return new ThemedImage (newImages); } else { var img = new Image (Toolkit.CurrentEngine.ImageBackendHandler.CreateMultiSizeIcon (allImages.Select (ExtensionMethods.GetBackend))); if (allImages.All (i => i.NativeRef.HasNativeSource)) { var sources = allImages.Select (i => i.NativeRef.NativeSource).ToArray (); img.NativeRef.SetSources (sources); } return img; } } public static Image CreateMultiResolutionImage (IEnumerable<Image> images) { if (Toolkit.CurrentEngine == null) throw new ToolkitNotInitializedException (); return new Image (Toolkit.CurrentEngine.ImageBackendHandler.CreateMultiResolutionImage (images.Select (ExtensionMethods.GetBackend))); } public static Image FromFile (string file) { var toolkit = Toolkit.CurrentEngine; if (toolkit == null) throw new ToolkitNotInitializedException (); var loader = new FileImageLoader (toolkit); return LoadImage (loader, file, null); } static Image CreateComposedNinePatch (Toolkit toolkit, IEnumerable<Tuple<string,ImageTagSet,bool,object>> altImages) { var npImage = new NinePatchImage (); foreach (var fi in altImages) { int i = fi.Item1.LastIndexOf ('@'); double scaleFactor; if (i == -1) scaleFactor = 1; else { int j = fi.Item1.IndexOf ('x', ++i); if (!double.TryParse (fi.Item1.Substring (i, j - i), out scaleFactor)) { toolkit.ImageBackendHandler.Dispose (fi.Item4); continue; } } npImage.AddFrame (new Image (fi.Item4, toolkit).ToBitmap (), scaleFactor); } return npImage; } public static Image FromStream (Stream stream) { var toolkit = Toolkit.CurrentEngine; if (toolkit == null) throw new ToolkitNotInitializedException (); return new Image (toolkit.ImageBackendHandler.LoadFromStream (stream), toolkit); } public static Image FromCustomLoader (IImageLoader loader, string fileName) { return FromCustomLoader (loader, fileName, null); } internal static Image FromCustomLoader (IImageLoader loader, string fileName, ImageTagSet tags) { var toolkit = Toolkit.CurrentEngine; if (toolkit == null) throw new ToolkitNotInitializedException (); var ld = new StreamImageLoader (toolkit, loader); return LoadImage (ld, fileName, tags); } static string GetExtension (string fileName) { if (fileName.EndsWith (".9.png", StringComparison.Ordinal)) return ".9.png"; else return Path.GetExtension (fileName); } public void Save (string file, ImageFileType fileType) { using (var f = File.OpenWrite (file)) Save (f, fileType); } public void Save (Stream stream, ImageFileType fileType) { ToolkitEngine.ImageBackendHandler.SaveToStream (ToBitmap ().Backend, stream, fileType); } /// <summary> /// Gets a value indicating whether this image has fixed size. /// </summary> /// <value><c>true</c> if this image has fixed size; otherwise, <c>false</c>.</value> /// <remarks> /// Some kinds of images such as vector images or multiple-size icons don't have a fixed size, /// and a specific size has to be chosen before they can be used. A size can be chosen by using /// the WithSize method. /// </remarks> public bool HasFixedSize { get { return !Size.IsZero; } } /// <summary> /// Gets the size of the image /// </summary> /// <value>The size of the image, or Size.Zero if the image doesn't have an intrinsic size</value> public Size Size { get { return !requestedSize.IsZero ? requestedSize : GetDefaultSize (); } internal set { requestedSize = value; } } /// <summary> /// Gets the width of the image /// </summary> /// <value>The width.</value> public double Width { get { return Size.Width; } } /// <summary> /// Gets the height of the image /// </summary> /// <value>The height.</value> public double Height { get { return Size.Height; } } /// <summary> /// Applies an alpha filter to the image /// </summary> /// <returns>A new image with the alpha filter applied</returns> /// <param name="alpha">Alpha to apply</param> /// <remarks>This is a lightweight operation. The alpha filter is applied when the image is rendered. /// The method doesn't make a copy of the image data.</remarks> public Image WithAlpha (double alpha) { return new Image (this) { requestedSize = requestedSize, requestedAlpha = alpha }; } /// <summary> /// Retuns a copy of the image with a specific size /// </summary> /// <returns>A new image with the new size</returns> /// <param name="width">Width.</param> /// <param name="height">Height.</param> /// <remarks> /// This is a lightweight operation. The image is scaled when it is rendered. /// The method doesn't make a copy of the image data. /// </remarks> public Image WithSize (double width, double height) { return new Image (this) { requestedSize = new Size (width, height) }; } /// <summary> /// Retuns a copy of the image with a specific size /// </summary> /// <returns>A new image with the new size</returns> /// <param name="size">The size.</param> /// <remarks> /// This is a lightweight operation. The image is scaled when it is rendered. /// The method doesn't make a copy of the image data. /// </remarks> public Image WithSize (Size size) { return new Image (this) { requestedSize = size }; } /// <summary> /// Retuns a copy of the image with a specific size /// </summary> /// <returns>A new image with the new size</returns> /// <param name="squaredSize">Width and height of the image (the image is expected to be squared)</param> /// <remarks> /// This is a lightweight operation. The image is scaled when it is rendered. /// The method doesn't make a copy of the image data. /// </remarks> public Image WithSize (double squaredSize) { return new Image (this) { requestedSize = new Size (squaredSize, squaredSize) }; } /// <summary> /// Retuns a copy of the image with a specific size /// </summary> /// <returns>A new image with the new size</returns> /// <param name="size">New size</param> /// <remarks> /// This is a lightweight operation. The image is scaled when it is rendered. /// The method doesn't make a copy of the image data. /// </remarks> public Image WithSize (IconSize size) { Size s; switch (size) { case IconSize.Small: s = new Size (16, 16); break; case IconSize.Medium: s = new Size (24, 24); break; case IconSize.Large: s = new Size (32, 32); break; default: throw new ArgumentOutOfRangeException ("size"); } return new Image (this) { requestedSize = s }; } internal Size GetFixedSize () { var size = Size; if (size.IsZero) throw new InvalidOperationException ("Image size has not been set and the image doesn't have a default size"); return size; } /// <summary> /// Retuns a copy of the image with a set of specific styles /// </summary> /// <returns>A new image with the new styles</returns> /// <param name="styles">Styles to apply</param> /// <remarks> /// This is a lightweight operation. /// The method doesn't make a copy of the image data. /// </remarks> public Image WithStyles (params string[] styles) { return new Image (this) { styles = StyleSet.Empty.AddRange (styles) }; } /// <summary> /// Retuns a copy of the image with a size that fits the provided size limits /// </summary> /// <returns>The image</returns> /// <param name="maxWidth">Max width.</param> /// <param name="maxHeight">Max height.</param> /// <remarks> /// This is a lightweight operation. The image is scaled when it is rendered. /// The method doesn't make a copy of the image data. /// </remarks> public Image WithBoxSize (double maxWidth, double maxHeight) { var size = GetFixedSize (); var ratio = Math.Min (maxWidth / size.Width, maxHeight / size.Height); return new Image (this) { requestedSize = new Size (size.Width * ratio, size.Height * ratio) }; } /// <summary> /// Retuns a copy of the image with a size that fits the provided size limits /// </summary> /// <returns>The image</returns> /// <param name="maxSize">Max width and height (the image is expected to be squared)</param> /// <remarks> /// This is a lightweight operation. The image is scaled when it is rendered. /// The method doesn't make a copy of the image data. /// </remarks> public Image WithBoxSize (double maxSize) { return WithBoxSize (maxSize, maxSize); } /// <summary> /// Retuns a copy of the image with a size that fits the provided size limits /// </summary> /// <returns>The image</returns> /// <param name="size">Max width and height</param> /// <remarks> /// This is a lightweight operation. The image is scaled when it is rendered. /// The method doesn't make a copy of the image data. /// </remarks> public Image WithBoxSize (Size size) { return WithBoxSize (size.Width, size.Height); } /// <summary> /// Retuns a scaled copy of the image /// </summary> /// <returns>The image</returns> /// <param name="scale">Scale to apply to the image size</param> /// <remarks> /// This is a lightweight operation. The image is scaled when it is rendered. /// The method doesn't make a copy of the image data. /// </remarks> public Image Scale (double scale) { if (!HasFixedSize) throw new InvalidOperationException ("Image must have a size in order to be scaled"); double w = Size.Width * scale; double h = Size.Height * scale; return new Image (this) { requestedSize = new Size (w, h) }; } /// <summary> /// Retuns a scaled copy of the image /// </summary> /// <returns>The image</returns> /// <param name="scaleX">Scale to apply to the width of the image</param> /// <param name="scaleY">Scale to apply to the height of the image</param> /// <remarks> /// This is a lightweight operation. The image is scaled when it is rendered. /// The method doesn't make a copy of the image data. /// </remarks> public Image Scale (double scaleX, double scaleY) { if (!HasFixedSize) throw new InvalidOperationException ("Image must have a size in order to be scaled"); double w = Size.Width * scaleX; double h = Size.Height * scaleY; return new Image (this) { requestedSize = new Size (w, h) }; } /// <summary> /// Converts the image to a bitmap /// </summary> /// <returns>The bitmap.</returns> /// <param name="format">Bitmap format</param> public BitmapImage ToBitmap (ImageFormat format = ImageFormat.ARGB32) { return ToBitmap (1d); } /// <summary> /// Converts the image to a bitmap /// </summary> /// <returns>The bitmap.</returns> /// <param name="renderTarget">Widget to be used as reference for determining the resolution of the bitmap</param> /// <param name="format">Bitmap format</param> public BitmapImage ToBitmap (Widget renderTarget, ImageFormat format = ImageFormat.ARGB32) { if (renderTarget.ParentWindow == null) throw new InvalidOperationException ("renderTarget is not bound to a window"); return ToBitmap (renderTarget.ParentWindow.Screen.ScaleFactor, format); } /// <summary> /// Converts the image to a bitmap /// </summary> /// <returns>The bitmap.</returns> /// <param name="renderTarget">Window to be used as reference for determining the resolution of the bitmap</param> /// <param name="format">Bitmap format</param> public BitmapImage ToBitmap (WindowFrame renderTarget, ImageFormat format = ImageFormat.ARGB32) { return ToBitmap (renderTarget.Screen.ScaleFactor, format); } /// <summary> /// Converts the image to a bitmap /// </summary> /// <returns>The bitmap.</returns> /// <param name="renderTarget">Screen to be used as reference for determining the resolution of the bitmap</param> /// <param name="format">Bitmap format</param> public BitmapImage ToBitmap (Screen renderTarget, ImageFormat format = ImageFormat.ARGB32) { return ToBitmap (renderTarget.ScaleFactor, format); } /// <summary> /// Converts the image to a bitmap /// </summary> /// <returns>The bitmap.</returns> /// <param name="scaleFactor">Scale factor of the bitmap</param> /// <param name="format">Bitmap format</param> public BitmapImage ToBitmap (double scaleFactor, ImageFormat format = ImageFormat.ARGB32) { var s = GetFixedSize (); var idesc = new ImageDescription { Alpha = requestedAlpha, Size = s, Styles = styles, Backend = Backend }; var bmp = ToolkitEngine.ImageBackendHandler.ConvertToBitmap (idesc, scaleFactor, format); return new BitmapImage (bmp, s, ToolkitEngine); } protected virtual Size GetDefaultSize () { return ToolkitEngine.ImageBackendHandler.GetSize (Backend); } } class NativeImageRef { object backend; int referenceCount = 1; Toolkit toolkit; NativeImageSource[] sources; public struct NativeImageSource { // Source file or resource name public string Source; // Assembly that contains the resource public Assembly ResourceAssembly; public Func<Stream[]> ImageLoader; public IImageLoader CustomImageLoader; public ImageDrawCallback DrawCallback; public string StockId; public ImageTagSet Tags; } public object Backend { get { return backend; } } public Toolkit Toolkit { get { return toolkit; } } public NativeImageSource NativeSource { get { return sources[0]; } } public bool HasNativeSource { get { return sources != null; } } public void SetSources (NativeImageSource[] sources) { this.sources = sources; } public void SetFileSource (string file, ImageTagSet tags) { sources = new [] { new NativeImageSource { Source = file, Tags = tags } }; } public void SetResourceSource (Assembly asm, string name, ImageTagSet tags) { sources = new [] { new NativeImageSource { Source = name, ResourceAssembly = asm, Tags = tags } }; } public void SetStreamSource (Func<Stream[]> imageLoader) { sources = new [] { new NativeImageSource { ImageLoader = imageLoader } }; } public void SetCustomLoaderSource (IImageLoader imageLoader, string fileName, ImageTagSet tags) { sources = new [] { new NativeImageSource { CustomImageLoader = imageLoader, Source = fileName, Tags = tags } }; } public void SetCustomDrawSource (ImageDrawCallback drawCallback) { sources = new [] { new NativeImageSource { DrawCallback = drawCallback } }; } public void SetStockSource (string stockID) { sources = new [] { new NativeImageSource { StockId = stockID } }; } public int ReferenceCount { get { return referenceCount; } } public NativeImageRef (object backend, Toolkit toolkit) { this.backend = backend; this.toolkit = toolkit; NextRef = this; if (toolkit.ImageBackendHandler.DisposeHandleOnUiThread) ResourceManager.RegisterResource (backend, toolkit.ImageBackendHandler.Dispose); } public NativeImageRef LoadForToolkit (Toolkit targetToolkit) { if (Toolkit == targetToolkit) return this; NativeImageRef newRef = null; var r = NextRef; while (r != this) { if (r.toolkit == targetToolkit) { newRef = r; break; } r = r.NextRef; } if (newRef != null) return newRef; object newBackend = null; if (sources != null) { var frames = new List<object> (); foreach (var s in sources) { if (s.ImageLoader != null) { var streams = s.ImageLoader (); try { if (streams.Length == 1) { newBackend = targetToolkit.ImageBackendHandler.LoadFromStream (streams [0]); } else { var backends = new object [streams.Length]; for (int n = 0; n < backends.Length; n++) { backends [n] = targetToolkit.ImageBackendHandler.LoadFromStream (streams [n]); } newBackend = targetToolkit.ImageBackendHandler.CreateMultiResolutionImage (backends); } } finally { foreach (var st in streams) st.Dispose (); } } else if (s.CustomImageLoader != null) { targetToolkit.Invoke (() => newBackend = Image.FromCustomLoader (s.CustomImageLoader, s.Source, s.Tags).GetBackend()); } else if (s.ResourceAssembly != null) { targetToolkit.Invoke (() => newBackend = Image.FromResource (s.ResourceAssembly, s.Source).GetBackend()); } else if (s.Source != null) targetToolkit.Invoke (() => newBackend = Image.FromFile (s.Source).GetBackend()); else if (s.DrawCallback != null) newBackend = targetToolkit.ImageBackendHandler.CreateCustomDrawn (s.DrawCallback); else if (s.StockId != null) newBackend = targetToolkit.GetStockIcon (s.StockId).GetBackend (); else throw new NotSupportedException (); frames.Add (newBackend); } newBackend = targetToolkit.ImageBackendHandler.CreateMultiSizeIcon (frames); } else { using (var s = new MemoryStream ()) { toolkit.ImageBackendHandler.SaveToStream (backend, s, ImageFileType.Png); s.Position = 0; newBackend = targetToolkit.ImageBackendHandler.LoadFromStream (s); } } newRef = new NativeImageRef (newBackend, targetToolkit); newRef.NextRef = NextRef; NextRef = newRef; return newRef; } public void AddReference () { System.Threading.Interlocked.Increment (ref referenceCount); } public void ReleaseReference (bool disposing) { if (System.Threading.Interlocked.Decrement (ref referenceCount) == 0) { if (disposing) { if (toolkit.ImageBackendHandler.DisposeHandleOnUiThread) ResourceManager.FreeResource (backend); else toolkit.ImageBackendHandler.Dispose (backend); } else ResourceManager.FreeResource (backend); } } /// <summary> /// Reference to the next native image, for a different toolkit /// </summary> public NativeImageRef NextRef { get; set; } } class ImageTagSet { string tags; string[] tagsArray; public static readonly ImageTagSet Empty = new ImageTagSet (new string[0]); public ImageTagSet (string [] tagsArray) { this.tagsArray = tagsArray; Array.Sort (tagsArray); } public bool IsEmpty { get { return tagsArray.Length == 0; } } public ImageTagSet (string tags) { tagsArray = tags.Split (new [] { '~' }, StringSplitOptions.RemoveEmptyEntries); Array.Sort (AsArray); } public string AsString { get { if (tags == null) tags = string.Join ("~", tagsArray); return tags; } } public string [] AsArray { get { return tagsArray; } } public override bool Equals (object obj) { var other = obj as ImageTagSet; if (other == null || tagsArray.Length != other.tagsArray.Length) return false; for (int n = 0; n < tagsArray.Length; n++) if (tagsArray [n] != other.tagsArray [n]) return false; return true; } public override int GetHashCode () { unchecked { int c = 0; foreach (var s in tagsArray) c %= s.GetHashCode (); return c; } } } abstract class ImageLoader { public abstract object LoadImage (string fileName); public abstract IEnumerable<string> GetAlternativeFiles (string fileName, string baseName, string ext); public abstract Image WrapImage (string fileName, ImageTagSet tags, object img, Size reqSize); } class ResourceImageLoader : ImageLoader { Assembly assembly; Toolkit toolkit; public ResourceImageLoader (Toolkit toolkit, Assembly assembly) { this.assembly = assembly; this.toolkit = toolkit; } public override object LoadImage (string fileName) { var img = toolkit.ImageBackendHandler.LoadFromResource (assembly, fileName); if (img == null) throw new InvalidOperationException ("Resource not found: " + fileName); return img; } public override IEnumerable<string> GetAlternativeFiles (string fileName, string baseName, string ext) { return assembly.GetManifestResourceNames ().Where (f => f.StartsWith (baseName, StringComparison.Ordinal) && f.EndsWith (ext, StringComparison.Ordinal)); } public override Image WrapImage (string fileName, ImageTagSet tags, object img, Size reqSize) { var res = new Image (img, toolkit) { requestedSize = reqSize }; res.NativeRef.SetResourceSource (assembly, fileName, tags); return res; } } class FileImageLoader : ImageLoader { Toolkit toolkit; public FileImageLoader (Toolkit toolkit) { this.toolkit = toolkit; } public override object LoadImage (string fileName) { var img = toolkit.ImageBackendHandler.LoadFromFile (fileName); if (img == null) throw new InvalidOperationException ("File not found: " + fileName); return img; } public override IEnumerable<string> GetAlternativeFiles (string fileName, string baseName, string ext) { if (!Context.RegisteredStyles.Any ()) { foreach (var s in Image.SupportedScales) { var fn = baseName + "@" + s + "x" + ext; if (File.Exists (fn)) yield return fn; } } else { var files = Directory.GetFiles (Path.GetDirectoryName (fileName), Path.GetFileName (baseName) + "*" + ext); foreach (var f in files) yield return f; } } public override Image WrapImage (string fileName, ImageTagSet tags, object img, Size reqSize) { var res = new Image (img, toolkit) { requestedSize = reqSize }; res.NativeRef.SetFileSource (fileName, tags); return res; } } class StreamImageLoader : ImageLoader { IImageLoader loader; Toolkit toolkit; public StreamImageLoader (Toolkit toolkit, IImageLoader loader) { this.toolkit = toolkit; this.loader = loader; } public override IEnumerable<string> GetAlternativeFiles (string fileName, string baseName, string ext) { return loader.GetAlternativeFiles (fileName, baseName, ext); } public override object LoadImage (string fileName) { using (var s = loader.LoadImage (fileName)) return toolkit.ImageBackendHandler.LoadFromStream (s); } public override Image WrapImage (string fileName, ImageTagSet tags, object img, Size reqSize) { var res = new Image (img, toolkit) { requestedSize = reqSize }; var ld = loader; res.NativeRef.SetCustomLoaderSource (loader, fileName, tags); return res; } } }
namespace RecourceConverter { partial class frmResourceConverter { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.txtRowStart = new System.Windows.Forms.TextBox(); this.txtLabelType = new System.Windows.Forms.TextBox(); this.txtFilename = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtKeyIndex = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.txtValueIndex = new System.Windows.Forms.TextBox(); this.btnConvert = new System.Windows.Forms.Button(); this.btnBrown = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.txtSheetName = new System.Windows.Forms.TextBox(); this.btnBrownResourceFile = new System.Windows.Forms.Button(); this.label5 = new System.Windows.Forms.Label(); this.txtResoucrFile = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.cmbFileType = new System.Windows.Forms.ComboBox(); this.btnGen = new System.Windows.Forms.Button(); this.btnBrown2 = new System.Windows.Forms.Button(); this.label7 = new System.Windows.Forms.Label(); this.txtFieldFilePath = new System.Windows.Forms.TextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txtTotalColumns = new System.Windows.Forms.TextBox(); this.label14 = new System.Windows.Forms.Label(); this.lblLabelType = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.btnSave = new System.Windows.Forms.Button(); this.cmbLanguage = new System.Windows.Forms.ComboBox(); this.txtDeleted = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.txtTotalCoumnsForLen = new System.Windows.Forms.TextBox(); this.label15 = new System.Windows.Forms.Label(); this.txtAllowNonEng = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.txtFieldIdNo = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.txtLengthColumnNo = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.txtFieldSheetName = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.cmbApp = new System.Windows.Forms.ComboBox(); this.btnCheckLov = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // txtRowStart // this.txtRowStart.Location = new System.Drawing.Point(420, 132); this.txtRowStart.Name = "txtRowStart"; this.txtRowStart.Size = new System.Drawing.Size(118, 21); this.txtRowStart.TabIndex = 19; this.txtRowStart.Text = "5"; // // txtLabelType // this.txtLabelType.Location = new System.Drawing.Point(420, 158); this.txtLabelType.Name = "txtLabelType"; this.txtLabelType.Size = new System.Drawing.Size(118, 21); this.txtLabelType.TabIndex = 21; this.txtLabelType.Text = "M"; // // txtFilename // this.txtFilename.Location = new System.Drawing.Point(139, 58); this.txtFilename.Name = "txtFilename"; this.txtFilename.ReadOnly = true; this.txtFilename.Size = new System.Drawing.Size(379, 21); this.txtFilename.TabIndex = 0; this.txtFilename.Text = "\\\\10.100.1.124\\test\\20080428HKFS\\Field"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 61); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(107, 12); this.label1.TabIndex = 1; this.label1.Text = "Source Excel File"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 164); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(65, 12); this.label2.TabIndex = 3; this.label2.Text = "Key Column"; // // txtKeyIndex // this.txtKeyIndex.Location = new System.Drawing.Point(139, 161); this.txtKeyIndex.Name = "txtKeyIndex"; this.txtKeyIndex.Size = new System.Drawing.Size(118, 21); this.txtKeyIndex.TabIndex = 2; this.txtKeyIndex.Text = "P"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(309, 188); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(77, 12); this.label3.TabIndex = 5; this.label3.Text = "Value Column"; // // txtValueIndex // this.txtValueIndex.Location = new System.Drawing.Point(420, 185); this.txtValueIndex.Name = "txtValueIndex"; this.txtValueIndex.Size = new System.Drawing.Size(118, 21); this.txtValueIndex.TabIndex = 4; this.txtValueIndex.Text = "Q"; // // btnConvert // this.btnConvert.Location = new System.Drawing.Point(421, 213); this.btnConvert.Name = "btnConvert"; this.btnConvert.Size = new System.Drawing.Size(121, 23); this.btnConvert.TabIndex = 6; this.btnConvert.Text = "Convert"; this.btnConvert.UseVisualStyleBackColor = true; this.btnConvert.Click += new System.EventHandler(this.button1_Click); // // btnBrown // this.btnBrown.Location = new System.Drawing.Point(524, 58); this.btnBrown.Name = "btnBrown"; this.btnBrown.Size = new System.Drawing.Size(33, 23); this.btnBrown.TabIndex = 7; this.btnBrown.Text = "..."; this.btnBrown.UseVisualStyleBackColor = true; this.btnBrown.Click += new System.EventHandler(this.btnBrown_Click); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 132); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(65, 12); this.label4.TabIndex = 9; this.label4.Text = "Sheet Name"; // // txtSheetName // this.txtSheetName.Location = new System.Drawing.Point(139, 129); this.txtSheetName.Name = "txtSheetName"; this.txtSheetName.Size = new System.Drawing.Size(118, 21); this.txtSheetName.TabIndex = 8; this.txtSheetName.Text = "Field$"; // // btnBrownResourceFile // this.btnBrownResourceFile.Location = new System.Drawing.Point(524, 94); this.btnBrownResourceFile.Name = "btnBrownResourceFile"; this.btnBrownResourceFile.Size = new System.Drawing.Size(33, 23); this.btnBrownResourceFile.TabIndex = 12; this.btnBrownResourceFile.Text = "..."; this.btnBrownResourceFile.UseVisualStyleBackColor = true; this.btnBrownResourceFile.Click += new System.EventHandler(this.btnBrownResourceFile_Click); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(6, 97); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(83, 12); this.label5.TabIndex = 11; this.label5.Text = "Resource File"; // // txtResoucrFile // this.txtResoucrFile.Location = new System.Drawing.Point(139, 94); this.txtResoucrFile.Name = "txtResoucrFile"; this.txtResoucrFile.ReadOnly = true; this.txtResoucrFile.Size = new System.Drawing.Size(379, 21); this.txtResoucrFile.TabIndex = 10; this.txtResoucrFile.Text = "D:\\MyWorkspace\\MSS-D\\MSS-D Client\\Taifook.MSS.Resources\\Properties\\Resources.resx" + ""; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(6, 17); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(59, 12); this.label6.TabIndex = 13; this.label6.Text = "File Type"; // // cmbFileType // this.cmbFileType.FormattingEnabled = true; this.cmbFileType.Items.AddRange(new object[] { "Field", "Message"}); this.cmbFileType.Location = new System.Drawing.Point(139, 14); this.cmbFileType.Name = "cmbFileType"; this.cmbFileType.Size = new System.Drawing.Size(121, 20); this.cmbFileType.TabIndex = 14; this.cmbFileType.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // btnGen // this.btnGen.Location = new System.Drawing.Point(424, 120); this.btnGen.Name = "btnGen"; this.btnGen.Size = new System.Drawing.Size(121, 23); this.btnGen.TabIndex = 15; this.btnGen.Text = "Field Length Gen"; this.btnGen.UseVisualStyleBackColor = true; this.btnGen.Click += new System.EventHandler(this.btnGen_Click); // // btnBrown2 // this.btnBrown2.Location = new System.Drawing.Point(524, 14); this.btnBrown2.Name = "btnBrown2"; this.btnBrown2.Size = new System.Drawing.Size(33, 23); this.btnBrown2.TabIndex = 18; this.btnBrown2.Text = "..."; this.btnBrown2.UseVisualStyleBackColor = true; this.btnBrown2.Click += new System.EventHandler(this.btnBrown2_Click); // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(6, 17); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(107, 12); this.label7.TabIndex = 17; this.label7.Text = "Source Excel File"; // // txtFieldFilePath // this.txtFieldFilePath.Location = new System.Drawing.Point(139, 14); this.txtFieldFilePath.Name = "txtFieldFilePath"; this.txtFieldFilePath.Size = new System.Drawing.Size(379, 21); this.txtFieldFilePath.TabIndex = 16; this.txtFieldFilePath.Text = "\\\\10.100.1.124\\test\\20080428HKFS\\Field"; // // groupBox1 // this.groupBox1.Controls.Add(this.btnCheckLov); this.groupBox1.Controls.Add(this.txtTotalColumns); this.groupBox1.Controls.Add(this.label14); this.groupBox1.Controls.Add(this.txtLabelType); this.groupBox1.Controls.Add(this.lblLabelType); this.groupBox1.Controls.Add(this.txtRowStart); this.groupBox1.Controls.Add(this.label13); this.groupBox1.Controls.Add(this.btnSave); this.groupBox1.Controls.Add(this.cmbLanguage); this.groupBox1.Controls.Add(this.txtDeleted); this.groupBox1.Controls.Add(this.label12); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.txtFilename); this.groupBox1.Controls.Add(this.txtKeyIndex); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.txtValueIndex); this.groupBox1.Controls.Add(this.cmbFileType); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.btnConvert); this.groupBox1.Controls.Add(this.btnBrownResourceFile); this.groupBox1.Controls.Add(this.btnBrown); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.txtSheetName); this.groupBox1.Controls.Add(this.txtResoucrFile); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Location = new System.Drawing.Point(12, 39); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(563, 281); this.groupBox1.TabIndex = 19; this.groupBox1.TabStop = false; this.groupBox1.Text = "groupBox1"; // // txtTotalColumns // this.txtTotalColumns.Location = new System.Drawing.Point(139, 215); this.txtTotalColumns.Name = "txtTotalColumns"; this.txtTotalColumns.Size = new System.Drawing.Size(118, 21); this.txtTotalColumns.TabIndex = 23; this.txtTotalColumns.Text = "32"; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(6, 218); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(83, 12); this.label14.TabIndex = 24; this.label14.Text = "Total Columns"; // // lblLabelType // this.lblLabelType.AutoSize = true; this.lblLabelType.Location = new System.Drawing.Point(309, 161); this.lblLabelType.Name = "lblLabelType"; this.lblLabelType.Size = new System.Drawing.Size(65, 12); this.lblLabelType.TabIndex = 22; this.lblLabelType.Text = "Label Type"; // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(309, 135); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(59, 12); this.label13.TabIndex = 20; this.label13.Text = "Row Start"; // // btnSave // this.btnSave.Location = new System.Drawing.Point(294, 213); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(121, 23); this.btnSave.TabIndex = 18; this.btnSave.Text = "Save Configuration"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // cmbLanguage // this.cmbLanguage.FormattingEnabled = true; this.cmbLanguage.Items.AddRange(new object[] { "", "zh-cn", "zh-tw"}); this.cmbLanguage.Location = new System.Drawing.Point(279, 14); this.cmbLanguage.Name = "cmbLanguage"; this.cmbLanguage.Size = new System.Drawing.Size(121, 20); this.cmbLanguage.TabIndex = 17; this.cmbLanguage.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // txtDeleted // this.txtDeleted.Location = new System.Drawing.Point(139, 188); this.txtDeleted.Name = "txtDeleted"; this.txtDeleted.Size = new System.Drawing.Size(118, 21); this.txtDeleted.TabIndex = 15; this.txtDeleted.Text = "D"; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(6, 191); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(53, 12); this.label12.TabIndex = 16; this.label12.Text = "Deleted?"; // // groupBox2 // this.groupBox2.Controls.Add(this.txtTotalCoumnsForLen); this.groupBox2.Controls.Add(this.label15); this.groupBox2.Controls.Add(this.txtAllowNonEng); this.groupBox2.Controls.Add(this.label11); this.groupBox2.Controls.Add(this.txtFieldIdNo); this.groupBox2.Controls.Add(this.label8); this.groupBox2.Controls.Add(this.txtLengthColumnNo); this.groupBox2.Controls.Add(this.label9); this.groupBox2.Controls.Add(this.txtFieldSheetName); this.groupBox2.Controls.Add(this.label10); this.groupBox2.Controls.Add(this.label7); this.groupBox2.Controls.Add(this.btnGen); this.groupBox2.Controls.Add(this.btnBrown2); this.groupBox2.Controls.Add(this.txtFieldFilePath); this.groupBox2.Location = new System.Drawing.Point(6, 326); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(563, 161); this.groupBox2.TabIndex = 20; this.groupBox2.TabStop = false; this.groupBox2.Text = "groupBox2"; // // txtTotalCoumnsForLen // this.txtTotalCoumnsForLen.Location = new System.Drawing.Point(424, 41); this.txtTotalCoumnsForLen.Name = "txtTotalCoumnsForLen"; this.txtTotalCoumnsForLen.Size = new System.Drawing.Size(118, 21); this.txtTotalCoumnsForLen.TabIndex = 27; this.txtTotalCoumnsForLen.Text = "32"; // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(291, 44); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(83, 12); this.label15.TabIndex = 28; this.label15.Text = "Total Columns"; // // txtAllowNonEng // this.txtAllowNonEng.Location = new System.Drawing.Point(148, 128); this.txtAllowNonEng.Name = "txtAllowNonEng"; this.txtAllowNonEng.Size = new System.Drawing.Size(118, 21); this.txtAllowNonEng.TabIndex = 25; this.txtAllowNonEng.Text = "V"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(15, 131); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(125, 12); this.label11.TabIndex = 26; this.label11.Text = "Allow Non_Eng Column"; // // txtFieldIdNo // this.txtFieldIdNo.Location = new System.Drawing.Point(148, 73); this.txtFieldIdNo.Name = "txtFieldIdNo"; this.txtFieldIdNo.Size = new System.Drawing.Size(118, 21); this.txtFieldIdNo.TabIndex = 19; this.txtFieldIdNo.Text = "P"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(15, 76); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(95, 12); this.label8.TabIndex = 20; this.label8.Text = "Field Id Column"; // // txtLengthColumnNo // this.txtLengthColumnNo.Location = new System.Drawing.Point(148, 101); this.txtLengthColumnNo.Name = "txtLengthColumnNo"; this.txtLengthColumnNo.Size = new System.Drawing.Size(118, 21); this.txtLengthColumnNo.TabIndex = 21; this.txtLengthColumnNo.Text = "W"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(15, 104); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(83, 12); this.label9.TabIndex = 22; this.label9.Text = "Length Column"; // // txtFieldSheetName // this.txtFieldSheetName.Location = new System.Drawing.Point(148, 41); this.txtFieldSheetName.Name = "txtFieldSheetName"; this.txtFieldSheetName.Size = new System.Drawing.Size(118, 21); this.txtFieldSheetName.TabIndex = 23; this.txtFieldSheetName.Text = "Field$"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(15, 44); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(65, 12); this.label10.TabIndex = 24; this.label10.Text = "Sheet Name"; // // cmbApp // this.cmbApp.FormattingEnabled = true; this.cmbApp.Location = new System.Drawing.Point(12, 12); this.cmbApp.Name = "cmbApp"; this.cmbApp.Size = new System.Drawing.Size(221, 20); this.cmbApp.TabIndex = 21; this.cmbApp.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // btnCheckLov // this.btnCheckLov.Location = new System.Drawing.Point(294, 252); this.btnCheckLov.Name = "btnCheckLov"; this.btnCheckLov.Size = new System.Drawing.Size(92, 23); this.btnCheckLov.TabIndex = 25; this.btnCheckLov.Text = "Check LOV"; this.btnCheckLov.UseVisualStyleBackColor = true; this.btnCheckLov.Click += new System.EventHandler(this.btnCheckLov_Click); // // frmResourceConverter // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(679, 554); this.Controls.Add(this.cmbApp); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Name = "frmResourceConverter"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TextBox txtFilename; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtKeyIndex; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtValueIndex; private System.Windows.Forms.Button btnConvert; private System.Windows.Forms.Button btnBrown; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtSheetName; private System.Windows.Forms.Button btnBrownResourceFile; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox txtResoucrFile; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox cmbFileType; private System.Windows.Forms.Button btnGen; private System.Windows.Forms.Button btnBrown2; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtFieldFilePath; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox txtAllowNonEng; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox txtFieldIdNo; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox txtLengthColumnNo; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox txtFieldSheetName; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox txtDeleted; private System.Windows.Forms.Label label12; private System.Windows.Forms.ComboBox cmbLanguage; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.ComboBox cmbApp; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label lblLabelType; private System.Windows.Forms.TextBox txtRowStart; private System.Windows.Forms.TextBox txtLabelType; private System.Windows.Forms.TextBox txtTotalColumns; private System.Windows.Forms.Label label14; private System.Windows.Forms.TextBox txtTotalCoumnsForLen; private System.Windows.Forms.Label label15; private System.Windows.Forms.Button btnCheckLov; } }
/*============================================================ ** ** ** Purpose: ** Defines a session for Event Log operations. The session can ** be configured for a remote machine and can use specific ** user credentials. ============================================================*/ using System.Security; using System.Collections.Generic; using System.Globalization; namespace System.Diagnostics.Eventing.Reader { /// <summary> /// Session Login Type /// </summary> public enum SessionAuthentication { Default = 0, Negotiate = 1, Kerberos = 2, Ntlm = 3 } /// <summary> /// The type: log / external log file to query /// </summary> public enum PathType { LogName = 1, FilePath = 2 } public class EventLogSession : IDisposable { // //the two context handles for rendering (for EventLogRecord). //the system and user context handles. They are both common for all the event instances and can be created only once. //access to the data member references is safe, while //invoking methods on it is marked SecurityCritical as appropriate. // internal EventLogHandle renderContextHandleSystem = EventLogHandle.Zero; internal EventLogHandle renderContextHandleUser = EventLogHandle.Zero; //the dummy sync object for the two contexts. private object _syncObject = null; private string _server; private string _user; private string _domain; private SessionAuthentication _logOnType; //we do not maintain the password here. // //access to the data member references is safe, while //invoking methods on it is marked SecurityCritical as appropriate. // private EventLogHandle _handle = EventLogHandle.Zero; //setup the System Context, once for all the EventRecords. [System.Security.SecuritySafeCritical] internal void SetupSystemContext() { if (!this.renderContextHandleSystem.IsInvalid) return; lock (_syncObject) { if (this.renderContextHandleSystem.IsInvalid) { //create the SYSTEM render context //call the EvtCreateRenderContext to get the renderContextHandleSystem, so that we can get the system/values/user properties. this.renderContextHandleSystem = NativeWrapper.EvtCreateRenderContext(0, null, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextSystem); } } } [System.Security.SecuritySafeCritical] internal void SetupUserContext() { lock (_syncObject) { if (this.renderContextHandleUser.IsInvalid) { //create the USER render context this.renderContextHandleUser = NativeWrapper.EvtCreateRenderContext(0, null, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextUser); } } } // marked as SecurityCritical because allocates SafeHandle. // marked as TreatAsSafe because performs Demand(). [System.Security.SecurityCritical] public EventLogSession() { //handle = EventLogHandle.Zero; _syncObject = new object(); } public EventLogSession(string server) : this(server, null, null, (SecureString)null, SessionAuthentication.Default) { } // marked as TreatAsSafe because performs Demand(). [System.Security.SecurityCritical] public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType) { if (server == null) server = "localhost"; _syncObject = new object(); _server = server; _domain = domain; _user = user; _logOnType = logOnType; UnsafeNativeMethods.EvtRpcLogin erLogin = new UnsafeNativeMethods.EvtRpcLogin(); erLogin.Server = _server; erLogin.User = _user; erLogin.Domain = _domain; erLogin.Flags = (int)_logOnType; erLogin.Password = CoTaskMemUnicodeSafeHandle.Zero; try { if (password != null) erLogin.Password.SetMemory(SecureStringMarshal.SecureStringToCoTaskMemUnicode(password)); //open a session using the erLogin structure. _handle = NativeWrapper.EvtOpenSession(UnsafeNativeMethods.EvtLoginClass.EvtRpcLogin, ref erLogin, 0, 0); } finally { erLogin.Password.Dispose(); } } internal EventLogHandle Handle { get { return _handle; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { if (disposing) { if (this == s_globalSession) throw new InvalidOperationException(); } if (this.renderContextHandleSystem != null && !this.renderContextHandleSystem.IsInvalid) this.renderContextHandleSystem.Dispose(); if (this.renderContextHandleUser != null && !this.renderContextHandleUser.IsInvalid) this.renderContextHandleUser.Dispose(); if (_handle != null && !_handle.IsInvalid) _handle.Dispose(); } public void CancelCurrentOperations() { NativeWrapper.EvtCancel(_handle); } private static EventLogSession s_globalSession = new EventLogSession(); public static EventLogSession GlobalSession { get { return s_globalSession; } } [System.Security.SecurityCritical] public IEnumerable<string> GetProviderNames() { List<string> namesList = new List<string>(100); using (EventLogHandle ProviderEnum = NativeWrapper.EvtOpenProviderEnum(this.Handle, 0)) { bool finish = false; do { string s = NativeWrapper.EvtNextPublisherId(ProviderEnum, ref finish); if (finish == false) namesList.Add(s); } while (finish == false); return namesList; } } [System.Security.SecurityCritical] public IEnumerable<string> GetLogNames() { List<string> namesList = new List<string>(100); using (EventLogHandle channelEnum = NativeWrapper.EvtOpenChannelEnum(this.Handle, 0)) { bool finish = false; do { string s = NativeWrapper.EvtNextChannelPath(channelEnum, ref finish); if (finish == false) namesList.Add(s); } while (finish == false); return namesList; } } public EventLogInformation GetLogInformation(string logName, PathType pathType) { if (logName == null) throw new ArgumentNullException("logName"); return new EventLogInformation(this, logName, pathType); } public void ExportLog(string path, PathType pathType, string query, string targetFilePath) { this.ExportLog(path, pathType, query, targetFilePath, false); } public void ExportLog(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors) { if (path == null) throw new ArgumentNullException("path"); if (targetFilePath == null) throw new ArgumentNullException("targetFilePath"); UnsafeNativeMethods.EvtExportLogFlags flag; switch (pathType) { case PathType.LogName: flag = UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogChannelPath; break; case PathType.FilePath: flag = UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogFilePath; break; default: throw new ArgumentOutOfRangeException("pathType"); } if (tolerateQueryErrors == false) NativeWrapper.EvtExportLog(this.Handle, path, query, targetFilePath, (int)flag); else NativeWrapper.EvtExportLog(this.Handle, path, query, targetFilePath, (int)flag | (int)UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogTolerateQueryErrors); } public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath) { this.ExportLogAndMessages(path, pathType, query, targetFilePath, false, CultureInfo.CurrentCulture); } public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors, CultureInfo targetCultureInfo) { if (targetCultureInfo == null) targetCultureInfo = CultureInfo.CurrentCulture; ExportLog(path, pathType, query, targetFilePath, tolerateQueryErrors); // Ignore the CultureInfo, pass 0 to use the calling thread's locale NativeWrapper.EvtArchiveExportedLog(this.Handle, targetFilePath, 0, 0); } public void ClearLog(string logName) { this.ClearLog(logName, null); } public void ClearLog(string logName, string backupPath) { if (logName == null) throw new ArgumentNullException("logName"); NativeWrapper.EvtClearLog(this.Handle, logName, backupPath, 0); } } }
using System; using System.IO; using System.Text; using System.Xml; using Google.GData.GoogleBase; using Google.GData.Client; namespace Google.GData.GoogleBase.Examples { ////////////////////////////////////////////////////////////////////// /// <summary>Simple command interface</summary> ////////////////////////////////////////////////////////////////////// interface ICommand { ////////////////////////////////////////////////////////////////////// /// <summary>Executes the command.</summary> ////////////////////////////////////////////////////////////////////// void Execute(); } ////////////////////////////////////////////////////////////////////// /// <summary>Base class for all commands that contains /// fields and methods.</summary> ////////////////////////////////////////////////////////////////////// abstract class CommandBase { protected readonly GBaseService service; protected readonly GBaseUriFactory uriFactory; private static readonly Encoding StreamEncoding = new UTF8Encoding(); protected CommandBase(GBaseService service, GBaseUriFactory uriFactory) { this.service = service; this.uriFactory = uriFactory; } ////////////////////////////////////////////////////////////////////// /// <summary>Copies data from a stream (UTF-8) into a text writer /// (Usually stdout)</summary> ////////////////////////////////////////////////////////////////////// protected static void Copy(Stream input, TextWriter output) { StreamReader reader = new StreamReader(input, StreamEncoding); Copy(reader, output); } ////////////////////////////////////////////////////////////////////// /// <summary>Copies characters from a TextReader to a TextWriter. /// </summary> ////////////////////////////////////////////////////////////////////// protected static void Copy(TextReader input, TextWriter output) { char[] buffer = new char[1024]; int l; while ( (l = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, l); } } ////////////////////////////////////////////////////////////////////// /// <summary>Writes a feed or entry to stdout.</summary> ////////////////////////////////////////////////////////////////////// protected void WriteToStandardOutput(AtomBase atomBase) { XmlTextWriter xmlWriter = new XmlTextWriter(Console.Out); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 2; atomBase.SaveToXml(xmlWriter); xmlWriter.Flush(); } ////////////////////////////////////////////////////////////////////// /// <summary>Reads a feed or entry from stdin.</summary> ////////////////////////////////////////////////////////////////////// protected GBaseFeed ReadFromStandardInput() { GBaseFeed feed = new GBaseFeed(uriFactory.ItemsFeedUri, service); Stream stdin = Console.OpenStandardInput(); try { feed.Parse(stdin, AlternativeFormat.Atom); return feed; } finally { stdin.Close(); } } } ////////////////////////////////////////////////////////////////////// /// <summary>Executes a query on the items feed and writes the /// result to standard output.</summary> ////////////////////////////////////////////////////////////////////// class QueryCommand : CommandBase, ICommand { private readonly string queryString; public QueryCommand(GBaseService service, GBaseUriFactory uriFactory, string queryString) : base(service, uriFactory) { this.queryString = queryString; } public void Execute() { GBaseQuery query = new GBaseQuery(uriFactory.ItemsFeedUri); query.GoogleBaseQuery = queryString; WriteToStandardOutput(service.Query(query)); } } ////////////////////////////////////////////////////////////////////// /// <summary>Deletes an item given its id/url.</summary> ////////////////////////////////////////////////////////////////////// class DeleteCommand : CommandBase, ICommand { private readonly Uri uri; public DeleteCommand(GBaseService service, GBaseUriFactory uriFactory, string uri) : base(service, uriFactory) { this.uri = new Uri(uri); } public void Execute() { service.Delete(uri); Console.WriteLine("Deleted: " + uri); } } ////////////////////////////////////////////////////////////////////// /// <summary>Execute an insert (POST) command on the server, /// reading the item to insert from standard input.</summary> ////////////////////////////////////////////////////////////////////// class InsertCommand : CommandBase, ICommand { public InsertCommand(GBaseService service, GBaseUriFactory uriFactory) : base(service, uriFactory) { } public void Execute() { GBaseFeed feed = ReadFromStandardInput(); GBaseEntry result = service.Insert(uriFactory.ItemsFeedUri, feed.Entries[0] as GBaseEntry); WriteToStandardOutput(result); } } ////////////////////////////////////////////////////////////////////// /// <summary>Execute an update (PUT) command on the server, /// reading the item to update from standard input.</summary> ////////////////////////////////////////////////////////////////////// class UpdateCommand : CommandBase, ICommand { public UpdateCommand(GBaseService service, GBaseUriFactory uriFactory) : base(service, uriFactory) { } public void Execute() { GBaseFeed feed = ReadFromStandardInput(); GBaseEntry entry = feed.Entries[0] as GBaseEntry; entry.EditUri = entry.Id.Uri; service.Update(entry); Console.WriteLine("Item updated: " + entry.Id.Uri); } } ////////////////////////////////////////////////////////////////////// /// <summary>Do a GET on the given url and writes the /// result to standard output, as a feed or as an entry. /// /// The big difference between this command and simply typing /// the url into a browser is that this query will be /// authenticated. /// </summary> ////////////////////////////////////////////////////////////////////// class GetCommand : CommandBase, ICommand { private readonly string url; public GetCommand(GBaseService service, GBaseUriFactory uriFactory, string url) : base(service, uriFactory) { this.url = url; } public void Execute() { GBaseFeed feed = service.Query(new GBaseQuery(new Uri(url))); if (feed.Entries.Count == 1) { // It was most probably a single entry Uri WriteToStandardOutput(feed.Entries[0]); } else { WriteToStandardOutput(feed); } } } ////////////////////////////////////////////////////////////////////// /// <summary>Do a POST on the feed's batch URL and writes the /// result to standard output, as a feed.</summary> ////////////////////////////////////////////////////////////////////// class BatchCommand : CommandBase, ICommand { public BatchCommand(GBaseService service, GBaseUriFactory uriFactory) : base(service, uriFactory) { } public void Execute() { GBaseFeed feed = ReadFromStandardInput(); GBaseFeed result = service.Batch(feed, uriFactory.ItemsFeedBatchUri); WriteToStandardOutput(result); } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using System.Runtime.InteropServices; using SharpDX.Mathematics.Interop; namespace SharpDX.Direct3D9 { public partial class VolumeTexture { /// <summary> /// Initializes a new instance of the <see cref="VolumeTexture"/> class. /// </summary> /// <param name="device">The device.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <unmanaged>HRESULT IDirect3DDevice9::CreateVolumeTexture([In] unsigned int Width,[In] unsigned int Height,[In] unsigned int Levels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[Out, Fast] IDirect3DVolumeTexture9** ppVolumeTexture,[In] void** pSharedHandle)</unmanaged> public VolumeTexture(Device device, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool) : base(IntPtr.Zero) { device.CreateVolumeTexture(width, height, depth, levelCount, (int)usage, format, pool, this, IntPtr.Zero); } /// <summary> /// Initializes a new instance of the <see cref="VolumeTexture"/> class. /// </summary> /// <param name="device">The device.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="sharedHandle">The shared handle.</param> /// <unmanaged>HRESULT IDirect3DDevice9::CreateVolumeTexture([In] unsigned int Width,[In] unsigned int Height,[In] unsigned int Levels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[Out, Fast] IDirect3DVolumeTexture9** ppVolumeTexture,[In] void** pSharedHandle)</unmanaged> public VolumeTexture(Device device, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, ref IntPtr sharedHandle) : base(IntPtr.Zero) { unsafe { fixed (void* pSharedHandle = &sharedHandle) device.CreateVolumeTexture(width, height, depth, levelCount, (int)usage, format, pool, this, new IntPtr(pSharedHandle)); } } /// <summary> /// Checks texture-creation parameters. /// </summary> /// <param name="device">Device associated with the texture.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="mipLevelCount">Requested number of mipmap levels for the texture.</param> /// <param name="usage">The requested usage for the texture.</param> /// <param name="format">Requested format for the texture.</param> /// <param name="pool">Memory class where the resource will be placed.</param> /// <returns> /// A value type containing the proposed values to pass to the texture creation functions. /// </returns> /// <unmanaged>HRESULT D3DXCheckVolumeTextureRequirements([In] IDirect3DDevice9* pDevice,[InOut] unsigned int* pWidth,[InOut] unsigned int* pHeight,[InOut] unsigned int* pDepth,[InOut] unsigned int* pNumMipLevels,[In] unsigned int Usage,[InOut] D3DFORMAT* pFormat,[In] D3DPOOL Pool)</unmanaged> public static VolumeTextureRequirements CheckRequirements(Device device, int width, int height, int depth, int mipLevelCount, Usage usage, Format format, Pool pool) { var result = new VolumeTextureRequirements(); D3DX9.CheckVolumeTextureRequirements(device, ref result.Width, ref result.Height, ref result.Depth, ref result.MipLevelCount, (int)usage, ref result.Format, pool); return result; } /// <summary> /// Uses a user-provided function to fill each texel of each mip level of a given texture. /// </summary> /// <param name="callback">A function that is used to fill the texture.</param> /// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns> /// <unmanaged>HRESULT D3DXFillVolumeTexture([In] IDirect3DVolumeTexture9* pVolumeTexture,[In] __function__stdcall* pFunction,[In] void* pData)</unmanaged> public void Fill(Fill3DCallback callback) { var handle = GCHandle.Alloc(callback); try { D3DX9.FillVolumeTexture(this, FillCallbackHelper.Native2DCallbackPtr, GCHandle.ToIntPtr(handle)); } finally { handle.Free(); } } /// <summary> /// Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture. /// </summary> /// <param name="shader">A texture shader object that is used to fill the texture.</param> /// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns> /// <unmanaged>HRESULT D3DXFillVolumeTextureTX([In] IDirect3DVolumeTexture9* pVolumeTexture,[In] ID3DXVolumeTextureShader* pVolumeTextureShader)</unmanaged> public void Fill(TextureShader shader) { D3DX9.FillVolumeTextureTX(this, shader); } /// <summary> /// Locks a box on a volume texture resource. /// </summary> /// <param name="level">The level.</param> /// <param name="flags">The flags.</param> /// <returns> /// A <see cref="DataBox"/> describing the region locked. /// </returns> /// <unmanaged>HRESULT IDirect3DVolumeTexture9::LockBox([In] unsigned int Level,[Out] D3DLOCKED_BOX* pLockedVolume,[In] const void* pBox,[In] D3DLOCK Flags)</unmanaged> public DataBox LockBox(int level, SharpDX.Direct3D9.LockFlags flags) { LockedBox lockedRect; LockBox(level, out lockedRect, IntPtr.Zero, flags); return new DataBox(lockedRect.PBits, lockedRect.RowPitch, lockedRect.SlicePitch); } /// <summary> /// Locks a box on a volume texture resource. /// </summary> /// <param name="level">The level.</param> /// <param name="box">The box.</param> /// <param name="flags">The flags.</param> /// <returns> /// A <see cref="DataRectangle"/> describing the region locked. /// </returns> /// <unmanaged>HRESULT IDirect3DVolumeTexture9::LockBox([In] unsigned int Level,[Out] D3DLOCKED_BOX* pLockedVolume,[In] const void* pBox,[In] D3DLOCK Flags)</unmanaged> public DataBox LockBox(int level, Box box, SharpDX.Direct3D9.LockFlags flags) { unsafe { LockedBox lockedRect; LockBox(level, out lockedRect, new IntPtr(&box), flags); return new DataBox(lockedRect.PBits, lockedRect.RowPitch, lockedRect.SlicePitch); } } /// <summary> /// Adds a dirty region to a texture resource. /// </summary> /// <returns> /// A <see cref="SharpDX.Result"/> object describing the result of the operation. /// </returns> /// <unmanaged>HRESULT IDirect3DVolumeTexture9::AddDirtyBox([In] const void* pDirtyBox)</unmanaged> public void AddDirtyBox() { AddDirtyBox(IntPtr.Zero); } /// <summary> /// Adds a dirty region to a texture resource. /// </summary> /// <param name="directBoxRef">The direct box ref.</param> /// <returns> /// A <see cref="SharpDX.Result"/> object describing the result of the operation. /// </returns> /// <unmanaged>HRESULT IDirect3DVolumeTexture9::AddDirtyBox([In] const void* pDirtyBox)</unmanaged> public void AddDirtyBox(Box directBoxRef) { unsafe { AddDirtyBox(new IntPtr(&directBoxRef)); } } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromFile(Device device, string filename) { VolumeTexture cubeVolumeTexture; D3DX9.CreateVolumeTextureFromFileW(device, filename, out cubeVolumeTexture); return cubeVolumeTexture; } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <param name="usage">The usage.</param> /// <param name="pool">The pool.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromFile(Device device, string filename, Usage usage, Pool pool) { return FromFile(device, filename, -1, -1, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromFile(Device device, string filename, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey) { return CreateFromFile(device, filename, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static unsafe VolumeTexture FromFile(Device device, string filename, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation) { fixed (void* pImageInfo = &imageInformation) return CreateFromFile(device, filename, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a file /// </summary> /// <param name="device">The device.</param> /// <param name="filename">The filename.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static unsafe VolumeTexture FromFile(Device device, string filename, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette) { palette = new PaletteEntry[256]; fixed (void* pImageInfo = &imageInformation) return CreateFromFile(device, filename, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemory([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromMemory(Device device, byte[] buffer) { VolumeTexture cubeVolumeTexture; unsafe { fixed (void* pData = buffer) D3DX9.CreateVolumeTextureFromFileInMemory(device, (IntPtr)pData, buffer.Length, out cubeVolumeTexture); } return cubeVolumeTexture; } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="usage">The usage.</param> /// <param name="pool">The pool.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromMemory(Device device, byte[] buffer, Usage usage, Pool pool) { return FromMemory(device, buffer, -1, -1, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromMemory(Device device, byte[] buffer, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey) { return CreateFromMemory(device, buffer, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static unsafe VolumeTexture FromMemory(Device device, byte[] buffer, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation) { fixed (void* pImageInfo = &imageInformation) return CreateFromMemory(device, buffer, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a memory buffer. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static unsafe VolumeTexture FromMemory(Device device, byte[] buffer, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette) { palette = new PaletteEntry[256]; fixed (void* pImageInfo = &imageInformation) return CreateFromMemory(device, buffer, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <returns>A <see cref="VolumeTexture"/></returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemory([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromStream(Device device, Stream stream) { VolumeTexture cubeVolumeTexture; if (stream is DataStream) { D3DX9.CreateVolumeTextureFromFileInMemory(device, ((DataStream)stream).PositionPointer, (int)(stream.Length - stream.Position), out cubeVolumeTexture); } else { unsafe { var data = Utilities.ReadStream(stream); fixed (void* pData = data) D3DX9.CreateVolumeTextureFromFileInMemory(device, (IntPtr)pData, data.Length, out cubeVolumeTexture); } } return cubeVolumeTexture; } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="usage">The usage.</param> /// <param name="pool">The pool.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromStream(Device device, Stream stream, Usage usage, Pool pool) { return FromStream(device, stream, 0, -1, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromStream(Device device, Stream stream, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey) { return FromStream(device, stream, 0, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="sizeBytes">The size bytes.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static VolumeTexture FromStream(Device device, Stream stream, int sizeBytes, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey) { return CreateFromStream(device, stream, sizeBytes, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="sizeBytes">The size bytes.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static unsafe VolumeTexture FromStream(Device device, Stream stream, int sizeBytes, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation) { fixed (void* pImageInfo = &imageInformation) return CreateFromStream(device, stream, sizeBytes, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="sizeBytes">The size bytes.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> public static unsafe VolumeTexture FromStream(Device device, Stream stream, int sizeBytes, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette) { palette = new PaletteEntry[256]; fixed (void* pImageInfo = &imageInformation) return CreateFromStream(device, stream, sizeBytes, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette); } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="buffer">The buffer.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> private static unsafe VolumeTexture CreateFromMemory(Device device, byte[] buffer, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette) { VolumeTexture cubeVolumeTexture; fixed (void* pBuffer = buffer) cubeVolumeTexture = CreateFromPointer( device, (IntPtr)pBuffer, buffer.Length, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, imageInformation, palette ); return cubeVolumeTexture; } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="stream">The stream.</param> /// <param name="sizeBytes">The size bytes.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns>A <see cref="VolumeTexture"/></returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> private static unsafe VolumeTexture CreateFromStream(Device device, Stream stream, int sizeBytes, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette) { VolumeTexture cubeVolumeTexture; sizeBytes = sizeBytes == 0 ? (int)(stream.Length - stream.Position): sizeBytes; if (stream is DataStream) { cubeVolumeTexture = CreateFromPointer( device, ((DataStream)stream).PositionPointer, sizeBytes, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, imageInformation, palette ); } else { var data = Utilities.ReadStream(stream); fixed (void* pData = data) cubeVolumeTexture = CreateFromPointer( device, (IntPtr)pData, data.Length, width, height, depth, levelCount, usage, format, pool, filter, mipFilter, colorKey, imageInformation, palette ); } stream.Position = sizeBytes; return cubeVolumeTexture; } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="pointer">The pointer.</param> /// <param name="sizeInBytes">The size in bytes.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> private static unsafe VolumeTexture CreateFromPointer(Device device, IntPtr pointer, int sizeInBytes, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette) { VolumeTexture cubeVolumeTexture; D3DX9.CreateVolumeTextureFromFileInMemoryEx( device, pointer, sizeInBytes, width, height, depth, levelCount, (int)usage, format, pool, (int)filter, (int)mipFilter, *(RawColorBGRA*)&colorKey, imageInformation, palette, out cubeVolumeTexture); return cubeVolumeTexture; } /// <summary> /// Creates a <see cref="VolumeTexture"/> from a stream. /// </summary> /// <param name="device">The device.</param> /// <param name="fileName">Name of the file.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="filter">The filter.</param> /// <param name="mipFilter">The mip filter.</param> /// <param name="colorKey">The color key.</param> /// <param name="imageInformation">The image information.</param> /// <param name="palette">The palette.</param> /// <returns> /// A <see cref="VolumeTexture"/> /// </returns> /// <unmanaged>HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DVolumeTexture9** ppVolumeTexture)</unmanaged> private unsafe static VolumeTexture CreateFromFile(Device device, string fileName, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette) { VolumeTexture cubeVolumeTexture; D3DX9.CreateVolumeTextureFromFileExW( device, fileName, width, height, depth, levelCount, (int)usage, format, pool, (int)filter, (int)mipFilter, *(RawColorBGRA*)&colorKey, imageInformation, palette, out cubeVolumeTexture); return cubeVolumeTexture; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>FeedPlaceholderView</c> resource.</summary> public sealed partial class FeedPlaceholderViewName : gax::IResourceName, sys::IEquatable<FeedPlaceholderViewName> { /// <summary>The possible contents of <see cref="FeedPlaceholderViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c>. /// </summary> CustomerPlaceholderType = 1, } private static gax::PathTemplate s_customerPlaceholderType = new gax::PathTemplate("customers/{customer_id}/feedPlaceholderViews/{placeholder_type}"); /// <summary>Creates a <see cref="FeedPlaceholderViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="FeedPlaceholderViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static FeedPlaceholderViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new FeedPlaceholderViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="FeedPlaceholderViewName"/> with the pattern /// <c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="placeholderTypeId">The <c>PlaceholderType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="FeedPlaceholderViewName"/> constructed from the provided ids. /// </returns> public static FeedPlaceholderViewName FromCustomerPlaceholderType(string customerId, string placeholderTypeId) => new FeedPlaceholderViewName(ResourceNameType.CustomerPlaceholderType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), placeholderTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(placeholderTypeId, nameof(placeholderTypeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedPlaceholderViewName"/> with pattern /// <c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="placeholderTypeId">The <c>PlaceholderType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedPlaceholderViewName"/> with pattern /// <c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c>. /// </returns> public static string Format(string customerId, string placeholderTypeId) => FormatCustomerPlaceholderType(customerId, placeholderTypeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedPlaceholderViewName"/> with pattern /// <c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="placeholderTypeId">The <c>PlaceholderType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedPlaceholderViewName"/> with pattern /// <c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c>. /// </returns> public static string FormatCustomerPlaceholderType(string customerId, string placeholderTypeId) => s_customerPlaceholderType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(placeholderTypeId, nameof(placeholderTypeId))); /// <summary> /// Parses the given resource name string into a new <see cref="FeedPlaceholderViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c></description> /// </item> /// </list> /// </remarks> /// <param name="feedPlaceholderViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="FeedPlaceholderViewName"/> if successful.</returns> public static FeedPlaceholderViewName Parse(string feedPlaceholderViewName) => Parse(feedPlaceholderViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="FeedPlaceholderViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedPlaceholderViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="FeedPlaceholderViewName"/> if successful.</returns> public static FeedPlaceholderViewName Parse(string feedPlaceholderViewName, bool allowUnparsed) => TryParse(feedPlaceholderViewName, allowUnparsed, out FeedPlaceholderViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeedPlaceholderViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c></description> /// </item> /// </list> /// </remarks> /// <param name="feedPlaceholderViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeedPlaceholderViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string feedPlaceholderViewName, out FeedPlaceholderViewName result) => TryParse(feedPlaceholderViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeedPlaceholderViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedPlaceholderViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeedPlaceholderViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string feedPlaceholderViewName, bool allowUnparsed, out FeedPlaceholderViewName result) { gax::GaxPreconditions.CheckNotNull(feedPlaceholderViewName, nameof(feedPlaceholderViewName)); gax::TemplatedResourceName resourceName; if (s_customerPlaceholderType.TryParseName(feedPlaceholderViewName, out resourceName)) { result = FromCustomerPlaceholderType(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(feedPlaceholderViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private FeedPlaceholderViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string placeholderTypeId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; PlaceholderTypeId = placeholderTypeId; } /// <summary> /// Constructs a new instance of a <see cref="FeedPlaceholderViewName"/> class from the component parts of /// pattern <c>customers/{customer_id}/feedPlaceholderViews/{placeholder_type}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="placeholderTypeId">The <c>PlaceholderType</c> ID. Must not be <c>null</c> or empty.</param> public FeedPlaceholderViewName(string customerId, string placeholderTypeId) : this(ResourceNameType.CustomerPlaceholderType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), placeholderTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(placeholderTypeId, nameof(placeholderTypeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>PlaceholderType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string PlaceholderTypeId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerPlaceholderType: return s_customerPlaceholderType.Expand(CustomerId, PlaceholderTypeId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as FeedPlaceholderViewName); /// <inheritdoc/> public bool Equals(FeedPlaceholderViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(FeedPlaceholderViewName a, FeedPlaceholderViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(FeedPlaceholderViewName a, FeedPlaceholderViewName b) => !(a == b); } public partial class FeedPlaceholderView { /// <summary> /// <see cref="FeedPlaceholderViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal FeedPlaceholderViewName ResourceNameAsFeedPlaceholderViewName { get => string.IsNullOrEmpty(ResourceName) ? null : FeedPlaceholderViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Linq.Expressions; using System.Reflection; using Remotion.Linq.Clauses.ExpressionTreeVisitors; using Remotion.Linq.Clauses.ResultOperators; using Remotion.Linq.Clauses.StreamedData; namespace Remotion.Linq.Clauses { /// <summary> /// Represents an operation that is executed on the result set of the query, aggregating, filtering, or restricting the number of result items /// before the query result is returned. /// </summary> public abstract class ResultOperatorBase { /// <summary> /// Executes this result operator in memory, on a given input. Executing result operators in memory should only be /// performed if the target query system does not support the operator. /// </summary> /// <param name="input">The input for the result operator. This must match the type of <see cref="IStreamedData"/> expected by the operator.</param> /// <returns>The result of the operator.</returns> /// <seealso cref="InvokeGenericExecuteMethod{TInput,TResult}"/> public abstract IStreamedData ExecuteInMemory(IStreamedData input); /// <summary> /// Gets information about the data streamed out of this <see cref="ResultOperatorBase"/>. This contains the result type a query would have if /// it ended with this <see cref="ResultOperatorBase"/>, and it optionally includes an <see cref="StreamedSequenceInfo.ItemExpression"/> describing /// the streamed sequence's items. /// </summary> /// <param name="inputInfo">Information about the data produced by the preceding <see cref="ResultOperatorBase"/>, or the <see cref="SelectClause"/> /// of the query if no previous <see cref="ResultOperatorBase"/> exists.</param> /// <returns>Gets information about the data streamed out of this <see cref="ResultOperatorBase"/>.</returns> public abstract IStreamedDataInfo GetOutputDataInfo(IStreamedDataInfo inputInfo); /// <summary> /// Clones this item, registering its clone with the <paramref name="cloneContext"/> if it is a query source clause. /// </summary> /// <param name="cloneContext">The clones of all query source clauses are registered with this <see cref="CloneContext"/>.</param> /// <returns>A clone of this item.</returns> public abstract ResultOperatorBase Clone(CloneContext cloneContext); /// <summary> /// Accepts the specified visitor by calling its <see cref="IQueryModelVisitor.VisitResultOperator"/> method. /// </summary> /// <param name="visitor">The visitor to accept.</param> /// <param name="queryModel">The query model in whose context this clause is visited.</param> /// <param name="index">The index of this item in the <paramref name="queryModel"/>'s <see cref="QueryModel.ResultOperators"/> collection.</param> public virtual void Accept(IQueryModelVisitor visitor, QueryModel queryModel, int index) { visitor.VisitResultOperator(this, queryModel, index); } /// <summary> /// Transforms all the expressions in this item via the given <paramref name="transformation"/> delegate. Subclasses must apply the /// <paramref name="transformation"/> to any expressions they hold. If a subclass does not hold any expressions, it shouldn't do anything /// in the implementation of this method. /// </summary> /// <param name="transformation">The transformation object. This delegate is called for each <see cref="Expression"/> within this /// item, and those expressions will be replaced with what the delegate returns.</param> public abstract void TransformExpressions(Func<Expression, Expression> transformation); /// <summary> /// Invokes a given generic method on an <see cref="IStreamedData"/> input via Reflection. Use this to implement /// <see cref="ExecuteInMemory(IStreamedData)"/> by defining a strongly typed, generic variant /// of <see cref="ExecuteInMemory(IStreamedData)"/>; then invoke that strongly typed /// variant via <see cref="InvokeGenericExecuteMethod{TInput,TResult}"/>. /// </summary> /// <typeparam name="TInput">The type of <see cref="IStreamedData"/> expected as an input to <paramref name="genericExecuteCaller"/>.</typeparam> /// <typeparam name="TResult">The type of <see cref="IStreamedData"/> expected as the output of <paramref name="genericExecuteCaller"/>.</typeparam> /// <param name="input">The input <see cref="IStreamedData"/> object to invoke the method on..</param> /// <param name="genericExecuteCaller">A delegate holding exactly one public generic method with exactly one generic argument. This method is /// called via Reflection on the given <paramref name="input"/> argument.</param> /// <returns>The result of invoking the method in <paramref name="genericExecuteCaller"/> on <paramref name="input"/>.</returns> /// <example> /// The <see cref="CountResultOperator"/> uses this method as follows: /// <code> /// public IStreamedData ExecuteInMemory (IStreamedData input) /// { /// ArgumentUtility.CheckNotNull ("input", input); /// return InvokeGenericExecuteMethod&lt;StreamedSequence, StreamedValue&gt; (input, ExecuteInMemory&lt;object&gt;); /// } /// /// public StreamedValue ExecuteInMemory&lt;T&gt; (StreamedSequence input) /// { /// var sequence = input.GetTypedSequence&lt;T&gt; (); /// var result = sequence.Sequence.Count (); /// return new StreamedValue (result); /// } /// </code> /// </example> protected TResult InvokeGenericExecuteMethod<TInput, TResult>(IStreamedData input, Func<TInput, TResult> genericExecuteCaller) where TInput : IStreamedData where TResult : IStreamedData { var method = genericExecuteCaller.Method; if (!method.IsGenericMethod || method.GetGenericArguments().Length != 1) { throw new ArgumentException( "Method to invoke ('" + method.Name + "') must be a generic method with exactly one generic argument.", "genericExecuteCaller"); } var closedGenericMethod = input.DataInfo.MakeClosedGenericExecuteMethod(method.GetGenericMethodDefinition()); return (TResult)InvokeExecuteMethod(closedGenericMethod, input); } /// <summary> /// Invokes the given <paramref name="method"/> via reflection on the given <paramref name="input"/>. /// </summary> /// <param name="input">The input to invoke the method with.</param> /// <param name="method">The method to be invoked.</param> /// <returns>The result of the invocation</returns> protected object InvokeExecuteMethod(MethodInfo method, object input) { if (!method.IsPublic) throw new ArgumentException("Method to invoke ('" + method.Name + "') must be a public method.", "method"); var targetObject = method.IsStatic ? null : this; try { return method.Invoke(targetObject, new[] { input }); } catch (TargetInvocationException ex) { throw ex.InnerException; } catch (ArgumentException ex) { var message = string.Format("Cannot call method '{0}' on input of type '{1}': {2}", method.Name, input.GetType(), ex.Message); throw new ArgumentException(message, "method"); } } /// <summary> /// Gets the constant value of the given expression, assuming it is a <see cref="ConstantExpression"/>. If it is /// not, an <see cref="InvalidOperationException"/> is thrown. /// </summary> /// <typeparam name="T">The expected value type. If the value is not of this type, an <see cref="InvalidOperationException"/> is thrown.</typeparam> /// <param name="expressionName">A string describing the value; this will be included in the exception message if an exception is thrown.</param> /// <param name="expression">The expression whose value to get.</param> /// <returns> /// The constant value of the given <paramref name="expression"/>. /// </returns> protected T GetConstantValueFromExpression<T>(string expressionName, Expression expression) { if (!typeof(T).IsAssignableFrom(expression.Type)) { var message = string.Format( "The value stored by the {0} expression ('{1}') is not of type '{2}', it is of type '{3}'.", expressionName, FormattingExpressionTreeVisitor.Format(expression), typeof(T), expression.Type); throw new ArgumentException(message, "expression"); } var itemAsConstantExpression = expression as ConstantExpression; if (itemAsConstantExpression != null) { return (T)itemAsConstantExpression.Value; } else { var message = string.Format( "The {0} expression ('{1}') is no ConstantExpression, it is a {2}.", expressionName, FormattingExpressionTreeVisitor.Format(expression), expression.GetType().Name); throw new ArgumentException(message, "expression"); } } protected void CheckSequenceItemType(StreamedSequenceInfo inputInfo, Type expectedItemType) { if (!expectedItemType.IsAssignableFrom(inputInfo.ResultItemType)) { var message = string.Format( "The input sequence must have items of type '{0}', but it has items of type '{1}'.", expectedItemType, inputInfo.ResultItemType); throw new ArgumentException(message, "inputInfo"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace System.Net { // More sophisticated password cache that stores multiple // name-password pairs and associates these with host/realm. public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable { private Dictionary<CredentialKey, NetworkCredential> _cache; private Dictionary<CredentialHostKey, NetworkCredential> _cacheForHosts; private int _version; public CredentialCache() { } public void Add(Uri uriPrefix, string authType, NetworkCredential cred) { if (uriPrefix == null) { throw new ArgumentNullException(nameof(uriPrefix)); } if (authType == null) { throw new ArgumentNullException(nameof(authType)); } if ((cred is SystemNetworkCredential) && !((string.Equals(authType, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase)) || (string.Equals(authType, NegotiationInfoClass.Kerberos, StringComparison.OrdinalIgnoreCase)) || (string.Equals(authType, NegotiationInfoClass.Negotiate, StringComparison.OrdinalIgnoreCase))) ) { throw new ArgumentException(SR.Format(SR.net_nodefaultcreds, authType), nameof(authType)); } ++_version; var key = new CredentialKey(uriPrefix, authType); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{cred.Domain}],[{cred.UserName}]"); if (_cache == null) { _cache = new Dictionary<CredentialKey, NetworkCredential>(); } _cache.Add(key, cred); } public void Add(string host, int port, string authenticationType, NetworkCredential credential) { if (host == null) { throw new ArgumentNullException(nameof(host)); } if (authenticationType == null) { throw new ArgumentNullException(nameof(authenticationType)); } if (host.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(host)), nameof(host)); } if (port < 0) { throw new ArgumentOutOfRangeException(nameof(port)); } if ((credential is SystemNetworkCredential) && !((string.Equals(authenticationType, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase)) || (string.Equals(authenticationType, NegotiationInfoClass.Kerberos, StringComparison.OrdinalIgnoreCase)) || (string.Equals(authenticationType, NegotiationInfoClass.Negotiate, StringComparison.OrdinalIgnoreCase))) ) { throw new ArgumentException(SR.Format(SR.net_nodefaultcreds, authenticationType), nameof(authenticationType)); } ++_version; var key = new CredentialHostKey(host, port, authenticationType); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{credential.Domain}],[{credential.UserName}]"); if (_cacheForHosts == null) { _cacheForHosts = new Dictionary<CredentialHostKey, NetworkCredential>(); } _cacheForHosts.Add(key, credential); } public void Remove(Uri uriPrefix, string authType) { if (uriPrefix == null || authType == null) { // These couldn't possibly have been inserted into // the cache because of the test in Add(). return; } if (_cache == null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Short-circuiting because the dictionary is null."); return; } ++_version; var key = new CredentialKey(uriPrefix, authType); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Removing key:[{key}]"); _cache.Remove(key); } public void Remove(string host, int port, string authenticationType) { if (host == null || authenticationType == null) { // These couldn't possibly have been inserted into // the cache because of the test in Add(). return; } if (port < 0) { return; } if (_cacheForHosts == null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Short-circuiting because the dictionary is null."); return; } ++_version; var key = new CredentialHostKey(host, port, authenticationType); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Removing key:[{key}]"); _cacheForHosts.Remove(key); } public NetworkCredential GetCredential(Uri uriPrefix, string authType) { if (uriPrefix == null) { throw new ArgumentNullException(nameof(uriPrefix)); } if (authType == null) { throw new ArgumentNullException(nameof(authType)); } if (NetEventSource.IsEnabled) NetEventSource.Enter(this, uriPrefix, authType); if (_cache == null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null."); return null; } int longestMatchPrefix = -1; NetworkCredential mostSpecificMatch = null; // Enumerate through every credential in the cache foreach (KeyValuePair<CredentialKey, NetworkCredential> pair in _cache) { CredentialKey key = pair.Key; // Determine if this credential is applicable to the current Uri/AuthType if (key.Match(uriPrefix, authType)) { int prefixLen = key.UriPrefixLength; // Check if the match is better than the current-most-specific match if (prefixLen > longestMatchPrefix) { // Yes: update the information about currently preferred match longestMatchPrefix = prefixLen; mostSpecificMatch = pair.Value; } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Returning {(mostSpecificMatch == null ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")")}"); return mostSpecificMatch; } public NetworkCredential GetCredential(string host, int port, string authenticationType) { if (host == null) { throw new ArgumentNullException(nameof(host)); } if (authenticationType == null) { throw new ArgumentNullException(nameof(authenticationType)); } if (host.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(host)), nameof(host)); } if (port < 0) { throw new ArgumentOutOfRangeException(nameof(port)); } if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host, port, authenticationType); if (_cacheForHosts == null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null."); return null; } var key = new CredentialHostKey(host, port, authenticationType); NetworkCredential match = null; _cacheForHosts.TryGetValue(key, out match); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Returning {((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")}"); return match; } public IEnumerator GetEnumerator() => CredentialEnumerator.Create(this); public static ICredentials DefaultCredentials => SystemNetworkCredential.s_defaultCredential; public static NetworkCredential DefaultNetworkCredentials => SystemNetworkCredential.s_defaultCredential; private class CredentialEnumerator : IEnumerator { internal static CredentialEnumerator Create(CredentialCache cache) { Debug.Assert(cache != null); if (cache._cache != null) { return cache._cacheForHosts != null ? new DoubleTableCredentialEnumerator(cache) : new SingleTableCredentialEnumerator<CredentialKey>(cache, cache._cache); } else { return cache._cacheForHosts != null ? new SingleTableCredentialEnumerator<CredentialHostKey>(cache, cache._cacheForHosts) : new CredentialEnumerator(cache); } } private readonly CredentialCache _cache; private readonly int _version; private bool _enumerating; private NetworkCredential _current; private CredentialEnumerator(CredentialCache cache) { Debug.Assert(cache != null); _cache = cache; _version = cache._version; } public object Current { get { if (!_enumerating) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_version != _cache._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } return _current; } } public bool MoveNext() { if (_version != _cache._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } return _enumerating = MoveNext(out _current); } protected virtual bool MoveNext(out NetworkCredential current) { current = null; return false; } public virtual void Reset() { _enumerating = false; } private class SingleTableCredentialEnumerator<TKey> : CredentialEnumerator { private Dictionary<TKey, NetworkCredential>.ValueCollection.Enumerator _enumerator; // mutable struct field deliberately not readonly. public SingleTableCredentialEnumerator(CredentialCache cache, Dictionary<TKey, NetworkCredential> table) : base(cache) { Debug.Assert(table != null); // Despite the ValueCollection allocation, ValueCollection's enumerator is faster // than Dictionary's enumerator for enumerating the values because it avoids // KeyValuePair copying. _enumerator = table.Values.GetEnumerator(); } protected override bool MoveNext(out NetworkCredential current) => DictionaryEnumeratorHelper.MoveNext(ref _enumerator, out current); public override void Reset() { DictionaryEnumeratorHelper.Reset(ref _enumerator); base.Reset(); } } private sealed class DoubleTableCredentialEnumerator : SingleTableCredentialEnumerator<CredentialKey> { private Dictionary<CredentialHostKey, NetworkCredential>.ValueCollection.Enumerator _enumerator; // mutable struct field deliberately not readonly. private bool _onThisEnumerator; public DoubleTableCredentialEnumerator(CredentialCache cache) : base(cache, cache._cache) { Debug.Assert(cache._cacheForHosts != null); // Despite the ValueCollection allocation, ValueCollection's enumerator is faster // than Dictionary's enumerator for enumerating the values because it avoids // KeyValuePair copying. _enumerator = cache._cacheForHosts.Values.GetEnumerator(); } protected override bool MoveNext(out NetworkCredential current) { if (!_onThisEnumerator) { if (base.MoveNext(out current)) { return true; } else { _onThisEnumerator = true; } } return DictionaryEnumeratorHelper.MoveNext(ref _enumerator, out current); } public override void Reset() { _onThisEnumerator = false; DictionaryEnumeratorHelper.Reset(ref _enumerator); base.Reset(); } } private static class DictionaryEnumeratorHelper { internal static bool MoveNext<TKey, TValue>(ref Dictionary<TKey, TValue>.ValueCollection.Enumerator enumerator, out TValue current) { bool result = enumerator.MoveNext(); current = enumerator.Current; return result; } // Allows calling Reset on Dictionary's struct enumerator without a box allocation. internal static void Reset<TEnumerator>(ref TEnumerator enumerator) where TEnumerator : IEnumerator { // The Dictionary enumerator's Reset method throws if the Dictionary has changed, but // CredentialCache.Reset should not throw, so we catch and swallow the exception. try { enumerator.Reset(); } catch (InvalidOperationException) { } } } } } // Abstraction for credentials in password-based // authentication schemes (basic, digest, NTLM, Kerberos). // // Note that this is not applicable to public-key based // systems such as SSL client authentication. // // "Password" here may be the clear text password or it // could be a one-way hash that is sufficient to // authenticate, as in HTTP/1.1 digest. internal sealed class SystemNetworkCredential : NetworkCredential { internal static readonly SystemNetworkCredential s_defaultCredential = new SystemNetworkCredential(); // We want reference equality to work. Making this private is a good way to guarantee that. private SystemNetworkCredential() : base(string.Empty, string.Empty, string.Empty) { } } internal struct CredentialHostKey : IEquatable<CredentialHostKey> { public readonly string Host; public readonly string AuthenticationType; public readonly int Port; internal CredentialHostKey(string host, int port, string authenticationType) { Debug.Assert(!string.IsNullOrEmpty(host)); Debug.Assert(port >= 0); Debug.Assert(authenticationType != null); Host = host; Port = port; AuthenticationType = authenticationType; } public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(AuthenticationType) ^ StringComparer.OrdinalIgnoreCase.GetHashCode(Host) ^ Port.GetHashCode(); public bool Equals(CredentialHostKey other) { bool equals = string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) && string.Equals(Host, other.Host, StringComparison.OrdinalIgnoreCase) && Port == other.Port; if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Equals({this},{other}) returns {equals}"); return equals; } public override bool Equals(object obj) => obj is CredentialHostKey && Equals((CredentialHostKey)obj); public override string ToString() => Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + AuthenticationType; } internal sealed class CredentialKey : IEquatable<CredentialKey> { public readonly Uri UriPrefix; public readonly int UriPrefixLength = -1; public readonly string AuthenticationType; internal CredentialKey(Uri uriPrefix, string authenticationType) { Debug.Assert(uriPrefix != null); Debug.Assert(authenticationType != null); UriPrefix = uriPrefix; UriPrefixLength = UriPrefix.ToString().Length; AuthenticationType = authenticationType; } internal bool Match(Uri uri, string authenticationType) { if (uri == null || authenticationType == null) { return false; } // If the protocols don't match, this credential is not applicable for the given Uri. if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase)) { return false; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Match({UriPrefix} & {uri})"); return IsPrefix(uri, UriPrefix); } // IsPrefix (Uri) // // Determines whether <prefixUri> is a prefix of this URI. A prefix // match is defined as: // // scheme match // + host match // + port match, if any // + <prefix> path is a prefix of <URI> path, if any // // Returns: // True if <prefixUri> is a prefix of this URI private static bool IsPrefix(Uri uri, Uri prefixUri) { Debug.Assert(uri != null); Debug.Assert(prefixUri != null); if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port) { return false; } int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/'); if (prefixLen > uri.AbsolutePath.LastIndexOf('/')) { return false; } return string.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase) == 0; } public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(AuthenticationType) ^ UriPrefix.GetHashCode(); public bool Equals(CredentialKey other) { if (other == null) { return false; } bool equals = string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) && UriPrefix.Equals(other.UriPrefix); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Equals({this},{other}) returns {equals}"); return equals; } public override bool Equals(object obj) => Equals(obj as CredentialKey); public override string ToString() => "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + UriPrefix + ":" + AuthenticationType; } }
// The MIT License (MIT) // // Copyright (c) 2021 Henk-Jan Lebbink // // 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 AsmDude { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Linq; using System.Xml; using System.Xml.XPath; using Amib.Threading; using AsmDude.SignatureHelp; using AsmDude.Tools; using AsmTools; using Microsoft.VisualStudio.Shell; public sealed class AsmDudeTools : IDisposable { private XmlDocument xmlData_; private IDictionary<string, AsmTokenType> type_; private IDictionary<string, AssemblerEnum> assembler_; private IDictionary<string, Arch> arch_; private IDictionary<string, string> description_; private readonly ISet<Mnemonic> mnemonics_switched_on_; private readonly ISet<Rn> register_switched_on_; private readonly ErrorListProvider errorListProvider_; private readonly MnemonicStore mnemonicStore_; private readonly PerformanceStore performanceStore_; private readonly SmartThreadPool threadPool_; #region Singleton Stuff private static readonly Lazy<AsmDudeTools> Lazy = new Lazy<AsmDudeTools>(() => new AsmDudeTools()); public static AsmDudeTools Instance { get { return Lazy.Value; } } #endregion Singleton Stuff /// <summary> /// Singleton pattern: use AsmDudeTools.Instance for the instance of this class /// </summary> private AsmDudeTools() { //AsmDudeToolsStatic.Output_INFO("AsmDudeTools constructor"); ThreadHelper.ThrowIfNotOnUIThread(); #region Initialize ErrorListProvider //this._errorListProvider = new ErrorListProvider(new ServiceProvider(Package.GetGlobalService(typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider)) as Microsoft.VisualStudio.OLE.Interop.IServiceProvider)) //{ // ProviderName = "Asm Errors", // ProviderGuid = new Guid(EnvDTE.Constants.vsViewKindCode), //}; IServiceProvider a = Package.GetGlobalService(typeof(System.IServiceProvider)) as IServiceProvider; this.errorListProvider_ = new ErrorListProvider(a) { ProviderName = "Asm Errors", ProviderGuid = new Guid(EnvDTE.Constants.vsViewKindCode), }; #endregion this.threadPool_ = new SmartThreadPool(); #region load Signature Store and Performance Store string path = AsmDudeToolsStatic.Get_Install_Path() + "Resources" + Path.DirectorySeparatorChar; { string filename_Regular = path + "signature-may2019.txt"; string filename_Hand = path + "signature-hand-1.txt"; this.mnemonicStore_ = new MnemonicStore(filename_Regular, filename_Hand); } { this.performanceStore_ = new PerformanceStore(path + "Performance" + Path.DirectorySeparatorChar); } #endregion this.Init_Data(); this.mnemonics_switched_on_ = new HashSet<Mnemonic>(); this.UpdateMnemonicSwitchedOn(); this.register_switched_on_ = new HashSet<Rn>(); this.UpdateRegisterSwitchedOn(); #region Experiments if (false) { string filename2 = AsmDudeToolsStatic.Get_Install_Path() + "Resources" + Path.DirectorySeparatorChar + "mnemonics-nasm.txt"; MnemonicStore store2 = new MnemonicStore(filename2, null); ISet<string> archs = new SortedSet<string>(); IDictionary<string, string> signaturesIntel = new Dictionary<string, string>(); IDictionary<string, string> signaturesNasm = new Dictionary<string, string>(); foreach (Mnemonic mnemonic in Enum.GetValues(typeof(Mnemonic))) { IEnumerable<AsmSignatureElement> intel = this.mnemonicStore_.GetSignatures(mnemonic); IEnumerable<AsmSignatureElement> nasm = store2.GetSignatures(mnemonic); signaturesIntel.Clear(); signaturesNasm.Clear(); int intelCount = 0; foreach (AsmSignatureElement e in intel) { intelCount++; string instruction = e.mnemonic.ToString() + " " + e.Operands_Str; if (signaturesIntel.ContainsKey(instruction)) { AsmDudeToolsStatic.Output_WARNING("Intel " + instruction + ": is already present with arch " + signaturesIntel[instruction] + "; new arch " + e.Arch_Str); } else { signaturesIntel.Add(instruction, e.Arch_Str); } } int nasmCount = 0; foreach (AsmSignatureElement e in nasm) { nasmCount++; string instruction = e.mnemonic.ToString() + " " + e.Operands_Str; if (signaturesNasm.ContainsKey(instruction)) { // AsmDudeToolsStatic.Output_WARNING("Nasm " + instruction + ": is already present with arch " + signaturesNasm[instruction] + "; new arch " + e.archStr); } else { signaturesNasm.Add(instruction, e.Arch_Str); } } foreach (AsmSignatureElement e in intel) { string instruction = e.mnemonic.ToString() + " " + e.Operands_Str; //AsmDudeToolsStatic.Output_INFO("Intel " + instruction + ": arch" + e.archStr); if (string.IsNullOrEmpty(e.Arch_Str)) { if (signaturesNasm.ContainsKey(instruction)) { AsmDudeToolsStatic.Output_INFO("Intel " + instruction + " has no arch, but NASM has \"" + signaturesNasm[instruction] + "\"."); } else { if (signaturesNasm.Count == 1) { AsmDudeToolsStatic.Output_INFO("Intel " + instruction + " has no arch, but NASM has \"" + signaturesNasm.GetEnumerator().Current + "\"."); } else { AsmDudeToolsStatic.Output_INFO("Intel " + instruction + " has no arch:"); foreach (KeyValuePair<string, string> pair in signaturesNasm) { AsmDudeToolsStatic.Output_INFO("\tNASM has " + pair.Key + ": \"" + pair.Value + "\"."); } AsmDudeToolsStatic.Output_INFO(" ----"); } } } } if (false) { if (intelCount != nasmCount) { foreach (AsmSignatureElement e in intel) { AsmDudeToolsStatic.Output_INFO("INTEL " + mnemonic + ": " + e); } foreach (AsmSignatureElement e in nasm) { AsmDudeToolsStatic.Output_INFO("NASM " + mnemonic + ": " + e); } } } } foreach (string str in archs) { AsmDudeToolsStatic.Output_INFO("INTEL arch " + str); } } if (false) { foreach (Arch arch in Enum.GetValues(typeof(Arch))) { int counter = 0; ISet<Mnemonic> usedMnemonics = new HashSet<Mnemonic>(); foreach (Mnemonic mnemonic in Enum.GetValues(typeof(Mnemonic))) { if (this.Mnemonic_Store.GetArch(mnemonic).Contains(arch)) { //AsmDudeToolsStatic.Output_INFO("AsmDudeTools constructor: arch="+arch+"; mnemonic=" + mnemonic); counter++; usedMnemonics.Add(mnemonic); } } string str = string.Empty; foreach (Mnemonic mnemonic in usedMnemonics) { str += mnemonic.ToString() + ","; } AsmDudeToolsStatic.Output_INFO("AsmDudeTools constructor: Architecture Option " + arch + " enables mnemonics " + str); } } if (false) { foreach (Mnemonic mnemonic in Enum.GetValues(typeof(Mnemonic))) { string keyword = mnemonic.ToString(); if (this.description_.ContainsKey(keyword)) { string description = this.description_[keyword]; string reference = this.Get_Url(mnemonic); this.Mnemonic_Store.SetHtmlRef(mnemonic, reference); } } AsmDudeToolsStatic.Output_INFO(this.Mnemonic_Store.ToString()); } if (false) { ISet<string> archs = new HashSet<string>(); foreach (Mnemonic mnemonic in Enum.GetValues(typeof(Mnemonic))) { if (!this.mnemonicStore_.HasElement(mnemonic)) { AsmDudeToolsStatic.Output_INFO("AsmDudeTools constructor: mnemonic " + mnemonic + " is not present"); } foreach (AsmSignatureElement e in this.mnemonicStore_.GetSignatures(mnemonic)) { foreach (string s in e.Arch_Str.Split(',')) { archs.Add(s.Trim()); } } } foreach (string s in archs) { AsmDudeToolsStatic.Output_INFO(s + ","); } } #endregion } #region Public Methods public bool MnemonicSwitchedOn(Mnemonic mnemonic) { return this.mnemonics_switched_on_.Contains(mnemonic); } public IEnumerable<Mnemonic> Get_Allowed_Mnemonics() { return this.mnemonics_switched_on_; } public void UpdateMnemonicSwitchedOn() { this.mnemonics_switched_on_.Clear(); ISet<Arch> selectedArchs = AsmDudeToolsStatic.Get_Arch_Swithed_On(); foreach (Mnemonic mnemonic in Enum.GetValues(typeof(Mnemonic))) { foreach (Arch a in this.Mnemonic_Store.GetArch(mnemonic)) { if (selectedArchs.Contains(a)) { this.mnemonics_switched_on_.Add(mnemonic); break; } } } } public bool RegisterSwitchedOn(Rn reg) { return this.register_switched_on_.Contains(reg); } public IEnumerable<Rn> Get_Allowed_Registers() { return this.register_switched_on_; } public void UpdateRegisterSwitchedOn() { this.register_switched_on_.Clear(); ISet<Arch> selectedArchs = AsmDudeToolsStatic.Get_Arch_Swithed_On(); foreach (Rn reg in Enum.GetValues(typeof(Rn))) { if (reg != Rn.NOREG) { if (selectedArchs.Contains(RegisterTools.GetArch(reg))) { this.register_switched_on_.Add(reg); } } } } public ErrorListProvider Error_List_Provider { get { return this.errorListProvider_; } } public MnemonicStore Mnemonic_Store { get { return this.mnemonicStore_; } } public PerformanceStore Performance_Store { get { return this.performanceStore_; } } public SmartThreadPool Thread_Pool { get { return this.threadPool_; } } /// <summary>Get the collection of Keywords (in CAPITALS), but NOT mnemonics and registers</summary> public IEnumerable<string> Get_Keywords() { if (this.type_ == null) { this.Init_Data(); } return this.type_.Keys; } public AsmTokenType Get_Token_Type_Att(string keyword) { Contract.Requires(keyword != null); Contract.Requires(keyword == keyword.ToUpperInvariant()); int length = keyword.Length; Contract.Requires(length > 0); char firstChar = keyword[0]; #region Test if keyword is a register if (firstChar == '%') { string keyword2 = keyword.Substring(1); Rn reg = RegisterTools.ParseRn(keyword2, true); if (reg != Rn.NOREG) { return (this.RegisterSwitchedOn(reg)) ? AsmTokenType.Register : AsmTokenType.Register; //TODO } } #endregion #region Test if keyword is an imm if (firstChar == '$') { return AsmTokenType.Constant; } #endregion #region Test if keyword is an instruction { (Mnemonic mnemonic, AttType type) = AsmSourceTools.ParseMnemonic_Att(keyword, true); if (mnemonic != Mnemonic.NONE) { return (this.MnemonicSwitchedOn(mnemonic)) ? AsmSourceTools.IsJump(mnemonic) ? AsmTokenType.Jump : AsmTokenType.Mnemonic : AsmSourceTools.IsJump(mnemonic) ? AsmTokenType.Jump : AsmTokenType.MnemonicOff; } } #endregion return this.type_.TryGetValue(keyword, out AsmTokenType tokenType) ? tokenType : AsmTokenType.UNKNOWN; } public AsmTokenType Get_Token_Type_Intel(string keyword) { Contract.Requires(keyword != null); Contract.Requires(keyword == keyword.ToUpperInvariant()); Mnemonic mnemonic = AsmSourceTools.ParseMnemonic(keyword, true); if (mnemonic != Mnemonic.NONE) { return (this.MnemonicSwitchedOn(mnemonic)) ? AsmSourceTools.IsJump(mnemonic) ? AsmTokenType.Jump : AsmTokenType.Mnemonic : AsmSourceTools.IsJump(mnemonic) ? AsmTokenType.Jump : AsmTokenType.MnemonicOff; } Rn reg = RegisterTools.ParseRn(keyword, true); if (reg != Rn.NOREG) { return (this.RegisterSwitchedOn(reg)) ? AsmTokenType.Register : AsmTokenType.Register; //TODO } return this.type_.TryGetValue(keyword, out AsmTokenType tokenType) ? tokenType : AsmTokenType.UNKNOWN; } public AssemblerEnum Get_Assembler(string keyword) { Contract.Requires(keyword != null); Contract.Requires(keyword == keyword.ToUpperInvariant()); return this.assembler_.TryGetValue(keyword, out AssemblerEnum value) ? value : AssemblerEnum.UNKNOWN; } /// <summary> /// get url for the provided keyword. Returns empty string if the keyword does not exist or the keyword does not have an url. /// </summary> public string Get_Url(Mnemonic mnemonic) { return this.Mnemonic_Store.GetHtmlRef(mnemonic); } /// <summary> /// get descripton for the provided keyword. Returns empty string if the keyword does not exist or the keyword does not have an description. Keyword has to be in CAPITALS /// </summary> public string Get_Description(string keyword) { Contract.Requires(keyword != null); Contract.Requires(keyword == keyword.ToUpperInvariant()); return this.description_.TryGetValue(keyword, out string description) ? description : string.Empty; } /// <summary> /// Get architecture of the provided keyword. Keyword has to be in CAPITALS /// </summary> public Arch Get_Architecture(string keyword) { Contract.Requires(keyword != null); Contract.Requires(keyword == keyword.ToUpperInvariant()); return this.arch_.TryGetValue(keyword, out Arch value) ? value : Arch.ARCH_NONE; } public void Invalidate_Data() { this.xmlData_ = null; this.type_ = null; this.description_ = null; } #endregion Public Methods #region Private Methods private void Init_Data() { this.type_ = new Dictionary<string, AsmTokenType>(); this.arch_ = new Dictionary<string, Arch>(); this.assembler_ = new Dictionary<string, AssemblerEnum>(); this.description_ = new Dictionary<string, string>(); // fill the dictionary with keywords XmlDocument xmlDoc = this.Get_Xml_Data(); foreach (XmlNode node in xmlDoc.SelectNodes("//misc")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found misc with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.Misc; this.arch_[name] = Retrieve_Arch(node); this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//directive")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found directive with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.Directive; this.arch_[name] = Retrieve_Arch(node); this.assembler_[name] = Retrieve_Assembler(node); this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//register")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found register with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); //this._type[name] = AsmTokenType.Register; this.arch_[name] = Retrieve_Arch(node); this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//userdefined1")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found userdefined1 with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.UserDefined1; this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//userdefined2")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found userdefined2 with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.UserDefined2; this.description_[name] = Retrieve_Description(node); } } foreach (XmlNode node in xmlDoc.SelectNodes("//userdefined3")) { XmlAttribute nameAttribute = node.Attributes["name"]; if (nameAttribute == null) { AsmDudeToolsStatic.Output_WARNING("AsmDudeTools:Init_Data: found userdefined3 with no name"); } else { string name = nameAttribute.Value.ToUpperInvariant(); this.type_[name] = AsmTokenType.UserDefined3; this.description_[name] = Retrieve_Description(node); } } } private static Arch Retrieve_Arch(XmlNode node) { try { XmlAttribute archAttribute = node.Attributes["arch"]; return (archAttribute == null) ? Arch.ARCH_NONE : ArchTools.ParseArch(archAttribute.Value, false, true); } catch (Exception) { return Arch.ARCH_NONE; } } private static AssemblerEnum Retrieve_Assembler(XmlNode node) { try { XmlAttribute archAttribute = node.Attributes["tool"]; return (archAttribute == null) ? AssemblerEnum.UNKNOWN : AsmSourceTools.ParseAssembler(archAttribute.Value, false); } catch (Exception) { return AssemblerEnum.UNKNOWN; } } private static string Retrieve_Description(XmlNode node) { try { XmlNode node2 = node.SelectSingleNode("./description"); return (node2 == null) ? string.Empty : node2.InnerText.Trim(); } catch (Exception) { return string.Empty; } } private XmlDocument Get_Xml_Data() { //Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "INFO: {0}:getXmlData", this.ToString())); if (this.xmlData_ == null) { string filename = AsmDudeToolsStatic.Get_Install_Path() + "Resources" + Path.DirectorySeparatorChar + "AsmDudeData.xml"; Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "INFO: AsmDudeTools:getXmlData: going to load file \"{0}\"", filename)); try { this.xmlData_ = new XmlDocument() { XmlResolver = null }; System.IO.StringReader sreader = new System.IO.StringReader(File.ReadAllText(filename)); using (XmlReader reader = XmlReader.Create(sreader, new XmlReaderSettings() { XmlResolver = null })) { this.xmlData_.Load(reader); } } catch (FileNotFoundException) { AsmDudeToolsStatic.Output_ERROR("AsmTokenTagger: could not find file \"" + filename + "\"."); } catch (XmlException) { AsmDudeToolsStatic.Output_ERROR("AsmTokenTagger: xml error while reading file \"" + filename + "\"."); } catch (Exception e) { AsmDudeToolsStatic.Output_ERROR("AsmTokenTagger: error while reading file \"" + filename + "\"." + e); } } return this.xmlData_; } #endregion #region IDisposable Support public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } ~AsmDudeTools() { this.Dispose(false); } private void Dispose(bool disposing) { if (disposing) { // free managed resources this.errorListProvider_.Dispose(); this.threadPool_.Dispose(); } // free native resources if there are any. } #endregion } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace ChainStoreWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }