context stringlengths 2.52k 185k | gt stringclasses 1 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.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Microsoft.CodeAnalysis.Scripting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Interactive
{
internal partial class InteractiveHost
{
/// <summary>
/// A remote singleton server-activated object that lives in the interactive host process and controls it.
/// </summary>
internal sealed class Service : MarshalByRefObject, IDisposable
{
private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false);
// Signaled when UI thread is ready to process messages.
private static readonly ManualResetEventSlim s_uiReady = new ManualResetEventSlim(false);
// A WinForms control that enables us to execute code on UI thread.
// TODO (tomat): consider removing dependency on WinForms.
private static Control s_ui;
internal static readonly ImmutableArray<string> DefaultSourceSearchPaths =
ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)));
internal static readonly ImmutableArray<string> DefaultReferenceSearchPaths =
ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
private readonly InteractiveAssemblyLoader _assemblyLoader;
private readonly MetadataShadowCopyProvider _metadataFileProvider;
// the search paths - updated from the hostObject
private ImmutableArray<string> _sourceSearchPaths;
private ObjectFormatter _objectFormatter;
private IRepl _repl;
private InteractiveHostObject _hostObject;
private ObjectFormattingOptions _formattingOptions;
// Session is not thread-safe by itself,
// so we need to lock whenever we compile a submission or add a reference:
private readonly object _sessionGuard = new object();
private ScriptOptions _options;
private ScriptState _lastResult;
private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create(
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),
FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
#region Setup
public Service()
{
// TODO (tomat): we should share the copied files with the host
_metadataFileProvider = new MetadataShadowCopyProvider(
Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"),
noShadowCopyDirectories: s_systemNoShadowCopyDirectories);
_options = ScriptOptions.Default.WithSearchPaths(DefaultReferenceSearchPaths);
_assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider);
_sourceSearchPaths = DefaultSourceSearchPaths;
_formattingOptions = new ObjectFormattingOptions(
memberFormat: MemberDisplayFormat.Inline,
quoteStrings: true,
useHexadecimalNumbers: false,
maxOutputLength: 200,
memberIndentation: " ");
// We want to be sure to delete the shadow-copied files when the process goes away. Frankly
// there's nothing we can do if the process is forcefully quit or goes down in a completely
// uncontrolled manner (like a stack overflow). When the process goes down in a controlled
// manned, we should generally expect this event to be called.
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
}
private void HandleProcessExit(object sender, EventArgs e)
{
Dispose();
AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit;
}
public void Dispose()
{
_metadataFileProvider.Dispose();
}
public override object InitializeLifetimeService()
{
return null;
}
public void Initialize(Type replType)
{
Contract.ThrowIfNull(replType);
_repl = (IRepl)Activator.CreateInstance(replType);
_objectFormatter = _repl.CreateObjectFormatter();
_hostObject = new InteractiveHostObject();
_options = _options
.WithBaseDirectory(Directory.GetCurrentDirectory())
.AddReferences(_hostObject.GetType().Assembly);
_hostObject.ReferencePaths.AddRange(_options.SearchPaths);
_hostObject.SourcePaths.AddRange(_sourceSearchPaths);
Console.OutputEncoding = Encoding.UTF8;
}
private static bool AttachToClientProcess(int clientProcessId)
{
Process clientProcess;
try
{
clientProcess = Process.GetProcessById(clientProcessId);
}
catch (ArgumentException)
{
return false;
}
clientProcess.EnableRaisingEvents = true;
clientProcess.Exited += new EventHandler((_, __) =>
{
s_clientExited.Set();
});
return clientProcess.IsAlive();
}
// for testing purposes
public void EmulateClientExit()
{
s_clientExited.Set();
}
internal static void RunServer(string[] args)
{
if (args.Length != 3)
{
throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>");
}
RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture));
}
/// <summary>
/// Implements remote server.
/// </summary>
private static void RunServer(string serverPort, string semaphoreName, int clientProcessId)
{
if (!AttachToClientProcess(clientProcessId))
{
return;
}
// Disables Windows Error Reporting for the process, so that the process fails fast.
// Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1)
// Note that GetErrorMode is not available on XP at all.
if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0))
{
SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX);
}
IpcServerChannel serverChannel = null;
IpcClientChannel clientChannel = null;
try
{
using (var semaphore = Semaphore.OpenExisting(semaphoreName))
{
// DEBUG: semaphore.WaitOne();
var serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
var clientProvider = new BinaryClientFormatterSinkProvider();
clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider);
ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false);
serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider);
ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(Service),
ServiceName,
WellKnownObjectMode.Singleton);
var uiThread = new Thread(UIThread);
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.IsBackground = true;
uiThread.Start();
s_uiReady.Wait();
// the client can instantiate interactive host now:
semaphore.Release();
}
s_clientExited.Wait();
}
finally
{
if (serverChannel != null)
{
ChannelServices.UnregisterChannel(serverChannel);
}
if (clientChannel != null)
{
ChannelServices.UnregisterChannel(clientChannel);
}
}
// force exit even if there are foreground threads running:
Environment.Exit(0);
}
private static void UIThread()
{
s_ui = new Control();
s_ui.CreateControl();
s_uiReady.Set();
Application.Run();
}
internal static string ServiceName
{
get { return typeof(Service).Name; }
}
private static string GenerateUniqueChannelLocalName()
{
return typeof(Service).FullName + Guid.NewGuid();
}
#endregion
#region Remote Async Entry Points
// Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.)
[OneWay]
public void SetPathsAsync(
RemoteAsyncOperation<object> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
Debug.Assert(operation != null);
Debug.Assert(referenceSearchPaths != null);
Debug.Assert(sourceSearchPaths != null);
Debug.Assert(baseDirectory != null);
lock (_sessionGuard)
{
_hostObject.ReferencePaths.Clear();
_hostObject.ReferencePaths.AddRange(referenceSearchPaths);
_options = _options.WithSearchPaths(referenceSearchPaths).WithBaseDirectory(baseDirectory);
_hostObject.SourcePaths.Clear();
_hostObject.SourcePaths.AddRange(sourceSearchPaths);
_sourceSearchPaths = sourceSearchPaths.AsImmutable();
Directory.SetCurrentDirectory(baseDirectory);
}
operation.Completed(null);
}
/// <summary>
/// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it.
/// Execution is performed on the UI thread.
/// </summary>
[OneWay]
public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting)
{
Debug.Assert(operation != null);
var success = false;
try
{
InitializeContext(initializationFile, isRestarting);
success = true;
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
CompleteExecution(operation, success);
}
}
private string ResolveReferencePath(string reference, string baseFilePath)
{
var references = _options.ReferenceResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (references.IsDefaultOrEmpty)
{
return null;
}
return references.Single().FilePath;
}
/// <summary>
/// Adds an assembly reference to the current session.
/// </summary>
[OneWay]
public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference)
{
Debug.Assert(operation != null);
Debug.Assert(reference != null);
var success = false;
try
{
// TODO (tomat): This lock blocks all other session operations.
// We should be able to run multiple assembly resolutions and code execution in parallel.
string fullPath;
lock (_sessionGuard)
{
fullPath = ResolveReferencePath(reference, baseFilePath: null);
if (fullPath != null)
{
success = LoadReference(fullPath, suppressWarnings: false, addReference: true);
}
}
if (fullPath == null)
{
Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference));
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
operation.Completed(success);
}
}
/// <summary>
/// Executes given script snippet on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
Debug.Assert(operation != null);
Debug.Assert(text != null);
var success = false;
try
{
success = Execute(text);
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
CompleteExecution(operation, success);
}
}
/// <summary>
/// Executes given script file on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path)
{
Debug.Assert(operation != null);
Debug.Assert(path != null);
string fullPath = null;
bool success = false;
try
{
fullPath = ResolveRelativePath(path, _options.BaseDirectory, displayPath: false);
success = fullPath != null && ExecuteFile(fullPath);
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
CompleteExecution(operation, success, fullPath);
}
}
private void CompleteExecution(RemoteAsyncOperation<RemoteExecutionResult> operation, bool success, string resolvedPath = null)
{
// TODO (tomat): we should be resetting this info just before the execution to ensure that the services see the same
// as the next execution.
// send any updates to the host object and current directory back to the client:
var newSourcePaths = _hostObject.SourcePaths.List.GetNewContent();
var newReferencePaths = _hostObject.ReferencePaths.List.GetNewContent();
var currentDirectory = Directory.GetCurrentDirectory();
var oldWorkingDirectory = _options.BaseDirectory;
var newWorkingDirectory = (oldWorkingDirectory != currentDirectory) ? currentDirectory : null;
// update local search paths, the client updates theirs on operation completion:
if (newSourcePaths != null)
{
_sourceSearchPaths = newSourcePaths.AsImmutable();
}
if (newReferencePaths != null)
{
_options = _options.WithSearchPaths(newReferencePaths);
}
_options = _options.WithBaseDirectory(currentDirectory);
operation.Completed(new RemoteExecutionResult(success, newSourcePaths, newReferencePaths, newWorkingDirectory, resolvedPath));
}
private static void ReportUnhandledException(Exception e)
{
Console.Error.WriteLine("Unexpected error:");
Console.Error.WriteLine(e);
Debug.Fail("Unexpected error");
Debug.WriteLine(e);
}
#endregion
#region Operations
// TODO (tomat): testing only
public void SetTestObjectFormattingOptions()
{
_formattingOptions = new ObjectFormattingOptions(
memberFormat: MemberDisplayFormat.Inline,
quoteStrings: true,
useHexadecimalNumbers: false,
maxOutputLength: int.MaxValue,
memberIndentation: " ");
}
/// <summary>
/// Loads references, set options and execute files specified in the initialization file.
/// Also prints logo unless <paramref name="isRestarting"/> is true.
/// </summary>
private void InitializeContext(string initializationFileOpt, bool isRestarting)
{
Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));
// TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?
if (!isRestarting)
{
Console.Out.WriteLine(_repl.GetLogo());
}
if (File.Exists(initializationFileOpt))
{
Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt)));
var parser = _repl.GetCommandLineParser();
// The base directory for relative paths is the directory that contains the .rsp file.
// Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
var args = parser.Parse(new[] { "@" + initializationFileOpt }, Path.GetDirectoryName(initializationFileOpt), RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/);
foreach (var error in args.Errors)
{
var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
}
if (args.Errors.Length == 0)
{
// TODO (tomat): other arguments
// TODO (tomat): parse options
lock (_sessionGuard)
{
// TODO (tomat): consolidate with other reference resolving
foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
{
// interactive command line parser doesn't accept modules or linked assemblies
Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);
string fullPath = ResolveReferencePath(cmdLineReference.Reference, baseFilePath: null);
LoadReference(fullPath, suppressWarnings: true, addReference: true);
}
}
var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
foreach (CommandLineSourceFile file in args.SourceFiles)
{
// execute all files as scripts (matches csi/vbi semantics)
string fullPath = ResolveRelativePath(file.Path, rspDirectory, displayPath: true);
if (fullPath != null)
{
ExecuteFile(fullPath);
}
}
}
}
if (!isRestarting)
{
Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation);
}
}
private string ResolveRelativePath(string path, string baseDirectory, bool displayPath)
{
List<string> attempts = new List<string>();
Func<string, bool> fileExists = file =>
{
attempts.Add(file);
return File.Exists(file);
};
string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, _sourceSearchPaths, fileExists);
if (fullPath == null)
{
if (displayPath)
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path);
}
else
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound);
}
if (attempts.Count > 0)
{
DisplaySearchPaths(Console.Error, attempts);
}
}
return fullPath;
}
private bool LoadReference(string fullOriginalPath, bool suppressWarnings, bool addReference)
{
AssemblyLoadResult result;
try
{
result = LoadFromPathThrowing(fullOriginalPath, addReference);
}
catch (FileNotFoundException e)
{
Console.Error.WriteLine(e.Message);
return false;
}
catch (ArgumentException e)
{
Console.Error.WriteLine((e.InnerException ?? e).Message);
return false;
}
catch (TargetInvocationException e)
{
// The user might have hooked AssemblyResolve event, which might have thrown an exception.
// Display stack trace in this case.
Console.Error.WriteLine(e.InnerException.ToString());
return false;
}
if (!result.IsSuccessful && !suppressWarnings)
{
Console.Out.WriteLine(string.Format(CultureInfo.CurrentCulture, FeaturesResources.RequestedAssemblyAlreadyLoaded, result.OriginalPath));
}
return true;
}
// Testing utility.
// TODO (tomat): needed since MetadataReference is not serializable .
// Has to be public to be callable via remoting.
public SerializableAssemblyLoadResult LoadReferenceThrowing(string reference, bool addReference)
{
var fullPath = ResolveReferencePath(reference, baseFilePath: null);
if (fullPath == null)
{
throw new FileNotFoundException(message: null, fileName: reference);
}
return LoadFromPathThrowing(fullPath, addReference);
}
private AssemblyLoadResult LoadFromPathThrowing(string fullOriginalPath, bool addReference)
{
var result = _assemblyLoader.LoadFromPath(fullOriginalPath);
if (addReference && result.IsSuccessful)
{
var reference = _metadataFileProvider.GetReference(fullOriginalPath);
_options = _options.AddReferences(reference);
}
return result;
}
public ObjectHandle ExecuteAndWrap(string text)
{
return new ObjectHandle(ExecuteInner(Compile(text)));
}
private Script<object> Compile(string text, string path = null)
{
// note that the actual submission execution runs on the UI thread, not under this lock:
lock (_sessionGuard)
{
Script script = _repl.CreateScript(text).WithOptions(_options);
if (_lastResult != null)
{
script = script.WithPrevious(_lastResult.Script);
}
else
{
script = script.WithGlobalsType(_hostObject.GetType());
}
if (path != null)
{
script = script.WithPath(path).WithOptions(script.Options.WithIsInteractive(false));
}
// force build so exception is thrown now if errors are found.
script.Build();
// load all references specified in #r's -- they will all be PE references (may be shadow copied):
foreach (PortableExecutableReference reference in script.GetCompilation().DirectiveReferences)
{
// FullPath refers to the original reference path, not the copy:
LoadReference(reference.FilePath, suppressWarnings: false, addReference: false);
}
return (Script<object>)script;
}
}
/// <summary>
/// Executes specified script file as a submission.
/// </summary>
/// <param name="fullPath">Full source path.</param>
/// <returns>True if the code has been executed. False if the code doesn't compile.</returns>
/// <remarks>
/// All errors are written to the error output stream.
/// Uses source search paths to resolve unrooted paths.
/// </remarks>
private bool ExecuteFile(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
string content;
try
{
content = File.ReadAllText(fullPath);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
return false;
}
// TODO (tomat): engine.CompileSubmission shouldn't throw
Script<object> script;
try
{
script = Compile(content, fullPath);
}
catch (CompilationErrorException e)
{
DisplayInteractiveErrors(e.Diagnostics, Console.Error);
return false;
}
object result;
ExecuteOnUIThread(script, out result);
return true;
}
private void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths)
{
writer.WriteLine(attemptedFilePaths.Count == 1 ?
FeaturesResources.SearchedInDirectory :
FeaturesResources.SearchedInDirectories);
foreach (string path in attemptedFilePaths)
{
writer.Write(" ");
writer.WriteLine(Path.GetDirectoryName(path));
}
}
/// <summary>
/// Executes specified code.
/// </summary>
/// <param name="text">Source code.</param>
/// <returns>True if the code has been executed. False if the code doesn't compile.</returns>
/// <remarks>
/// All errors are written to the error output stream.
/// The resulting value (if any) is formatted and printed to the output stream.
/// </remarks>
private bool Execute(string text)
{
Script<object> script;
try
{
script = Compile(text);
}
catch (CompilationErrorException e)
{
DisplayInteractiveErrors(e.Diagnostics, Console.Error);
return false;
}
object result;
if (!ExecuteOnUIThread(script, out result))
{
return true;
}
bool hasValue;
var resultType = script.GetCompilation().GetSubmissionResultType(out hasValue);
if (hasValue)
{
if (resultType != null && resultType.SpecialType == SpecialType.System_Void)
{
Console.Out.WriteLine(_objectFormatter.VoidDisplayString);
}
else
{
Console.Out.WriteLine(_objectFormatter.FormatObject(result, _formattingOptions));
}
}
return true;
}
private class ExecuteSubmissionError
{
public readonly Exception Exception;
public ExecuteSubmissionError(Exception exception)
{
this.Exception = exception;
}
}
private bool ExecuteOnUIThread(Script<object> script, out object result)
{
result = s_ui.Invoke(new Func<object>(() =>
{
try
{
return ExecuteInner(script);
}
catch (Exception e)
{
return new ExecuteSubmissionError(e);
}
}));
var error = result as ExecuteSubmissionError;
if (error != null)
{
// TODO (tomat): format exception
Console.Error.WriteLine(error.Exception);
return false;
}
else
{
return true;
}
}
private object ExecuteInner(Script<object> script)
{
var globals = _lastResult != null ? (object)_lastResult : (object)_hostObject;
var result = script.RunAsync(globals, CancellationToken.None); // TODO
_lastResult = result;
var task = result.ReturnValue;
return task.Result; // For now, submissions are assumed to be synchronous.
}
private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output)
{
var displayedDiagnostics = new List<Diagnostic>();
const int MaxErrorCount = 5;
for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++)
{
displayedDiagnostics.Add(diagnostics[i]);
}
displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start);
var formatter = _repl.GetDiagnosticFormatter();
foreach (var diagnostic in displayedDiagnostics)
{
output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo));
}
if (diagnostics.Length > MaxErrorCount)
{
int notShown = diagnostics.Length - MaxErrorCount;
output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors"));
}
}
#endregion
#region Win32 API
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode SetErrorMode(ErrorMode mode);
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode GetErrorMode();
[Flags]
internal enum ErrorMode : int
{
/// <summary>
/// Use the system default, which is to display all error dialog boxes.
/// </summary>
SEM_FAILCRITICALERRORS = 0x0001,
/// <summary>
/// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
/// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup.
/// This is to prevent error mode dialogs from hanging the application.
/// </summary>
SEM_NOGPFAULTERRORBOX = 0x0002,
/// <summary>
/// The system automatically fixes memory alignment faults and makes them invisible to the application.
/// It does this for the calling process and any descendant processes. This feature is only supported by
/// certain processor architectures. For more information, see the Remarks section.
/// After this value is set for a process, subsequent attempts to clear the value are ignored.
/// </summary>
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
/// <summary>
/// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process.
/// </summary>
SEM_NOOPENFILEERRORBOX = 0x8000,
}
#endregion
#region Testing
// TODO(tomat): remove when the compiler supports events
// For testing purposes only!
public void HookMaliciousAssemblyResolve()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) =>
{
int i = 0;
while (true)
{
if (i < 10)
{
i = i + 1;
}
else if (i == 10)
{
Console.Error.WriteLine("in the loop");
i = i + 1;
}
}
});
}
public void RemoteConsoleWrite(byte[] data, bool isError)
{
using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput())
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
public bool IsShadowCopy(string path)
{
return _metadataFileProvider.IsShadowCopy(path);
}
#endregion
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Queue.Protocol;
using MS.Test.Common.MsTestLib;
using StorageTestLib;
using Management.Storage.ScenarioTest.Common;
namespace Management.Storage.ScenarioTest
{
/// <summary>
/// this class contains all the functional test cases for PowerShell Queue cmdlets
/// </summary>
[TestClass]
class CLIQueueFunc
{
private static CloudStorageAccount _StorageAccount;
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
Trace.WriteLine("ClassInit");
Test.FullClassName = testContext.FullyQualifiedTestClassName;
_StorageAccount = TestBase.GetCloudStorageAccountFromConfig();
// import module
string moduleFilePath = Test.Data.Get("ModuleFilePath");
if (moduleFilePath.Length > 0)
PowerShellAgent.ImportModule(moduleFilePath);
// $context = New-AzureStorageContext -ConnectionString ...
PowerShellAgent.SetStorageContext(_StorageAccount.ToString(true));
}
//
//Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void MyClassCleanup()
{
Trace.WriteLine("ClasssCleanup");
}
//Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
Trace.WriteLine("TestInit");
Test.Start(TestContext.FullyQualifiedTestClassName, TestContext.TestName);
}
//Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
Trace.WriteLine("TestCleanup");
// do not clean up the blobs here for investigation
// every test case should do cleanup in its init
Test.End(TestContext.FullyQualifiedTestClassName, TestContext.TestName);
}
#endregion
[TestMethod]
[TestCategory(Tag.Function)]
public void CreateInvalidQueue()
{
CreateInvalidQueue(new PowerShellAgent());
}
[TestMethod]
[TestCategory(Tag.Function)]
public void CreateExistingQueue()
{
CreateExistingQueue(new PowerShellAgent());
}
[TestMethod]
[TestCategory(Tag.Function)]
public void QueueListOperations()
{
QueueListOperations(new PowerShellAgent());
}
[TestMethod]
[TestCategory(Tag.Function)]
public void GetNonExistingQueue()
{
GetNonExistingQueue(new PowerShellAgent());
}
[TestMethod]
[TestCategory(Tag.Function)]
public void EnumerateAllQueues()
{
EnumerateAllQueues(new PowerShellAgent());
}
[TestMethod]
[TestCategory(Tag.Function)]
public void RemoveNonExistingQueue()
{
RemoveNonExistingQueue(new PowerShellAgent());
}
[TestMethod]
[TestCategory(Tag.Function)]
public void RemoveQueueWithoutForce()
{
RemoveQueueWithoutForce(new PowerShellAgent());
}
[TestMethod]
[TestCategory(Tag.Function)]
public void GetMessageCount()
{
GetMessageCount(new PowerShellAgent());
}
/// <summary>
/// Functional Cases : for New-AzureStorageQueue
/// 1. Create a list of new Queues (Positive 2)
/// 2. Create a list of Queues that already exist (Negative 4)
/// 3. Create a list of Queues that some of them already exist (Negative 5)
///
/// Functional Cases : for Get-AzureStorageQueue
/// 4. Get a list of Queues by using wildcards in the name (Positive 2)
///
/// Functional Cases : for Remove-AzureStorageQueue
/// 5. Remove a list of existing Queues by using pipeline (Positive 3)
/// </summary>
internal void QueueListOperations(Agent agent)
{
string PREFIX = Utility.GenNameString("uniqueprefix-") + "-";
string[] QUEUE_NAMES = new string[] { Utility.GenNameString(PREFIX), Utility.GenNameString(PREFIX), Utility.GenNameString(PREFIX) };
// PART_EXISTING_NAMES differs only the last element with Queue_NAMES
string[] PARTLY_EXISTING_NAMES = new string[QUEUE_NAMES.Length];
Array.Copy(QUEUE_NAMES, PARTLY_EXISTING_NAMES, QUEUE_NAMES.Length - 1);
PARTLY_EXISTING_NAMES[QUEUE_NAMES.Length - 1] = Utility.GenNameString(PREFIX);
string[] MERGED_NAMES = QUEUE_NAMES.Union(PARTLY_EXISTING_NAMES).ToArray();
Array.Sort(MERGED_NAMES);
// Generate the comparison data
Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>();
foreach (string name in MERGED_NAMES)
{
comp.Add(Utility.GenComparisonData(StorageObjectType.Queue, name));
}
CloudQueueClient queueClient = _StorageAccount.CreateCloudQueueClient();
// Check if all the above Queues have been removed
foreach (string name in MERGED_NAMES)
{
CloudQueue Queue = queueClient.GetQueueReference(name);
Queue.DeleteIfExists();
}
//--------------1. New operation--------------
Test.Assert(agent.NewAzureStorageQueue(QUEUE_NAMES), Utility.GenComparisonData("NewAzureStorageQueue", true));
// Verification for returned values
Test.Assert(agent.Output.Count == 3, "3 row returned : {0}", agent.Output.Count);
// Check if all the above queues have been created
foreach (string name in QUEUE_NAMES)
{
CloudQueue queue = queueClient.GetQueueReference(name);
Test.Assert(queue.Exists(), "queue {0} should exist", name);
}
try
{
//--------------2. New operation--------------
Test.Assert(!agent.NewAzureStorageQueue(QUEUE_NAMES), Utility.GenComparisonData("NewAzureStorageQueue", false));
// Verification for returned values
Test.Assert(agent.Output.Count == 0, "0 row returned : {0}", agent.Output.Count);
int i = 0;
foreach (string name in QUEUE_NAMES)
{
Test.Assert(agent.ErrorMessages[i].Equals(String.Format("Queue '{0}' already exists.", name)), agent.ErrorMessages[i]);
++i;
}
//--------------3. New operation--------------
Test.Assert(!agent.NewAzureStorageQueue(PARTLY_EXISTING_NAMES), Utility.GenComparisonData("NewAzureStorageQueue", false));
// Verification for returned values
Test.Assert(agent.Output.Count == 1, "1 row returned : {0}", agent.Output.Count);
// Check if all the above queues have been created
foreach (string name in QUEUE_NAMES)
{
CloudQueue queue = queueClient.GetQueueReference(name);
Test.Assert(queue.Exists(), "queue {0} should exist", name);
}
//--------------4. Get operation--------------
Test.Assert(agent.GetAzureStorageQueue("*" + PREFIX + "*"), Utility.GenComparisonData("GetAzureStorageQueue", true));
// Verification for returned values
agent.OutputValidation(_StorageAccount.CreateCloudQueueClient().ListQueues(PREFIX, QueueListingDetails.All));
// use Prefix parameter
Test.Assert(agent.GetAzureStorageQueueByPrefix(PREFIX), Utility.GenComparisonData("GetAzureStorageQueueByPrefix", true));
// Verification for returned values
agent.OutputValidation(_StorageAccount.CreateCloudQueueClient().ListQueues(PREFIX, QueueListingDetails.All));
}
finally {
//--------------5. Remove operation--------------
Test.Assert(agent.RemoveAzureStorageQueue(MERGED_NAMES), Utility.GenComparisonData("RemoveAzureStorageQueue", true));
// Check if all the above queues have been removed
foreach (string name in QUEUE_NAMES)
{
CloudQueue queue = queueClient.GetQueueReference(name);
Test.Assert(!queue.Exists(), "queue {0} should not exist", name);
}
}
}
/// <summary>
/// Negative Functional Cases : for New-AzureStorageQueue
/// 1. Create a Queue that already exists (Negative 3)
/// </summary>
internal void CreateExistingQueue(Agent agent)
{
string QUEUE_NAME = Utility.GenNameString("existing");
// create queue if not exists
CloudQueue queue = _StorageAccount.CreateCloudQueueClient().GetQueueReference(QUEUE_NAME);
queue.CreateIfNotExists();
try
{
//--------------New operation--------------
Test.Assert(!agent.NewAzureStorageQueue(QUEUE_NAME), Utility.GenComparisonData("NewAzureStorageQueue", false));
// Verification for returned values
Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count);
Test.Assert(agent.ErrorMessages[0].Equals(String.Format("Queue '{0}' already exists.", QUEUE_NAME)), agent.ErrorMessages[0]);
}
finally
{
// Recover the environment
queue.DeleteIfExists();
}
}
/// <summary>
/// Negative Functional Cases : for New-AzureStorageQueue
/// 1. Create a new queue with an invalid queue name (Negative 1)
/// </summary>
internal void CreateInvalidQueue(Agent agent)
{
string queueName = Utility.GenNameString("abc_");
//--------------New operation--------------
Test.Assert(!agent.NewAzureStorageQueue(queueName), Utility.GenComparisonData("NewAzureStorageQueue", false));
// Verification for returned values
Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count);
Test.Assert(agent.ErrorMessages[0].StartsWith(String.Format("Queue name '{0}' is invalid.", queueName)), agent.ErrorMessages[0]);
}
/// <summary>
/// Negative Functional Cases : for Get-AzureStorageQueue
/// 1. Get a non-existing queue (Negative 1)
/// </summary>
internal void GetNonExistingQueue(Agent agent)
{
string QUEUE_NAME = Utility.GenNameString("nonexisting");
// Delete the queue if it exists
CloudQueue queue = _StorageAccount.CreateCloudQueueClient().GetQueueReference(QUEUE_NAME);
queue.DeleteIfExists();
//--------------Get operation--------------
Test.Assert(!agent.GetAzureStorageQueue(QUEUE_NAME), Utility.GenComparisonData("GetAzureStorageQueue", false));
// Verification for returned values
Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count);
Test.Assert(agent.ErrorMessages[0].Equals(String.Format("Can not find queue '{0}'.", QUEUE_NAME)), agent.ErrorMessages[0]);
}
/// <summary>
/// Functional Cases : for Get-AzureStorageQueue
/// 1. Validate that all the queues can be enumerated (Positive 5)
/// </summary>
internal void EnumerateAllQueues(Agent agent)
{
//--------------Get operation--------------
Test.Assert(agent.GetAzureStorageQueue(""), Utility.GenComparisonData("EnumerateAllQueues", false));
// Verification for returned values
agent.OutputValidation(_StorageAccount.CreateCloudQueueClient().ListQueues());
}
/// <summary>
/// Negative Functional Cases : for Remove-AzureStorageQueue
/// 1. Remove a non-existing queue (Negative 2)
/// </summary>
internal void RemoveNonExistingQueue(Agent agent)
{
string QUEUE_NAME = Utility.GenNameString("nonexisting");
// Delete the queue if it exists
CloudQueue queue = _StorageAccount.CreateCloudQueueClient().GetQueueReference(QUEUE_NAME);
queue.DeleteIfExists();
//--------------Remove operation--------------
Test.Assert(!agent.RemoveAzureStorageQueue(QUEUE_NAME), Utility.GenComparisonData("RemoveAzureStorageQueue", false));
// Verification for returned values
Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count);
Test.Assert(agent.ErrorMessages[0].Equals(String.Format("Can not find queue '{0}'.", QUEUE_NAME)), agent.ErrorMessages[0]);
}
/// <summary>
/// Negative Functional Cases : for Remove-AzureStorageQueue
/// 1. Remove the queue without by force (Negative 3)
/// </summary>
internal void RemoveQueueWithoutForce(Agent agent)
{
string QUEUE_NAME = Utility.GenNameString("withoutforce-");
// create queue if not exists
CloudQueue queue = _StorageAccount.CreateCloudQueueClient().GetQueueReference(QUEUE_NAME);
queue.CreateIfNotExists();
try
{
//--------------Remove operation--------------
Test.Assert(!agent.RemoveAzureStorageQueue(QUEUE_NAME, false), Utility.GenComparisonData("RemoveAzureStorageQueue", false));
// Verification for returned values
Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count);
Test.Assert(agent.ErrorMessages[0].StartsWith("A command that prompts the user failed because"), agent.ErrorMessages[0]);
}
finally
{
queue.DeleteIfExists();
}
}
/// <summary>
/// Positive Functional Cases : for Get-AzureStorageQueue
/// 1. Get the ApproximateMessageCount of the queue (Positive 5)
/// </summary>
internal void GetMessageCount(Agent agent)
{
const int MAX_SIZE = 32;
string QUEUE_NAME = Utility.GenNameString("messagecount-");
// create queue if not exists
CloudQueue queue = _StorageAccount.CreateCloudQueueClient().GetQueueReference(QUEUE_NAME);
queue.CreateIfNotExists();
// insert random count queues
Random random = new Random();
int count = random.Next(MAX_SIZE) + 1; // count >= 1
for (int i = 1; i <= count; ++i)
queue.AddMessage(new CloudQueueMessage("message " + i));
// generate comparsion data
Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>();
var dic = Utility.GenComparisonData(StorageObjectType.Queue, QUEUE_NAME);
dic["ApproximateMessageCount"] = count;
comp.Add(dic);
try
{
//--------------Get operation--------------
Test.Assert(agent.GetAzureStorageQueue(QUEUE_NAME), Utility.GenComparisonData("GetAzureStorageQueue", true));
// Verification for returned values
agent.OutputValidation(comp);
}
finally
{
queue.DeleteIfExists();
}
}
}
}
| |
/**
* 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.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace Thrift.Transport
{
/// <summary>
/// SSL Socket Wrapper class
/// </summary>
public class TTLSSocket : TStreamTransport
{
/// <summary>
/// Internal TCP Client
/// </summary>
private TcpClient client;
/// <summary>
/// The host
/// </summary>
private readonly string host;
/// <summary>
/// The port
/// </summary>
private readonly int port;
/// <summary>
/// The timeout for the connection
/// </summary>
private int timeout;
/// <summary>
/// Internal SSL Stream for IO
/// </summary>
private SslStream secureStream;
/// <summary>
/// Defines wheter or not this socket is a server socket<br/>
/// This is used for the TLS-authentication
/// </summary>
private readonly bool isServer;
/// <summary>
/// The certificate
/// </summary>
private readonly X509Certificate certificate;
/// <summary>
/// User defined certificate validator.
/// </summary>
private readonly RemoteCertificateValidationCallback certValidator;
/// <summary>
/// The function to determine which certificate to use.
/// </summary>
private readonly LocalCertificateSelectionCallback localCertificateSelectionCallback;
/// <summary>
/// Initializes a new instance of the <see cref="TTLSSocket"/> class.
/// </summary>
/// <param name="client">An already created TCP-client</param>
/// <param name="certificate">The certificate.</param>
/// <param name="isServer">if set to <c>true</c> [is server].</param>
/// <param name="certValidator">User defined cert validator.</param>
/// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
public TTLSSocket(
TcpClient client,
X509Certificate certificate,
bool isServer = false,
RemoteCertificateValidationCallback certValidator = null,
LocalCertificateSelectionCallback localCertificateSelectionCallback = null)
{
this.client = client;
this.certificate = certificate;
this.certValidator = certValidator;
this.localCertificateSelectionCallback = localCertificateSelectionCallback;
this.isServer = isServer;
if (IsOpen)
{
base.inputStream = client.GetStream();
base.outputStream = client.GetStream();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="TTLSSocket"/> class.
/// </summary>
/// <param name="host">The host, where the socket should connect to.</param>
/// <param name="port">The port.</param>
/// <param name="certificatePath">The certificate path.</param>
/// <param name="certValidator">User defined cert validator.</param>
/// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
public TTLSSocket(
string host,
int port,
string certificatePath,
RemoteCertificateValidationCallback certValidator = null,
LocalCertificateSelectionCallback localCertificateSelectionCallback = null)
: this(host, port, 0, new X509Certificate(certificatePath), certValidator, localCertificateSelectionCallback)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TTLSSocket"/> class.
/// </summary>
/// <param name="host">The host, where the socket should connect to.</param>
/// <param name="port">The port.</param>
/// <param name="certificate">The certificate.</param>
/// <param name="certValidator">User defined cert validator.</param>
/// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
public TTLSSocket(
string host,
int port,
X509Certificate certificate,
RemoteCertificateValidationCallback certValidator = null,
LocalCertificateSelectionCallback localCertificateSelectionCallback = null)
: this(host, port, 0, certificate, certValidator, localCertificateSelectionCallback)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TTLSSocket"/> class.
/// </summary>
/// <param name="host">The host, where the socket should connect to.</param>
/// <param name="port">The port.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="certificate">The certificate.</param>
/// <param name="certValidator">User defined cert validator.</param>
/// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
public TTLSSocket(
string host,
int port,
int timeout,
X509Certificate certificate,
RemoteCertificateValidationCallback certValidator = null,
LocalCertificateSelectionCallback localCertificateSelectionCallback = null)
{
this.host = host;
this.port = port;
this.timeout = timeout;
this.certificate = certificate;
this.certValidator = certValidator;
this.localCertificateSelectionCallback = localCertificateSelectionCallback;
InitSocket();
}
/// <summary>
/// Creates the TcpClient and sets the timeouts
/// </summary>
private void InitSocket()
{
this.client = new TcpClient();
client.ReceiveTimeout = client.SendTimeout = timeout;
// In linux calling client.Client will cause ConnectAsync(string, int) throw the System.PlatformNotSupportedException.
// Once we access TcpClient.Client in linux, a wrong System.PlatformNotSupportedException will be thrown. It's a bug of System.Net.Sockets
// So change to client.NoDelay instead of client.Client.NoDelay
client.NoDelay = true;
}
/// <summary>
/// Sets Send / Recv Timeout for IO
/// </summary>
public int Timeout
{
set
{
this.client.ReceiveTimeout = this.client.SendTimeout = this.timeout = value;
}
}
/// <summary>
/// Gets the TCP client.
/// </summary>
public TcpClient TcpClient
{
get
{
return client;
}
}
/// <summary>
/// Gets the host.
/// </summary>
public string Host
{
get
{
return host;
}
}
/// <summary>
/// Gets the port.
/// </summary>
public int Port
{
get
{
return port;
}
}
/// <summary>
/// Gets a value indicating whether TCP Client is Cpen
/// </summary>
public override bool IsOpen
{
get
{
if (this.client == null)
{
return false;
}
return this.client.Connected;
}
}
/// <summary>
/// Validates the certificates!<br/>
/// </summary>
/// <param name="sender">The sender-object.</param>
/// <param name="certificate">The used certificate.</param>
/// <param name="chain">The certificate chain.</param>
/// <param name="sslPolicyErrors">An enum, which lists all the errors from the .NET certificate check.</param>
/// <returns></returns>
private bool DefaultCertificateValidator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslValidationErrors)
{
return (sslValidationErrors == SslPolicyErrors.None);
}
/// <summary>
/// Connects to the host and starts the routine, which sets up the TLS
/// </summary>
public override void Open()
{
if (IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
}
if (string.IsNullOrEmpty(host))
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
}
if (port <= 0)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
}
if (client == null)
{
InitSocket();
}
#if NETSTANDARD1_4 || NETSTANDARD1_5
client.ConnectAsync(host, port).Wait();
#else
client.Connect(host, port);
#endif
setupTLS();
}
/// <summary>
/// Creates a TLS-stream and lays it over the existing socket
/// </summary>
public void setupTLS()
{
RemoteCertificateValidationCallback validator = this.certValidator ?? DefaultCertificateValidator;
if( this.localCertificateSelectionCallback != null)
{
this.secureStream = new SslStream(
this.client.GetStream(),
false,
validator,
this.localCertificateSelectionCallback
);
}
else
{
this.secureStream = new SslStream(
this.client.GetStream(),
false,
validator
);
}
try
{
if (isServer)
{
// Server authentication
#if NETSTANDARD1_4 || NETSTANDARD1_5
this.secureStream.AuthenticateAsServerAsync(this.certificate, this.certValidator != null, SslProtocols.Tls, true).Wait();
#else
this.secureStream.AuthenticateAsServer(this.certificate, this.certValidator != null, SslProtocols.Tls, true);
#endif
}
else
{
// Client authentication
#if NETSTANDARD1_4 || NETSTANDARD1_5
this.secureStream.AuthenticateAsClientAsync(host, new X509CertificateCollection { certificate }, SslProtocols.Tls, true).Wait();
#else
this.secureStream.AuthenticateAsClient(host, new X509CertificateCollection { certificate }, SslProtocols.Tls, true);
#endif
}
}
catch (Exception)
{
this.Close();
throw;
}
inputStream = this.secureStream;
outputStream = this.secureStream;
}
/// <summary>
/// Closes the SSL Socket
/// </summary>
public override void Close()
{
base.Close();
if (this.client != null)
{
#if NETSTANDARD1_4 || NETSTANDARD1_5
this.client.Dispose();
#else
this.client.Close();
#endif
this.client = null;
}
if (this.secureStream != null)
{
this.secureStream.Dispose();
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/9/2009 2:07:29 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace DotSpatial.Data
{
public class AttributeCache : IEnumerable<Dictionary<string, object>>
{
private static int _rowsPerPage;
private readonly IAttributeSource _dataSupply;
/// <summary>
/// The row being edited
/// </summary>
public Dictionary<string, object> EditRow { get; set; }
/// <summary>
/// The pages currently stored in the cache
/// </summary>
public DataPage[] Pages { get; set; }
private int _editRowIndex;
/// <summary>
/// Constructs a new Cache object that can create data tables by using a DataPageRetriever
/// </summary>
/// <param name="dataSupplier">Any structure that implements IDataPageRetriever</param>
/// <param name="rowsPerPage">The rows per page</param>
public AttributeCache(IAttributeSource dataSupplier, int rowsPerPage)
{
_dataSupply = dataSupplier;
_rowsPerPage = rowsPerPage;
_editRowIndex = -1;
LoadFirstTwoPages();
}
/// <summary>
/// The integer index of the row being edited
/// </summary>
public int EditRowIndex
{
get { return _editRowIndex; }
set
{
if (value < 0 || value >= _dataSupply.NumRows())
{
EditRow = null;
return;
}
EditRow = RetrieveElement(value);
_editRowIndex = value;
}
}
/// <summary>
/// The number of rows in the data supply
/// </summary>
public int NumRows
{
get { return _dataSupply.NumRows(); }
}
#region IEnumerable<Dictionary<string,object>> Members
/// <inheritdoc />
public IEnumerator<Dictionary<string, object>> GetEnumerator()
{
return new AttributeCacheEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new AttributeCacheEnumerator(this);
}
#endregion
/// <summary>
/// Saves the changes in the edit row to the tabular cache as well as the underlying database
/// </summary>
public void SaveChanges()
{
_dataSupply.Edit(EditRowIndex, EditRow);
DataRow dr = null;
if (IsRowCachedInPage(0, _editRowIndex))
{
dr = Pages[0].Table.Rows[_editRowIndex];
}
if (IsRowCachedInPage(1, _editRowIndex))
{
dr = Pages[1].Table.Rows[_editRowIndex];
}
if (dr == null) return;
foreach (KeyValuePair<string, object> pair in EditRow)
{
dr[pair.Key] = pair.Value;
}
}
// Sets the value of the element parameter if the value is in the cache.
private bool IfPageCachedThenSetElement(int rowIndex,
int columnIndex, ref object element)
{
element = string.Empty;
int index = rowIndex % _rowsPerPage;
if (IsRowCachedInPage(0, rowIndex))
{
if (Pages[0].Table.Rows.Count <= index) return true;
element = Pages[0].Table.Rows[index][columnIndex];
return true;
}
if (IsRowCachedInPage(1, rowIndex))
{
if (Pages[1].Table.Rows.Count <= index) return true;
element = Pages[1].Table.Rows[index][columnIndex];
return true;
}
return false;
}
// Sets the value of the element parameter if the value is in the cache.
private bool IfPageCachedThenSetElement(int rowIndex, ref Dictionary<string, object> element)
{
if (IsRowCachedInPage(0, rowIndex))
{
DataRow dr = Pages[0].Table.Rows[rowIndex % _rowsPerPage];
foreach (DataColumn column in Pages[0].Table.Columns)
{
string name = column.ColumnName;
element.Add(name, dr[name]);
}
return true;
}
if (IsRowCachedInPage(1, rowIndex))
{
DataRow dr = Pages[1].Table.Rows[rowIndex % _rowsPerPage];
foreach (DataColumn column in Pages[0].Table.Columns)
{
string name = column.ColumnName;
element.Add(name, dr[name]);
}
return true;
}
return false;
}
/// <summary>
/// Obtains the element at the specified index
/// </summary>
/// <param name="rowIndex"></param>
/// <returns></returns>
public Dictionary<string, object> RetrieveElement(int rowIndex)
{
if (EditRowIndex == rowIndex)
{
return EditRow;
}
Dictionary<string, object> element = new Dictionary<string, object>();
if (IfPageCachedThenSetElement(rowIndex, ref element))
{
return element;
}
return RetrieveDataCacheItThenReturnElement(rowIndex);
}
/// <summary>
/// Obtains the element at the specified index
/// </summary>
/// <param name="rowIndex"></param>
/// <param name="columnIndex"></param>
/// <returns></returns>
public object RetrieveElement(int rowIndex, int columnIndex)
{
object element = null;
DataColumn[] columns = _dataSupply.GetColumns();
if (rowIndex == _editRowIndex && EditRow != null)
{
return EditRow[columns[columnIndex].ColumnName];
}
if (IfPageCachedThenSetElement(rowIndex, columnIndex, ref element))
{
return element;
}
return RetrieveDataCacheItThenReturnElement(
rowIndex, columnIndex);
}
private void LoadFirstTwoPages()
{
DataPage p1 = new DataPage(_dataSupply.GetAttributes(DataPage.MapToLowerBoundary(0), _rowsPerPage), 0);
DataPage p2 =
new DataPage(_dataSupply.GetAttributes(DataPage.MapToLowerBoundary(_rowsPerPage), _rowsPerPage),
_rowsPerPage);
Pages = new[] { p1, p2 };
}
private object RetrieveDataCacheItThenReturnElement(
int rowIndex, int columnIndex)
{
// Retrieve a page worth of data containing the requested value.
DataTable table = _dataSupply.GetAttributes(
DataPage.MapToLowerBoundary(rowIndex), _rowsPerPage);
// Replace the cached page furthest from the requested cell
// with a new page containing the newly retrieved data.
Pages[GetIndexToUnusedPage(rowIndex)] = new DataPage(table, rowIndex);
return RetrieveElement(rowIndex, columnIndex);
}
private Dictionary<string, object> RetrieveDataCacheItThenReturnElement(int rowIndex)
{
// Retrieve a page worth of data containing the requested value.
DataTable table = _dataSupply.GetAttributes(DataPage.MapToLowerBoundary(rowIndex), _rowsPerPage);
// Replace the cached page furthest from the requested cell
// with a new page containing the newly retrieved data.
Pages[GetIndexToUnusedPage(rowIndex)] = new DataPage(table, rowIndex);
return RetrieveElement(rowIndex);
}
// Returns the index of the cached page most distant from the given index
// and therefore least likely to be reused.
private int GetIndexToUnusedPage(int rowIndex)
{
if (rowIndex > Pages[0].HighestIndex &&
rowIndex > Pages[1].HighestIndex)
{
int offsetFromPage0 = rowIndex - Pages[0].HighestIndex;
int offsetFromPage1 = rowIndex - Pages[1].HighestIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
else
{
int offsetFromPage0 = Pages[0].LowestIndex - rowIndex;
int offsetFromPage1 = Pages[1].LowestIndex - rowIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
}
// Returns a value indicating whether the given row index is contained
// in the given DataPage.
private bool IsRowCachedInPage(int pageNumber, int rowIndex)
{
return rowIndex <= Pages[pageNumber].HighestIndex &&
rowIndex >= Pages[pageNumber].LowestIndex;
}
#region Nested type: AttributeCacheEnumerator
/// <summary>
/// Enumerates the dictionaries that represent row content stored by field name.
/// </summary>
private class AttributeCacheEnumerator : IEnumerator<Dictionary<string, object>>
{
private readonly AttributeCache _cache;
private int _row;
private Dictionary<string, object> _rowContent;
/// <summary>
/// Creates a new AttributeCacheEnumerator
/// </summary>
/// <param name="cache"></param>
public AttributeCacheEnumerator(AttributeCache cache)
{
_cache = cache;
}
#region IEnumerator<Dictionary<string,object>> Members
/// <inheritdoc />
public Dictionary<string, object> Current
{
get { return _rowContent; }
}
/// <inheritdoc />
public void Dispose()
{
}
/// <inheritdoc />
object IEnumerator.Current
{
get { return _rowContent; }
}
/// <inheritdoc />
public bool MoveNext()
{
_row += 1;
if (_row >= _cache._dataSupply.NumRows()) return false;
_rowContent = _cache.RetrieveElement(_row);
return true;
}
/// <inheritdoc />
public void Reset()
{
_row = -1;
}
#endregion
}
#endregion
#region Nested type: DataPage
/// <summary>
/// Represents one page of data.
/// </summary>
public struct DataPage
{
/// <summary>
/// The data Table
/// </summary>
public readonly DataTable Table;
private readonly int _highestIndexValue;
private readonly int _lowestIndexValue;
/// <summary>
/// A Data page representing one page of data-row values
/// </summary>
/// <param name="table">The DataTable that controls the content</param>
/// <param name="rowIndex">The integer row index</param>
public DataPage(DataTable table, int rowIndex)
{
Table = table;
_lowestIndexValue = MapToLowerBoundary(rowIndex);
_highestIndexValue = MapToUpperBoundary(rowIndex);
Debug.Assert(_lowestIndexValue >= 0);
Debug.Assert(_highestIndexValue >= 0);
}
/// <summary>
/// The integer lowest index of the page
/// </summary>
public int LowestIndex
{
get
{
return _lowestIndexValue;
}
}
/// <summary>
/// The integer highest index of the page
/// </summary>
public int HighestIndex
{
get
{
return _highestIndexValue;
}
}
/// <summary>
/// Tests to see if the specified index is in this page.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public bool Contains(int index)
{
return index > _lowestIndexValue && index < _highestIndexValue;
}
/// <summary>
/// Given an arbitrary row index, this calculates what the lower boundary would be for the page containing the index
/// </summary>
/// <param name="rowIndex"></param>
/// <returns></returns>
public static int MapToLowerBoundary(int rowIndex)
{
// Return the lowest index of a page containing the given index.
return (rowIndex / _rowsPerPage) * _rowsPerPage;
}
/// <summary>
/// Given an arbitrary row index, this calculates the upper boundary for the page containing the index
/// </summary>
/// <param name="rowIndex"></param>
/// <returns></returns>
private static int MapToUpperBoundary(int rowIndex)
{
// Return the highest index of a page containing the given index.
return MapToLowerBoundary(rowIndex) + _rowsPerPage - 1;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using Xunit;
namespace System.IO
{
public class FileSystemAclExtensionsTests
{
private const int DefaultBufferSize = 4096;
#region Test methods
#region GetAccessControl
[Fact]
public void GetAccessControl_DirectoryInfo_InvalidArguments()
{
Assert.Throws<NullReferenceException>(() => FileSystemAclExtensions.GetAccessControl((DirectoryInfo)null));
}
[Fact]
public void GetAccessControl_DirectoryInfo_ReturnsValidObject()
{
using (var directory = new TempDirectory())
{
DirectoryInfo directoryInfo = new DirectoryInfo(directory.Path);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
Assert.NotNull(directorySecurity);
Assert.Equal(typeof(FileSystemRights), directorySecurity.AccessRightType);
}
}
[Fact]
public void GetAccessControl_DirectoryInfo_AccessControlSections_InvalidArguments()
{
Assert.Throws<NullReferenceException>(() => FileSystemAclExtensions.GetAccessControl((DirectoryInfo)null, new AccessControlSections()));
}
[Fact]
public void GetAccessControl_DirectoryInfo_AccessControlSections_ReturnsValidObject()
{
using (var directory = new TempDirectory())
{
DirectoryInfo directoryInfo = new DirectoryInfo(directory.Path);
AccessControlSections accessControlSections = new AccessControlSections();
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(accessControlSections);
Assert.NotNull(directorySecurity);
Assert.Equal(typeof(FileSystemRights), directorySecurity.AccessRightType);
}
}
[Fact]
public void GetAccessControl_FileInfo_InvalidArguments()
{
Assert.Throws<NullReferenceException>(() => FileSystemAclExtensions.GetAccessControl((FileInfo)null));
}
[Fact]
public void GetAccessControl_FileInfo_ReturnsValidObject()
{
using (var directory = new TempDirectory())
using (var file = new TempFile(Path.Combine(directory.Path, "file.txt")))
{
FileInfo fileInfo = new FileInfo(file.Path);
FileSecurity fileSecurity = fileInfo.GetAccessControl();
Assert.NotNull(fileSecurity);
Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType);
}
}
[Fact]
public void GetAccessControl_FileInfo_AccessControlSections_InvalidArguments()
{
Assert.Throws<NullReferenceException>(() => FileSystemAclExtensions.GetAccessControl((FileInfo)null, new AccessControlSections()));
}
[Fact]
public void GetAccessControl_FileInfo_AccessControlSections_ReturnsValidObject()
{
using (var directory = new TempDirectory())
using (var file = new TempFile(Path.Combine(directory.Path, "file.txt")))
{
FileInfo fileInfo = new FileInfo(file.Path);
AccessControlSections accessControlSections = new AccessControlSections();
FileSecurity fileSecurity = fileInfo.GetAccessControl(accessControlSections);
Assert.NotNull(fileSecurity);
Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType);
}
}
[Fact]
public void GetAccessControl_Filestream_InvalidArguments()
{
Assert.Throws<NullReferenceException>(() => FileSystemAclExtensions.GetAccessControl((FileStream)null));
}
[Fact]
public void GetAccessControl_Filestream_ReturnValidObject()
{
using (var directory = new TempDirectory())
using (var file = new TempFile(Path.Combine(directory.Path, "file.txt")))
using (FileStream fileStream = File.Open(file.Path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None))
{
FileSecurity fileSecurity = FileSystemAclExtensions.GetAccessControl(fileStream);
Assert.NotNull(fileSecurity);
Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType);
}
}
#endregion
#region SetAccessControl
[Fact]
public void SetAccessControl_DirectoryInfo_DirectorySecurity_InvalidArguments()
{
using (var directory = new TempDirectory())
{
DirectoryInfo directoryInfo = new DirectoryInfo(directory.Path);
AssertExtensions.Throws<ArgumentNullException>("directorySecurity", () => directoryInfo.SetAccessControl((DirectorySecurity)null));
}
}
[Fact]
public void SetAccessControl_DirectoryInfo_DirectorySecurity_Success()
{
using (var directory = new TempDirectory())
{
DirectoryInfo directoryInfo = new DirectoryInfo(directory.Path);
DirectorySecurity directorySecurity = new DirectorySecurity();
directoryInfo.SetAccessControl(directorySecurity);
}
}
[Fact]
public void SetAccessControl_FileInfo_FileSecurity_InvalidArguments()
{
using (var directory = new TempDirectory())
using (var file = new TempFile(Path.Combine(directory.Path, "file.txt")))
{
FileInfo fileInfo = new FileInfo(file.Path);
AssertExtensions.Throws<ArgumentNullException>("fileSecurity", () => fileInfo.SetAccessControl((FileSecurity)null));
}
}
[Fact]
public void SetAccessControl_FileInfo_FileSecurity_Success()
{
using (var directory = new TempDirectory())
using (var file = new TempFile(Path.Combine(directory.Path, "file.txt")))
{
FileInfo fileInfo = new FileInfo(file.Path);
FileSecurity fileSecurity = new FileSecurity();
fileInfo.SetAccessControl(fileSecurity);
}
}
[Fact]
public void SetAccessControl_FileStream_FileSecurity_InvalidArguments()
{
Assert.Throws<NullReferenceException>(() => FileSystemAclExtensions.SetAccessControl((FileStream)null, (FileSecurity)null));
}
[Fact]
public void SetAccessControl_FileStream_FileSecurity_InvalidFileSecurityObject()
{
using (var directory = new TempDirectory())
using (var file = new TempFile(Path.Combine(directory.Path, "file.txt")))
using (FileStream fileStream = File.Open(file.Path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None))
{
AssertExtensions.Throws<ArgumentNullException>("fileSecurity", () => FileSystemAclExtensions.SetAccessControl(fileStream, (FileSecurity)null));
}
}
[Fact]
public void SetAccessControl_FileStream_FileSecurity_Success()
{
using (var directory = new TempDirectory())
using (var file = new TempFile(Path.Combine(directory.Path, "file.txt")))
using (FileStream fileStream = File.Open(file.Path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None))
{
FileSecurity fileSecurity = new FileSecurity();
FileSystemAclExtensions.SetAccessControl(fileStream, fileSecurity);
}
}
#endregion
#region DirectoryInfo Create
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void DirectoryInfo_Create_NullDirectoryInfo()
{
DirectoryInfo info = null;
DirectorySecurity security = new DirectorySecurity();
Assert.Throws<ArgumentNullException>("directoryInfo", () =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, security);
}
else
{
info.Create(security);
}
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void DirectoryInfo_Create_NullDirectorySecurity()
{
DirectoryInfo info = new DirectoryInfo("path");
Assert.Throws<ArgumentNullException>("directorySecurity", () =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, null);
}
else
{
info.Create(null);
}
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void DirectoryInfo_Create_NotFound()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.Path, Guid.NewGuid().ToString(), "ParentDoesNotExist");
DirectoryInfo info = new DirectoryInfo(path);
DirectorySecurity security = new DirectorySecurity();
Assert.Throws<UnauthorizedAccessException>(() =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, security);
}
else
{
info.Create(security);
}
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void DirectoryInfo_Create_DefaultDirectorySecurity()
{
DirectorySecurity security = new DirectorySecurity();
VerifyDirectorySecurity(security);
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.ReadAndExecute, AccessControlType.Allow)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.ReadAndExecute, AccessControlType.Deny)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.WriteData, AccessControlType.Allow)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.WriteData, AccessControlType.Deny)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.FullControl, AccessControlType.Allow)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.FullControl, AccessControlType.Deny)]
public void DirectoryInfo_Create_DirectorySecurityWithSpecificAccessRule(
WellKnownSidType sid,
FileSystemRights rights,
AccessControlType controlType)
{
DirectorySecurity security = GetDirectorySecurity(sid, rights, controlType);
VerifyDirectorySecurity(security);
}
#endregion
#region FileInfo Create
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void FileInfo_Create_NullFileInfo()
{
FileInfo info = null;
FileSecurity security = new FileSecurity();
Assert.Throws<ArgumentNullException>("fileInfo", () =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, FileMode.Create, FileSystemRights.WriteData, FileShare.Read, DefaultBufferSize, FileOptions.None, security);
}
else
{
info.Create(FileMode.Create, FileSystemRights.WriteData, FileShare.Read, DefaultBufferSize, FileOptions.None, security);
}
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void FileInfo_Create_NullFileSecurity()
{
FileInfo info = new FileInfo("path");
Assert.Throws<ArgumentNullException>("fileSecurity", () =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, FileMode.Create, FileSystemRights.WriteData, FileShare.Read, DefaultBufferSize, FileOptions.None, null);
}
else
{
info.Create(FileMode.Create, FileSystemRights.WriteData, FileShare.Read, DefaultBufferSize, FileOptions.None, null);
}
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void FileInfo_Create_NotFound()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.Path, Guid.NewGuid().ToString(), "file.txt");
FileInfo info = new FileInfo(path);
FileSecurity security = new FileSecurity();
Assert.Throws<DirectoryNotFoundException>(() =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, FileMode.Create, FileSystemRights.WriteData, FileShare.Read, DefaultBufferSize, FileOptions.None, security);
}
else
{
info.Create(FileMode.Create, FileSystemRights.WriteData, FileShare.Read, DefaultBufferSize, FileOptions.None, security);
}
});
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[InlineData((FileMode)int.MinValue)]
[InlineData((FileMode)0)]
[InlineData((FileMode)int.MaxValue)]
public void FileInfo_Create_FileSecurity_InvalidFileMode(FileMode invalidMode)
{
FileSecurity security = new FileSecurity();
FileInfo info = new FileInfo("path");
Assert.Throws<ArgumentOutOfRangeException>("mode", () =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, invalidMode, FileSystemRights.WriteData, FileShare.Read, DefaultBufferSize, FileOptions.None, security); ;
}
else
{
info.Create(invalidMode, FileSystemRights.WriteData, FileShare.Read, DefaultBufferSize, FileOptions.None, security);
}
});
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[InlineData((FileShare)(-1))]
[InlineData((FileShare)int.MaxValue)]
public void FileInfo_Create_FileSecurity_InvalidFileShare(FileShare invalidFileShare)
{
FileSecurity security = new FileSecurity();
FileInfo info = new FileInfo("path");
Assert.Throws<ArgumentOutOfRangeException>("share", () =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, FileMode.Create, FileSystemRights.WriteData, invalidFileShare, DefaultBufferSize, FileOptions.None, security);
}
else
{
info.Create(FileMode.Create, FileSystemRights.WriteData, invalidFileShare, DefaultBufferSize, FileOptions.None, security);
}
});
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[InlineData(int.MinValue)]
[InlineData(0)]
public void FileInfo_Create_FileSecurity_InvalidBufferSize(int invalidBufferSize)
{
FileSecurity security = new FileSecurity();
FileInfo info = new FileInfo("path");
Assert.Throws<ArgumentOutOfRangeException>("bufferSize", () =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, FileMode.Create, FileSystemRights.WriteData, FileShare.Read, invalidBufferSize, FileOptions.None, security);
}
else
{
info.Create(FileMode.Create, FileSystemRights.WriteData, FileShare.Read, invalidBufferSize, FileOptions.None, security);
}
});
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[InlineData(FileMode.Truncate, FileSystemRights.Read)]
[InlineData(FileMode.Truncate, FileSystemRights.ReadData)]
[InlineData(FileMode.CreateNew, FileSystemRights.Read)]
[InlineData(FileMode.CreateNew, FileSystemRights.ReadData)]
[InlineData(FileMode.Create, FileSystemRights.Read)]
[InlineData(FileMode.Create, FileSystemRights.ReadData)]
[InlineData(FileMode.Append, FileSystemRights.Read)]
[InlineData(FileMode.Append, FileSystemRights.ReadData)]
public void FileInfo_Create_FileSecurity_ForbiddenCombo_FileModeFileSystemSecurity(FileMode mode, FileSystemRights rights)
{
FileSecurity security = new FileSecurity();
FileInfo info = new FileInfo("path");
Assert.Throws<ArgumentException>(() =>
{
if (PlatformDetection.IsFullFramework)
{
FileSystemAclExtensions.Create(info, mode, rights, FileShare.Read, DefaultBufferSize, FileOptions.None, security);
}
else
{
info.Create(mode, rights, FileShare.Read, DefaultBufferSize, FileOptions.None, security);
}
});
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void FileInfo_Create_DefaultFileSecurity()
{
FileSecurity security = new FileSecurity();
VerifyFileSecurity(security);
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.ReadAndExecute, AccessControlType.Allow)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.ReadAndExecute, AccessControlType.Deny)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.WriteData, AccessControlType.Allow)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.WriteData, AccessControlType.Deny)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.FullControl, AccessControlType.Allow)]
[InlineData(WellKnownSidType.BuiltinUsersSid, FileSystemRights.FullControl, AccessControlType.Deny)]
public void FileInfo_Create_FileSecurity_SpecificAccessRule(WellKnownSidType sid, FileSystemRights rights, AccessControlType controlType)
{
FileSecurity security = GetFileSecurity(sid, rights, controlType);
VerifyFileSecurity(security);
}
#endregion
#endregion
#region Helper methods
private DirectorySecurity GetDirectorySecurity(WellKnownSidType sid, FileSystemRights rights, AccessControlType controlType)
{
DirectorySecurity security = new DirectorySecurity();
SecurityIdentifier identity = new SecurityIdentifier(sid, null);
FileSystemAccessRule accessRule = new FileSystemAccessRule(identity, rights, controlType);
security.AddAccessRule(accessRule);
return security;
}
private void VerifyDirectorySecurity(DirectorySecurity expectedSecurity)
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.Path, "directory");
DirectoryInfo info = new DirectoryInfo(path);
info.Create(expectedSecurity);
Assert.True(Directory.Exists(path));
DirectoryInfo actualInfo = new DirectoryInfo(info.FullName);
DirectorySecurity actualSecurity = actualInfo.GetAccessControl();
VerifyAccessSecurity(expectedSecurity, actualSecurity);
}
private FileSecurity GetFileSecurity(WellKnownSidType sid, FileSystemRights rights, AccessControlType controlType)
{
FileSecurity security = new FileSecurity();
SecurityIdentifier identity = new SecurityIdentifier(sid, null);
FileSystemAccessRule accessRule = new FileSystemAccessRule(identity, rights, controlType);
security.AddAccessRule(accessRule);
return security;
}
private void VerifyFileSecurity(FileSecurity expectedSecurity)
{
VerifyFileSecurity(FileMode.Create, FileSystemRights.WriteData, FileShare.Read, DefaultBufferSize, FileOptions.None, expectedSecurity);
}
private void VerifyFileSecurity(FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity expectedSecurity)
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.Path, "file.txt");
FileInfo info = new FileInfo(path);
info.Create(mode, rights, share, bufferSize, options, expectedSecurity);
Assert.True(File.Exists(path));
FileInfo actualInfo = new FileInfo(info.FullName);
FileSecurity actualSecurity = actualInfo.GetAccessControl();
VerifyAccessSecurity(expectedSecurity, actualSecurity);
}
private void VerifyAccessSecurity(CommonObjectSecurity expectedSecurity, CommonObjectSecurity actualSecurity)
{
Assert.Equal(typeof(FileSystemRights), expectedSecurity.AccessRightType);
Assert.Equal(typeof(FileSystemRights), actualSecurity.AccessRightType);
List<FileSystemAccessRule> expectedAccessRules = expectedSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier))
.Cast<FileSystemAccessRule>().ToList();
List<FileSystemAccessRule> actualAccessRules = actualSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier))
.Cast<FileSystemAccessRule>().ToList();
Assert.Equal(expectedAccessRules.Count, actualAccessRules.Count);
if (expectedAccessRules.Count > 0)
{
Assert.All(expectedAccessRules, actualAccessRule =>
{
int count = expectedAccessRules.Count(expectedAccessRule => AreAccessRulesEqual(expectedAccessRule, actualAccessRule));
Assert.True(count > 0);
});
}
}
private bool AreAccessRulesEqual(FileSystemAccessRule expectedRule, FileSystemAccessRule actualRule)
{
return
expectedRule.AccessControlType == actualRule.AccessControlType &&
expectedRule.FileSystemRights == actualRule.FileSystemRights &&
expectedRule.InheritanceFlags == actualRule.InheritanceFlags &&
expectedRule.PropagationFlags == actualRule.PropagationFlags;
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal.NetworkSenders
{
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using NLog.Common;
/// <summary>
/// A base class for all network senders. Supports one-way sending of messages
/// over various protocols.
/// </summary>
internal abstract class NetworkSender : IDisposable
{
private static int currentSendTime;
/// <summary>
/// Initializes a new instance of the <see cref="NetworkSender" /> class.
/// </summary>
/// <param name="url">The network URL.</param>
protected NetworkSender(string url)
{
this.Address = url;
this.LastSendTime = Interlocked.Increment(ref currentSendTime);
}
/// <summary>
/// Finalizes an instance of the NetworkSender class.
/// </summary>
~NetworkSender()
{
this.Dispose(false);
}
/// <summary>
/// Gets the address of the network endpoint.
/// </summary>
public string Address { get; private set; }
/// <summary>
/// Gets the last send time.
/// </summary>
public int LastSendTime { get; private set; }
/// <summary>
/// Initializes this network sender.
/// </summary>
public void Initialize()
{
this.DoInitialize();
}
/// <summary>
/// Closes the sender and releases any unmanaged resources.
/// </summary>
/// <param name="continuation">The continuation.</param>
public void Close(AsyncContinuation continuation)
{
this.DoClose(continuation);
}
/// <summary>
/// Flushes any pending messages and invokes a continuation.
/// </summary>
/// <param name="continuation">The continuation.</param>
public void FlushAsync(AsyncContinuation continuation)
{
this.DoFlush(continuation);
}
/// <summary>
/// Send the given text over the specified protocol.
/// </summary>
/// <param name="bytes">Bytes to be sent.</param>
/// <param name="offset">Offset in buffer.</param>
/// <param name="length">Number of bytes to send.</param>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Send(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation)
{
this.LastSendTime = Interlocked.Increment(ref currentSendTime);
this.DoSend(bytes, offset, length, asyncContinuation);
}
/// <summary>
/// Closes the sender and releases any unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Performs sender-specific initialization.
/// </summary>
protected virtual void DoInitialize()
{
}
/// <summary>
/// Performs sender-specific close operation.
/// </summary>
/// <param name="continuation">The continuation.</param>
protected virtual void DoClose(AsyncContinuation continuation)
{
continuation(null);
}
/// <summary>
/// Performs sender-specific flush.
/// </summary>
/// <param name="continuation">The continuation.</param>
protected virtual void DoFlush(AsyncContinuation continuation)
{
continuation(null);
}
/// <summary>
/// Actually sends the given text over the specified protocol.
/// </summary>
/// <param name="bytes">The bytes to be sent.</param>
/// <param name="offset">Offset in buffer.</param>
/// <param name="length">Number of bytes to send.</param>
/// <param name="asyncContinuation">The async continuation to be invoked after the buffer has been sent.</param>
/// <remarks>To be overridden in inheriting classes.</remarks>
protected abstract void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation);
#if !WINDOWS_PHONE_7
/// <summary>
/// Parses the URI into an endpoint address.
/// </summary>
/// <param name="uri">The URI to parse.</param>
/// <param name="addressFamily">The address family.</param>
/// <returns>Parsed endpoint.</returns>
protected virtual EndPoint ParseEndpointAddress(Uri uri, AddressFamily addressFamily)
{
#if SILVERLIGHT
return new DnsEndPoint(uri.Host, uri.Port, addressFamily);
#else
switch (uri.HostNameType)
{
case UriHostNameType.IPv4:
case UriHostNameType.IPv6:
return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port);
default:
{
var addresses = Dns.GetHostEntry(uri.Host).AddressList;
foreach (var addr in addresses)
{
if (addr.AddressFamily == addressFamily || addressFamily == AddressFamily.Unspecified)
{
return new IPEndPoint(addr, uri.Port);
}
}
throw new IOException("Cannot resolve '" + uri.Host + "' to an address in '" + addressFamily + "'");
}
}
#endif
}
#endif
private void Dispose(bool disposing)
{
if (disposing)
{
this.Close(ex => { });
}
}
}
}
| |
// 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.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.MetadataAsSource
{
internal partial class AbstractMetadataAsSourceService
{
internal class DocCommentFormatter
{
private static readonly int s_indentSize = 2;
private static readonly int s_wrapLength = 80;
private static readonly string s_summaryHeader = FeaturesResources.Summary_colon;
private static readonly string s_paramHeader = FeaturesResources.Parameters_colon;
private static readonly string s_labelFormat = "{0}:";
private static readonly string s_typeParameterHeader = FeaturesResources.Type_parameters_colon;
private static readonly string s_returnsHeader = FeaturesResources.Returns_colon;
private static readonly string s_exceptionsHeader = FeaturesResources.Exceptions_colon;
private static readonly string s_remarksHeader = FeaturesResources.Remarks_colon;
internal static ImmutableArray<string> Format(IDocumentationCommentFormattingService docCommentFormattingService, DocumentationComment docComment)
{
var formattedCommentLinesBuilder = ArrayBuilder<string>.GetInstance();
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.ToImmutableAndFree();
}
private static ImmutableArray<string> CreateWrappedTextFromRawText(string rawText)
{
var lines = ArrayBuilder<string>.GetInstance();
// 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.ToImmutableAndFree();
}
private static void SplitRawLineIntoFormattedLines(
string line, ArrayBuilder<string> 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 1999-2012 Alibaba Group.
*
* 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.Text;
using Sharpen;
using Tup.Cobar4Net.Config.Model;
using Tup.Cobar4Net.Parser.Ast.Stmt;
using Tup.Cobar4Net.Parser.Ast.Stmt.Dml;
using Tup.Cobar4Net.Parser.Recognizer;
using Tup.Cobar4Net.Parser.Recognizer.Mysql.Lexer;
using Tup.Cobar4Net.Parser.Recognizer.Mysql.Syntax;
using Tup.Cobar4Net.Parser.Visitor;
using Tup.Cobar4Net.Route.Visitor;
namespace Tup.Cobar4Net.Route.Perf
{
/// <author>
/// <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a>
/// </author>
public class ServerRoutePerformance
{
private readonly SchemaConfig schema = null;
/// <exception cref="System.Exception" />
public virtual void Perf()
{
TestProvider provider;
provider = new InsertLongSQLGen();
provider = new InsertLongSQLGenShort();
provider = new SelectShort();
provider = new InsertLong();
provider = new SelectLongIn();
provider = new ShardingMultiTableSpace();
provider = new ShardingDefaultSpace();
provider = new ShardingTableSpace();
var schema = GetSchema();
var sql = provider.GetSql();
Console.Out.WriteLine(ServerRouter.Route(schema, sql, null, null));
var start = Runtime.CurrentTimeMillis();
provider.Route(schema, 1, sql);
long end;
var loop = 200*10000;
start = Runtime.CurrentTimeMillis();
provider.Route(schema, loop, sql);
end = Runtime.CurrentTimeMillis();
Console.Out.WriteLine((end - start)*1000.0d/loop + " us");
}
// CobarConfig conf = CobarServer.getInstance().getConfig();
// schema = conf.getSchemas().get("cndb");
/// <param name="args" />
/// <exception cref="System.Exception" />
public static void Main(string[] args)
{
var perf = new ServerRoutePerformance();
perf.Perf();
}
protected internal virtual SchemaConfig GetSchema()
{
return schema;
}
private abstract class TestProvider
{
/// <exception cref="System.Exception" />
public abstract string GetSql();
/// <exception cref="System.Exception" />
public abstract void Route(SchemaConfig schema, int loop, string sql);
}
private class ShardingDefaultSpace : TestProvider
{
private ISqlStatement stmt;
/// <exception cref="System.Exception" />
public override void Route(SchemaConfig schema, int loop, string sql)
{
for (var i = 0; i < loop; ++i)
{
// SQLLexer lexer = new SQLLexer(sql);
// DmlSelectStatement select = new DmlSelectParser(lexer, new
// SQLExprParser(lexer)).select();
// PartitionKeyVisitor visitor = new
// PartitionKeyVisitor(schema.getTablesSpace());
// select.accept(visitor);
// visitor.getColumnValue();
ServerRouter.Route(schema, sql, null, null);
}
}
// StringBuilder s = new StringBuilder();
// stmt.accept(new MySqlOutputAstVisitor(s));
// s.toString();
/// <exception cref="System.Exception" />
public override string GetSql()
{
var sql = "insert into xoffer (member_id, gmt_create) values ('1','2001-09-13 20:20:33')";
stmt = SqlParserDelegate.Parse(sql);
return "insert into xoffer (member_id, gmt_create) values ('1','2001-09-13 20:20:33')";
}
}
private class ShardingTableSpace : TestProvider
{
private ISqlStatement stmt;
/// <exception cref="System.Exception" />
public override void Route(SchemaConfig schema, int loop, string sql)
{
for (var i = 0; i < loop; ++i)
{
// SQLLexer lexer = new SQLLexer(sql);
// DmlSelectStatement select = new DmlSelectParser(lexer, new
// SQLExprParser(lexer)).select();
// PartitionKeyVisitor visitor = new
// PartitionKeyVisitor(schema.getTablesSpace());
// select.accept(visitor);
// visitor.getColumnValue();
ServerRouter.Route(schema, sql, null, null);
}
}
// StringBuilder s = new StringBuilder();
// stmt.accept(new MySqlOutputAstVisitor(s));
// s.toString();
/// <exception cref="System.Exception" />
public override string GetSql()
{
var sql = "insert into offer (member_id, gmt_create) values ('1','2001-09-13 20:20:33')";
stmt = SqlParserDelegate.Parse(sql);
return
"insert into offer (member_id, gmt_create) values ('1','2001-09-13 20:20:33'),('1','2001-09-13 20:20:34')";
}
}
private class ShardingMultiTableSpace : TestProvider
{
private ISqlStatement stmt;
/// <exception cref="System.Exception" />
public override void Route(SchemaConfig schema, int loop, string sql)
{
for (var i = 0; i < loop*5; ++i)
{
// SQLLexer lexer = new SQLLexer(sql);
// DmlSelectStatement select = new DmlSelectParser(lexer, new
// SQLExprParser(lexer)).select();
// PartitionKeyVisitor visitor = new
// PartitionKeyVisitor(schema.getTablesSpace());
// select.accept(visitor);
// visitor.getColumnValue();
ServerRouter.Route(schema, sql, null, null);
}
}
// StringBuilder s = new StringBuilder();
// stmt.accept(new MySqlOutputAstVisitor(s));
// s.toString();
/// <exception cref="System.Exception" />
public override string GetSql()
{
var sql = "select id,member_id,gmt_create from offer where member_id in ('22')";
stmt = SqlParserDelegate.Parse(sql);
return "select id,member_id,gmt_create from offer where member_id in ('1','22','333','1124','4525')";
}
}
private class SelectShort : TestProvider
{
/// <exception cref="System.Exception" />
public override void Route(SchemaConfig schema, int loop, string sql)
{
for (var i = 0; i < loop; ++i)
{
var lexer = new MySqlLexer(sql);
var select = new MySqlDmlSelectParser(lexer, new MySqlExprParser(lexer)).Select();
var visitor = new PartitionKeyVisitor(schema.Tables);
select.Accept(visitor);
}
}
// visitor.getColumnValue();
// ServerRoute.route(schema, sql);
/// <exception cref="System.Exception" />
public override string GetSql()
{
return
" seLEcT id, member_id , image_path \t , image_size , STATUS, gmt_modified from offer_detail wheRe \t\t\n offer_id = 123 AND member_id\t=\t-123.456";
}
}
private class SelectLongIn : TestProvider
{
/// <exception cref="System.Exception" />
public override void Route(SchemaConfig schema, int loop, string sql)
{
for (var i = 0; i < loop; ++i)
{
var lexer = new MySqlLexer(sql);
var select = new MySqlDmlSelectParser(lexer, new MySqlExprParser(lexer)).Select();
var visitor = new PartitionKeyVisitor(schema.Tables);
select.Accept(visitor);
}
}
// visitor.getColumnValue();
// ServerRoute.route(schema, sql);
/// <exception cref="System.Exception" />
public override string GetSql()
{
var sb = new StringBuilder();
sb.Append(" seLEcT id, member_id , image_path \t , image_size , STATUS, gmt_modified from")
.Append(" offer_detail wheRe \t\t\n offer_id in (");
for (var i = 0; i < 1024; ++i)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append(i);
}
sb.Append(") AND member_id\t=\t-123.456");
// System.out.println(sb.length());
return sb.ToString();
}
}
private class InsertLong : TestProvider
{
/// <exception cref="System.Exception" />
public override string GetSql()
{
var sb = new StringBuilder("insert into offer_detail (offer_id, gmt) values ");
for (var i = 0; i < 1024; ++i)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append("(" + i + ", now())");
}
// System.out.println(sb.length());
return sb.ToString();
}
/// <exception cref="System.Exception" />
public override void Route(SchemaConfig schema, int loop, string sql)
{
for (var i = 0; i < loop; ++i)
{
var lexer = new MySqlLexer(sql);
var insert = new MySqlDmlInsertParser(lexer, new MySqlExprParser(lexer)).Insert();
}
}
// PartitionKeyVisitor visitor = new
// PartitionKeyVisitor(schema.getTablesSpace());
// insert.accept(visitor);
// visitor.getColumnValue();
// SQLLexer lexer = new SQLLexer(sql);
// new DmlInsertParser(lexer, new
// SQLExprParser(lexer)).insert();
// RouteResultset rrs = ServerRoute.route(schema, sql);
// System.out.println(rrs);
}
private class InsertLongSQLGen : TestProvider
{
private readonly int sqlSize = 0;
private DmlInsertStatement insert;
/// <exception cref="System.Exception" />
public override string GetSql()
{
var sql = new InsertLong().GetSql();
var lexer = new MySqlLexer(sql);
insert = new MySqlDmlInsertParser(lexer, new MySqlExprParser(lexer)).Insert();
return sql;
}
/// <exception cref="System.Exception" />
public override void Route(SchemaConfig schema, int loop, string sql)
{
for (var i = 0; i < loop; ++i)
{
var sb = new StringBuilder(sqlSize);
insert.Accept(new MySqlOutputAstVisitor(sb));
sb.ToString();
}
}
}
private class InsertLongSQLGenShort : TestProvider
{
private DmlInsertStatement insert;
private int sqlSize;
/// <exception cref="System.Exception" />
public override string GetSql()
{
var sb = new StringBuilder("insert into offer_detail (offer_id, gmt) values ");
for (var i = 0; i < 8; ++i)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append("(" + (i + 100) + ", now())");
}
var sql = sb.ToString();
var lexer = new MySqlLexer(sql);
insert = new MySqlDmlInsertParser(lexer, new MySqlExprParser(lexer)).Insert();
sqlSize = new InsertLong().GetSql().Length;
return sql;
}
/// <exception cref="System.Exception" />
public override void Route(SchemaConfig schema, int loop, string sql)
{
for (var i = 0; i < loop; ++i)
{
for (var j = 0; j < 128; ++j)
{
var sb = new StringBuilder();
insert.Accept(new MySqlOutputAstVisitor(sb));
sb.ToString();
}
}
}
}
}
}
| |
/*
* 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 {
public const int InitialRevision = 1;
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 = InitialRevision;
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);
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 {
bag = ContentCodeBag.ParseCodes (fetcher.Fetch ("/content-codes"));
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 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) {
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);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Web.Services.Protocols;
using AppUtil;
using Vim25Api;
namespace PropertyCollector
{
///<summary>
/// This sample excercise the PropertyCollector API of all the managed entity.
///</summary>
///<param name="dcName">Required: Name of the datacenter.</param>
///<param name="vmDnsName">Required: Dns name of a virtual machine.</param>
///<remarks>
///--url [webserviceurl]
///--username [username] --password [password] --dcName [datacenterName]
///--vmDnsName [vmDnsName]
///</remarks>
public class PropertyCollector
{
static VimService _service;
static ServiceContent _sic;
private static AppUtil.AppUtil cb = null;
Log log = new Log();
/// <summary>
/// This method is used to add application specific user options
/// </summary>
///<returns> Array of OptionSpec containing the details of
/// application specific user options
///</returns>
private static OptionSpec[] constructOptions()
{
OptionSpec[] useroptions = new OptionSpec[2];
useroptions[0] = new OptionSpec("dcName", "String", 1
, "Name of the Datacenter"
, null);
useroptions[1] = new OptionSpec("vmDnsName", "String", 1,
"Virtual machine dns name",
null);
return useroptions;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main(String[] args)
{
try
{
PropertyCollector app = new PropertyCollector();
cb = AppUtil.AppUtil.initialize("PropertyCollector",
PropertyCollector.constructOptions(),
args);
cb.connect();
ManagedObjectReference sic = cb.getConnection().ServiceRef;
_sic = cb.getConnection()._sic;
_service = cb.getConnection()._service;
String dcName = cb.get_option("dcName");
String vmDnsName = cb.get_option("vmDnsName");
ObjectContent[] ocs = null;
ManagedObjectReference dcMoRef
= cb.getServiceUtil().GetDecendentMoRef(null, "Datacenter", dcName);
if (dcMoRef == null)
{
Console.WriteLine("Datacenter not found");
}
else
{
ManagedObjectReference vmMoRef =
_service.FindByDnsName(_sic.searchIndex,
dcMoRef, vmDnsName, true);
if (vmMoRef == null)
{
Console.WriteLine("The virtual machine with DNS '" + vmDnsName
+ "' not found ");
}
else
{
// Retrieve name and powerState from a Virtual Machine
Object[] properties
= getProperties(vmMoRef, new String[] { "name", "runtime.powerState" });
String vmName = (String)properties[0];
VirtualMachinePowerState vmState
= (VirtualMachinePowerState)properties[1];
if (vmName != null && vmState != null)
{
Console.WriteLine("The VM with DNS name \'" + vmDnsName
+ "\' is named \'" + vmName +
"\' and is " + vmState.ToString());
}
ocs = getDatacenters();
printObjectContent(ocs, "All Datacenters");
// Find all the VMs in the Datacenter
ocs = getVMs(dcMoRef);
printObjectContent(ocs, "All VMs in the Datacenter: " + dcName);
//Find all the Hosts in the Datacenter
ocs = getHosts(dcMoRef);
printObjectContent(ocs, "All Hosts in the Datacenter: " + dcName);
// Display summary information about a VM
ocs = getVMInfo(vmMoRef);
printVmInfo(ocs);
// Display all of inventory
ocs = getInventory();
printInventoryTree(ocs);
ocs = getNetworkInfo(dcMoRef);
printNetworkInfo(ocs);
cb.disConnect();
Console.WriteLine("Press any key to exit:");
Console.Read();
}
}
}
catch (SoapException e)
{
if (e.Detail.FirstChild.LocalName.Equals("DuplicateNameFault"))
{
Console.WriteLine("Managed Entity with the name already exists");
}
else if (e.Detail.FirstChild.LocalName.Equals("InvalidArgumentFault"))
{
Console.WriteLine("Specification is invalid");
}
else if (e.Detail.FirstChild.LocalName.Equals("InvalidNameFault"))
{
Console.WriteLine("Managed Entity Name is empty or too long");
}
else if (e.Detail.FirstChild.LocalName.Equals("RuntimeFault"))
{
Console.WriteLine(e.Message.ToString() + "Either parent name or item name is invalid");
}
else if (e.Detail.FirstChild.LocalName.Equals("RuntimeFault"))
{
Console.WriteLine(e.Message.ToString() + " "
+ "The Operation is not supported on this object");
}
else
{
Console.WriteLine(e.Message.ToString() + " "
+ "The Operation is not supported on this object");
}
}
Console.Read();
}
///<summary>
///Retrieve properties from a single MoRef.
///</summary>
private static Object[] getProperties(ManagedObjectReference moRef, String[] properties)
{
PropertySpec pSpec = new PropertySpec();
pSpec.type = moRef.type;
pSpec.pathSet = properties;
ObjectSpec oSpec = new ObjectSpec();
// Set the starting object
oSpec.obj = moRef;
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.propSet = new PropertySpec[] { pSpec };
pfSpec.objectSet = new ObjectSpec[] { oSpec };
ObjectContent[] ocs = _service.RetrieveProperties(
_sic.propertyCollector,
new PropertyFilterSpec[] { pfSpec });
Object[] ret = new Object[properties.Length];
if (ocs != null)
{
for (int i = 0; i < ocs.Length; ++i)
{
ObjectContent oc = ocs[i];
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
for (int j = 0; j < dps.Length; ++j)
{
DynamicProperty dp = dps[j];
for (int p = 0; p < ret.Length; ++p)
{
if (properties[p].Equals(dp.name))
{
ret[p] = dp.val;
}
}
}
}
}
}
return ret;
}
///<summary>
/// Print out the ObjectContent[]
/// returned from RetrieveProperties()
///</summary>
private static void printObjectContent(ObjectContent[] ocs,
String title)
{
// Print out the title to label the output
Console.WriteLine(title);
if (ocs != null)
{
for (int i = 0; i < ocs.Length; ++i)
{
ObjectContent oc = ocs[i];
// Print out the managed object type
Console.WriteLine(oc.obj.type);
Console.WriteLine(" Property Name:Value");
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
for (int j = 0; j < dps.Length; ++j)
{
DynamicProperty dp = dps[j];
// Print out the property name and value
Console.WriteLine(" " + dp.name + ": "
+ dp.val);
}
}
}
}
}
///<summary>
///Specifications to find all the Datacenters and
///retrieve their name, vmFolder and hostFolder values.
///</summary>
private static ObjectContent[] getDatacenters()
{
// The PropertySpec object specifies what properties
// to retrieve from what type of Managed Object
PropertySpec pSpec = new PropertySpec();
pSpec.type = "Datacenter";
pSpec.pathSet = new String[] {
"name", "vmFolder", "hostFolder" };
// The following TraversalSpec and SelectionSpec
// objects create the following relationship:
//
// a. Folder -> childEntity
// b. recurse to a.
//
// This specifies that starting with a Folder
// managed object, traverse through its childEntity
// property. For each element in the childEntity
// property, process by going back to the 'parent'
// TraversalSpec.
// SelectionSpec to cause Folder recursion
SelectionSpec recurseFolders = new SelectionSpec();
// The name of a SelectionSpec must refer to a
// TraversalSpec with the same name value.
recurseFolders.name = "folder2childEntity";
// Traverse from a Folder through the 'childEntity' property
TraversalSpec folder2childEntity = new TraversalSpec();
// Select the Folder type managed object
folder2childEntity.type = "Folder";
// Traverse through the childEntity property of the Folder
folder2childEntity.path = "childEntity";
// Name this TraversalSpec so the SelectionSpec above
// can refer to it
folder2childEntity.name = recurseFolders.name;
// Add the SelectionSpec above to this traversal so that
// we will recurse through the tree via the childEntity
// property
folder2childEntity.selectSet = new SelectionSpec[] {
recurseFolders };
// The ObjectSpec object specifies the starting object and
// any TraversalSpecs used to specify other objects
// for consideration
ObjectSpec oSpec = new ObjectSpec();
oSpec.obj = _sic.rootFolder;
// We set skip to true because we are not interested
// in retrieving properties from the root Folder
oSpec.skip = true;
// Specify the TraversalSpec. This is what causes
// other objects besides the starting object to
// be considered part of the collection process
oSpec.selectSet = new SelectionSpec[] { folder2childEntity };
// The PropertyFilterSpec object is used to hold the
// ObjectSpec and PropertySpec objects for the call
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.propSet = new PropertySpec[] { pSpec };
pfSpec.objectSet = new ObjectSpec[] { oSpec };
// RetrieveProperties() returns the properties
// selected from the PropertyFilterSpec
return _service.RetrieveProperties(
_sic.propertyCollector,
new PropertyFilterSpec[] { pfSpec });
}
///<summary>
/// Specifications to find all the VMs in a Datacenter and
/// retrieve their name and runtime.powerState values.
///</summary>
private static ObjectContent[] getVMs(ManagedObjectReference dcMoRef)
{
// The PropertySpec object specifies what properties
// retrieve from what type of Managed Object
PropertySpec pSpec = new PropertySpec();
pSpec.type = "VirtualMachine";
pSpec.pathSet = new String[] { "name", "runtime.powerState" };
SelectionSpec recurseFolders = new SelectionSpec();
recurseFolders.name = "folder2childEntity";
TraversalSpec folder2childEntity = new TraversalSpec();
folder2childEntity.type = "Folder";
folder2childEntity.path = "childEntity";
folder2childEntity.name = recurseFolders.name;
folder2childEntity.selectSet =
new SelectionSpec[] { recurseFolders };
// Traverse from a Datacenter through the 'vmFolder' property
TraversalSpec dc2vmFolder = new TraversalSpec();
dc2vmFolder.type = "Datacenter";
dc2vmFolder.path = "vmFolder";
dc2vmFolder.selectSet =
new SelectionSpec[] { folder2childEntity };
ObjectSpec oSpec = new ObjectSpec();
oSpec.obj = dcMoRef;
oSpec.skip = true;
oSpec.selectSet = new SelectionSpec[] { dc2vmFolder };
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.propSet = new PropertySpec[] { pSpec };
pfSpec.objectSet = new ObjectSpec[] { oSpec };
return _service.RetrieveProperties(_sic.propertyCollector,
new PropertyFilterSpec[] { pfSpec });
}
private static ObjectContent[] getHosts(ManagedObjectReference dcMoRef)
{
// PropertySpec specifies what properties to
// retrieve from what type of Managed Object
PropertySpec pSpec = new PropertySpec();
pSpec.type = "HostSystem";
pSpec.pathSet = new String[] { "name", "runtime.connectionState" };
SelectionSpec recurseFolders = new SelectionSpec();
recurseFolders.name = "folder2childEntity";
TraversalSpec computeResource2host = new TraversalSpec();
computeResource2host.type = "ComputeResource";
computeResource2host.path = "host";
TraversalSpec folder2childEntity = new TraversalSpec();
folder2childEntity.type = "Folder";
folder2childEntity.path = "childEntity";
folder2childEntity.name = recurseFolders.name;
// Add BOTH of the specifications to this specification
folder2childEntity.selectSet = new SelectionSpec[] { recurseFolders };
// Traverse from a Datacenter through
// the 'hostFolder' property
TraversalSpec dc2hostFolder = new TraversalSpec();
dc2hostFolder.type = "Datacenter";
dc2hostFolder.path = "hostFolder";
dc2hostFolder.selectSet = new SelectionSpec[] { folder2childEntity };
ObjectSpec oSpec = new ObjectSpec();
oSpec.obj = dcMoRef;
oSpec.skip = true;
oSpec.selectSet = new SelectionSpec[] { dc2hostFolder };
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.propSet = new PropertySpec[] { pSpec };
pfSpec.objectSet = new ObjectSpec[] { oSpec };
return _service.RetrieveProperties(
_sic.propertyCollector,
new PropertyFilterSpec[] { pfSpec });
}
private static ObjectContent[] getVMInfo(ManagedObjectReference vmMoRef)
{
// This spec selects VirtualMachine information
PropertySpec vmPropSpec = new PropertySpec();
vmPropSpec.type = "VirtualMachine";
vmPropSpec.pathSet = new String[] {
"name",
"config.guestFullName",
"config.hardware.memoryMB",
"config.hardware.numCPU",
"guest.toolsStatus",
"guestHeartbeatStatus",
"guest.ipAddress",
"guest.hostName",
"runtime.powerState",
"summary.quickStats.overallCpuUsage",
"summary.quickStats.hostMemoryUsage",
"summary.quickStats.guestMemoryUsage", };
PropertySpec hostPropSpec = new PropertySpec();
hostPropSpec.type = "HostSystem";
hostPropSpec.pathSet = new String[] { "name" };
PropertySpec taskPropSpec = new PropertySpec();
taskPropSpec.type = "Task";
taskPropSpec.pathSet = new String[] { "info.name", "info.completeTime" };
PropertySpec datastorePropSpec = new PropertySpec();
datastorePropSpec.type = "Datastore";
datastorePropSpec.pathSet = new String[] { "info" };
PropertySpec networkPropSpec = new PropertySpec();
networkPropSpec.type = "Network";
networkPropSpec.pathSet = new String[] { "name" };
TraversalSpec hostTraversalSpec = new TraversalSpec();
hostTraversalSpec.type = "VirtualMachine";
hostTraversalSpec.path = "runtime.host";
TraversalSpec taskTravesalSpec = new TraversalSpec();
taskTravesalSpec.type = "VirtualMachine";
taskTravesalSpec.path = "recentTask";
TraversalSpec datastoreTraversalSpec = new TraversalSpec();
datastoreTraversalSpec.type = "VirtualMachine";
datastoreTraversalSpec.path = "datastore";
TraversalSpec networkTraversalSpec = new TraversalSpec();
networkTraversalSpec.type = "VirtualMachine";
networkTraversalSpec.path = "network";
// ObjectSpec specifies the starting object and
// any TraversalSpecs used to specify other objects
// for consideration
ObjectSpec oSpec = new ObjectSpec();
oSpec.obj = vmMoRef;
// Add the TraversalSpec objects to the ObjectSpec
// This specifies what additional object we want to
// consider during the process.
oSpec.selectSet = new SelectionSpec[] {
hostTraversalSpec,
taskTravesalSpec,
datastoreTraversalSpec,
networkTraversalSpec };
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
// Add the PropertySpec objects to the PropertyFilterSpec
// This specifies what data we want to collect while
// processing the found objects from the ObjectSpec
pfSpec.propSet = new PropertySpec[] {
vmPropSpec,
hostPropSpec,
taskPropSpec,
datastorePropSpec,
networkPropSpec };
pfSpec.objectSet = new ObjectSpec[] { oSpec };
return _service.RetrieveProperties(
_sic.propertyCollector,
new PropertyFilterSpec[] { pfSpec });
}
///<summary>
///Take the ObjectContent[] from RetrieveProperties()
///and print it out.
///</summary>
private static void printVmInfo(ObjectContent[] ocs)
{
if (ocs != null)
{
//Each instance of ObjectContent contains the properties
// retrieved for one instance of a managed object
for (int oci = 0; oci < ocs.Length; ++oci)
{
// Properties for one managed object
ObjectContent oc = ocs[oci];
// Get the type of managed object
String type = oc.obj.type;
Console.WriteLine("VM Information");
// Handle data from VirtualMachine managed objects
if ("VirtualMachine".Equals(type))
{
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
// Each instance of DynamicProperty contains a
// single property from the managed object
// This data comes back as name-value pairs
// The code below is checking each name and
// assigning the proper field in the data
// object
for (int j = 0; j < dps.Length; ++j)
{
DynamicProperty dp = dps[j];
if ("name".Equals(dp.name))
{
Console.WriteLine(" Name : " + (String)dp.val);
}
else if ("config.guestFullName".Equals(dp.name))
{
Console.WriteLine(" Guest OS Name : " + (String)dp.val);
}
else if ("config.hardware.memoryMB".Equals(dp.name))
{
Console.WriteLine(" Memory : " + (int)dp.val);
}
else if ("config.hardware.numCPU".Equals(dp.name))
{
Console.WriteLine(" Num vCPU : " + (int)dp.val);
}
else if ("guest.toolsStatus".Equals(dp.name))
{
Console.WriteLine(" VMware Tools : " + (VirtualMachineToolsStatus)dp.val);
}
else if ("guestHeartbeatStatus".Equals(dp.name))
{
Console.WriteLine(" Guest Heartbeat : " + (ManagedEntityStatus)dp.val);
}
else if ("guest.ipAddress".Equals(dp.name))
{
Console.WriteLine(" Guest IP Address : " + (String)dp.val);
}
else if ("guest.hostName".Equals(dp.name))
{
Console.WriteLine(" Guest DNS Name : " + (String)dp.val);
}
else if ("runtime.powerState".Equals(dp.name))
{
Console.WriteLine(" State : " + (VirtualMachinePowerState)dp.val);
}
else if (
"summary.quickStats.overallCpuUsage".Equals(dp.name))
{
Console.WriteLine(" CPU Usage : " + (int)dp.val + " MHz");
}
else if (
"summary.quickStats.hostMemoryUsage".Equals(dp.name))
{
Console.WriteLine(" Host Memory Usage : " + (int)dp.val + " MB");
}
else if (
"summary.quickStats.guestMemoryUsage".Equals(dp.name))
{
Console.WriteLine(" Guest Memory Usage : " + (int)dp.val + " MB");
}
}
}
// Handle data from HostSystem managed objects
}
else if ("HostSystem".Equals(type))
{
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
for (int j = 0; j < dps.Length; ++j)
{
DynamicProperty dp = dps[j];
if ("name".Equals(dp.name))
{
Console.WriteLine(" Host : " + (String)dp.val);
}
}
}
// Handle data from Task managed objects
}
else if ("Task".Equals(type))
{
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
Boolean taskCompleted = false;
String taskName = "";
for (int j = 0; j < dps.Length; ++j)
{
DynamicProperty dp = dps[j];
if ("info.name".Equals(dp.name))
{
Console.WriteLine(" Active Tasks : " + (String)dp.val);
}
else if ("info.completeTime".Equals(dp
.name))
{
taskCompleted = true;
}
}
if (!taskCompleted)
{
Console.WriteLine(" Tasks Status : " + taskCompleted);
}
}
// Handle data from Datastore managed objects
}
else if ("Datastore".Equals(type))
{
Console.WriteLine(" Datastores :");
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
for (int j = 0; j < dps.Length; ++j)
{
DynamicProperty dp = dps[j];
if ("info".Equals(dp.name))
{
DatastoreInfo dInfo = (DatastoreInfo)dp.val;
int cap = 0;
if (dInfo.GetType().Name.Equals("VmfsDatastoreInfo"))
{
VmfsDatastoreInfo vmfsInfo =
(VmfsDatastoreInfo)dInfo;
if (vmfsInfo.vmfs != null)
{
cap = (int)(vmfsInfo.vmfs.capacity / 1024 / 1024 / 1024);
}
}
else if (dInfo.GetType().Name.Equals("NasDatastoreInfo"))
{
NasDatastoreInfo nasInfo =
(NasDatastoreInfo)dInfo;
if (nasInfo.nas != null)
{
cap = (int)(nasInfo.nas.capacity / 1024 / 1024 / 1024);
}
}
Console.WriteLine(" Name : " + dInfo.name);
Console.WriteLine(" Free Space : " + (dInfo.freeSpace) / 1024 / 1024 / 1024 + "GB");
Console.WriteLine(" Capacity : " + cap + "GB");
}
}
}
// Handle data from Network managed objects
}
else if ("Network".Equals(type))
{
Console.WriteLine(" Networks :");
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
for (int j = 0; j < dps.Length; ++j)
{
DynamicProperty dp = dps[j];
if ("name".Equals(dp.name))
{
Console.WriteLine(" Name : " + (String)dp.val);
}
}
}
}
}
// Print out the results
//Console.WriteLine(vmInfo.toString());
}
}
///<summary>
/// Specifications to find all items in inventory and
/// retrieve their name and parent values.
///</summary>
private static ObjectContent[] getInventory()
{
string[][] typeInfo = new string[][] {
new string[] { "ManagedEntity", "parent", "name" }, };
ObjectContent[] ocary =
cb.getServiceUtil().GetContentsRecursively(null, null, typeInfo, true);
return ocary;
}
private class MeNode
{
private ManagedObjectReference parent;
private ManagedObjectReference node;
private String name;
private ArrayList children = new ArrayList();
public MeNode(ManagedObjectReference parent,
ManagedObjectReference node, String name)
{
this.setParent(parent);
this.setNode(node);
this.setName(name);
}
public void setParent(ManagedObjectReference parent)
{
this.parent = parent;
}
public ManagedObjectReference getParent()
{
return parent;
}
public void setNode(ManagedObjectReference node)
{
this.node = node;
}
public ManagedObjectReference getNode()
{
return node;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setChildren(ArrayList children)
{
this.children = children;
}
public ArrayList getChildren()
{
return children;
}
}
///<summary>
/// Recursive method to print an inventory tree node
///</summary>
private static void printNode(MeNode node, int indent)
{
// Make it pretty
for (int i = 0; i < indent; ++i)
{
Console.Write(' ');
}
Console.WriteLine(node.getName() +
" (" + node.getNode().type + ")");
if (node.getChildren().Count != 0)
{
for (int c = 0; c < node.getChildren().Count; ++c)
{
printNode((MeNode)
node.getChildren()[c], indent + 2);
}
}
}
///<summary>
/// Print the inventory tree retrieved from
/// the PropertyCollector
///</summary>
private static void printInventoryTree(ObjectContent[] ocs)
{
// Hashtable MoRef.Value -> MeNode
Hashtable nodes = new Hashtable();
// The root folder node
MeNode root = null;
for (int oci = 0; oci < ocs.Length; ++oci)
{
ObjectContent oc = ocs[oci];
ManagedObjectReference mor = oc.obj;
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
ManagedObjectReference parent = null;
String name = null;
for (int dpi = 0; dpi < dps.Length; ++dpi)
{
DynamicProperty dp = dps[dpi];
if (dp != null)
{
if ("name".Equals(dp.name))
{
name = (String)dp.val;
}
if ("parent".Equals(dp.name))
{
parent = (ManagedObjectReference)dp
.val;
}
}
}
// Create a MeNode to hold the data
MeNode node = new MeNode(parent, mor, name);
// The root folder has no parent
if (parent == null)
{
root = node;
}
// Add the node
nodes.Add(node.getNode().Value, node);
}
}
// Build the nodes into a tree
foreach (String key in nodes.Keys)
{
MeNode meNode = nodes[key] as MeNode;
if (meNode.getParent() != null)
{
MeNode parent = (MeNode)nodes[meNode.getParent().Value];
parent.getChildren().Add(meNode);
}
}
Console.WriteLine("Inventory Tree");
printNode(root, 0);
}
///<summary>
/// Specifications to find all Networks in a Datacenter,
/// list all VMs on each Network,
/// list all Hosts on each Network
///</summary>
private static ObjectContent[] getNetworkInfo(
ManagedObjectReference dcMoRef)
{
// PropertySpec specifies what properties to
// retrieve from what type of Managed Object
// This spec selects the Network name
PropertySpec networkPropSpec = new PropertySpec();
networkPropSpec.type = "Network";
networkPropSpec.pathSet = new String[] { "name" };
// This spec selects HostSystem information
PropertySpec hostPropSpec = new PropertySpec();
hostPropSpec.type = "HostSystem";
hostPropSpec.pathSet = new String[] { "network", "name",
"summary.hardware", "runtime.connectionState",
"summary.overallStatus", "summary.quickStats" };
// This spec selects VirtualMachine information
PropertySpec vmPropSpec = new PropertySpec();
vmPropSpec.type = "VirtualMachine";
vmPropSpec.pathSet = new String[] { "network", "name",
"runtime.host", "runtime.powerState",
"summary.overallStatus", "summary.quickStats" };
// The following TraversalSpec and SelectionSpec
// objects create the following relationship:
//
// a. Datacenter -> network
// b. Network -> host
// c. Network -> vm
// b. Traverse from a Network through the 'host' property
TraversalSpec network2host = new TraversalSpec();
network2host.type = "Network";
network2host.path = "host";
// c. Traverse from a Network through the 'vm' property
TraversalSpec network2vm = new TraversalSpec();
network2vm.type = "Network";
network2vm.path = "vm";
// a. Traverse from a Datacenter through
// the 'network' property
TraversalSpec dc2network = new TraversalSpec();
dc2network.type = "Datacenter";
dc2network.path = "network";
dc2network.selectSet = new SelectionSpec[] {
// Add b. traversal
network2host,
// Add c. traversal
network2vm };
// ObjectSpec specifies the starting object and
// any TraversalSpecs used to specify other objects
// for consideration
ObjectSpec oSpec = new ObjectSpec();
oSpec.obj = dcMoRef;
oSpec.skip = true;
oSpec.selectSet = new SelectionSpec[] { dc2network };
// PropertyFilterSpec is used to hold the ObjectSpec and
// PropertySpec for the call
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.propSet = new PropertySpec[] { networkPropSpec,
hostPropSpec, vmPropSpec };
pfSpec.objectSet = new ObjectSpec[] { oSpec };
// RetrieveProperties() returns the properties
// selected from the PropertyFilterSpec
return _service.RetrieveProperties(
_sic.propertyCollector,
new PropertyFilterSpec[] { pfSpec });
}
private class Host
{
private ManagedObjectReference moRef;
private String name;
private HostHardwareSummary hardware;
private HostSystemConnectionState connectionState;
private ManagedEntityStatus overallStatus;
private HostListSummaryQuickStats quickStats;
public Host(ManagedObjectReference _this)
{
this.setMoRef(_this);
}
public Host(ManagedObjectReference _this,
String name,
HostHardwareSummary hardware,
HostSystemConnectionState connectionState,
ManagedEntityStatus overallStatus,
HostListSummaryQuickStats quickStats)
{
this.setMoRef(_this);
this.setName(name);
this.setHardware(hardware);
this.setConnectionState(connectionState);
this.setOverallStatus(overallStatus);
this.setQuickStats(quickStats);
}
public void setMoRef(ManagedObjectReference moRef)
{
this.moRef = moRef;
}
public ManagedObjectReference getMoRef()
{
return moRef;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setHardware(HostHardwareSummary hardware)
{
this.hardware = hardware;
}
public HostHardwareSummary getHardware()
{
return hardware;
}
public void setConnectionState(
HostSystemConnectionState connectionState)
{
this.connectionState = connectionState;
}
public HostSystemConnectionState getConnectionState()
{
return connectionState;
}
public void setOverallStatus(
ManagedEntityStatus overallStatus)
{
this.overallStatus = overallStatus;
}
public ManagedEntityStatus getOverallStatus()
{
return overallStatus;
}
public void setQuickStats(
HostListSummaryQuickStats quickStats)
{
this.quickStats = quickStats;
}
public HostListSummaryQuickStats getQuickStats()
{
return quickStats;
}
}
private class VirtualMachine
{
private ManagedObjectReference moRef;
private String name;
private ManagedObjectReference host;
private VirtualMachinePowerState powerState;
private ManagedEntityStatus overallStatus;
private VirtualMachineQuickStats quickStats;
public VirtualMachine(ManagedObjectReference _this)
{
this.setMoRef(_this);
}
public VirtualMachine(ManagedObjectReference _this,
String name,
ManagedObjectReference host,
VirtualMachinePowerState powerState,
ManagedEntityStatus overallStatus,
VirtualMachineQuickStats quickStats)
{
this.setMoRef(_this);
this.setName(name);
this.setHost(host);
this.setPowerState(powerState);
this.setOverallStatus(overallStatus);
this.setQuickStats(quickStats);
}
public void setMoRef(ManagedObjectReference moRef)
{
this.moRef = moRef;
}
public ManagedObjectReference getMoRef()
{
return moRef;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setHost(ManagedObjectReference host)
{
this.host = host;
}
public ManagedObjectReference getHost()
{
return host;
}
public void setPowerState(
VirtualMachinePowerState powerState)
{
this.powerState = powerState;
}
public VirtualMachinePowerState getPowerState()
{
return powerState;
}
public void setOverallStatus(
ManagedEntityStatus overallStatus)
{
this.overallStatus = overallStatus;
}
public ManagedEntityStatus getOverallStatus()
{
return overallStatus;
}
public void setQuickStats(
VirtualMachineQuickStats quickStats)
{
this.quickStats = quickStats;
}
public VirtualMachineQuickStats getQuickStats()
{
return quickStats;
}
}
private class Network
{
private ManagedObjectReference moRef;
private String name;
public Network(ManagedObjectReference _this)
{
this.setMoRef(_this);
}
public void setMoRef(ManagedObjectReference moRef)
{
this.moRef = moRef;
}
public ManagedObjectReference getMoRef()
{
return moRef;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
///<summary>
///Take the ObjectContent[] from RetrieveProperties()
///and print it out.
///ObjectContent[] should have Network information
///</summary>
private static void printNetworkInfo(ObjectContent[] ocs)
{
// Network MoRef -> Network
Hashtable networksByNetwork = new Hashtable();
// Network MoRef -> Host
Hashtable hostsByNetwork = new Hashtable();
// Network MoRef -> VirtualMachine
Hashtable vmsByNetwork = new Hashtable();
// HostSystem MoRef -> Host
Hashtable hostByHost = new Hashtable();
if (ocs != null)
{
for (int i = 0; i < ocs.Length; ++i)
{
ObjectContent oc = ocs[i];
String type = oc.obj.type;
// Create our Network objects
if ("Network".Equals(type))
{
Network network = new Network(oc.obj);
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
for (int j = 0; j < dps.Length; ++j)
{
DynamicProperty dp = dps[j];
if ("name".Equals(dp.name))
{
network.setName((String)dp.val);
}
}
}
// Put them in the Map
networksByNetwork.Add(oc.obj.Value,
network);
// Create our Host objects
}
else if ("HostSystem".Equals(type))
{
Host cHost = new Host(oc.obj);
ManagedObjectReference[] network = null;
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
for (int j = 0; j < dps.Length; ++j)
{
String pName = dps[j].name;
Object pVal = dps[j].val;
if ("name".Equals(pName))
{
cHost.setName((String)pVal);
}
else if ("network".Equals(pName))
{
network =
(ManagedObjectReference[])pVal;
}
else if (
"summary.hardware".Equals(pName))
{
cHost.setHardware(
(HostHardwareSummary)pVal);
}
else if ("runtime.connectionState"
.Equals(pName))
{
cHost.setConnectionState(
(HostSystemConnectionState)pVal);
}
else if ("summary.overallStatus"
.Equals(pName))
{
cHost.setOverallStatus(
(ManagedEntityStatus)pVal);
}
else if ("summary.quickStats"
.Equals(pName))
{
cHost.setQuickStats(
(HostListSummaryQuickStats)pVal);
}
}
}
Host host = new Host(
cHost.getMoRef(),
cHost.getName(),
cHost.getHardware(),
cHost.getConnectionState(),
cHost.getOverallStatus(),
cHost.getQuickStats());
hostByHost.Add(
host.getMoRef().Value, host);
for (int n = 0; n < network.Length; ++n)
{
ArrayList hl = (ArrayList)hostsByNetwork[network[n].Value];
if (hl == null)
{
hl = new ArrayList();
hostsByNetwork.Add(network[n].Value,
hl);
}
hl.Add(host);
}
// Create our VirtualMachine objects
}
else if ("VirtualMachine".Equals(type))
{
VirtualMachine cVm =
new VirtualMachine(oc.obj);
ManagedObjectReference[] network = null;
DynamicProperty[] dps = oc.propSet;
if (dps != null)
{
for (int j = 0; j < dps.Length; ++j)
{
String pName = dps[j].name;
Object pVal = dps[j].val;
if ("name".Equals(pName))
{
cVm.setName((String)pVal);
}
else if ("network".Equals(pName))
{
network =
(ManagedObjectReference[])pVal;
}
else if ("runtime.host".Equals(pName))
{
cVm.setHost(
(ManagedObjectReference)pVal);
}
else if ("runtime.powerState"
.Equals(pName))
{
cVm.setPowerState(
(VirtualMachinePowerState)pVal);
}
else if ("summary.overallStatus"
.Equals(pName))
{
cVm.setOverallStatus(
(ManagedEntityStatus)pVal);
}
else if ("summary.quickStats"
.Equals(pName))
{
cVm.setQuickStats(
(VirtualMachineQuickStats)pVal);
}
}
}
VirtualMachine vm = new VirtualMachine(
cVm.getMoRef(),
cVm.getName(),
cVm.getHost(),
cVm.getPowerState(),
cVm.getOverallStatus(),
cVm.getQuickStats());
for (int n = 0; n < network.Length; ++n)
{
ArrayList vml = (ArrayList)vmsByNetwork[network[n].Value];
if (vml == null)
{
vml = new ArrayList();
vmsByNetwork.Add(network[n].Value,
vml);
}
vml.Add(vm);
}
}
}
}
// Now the Hashtables have all the information
// Now populate our Network object with the Hosts
// and VMs connected and print out the 'tables'
for (IEnumerator nit = networksByNetwork.GetEnumerator();
nit.MoveNext(); )
{
foreach (String key in networksByNetwork.Keys)
{
Network network = networksByNetwork[key] as Network;
if (network != null)
{
ArrayList vms = (ArrayList)
vmsByNetwork[network.getMoRef().Value];
ArrayList hosts = (ArrayList)hostsByNetwork[network.getMoRef().Value];
Console.WriteLine("Network: " + network.getName());
Console.WriteLine(" Virtual Machines:");
if (vms != null)
{
for (IEnumerator vmIt = vms.GetEnumerator(); vmIt.MoveNext(); )
{
VirtualMachine vm = (VirtualMachine)vmIt.Current;
Host host =
(Host)hostByHost[vm.getHost().Value];
int cpuUsage =
vm.getQuickStats().overallCpuUsage;
int memUsage =
vm.getQuickStats().hostMemoryUsage;
StringBuilder sb = new StringBuilder();
sb
.Append(" Name :")
.Append(vm.getName())
.Append("\n")
.Append(" State :")
.Append(vm.getPowerState())
.Append("\n")
.Append(" Status :")
.Append(vm.getOverallStatus())
.Append("\n")
.Append(" Host Name :")
.Append(host != null ? host.getName() : "")
.Append("\n")
.Append(" Host CPU MHZ :")
.Append(cpuUsage != null ? cpuUsage
: 0)
.Append("\n")
.Append(" Host Mem = MB :")
.Append(memUsage != null ?
memUsage / 1024 / 1024
: 0)
.Append("\n");
Console.WriteLine(sb.ToString());
}
}
Console.WriteLine(" Hosts:");
if (hosts != null)
{
for (IEnumerator hostIt = hosts.GetEnumerator();
hostIt.MoveNext(); )
{
Host host = (Host)hostIt.Current;
int cpuUsage =
host.getQuickStats().overallCpuUsage;
int memUsage = host.getQuickStats().overallMemoryUsage;
StringBuilder sb = new StringBuilder();
sb
.Append(" Name :")
.Append(host.getName())
.Append("\n")
.Append(" State :")
.Append(host.getConnectionState())
.Append("\n")
.Append(" Status :")
.Append(host.getOverallStatus())
.Append("\n")
.Append(" CPU % :")
.Append(cpuUsage != null ? cpuUsage : 0)
.Append("\n")
.Append(" Mem MB :")
.Append(memUsage != null ? memUsage
: 0).Append("\n");
Console.WriteLine(sb.ToString());
}
}
}
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RegexBoyerMoore.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
// The RegexBoyerMoore object precomputes the Boyer-Moore
// tables for fast string scanning. These tables allow
// you to scan for the first occurance of a string within
// a large body of text without examining every character.
// The performance of the heuristic depends on the actual
// string and the text being searched, but usually, the longer
// the string that is being searched for, the fewer characters
// need to be examined.
namespace System.Text.RegularExpressions
{
using System.Collections;
using System.Diagnostics;
using System.Globalization;
internal sealed class RegexBoyerMoore {
internal int[] _positive;
internal int[] _negativeASCII;
internal int[][] _negativeUnicode;
internal String _pattern;
internal int _lowASCII;
internal int _highASCII;
internal bool _rightToLeft;
internal bool _caseInsensitive;
internal CultureInfo _culture;
internal const int infinite = 0x7FFFFFFF;
/*
* Constructs a Boyer-Moore state machine for searching for the string
* pattern. The string must not be zero-length.
*/
internal RegexBoyerMoore(String pattern, bool caseInsensitive, bool rightToLeft, CultureInfo culture) {
/*
* Sorry, you just can't use Boyer-Moore to find an empty pattern.
* We're doing this for your own protection. (Really, for speed.)
*/
Debug.Assert(pattern.Length != 0, "RegexBoyerMoore called with an empty string. This is bad for perf");
int beforefirst;
int last;
int bump;
int examine;
int scan;
int match;
char ch;
// We do the ToLower character by character for consistency. With surrogate chars, doing
// a ToLower on the entire string could actually change the surrogate pair. This is more correct
// linguistically, but since Regex doesn't support surrogates, it's more important to be
// consistent.
if (caseInsensitive) {
StringBuilder sb = new StringBuilder(pattern.Length);
for (int i=0; i<pattern.Length; i++)
sb.Append(Char.ToLower(pattern[i], culture));
pattern = sb.ToString();
}
_pattern = pattern;
_rightToLeft = rightToLeft;
_caseInsensitive = caseInsensitive;
_culture = culture;
if (!rightToLeft) {
beforefirst = -1;
last = pattern.Length - 1;
bump = 1;
}
else {
beforefirst = pattern.Length;
last = 0;
bump = -1;
}
/*
* PART I - the good-suffix shift table
*
* compute the positive requirement:
* if char "i" is the first one from the right that doesn't match,
* then we know the matcher can advance by _positive[i].
*
* <STRIP> This algorithm appears to be a simplified variant of the
* standard Boyer-Moore good suffix calculation. It could
* be one of D.M. Sunday's variations, but I have not found which one.
* </STRIP>
* <
*/
_positive = new int[pattern.Length];
examine = last;
ch = pattern[examine];
_positive[examine] = bump;
examine -= bump;
for (;;) {
// find an internal char (examine) that matches the tail
for (;;) {
if (examine == beforefirst)
goto OuterloopBreak;
if (pattern[examine] == ch)
break;
examine -= bump;
}
match = last;
scan = examine;
// find the length of the match
for (;;) {
if (scan == beforefirst || pattern[match] != pattern[scan]) {
// at the end of the match, note the difference in _positive
// this is not the length of the match, but the distance from the internal match
// to the tail suffix.
if (_positive[match] == 0)
_positive[match] = match - scan;
// System.Diagnostics.Debug.WriteLine("Set positive[" + match + "] to " + (match - scan));
break;
}
scan -= bump;
match -= bump;
}
examine -= bump;
}
OuterloopBreak:
match = last - bump;
// scan for the chars for which there are no shifts that yield a different candidate
/* <STRIP>
* The inside of the if statement used to say
* "_positive[match] = last - beforefirst;"
* I've changed it to the below code. This
* is slightly less agressive in how much we skip, but at worst it
* should mean a little more work rather than skipping a potential
* match.
* </STRIP>
*/
while (match != beforefirst) {
if (_positive[match] == 0)
_positive[match] = bump;
match -= bump;
}
//System.Diagnostics.Debug.WriteLine("good suffix shift table:");
//for (int i=0; i<_positive.Length; i++)
// System.Diagnostics.Debug.WriteLine("\t_positive[" + i + "] = " + _positive[i]);
/*
* PART II - the bad-character shift table
*
* compute the negative requirement:
* if char "ch" is the reject character when testing position "i",
* we can slide up by _negative[ch];
* (_negative[ch] = str.Length - 1 - str.LastIndexOf(ch))
*
* the lookup table is divided into ASCII and Unicode portions;
* only those parts of the Unicode 16-bit code set that actually
* appear in the string are in the table. (Maximum size with
* Unicode is 65K; ASCII only case is 512 bytes.)
*/
_negativeASCII = new int[128];
for (int i = 0; i < 128; i++)
_negativeASCII[i] = last - beforefirst;
_lowASCII = 127;
_highASCII = 0;
for (examine = last; examine != beforefirst; examine -= bump) {
ch = pattern[examine];
if (ch < 128) {
if (_lowASCII > ch)
_lowASCII = ch;
if (_highASCII < ch)
_highASCII = ch;
if (_negativeASCII[ch] == last - beforefirst)
_negativeASCII[ch] = last - examine;
}
else {
int i = ch >> 8;
int j = ch & 0xFF;
if (_negativeUnicode == null) {
_negativeUnicode = new int[256][];
}
if (_negativeUnicode[i] == null) {
int[] newarray = new int[256];
for (int k = 0; k < 256; k++)
newarray[k] = last - beforefirst;
if (i == 0) {
System.Array.Copy(_negativeASCII, newarray, 128);
_negativeASCII = newarray;
}
_negativeUnicode[i] = newarray;
}
if (_negativeUnicode[i][j] == last - beforefirst)
_negativeUnicode[i][j] = last - examine;
}
}
}
private bool MatchPattern(string text, int index) {
if (_caseInsensitive) {
if( text.Length - index < _pattern.Length) {
return false;
}
TextInfo textinfo = _culture.TextInfo;
for( int i = 0; i < _pattern.Length; i++) {
Debug.Assert(textinfo.ToLower(_pattern[i]) == _pattern[i], "pattern should be converted to lower case in constructor!");
if( textinfo.ToLower(text[index + i]) != _pattern[i]) {
return false;
}
}
return true;
}
else {
return(0 == String.CompareOrdinal(_pattern, 0, text, index, _pattern.Length));
}
}
/*
* When a regex is anchored, we can do a quick IsMatch test instead of a Scan
*/
internal bool IsMatch(String text, int index, int beglimit, int endlimit) {
if (!_rightToLeft) {
if (index < beglimit || endlimit - index < _pattern.Length)
return false;
return MatchPattern(text, index);
}
else {
if (index > endlimit || index - beglimit < _pattern.Length)
return false;
return MatchPattern(text, index - _pattern.Length);
}
}
/*
* Scan uses the Boyer-Moore algorithm to find the first occurrance
* of the specified string within text, beginning at index, and
* constrained within beglimit and endlimit.
*
* The direction and case-sensitivity of the match is determined
* by the arguments to the RegexBoyerMoore constructor.
*/
internal int Scan(String text, int index, int beglimit, int endlimit) {
int test;
int test2;
int match;
int startmatch;
int endmatch;
int advance;
int defadv;
int bump;
char chMatch;
char chTest;
int[] unicodeLookup;
if (!_rightToLeft) {
defadv = _pattern.Length;
startmatch = _pattern.Length - 1;
endmatch = 0;
test = index + defadv - 1;
bump = 1;
}
else {
defadv = -_pattern.Length;
startmatch = 0;
endmatch = -defadv - 1;
test = index + defadv;
bump = -1;
}
chMatch = _pattern[startmatch];
for (;;) {
if (test >= endlimit || test < beglimit)
return -1;
chTest = text[test];
if (_caseInsensitive)
chTest = Char.ToLower(chTest, _culture);
if (chTest != chMatch) {
if (chTest < 128)
advance = _negativeASCII[chTest];
else if (null != _negativeUnicode && (null != (unicodeLookup = _negativeUnicode[chTest >> 8])))
advance = unicodeLookup[chTest & 0xFF];
else
advance = defadv;
test += advance;
}
else { // if (chTest == chMatch)
test2 = test;
match = startmatch;
for (;;) {
if (match == endmatch)
return(_rightToLeft ? test2 + 1 : test2);
match -= bump;
test2 -= bump;
chTest = text[test2];
if (_caseInsensitive)
chTest = Char.ToLower(chTest, _culture);
if (chTest != _pattern[match]) {
advance = _positive[match];
if ((chTest & 0xFF80) == 0)
test2 = (match - startmatch) + _negativeASCII[chTest];
else if (null != _negativeUnicode && (null != (unicodeLookup = _negativeUnicode[chTest >> 8])))
test2 = (match - startmatch) + unicodeLookup[chTest & 0xFF];
else {
test += advance;
break;
}
if (_rightToLeft ? test2 < advance : test2 > advance)
advance = test2;
test += advance;
break;
}
}
}
}
}
/*
* Used when dumping for debugging.
*/
public override String ToString() {
return _pattern;
}
#if DBG
public String Dump(String indent) {
StringBuilder sb = new StringBuilder();
sb.Append(indent + "BM Pattern: " + _pattern + "\n");
sb.Append(indent + "Positive: ");
for (int i = 0; i < _positive.Length; i++) {
sb.Append(_positive[i].ToString(CultureInfo.InvariantCulture) + " ");
}
sb.Append("\n");
if (_negativeASCII != null) {
sb.Append(indent + "Negative table\n");
for (int i = 0; i < _negativeASCII.Length; i++) {
if (_negativeASCII[i] != _pattern.Length) {
sb.Append(indent + " " + Regex.Escape(Convert.ToString((char)i, CultureInfo.InvariantCulture)) + " " + _negativeASCII[i].ToString(CultureInfo.InvariantCulture) + "\n");
}
}
}
return sb.ToString();
}
#endif
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Compression
{
public partial class DeflateStream : Stream
{
private const int DefaultBufferSize = 8192;
private Stream _stream;
private CompressionMode _mode;
private bool _leaveOpen;
private Inflater _inflater;
private Deflater _deflater;
private byte[] _buffer;
private int _activeAsyncOperation; // 1 == true, 0 == false
private bool _wroteBytes;
public DeflateStream(Stream stream, CompressionMode mode) : this(stream, mode, leaveOpen: false)
{
}
public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, leaveOpen, ZLibNative.Deflate_DefaultWindowBits)
{
}
// Implies mode = Compress
public DeflateStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, leaveOpen: false)
{
}
// Implies mode = Compress
public DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) : this(stream, compressionLevel, leaveOpen, ZLibNative.Deflate_DefaultWindowBits)
{
}
/// <summary>
/// Internal constructor to check stream validity and call the correct initialization function depending on
/// the value of the CompressionMode given.
/// </summary>
internal DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen, int windowBits)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
switch (mode)
{
case CompressionMode.Decompress:
InitializeInflater(stream, leaveOpen, windowBits);
break;
case CompressionMode.Compress:
InitializeDeflater(stream, leaveOpen, windowBits, CompressionLevel.Optimal);
break;
default:
throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(mode));
}
}
/// <summary>
/// Internal constructor to specify the compressionlevel as well as the windowbits
/// </summary>
internal DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowBits)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
InitializeDeflater(stream, leaveOpen, windowBits, compressionLevel);
}
/// <summary>
/// Sets up this DeflateStream to be used for Zlib Inflation/Decompression
/// </summary>
internal void InitializeInflater(Stream stream, bool leaveOpen, int windowBits)
{
Debug.Assert(stream != null);
if (!stream.CanRead)
throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream));
_inflater = new Inflater(windowBits);
_stream = stream;
_mode = CompressionMode.Decompress;
_leaveOpen = leaveOpen;
}
/// <summary>
/// Sets up this DeflateStream to be used for Zlib Deflation/Compression
/// </summary>
internal void InitializeDeflater(Stream stream, bool leaveOpen, int windowBits, CompressionLevel compressionLevel)
{
Debug.Assert(stream != null);
if (!stream.CanWrite)
throw new ArgumentException(SR.NotSupported_UnwritableStream, nameof(stream));
_deflater = new Deflater(compressionLevel, windowBits);
_stream = stream;
_mode = CompressionMode.Compress;
_leaveOpen = leaveOpen;
InitializeBuffer();
}
private void InitializeBuffer()
{
Debug.Assert(_buffer == null);
_buffer = ArrayPool<byte>.Shared.Rent(DefaultBufferSize);
}
private void EnsureBufferInitialized()
{
if (_buffer == null)
{
InitializeBuffer();
}
}
public Stream BaseStream => _stream;
public override bool CanRead
{
get
{
if (_stream == null)
{
return false;
}
return (_mode == CompressionMode.Decompress && _stream.CanRead);
}
}
public override bool CanWrite
{
get
{
if (_stream == null)
{
return false;
}
return (_mode == CompressionMode.Compress && _stream.CanWrite);
}
}
public override bool CanSeek => false;
public override long Length
{
get { throw new NotSupportedException(SR.NotSupported); }
}
public override long Position
{
get { throw new NotSupportedException(SR.NotSupported); }
set { throw new NotSupportedException(SR.NotSupported); }
}
public override void Flush()
{
EnsureNotDisposed();
if (_mode == CompressionMode.Compress)
FlushBuffers();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
EnsureNoActiveAsyncOperation();
EnsureNotDisposed();
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
return _mode != CompressionMode.Compress || !_wroteBytes ? Task.CompletedTask : FlushAsyncCore(cancellationToken);
}
private async Task FlushAsyncCore(CancellationToken cancellationToken)
{
AsyncOperationStarting();
try
{
// Compress any bytes left:
await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false);
// Pull out any bytes left inside deflater:
bool flushSuccessful;
do
{
int compressedBytes;
flushSuccessful = _deflater.Flush(_buffer, out compressedBytes);
if (flushSuccessful)
{
await _stream.WriteAsync(new ReadOnlyMemory<byte>(_buffer, 0, compressedBytes), cancellationToken).ConfigureAwait(false);
}
Debug.Assert(flushSuccessful == (compressedBytes > 0));
} while (flushSuccessful);
}
finally
{
AsyncOperationCompleting();
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.NotSupported);
}
public override void SetLength(long value)
{
throw new NotSupportedException(SR.NotSupported);
}
public override int ReadByte()
{
EnsureDecompressionMode();
EnsureNotDisposed();
// Try to read a single byte from zlib without allocating an array, pinning an array, etc.
// If zlib doesn't have any data, fall back to the base stream implementation, which will do that.
byte b;
return _inflater.Inflate(out b) ? b : base.ReadByte();
}
public override int Read(byte[] array, int offset, int count)
{
ValidateParameters(array, offset, count);
return ReadCore(new Span<byte>(array, offset, count));
}
public override int Read(Span<byte> buffer)
{
if (GetType() != typeof(DeflateStream))
{
// DeflateStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
// to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
// should use the behavior of Read(byte[],int,int) overload.
return base.Read(buffer);
}
else
{
return ReadCore(buffer);
}
}
internal int ReadCore(Span<byte> buffer)
{
EnsureDecompressionMode();
EnsureNotDisposed();
EnsureBufferInitialized();
int totalRead = 0;
while (true)
{
int bytesRead = _inflater.Inflate(buffer.Slice(totalRead));
totalRead += bytesRead;
if (totalRead == buffer.Length)
{
break;
}
// If the stream is finished then we have a few potential cases here:
// 1. DeflateStream => return
// 2. GZipStream that is finished but may have an additional GZipStream appended => feed more input
// 3. GZipStream that is finished and appended with garbage => return
if (_inflater.Finished() && (!_inflater.IsGzipStream() || !_inflater.NeedsInput()))
{
break;
}
if (_inflater.NeedsInput())
{
int bytes = _stream.Read(_buffer, 0, _buffer.Length);
if (bytes <= 0)
{
break;
}
else if (bytes > _buffer.Length)
{
// The stream is either malicious or poorly implemented and returned a number of
// bytes larger than the buffer supplied to it.
throw new InvalidDataException(SR.GenericInvalidData);
}
_inflater.SetInput(_buffer, 0, bytes);
}
}
return totalRead;
}
private void ValidateParameters(byte[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (array.Length - offset < count)
throw new ArgumentException(SR.InvalidArgumentOffsetCount);
}
private void EnsureNotDisposed()
{
if (_stream == null)
ThrowStreamClosedException();
}
private static void ThrowStreamClosedException()
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
private void EnsureDecompressionMode()
{
if (_mode != CompressionMode.Decompress)
ThrowCannotReadFromDeflateStreamException();
}
private static void ThrowCannotReadFromDeflateStreamException()
{
throw new InvalidOperationException(SR.CannotReadFromDeflateStream);
}
private void EnsureCompressionMode()
{
if (_mode != CompressionMode.Compress)
ThrowCannotWriteToDeflateStreamException();
}
private static void ThrowCannotWriteToDeflateStreamException()
{
throw new InvalidOperationException(SR.CannotWriteToDeflateStream);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public override Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
ValidateParameters(array, offset, count);
return ReadAsyncMemory(new Memory<byte>(array, offset, count), cancellationToken).AsTask();
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
{
if (GetType() != typeof(DeflateStream))
{
// Ensure that existing streams derived from DeflateStream and that override ReadAsync(byte[],...)
// get their existing behaviors when the newer Memory-based overload is used.
return base.ReadAsync(buffer, cancellationToken);
}
else
{
return ReadAsyncMemory(buffer, cancellationToken);
}
}
internal ValueTask<int> ReadAsyncMemory(Memory<byte> buffer, CancellationToken cancellationToken)
{
EnsureDecompressionMode();
EnsureNoActiveAsyncOperation();
EnsureNotDisposed();
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
EnsureBufferInitialized();
bool cleanup = true;
AsyncOperationStarting();
try
{
while (true)
{
// Finish inflating any bytes in the input buffer
int bytesRead = 0, bytesReadIteration = -1;
while (bytesRead < buffer.Length && bytesReadIteration != 0)
{
bytesReadIteration = _inflater.Inflate(buffer.Span.Slice(bytesRead));
bytesRead += bytesReadIteration;
}
if (bytesRead != 0)
{
// If decompression output buffer is not empty, return immediately.
return new ValueTask<int>(bytesRead);
}
// If the stream is finished then we have a few potential cases here:
// 1. DeflateStream that is finished => return
// 2. GZipStream that is finished but may have an additional GZipStream appended => feed more input
// 3. GZipStream that is finished and appended with garbage => return
if (_inflater.Finished() && (!_inflater.IsGzipStream() || !_inflater.NeedsInput()))
{
return new ValueTask<int>(0);
}
if (_inflater.NeedsInput())
{
// If there is no data on the output buffer and we are not at
// the end of the stream, we need to get more data from the base stream
ValueTask<int> readTask = _stream.ReadAsync(_buffer, cancellationToken);
cleanup = false;
return FinishReadAsyncMemory(readTask, buffer, cancellationToken);
}
}
}
finally
{
// if we haven't started any async work, decrement the counter to end the transaction
if (cleanup)
{
AsyncOperationCompleting();
}
}
}
private async ValueTask<int> FinishReadAsyncMemory(
ValueTask<int> readTask, Memory<byte> buffer, CancellationToken cancellationToken)
{
try
{
while (true)
{
if (_inflater.NeedsInput())
{
int bytesRead = await readTask.ConfigureAwait(false);
EnsureNotDisposed();
if (bytesRead <= 0)
{
// This indicates the base stream has received EOF
return 0;
}
else if (bytesRead > _buffer.Length)
{
// The stream is either malicious or poorly implemented and returned a number of
// bytes larger than the buffer supplied to it.
throw new InvalidDataException(SR.GenericInvalidData);
}
cancellationToken.ThrowIfCancellationRequested();
// Feed the data from base stream into decompression engine
_inflater.SetInput(_buffer, 0, bytesRead);
}
// Finish inflating any bytes in the input buffer
int inflatedBytes = 0, bytesReadIteration = -1;
while (inflatedBytes < buffer.Length && bytesReadIteration != 0)
{
bytesReadIteration = _inflater.Inflate(buffer.Span.Slice(inflatedBytes));
inflatedBytes += bytesReadIteration;
}
// There are a few different potential states here
// 1. DeflateStream or GZipStream that succesfully read bytes => return those bytes
// 2. DeflateStream or GZipStream that didn't read bytes and isn't finished => feed more input
// 3. DeflateStream that didn't read bytes, but is finished => return 0
// 4. GZipStream that is finished but is appended with another gzip stream => feed more input
// 5. GZipStream that is finished and appended with garbage => return 0
if (inflatedBytes != 0)
{
// If decompression output buffer is not empty, return immediately.
return inflatedBytes;
}
else if (_inflater.Finished() && (!_inflater.IsGzipStream() || !_inflater.NeedsInput()))
{
return 0;
}
else if (_inflater.NeedsInput())
{
// We could have read in head information and didn't get any data.
// Read from the base stream again.
readTask = _stream.ReadAsync(_buffer, cancellationToken);
}
}
}
finally
{
AsyncOperationCompleting();
}
}
public override void Write(byte[] array, int offset, int count)
{
ValidateParameters(array, offset, count);
WriteCore(new ReadOnlySpan<byte>(array, offset, count));
}
public override void Write(ReadOnlySpan<byte> buffer)
{
if (GetType() != typeof(DeflateStream))
{
// DeflateStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
// to this Write(ReadOnlySpan<byte>) overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload
// should use the behavior of Write(byte[],int,int) overload.
base.Write(buffer);
}
else
{
WriteCore(buffer);
}
}
internal void WriteCore(ReadOnlySpan<byte> buffer)
{
EnsureCompressionMode();
EnsureNotDisposed();
// Write compressed the bytes we already passed to the deflater:
WriteDeflaterOutput();
unsafe
{
// Pass new bytes through deflater and write them too:
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
_deflater.SetInput(bufferPtr, buffer.Length);
WriteDeflaterOutput();
_wroteBytes = true;
}
}
}
private void WriteDeflaterOutput()
{
while (!_deflater.NeedsInput())
{
int compressedBytes = _deflater.GetDeflateOutput(_buffer);
if (compressedBytes > 0)
{
_stream.Write(_buffer, 0, compressedBytes);
}
}
}
// This is called by Flush:
private void FlushBuffers()
{
// Make sure to only "flush" when we actually had some input:
if (_wroteBytes)
{
// Compress any bytes left:
WriteDeflaterOutput();
// Pull out any bytes left inside deflater:
bool flushSuccessful;
do
{
int compressedBytes;
flushSuccessful = _deflater.Flush(_buffer, out compressedBytes);
if (flushSuccessful)
{
_stream.Write(_buffer, 0, compressedBytes);
}
Debug.Assert(flushSuccessful == (compressedBytes > 0));
} while (flushSuccessful);
}
}
// This is called by Dispose:
private void PurgeBuffers(bool disposing)
{
if (!disposing)
return;
if (_stream == null)
return;
if (_mode != CompressionMode.Compress)
return;
// Some deflaters (e.g. ZLib) write more than zero bytes for zero byte inputs.
// This round-trips and we should be ok with this, but our legacy managed deflater
// always wrote zero output for zero input and upstack code (e.g. ZipArchiveEntry)
// took dependencies on it. Thus, make sure to only "flush" when we actually had
// some input:
if (_wroteBytes)
{
// Compress any bytes left
WriteDeflaterOutput();
// Pull out any bytes left inside deflater:
bool finished;
do
{
int compressedBytes;
finished = _deflater.Finish(_buffer, out compressedBytes);
if (compressedBytes > 0)
_stream.Write(_buffer, 0, compressedBytes);
} while (!finished);
}
else
{
// In case of zero length buffer, we still need to clean up the native created stream before
// the object get disposed because eventually ZLibNative.ReleaseHandle will get called during
// the dispose operation and although it frees the stream but it return error code because the
// stream state was still marked as in use. The symptoms of this problem will not be seen except
// if running any diagnostic tools which check for disposing safe handle objects
bool finished;
do
{
int compressedBytes;
finished = _deflater.Finish(_buffer, out compressedBytes);
} while (!finished);
}
}
private async Task PurgeBuffersAsync()
{
// Same logic as PurgeBuffers, except with async counterparts.
if (_stream == null)
return;
if (_mode != CompressionMode.Compress)
return;
// Some deflaters (e.g. ZLib) write more than zero bytes for zero byte inputs.
// This round-trips and we should be ok with this, but our legacy managed deflater
// always wrote zero output for zero input and upstack code (e.g. ZipArchiveEntry)
// took dependencies on it. Thus, make sure to only "flush" when we actually had
// some input.
if (_wroteBytes)
{
// Compress any bytes left
await WriteDeflaterOutputAsync(default).ConfigureAwait(false);
// Pull out any bytes left inside deflater:
bool finished;
do
{
int compressedBytes;
finished = _deflater.Finish(_buffer, out compressedBytes);
if (compressedBytes > 0)
await _stream.WriteAsync(new ReadOnlyMemory<byte>(_buffer, 0, compressedBytes)).ConfigureAwait(false);
} while (!finished);
}
else
{
// In case of zero length buffer, we still need to clean up the native created stream before
// the object get disposed because eventually ZLibNative.ReleaseHandle will get called during
// the dispose operation and although it frees the stream, it returns an error code because the
// stream state was still marked as in use. The symptoms of this problem will not be seen except
// if running any diagnostic tools which check for disposing safe handle objects.
bool finished;
do
{
int compressedBytes;
finished = _deflater.Finish(_buffer, out compressedBytes);
} while (!finished);
}
}
protected override void Dispose(bool disposing)
{
try
{
PurgeBuffers(disposing);
}
finally
{
// Close the underlying stream even if PurgeBuffers threw.
// Stream.Close() may throw here (may or may not be due to the same error).
// In this case, we still need to clean up internal resources, hence the inner finally blocks.
try
{
if (disposing && !_leaveOpen)
_stream?.Dispose();
}
finally
{
_stream = null;
try
{
_deflater?.Dispose();
_inflater?.Dispose();
}
finally
{
_deflater = null;
_inflater = null;
byte[] buffer = _buffer;
if (buffer != null)
{
_buffer = null;
if (!AsyncOperationIsActive)
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
base.Dispose(disposing);
}
}
}
}
public override ValueTask DisposeAsync()
{
return GetType() == typeof(DeflateStream) ?
DisposeAsyncCore() :
base.DisposeAsync();
}
private async ValueTask DisposeAsyncCore()
{
// Same logic as Dispose(true), except with async counterparts.
try
{
await PurgeBuffersAsync().ConfigureAwait(false);
}
finally
{
// Close the underlying stream even if PurgeBuffers threw.
// Stream.Close() may throw here (may or may not be due to the same error).
// In this case, we still need to clean up internal resources, hence the inner finally blocks.
Stream stream = _stream;
_stream = null;
try
{
if (!_leaveOpen && stream != null)
await stream.DisposeAsync().ConfigureAwait(false);
}
finally
{
try
{
_deflater?.Dispose();
_inflater?.Dispose();
}
finally
{
_deflater = null;
_inflater = null;
byte[] buffer = _buffer;
if (buffer != null)
{
_buffer = null;
if (!AsyncOperationIsActive)
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
}
}
}
public override IAsyncResult BeginWrite(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(WriteAsync(array, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
public override Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
ValidateParameters(array, offset, count);
return WriteAsyncMemory(new ReadOnlyMemory<byte>(array, offset, count), cancellationToken).AsTask();
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
if (GetType() != typeof(DeflateStream))
{
// Ensure that existing streams derived from DeflateStream and that override WriteAsync(byte[],...)
// get their existing behaviors when the newer Memory-based overload is used.
return base.WriteAsync(buffer, cancellationToken);
}
else
{
return WriteAsyncMemory(buffer, cancellationToken);
}
}
internal ValueTask WriteAsyncMemory(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
EnsureCompressionMode();
EnsureNoActiveAsyncOperation();
EnsureNotDisposed();
return new ValueTask(cancellationToken.IsCancellationRequested ?
Task.FromCanceled<int>(cancellationToken) :
WriteAsyncMemoryCore(buffer, cancellationToken));
}
private async Task WriteAsyncMemoryCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
AsyncOperationStarting();
try
{
await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false);
// Pass new bytes through deflater
_deflater.SetInput(buffer);
await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false);
_wroteBytes = true;
}
finally
{
AsyncOperationCompleting();
}
}
/// <summary>
/// Writes the bytes that have already been deflated
/// </summary>
private async Task WriteDeflaterOutputAsync(CancellationToken cancellationToken)
{
while (!_deflater.NeedsInput())
{
int compressedBytes = _deflater.GetDeflateOutput(_buffer);
if (compressedBytes > 0)
{
await _stream.WriteAsync(new ReadOnlyMemory<byte>(_buffer, 0, compressedBytes), cancellationToken).ConfigureAwait(false);
}
}
}
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
EnsureDecompressionMode();
EnsureNotDisposed();
new CopyToStream(this, destination, bufferSize).CopyFromSourceToDestination();
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validation as base CopyToAsync would do
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// Validation as ReadAsync would do
EnsureDecompressionMode();
EnsureNoActiveAsyncOperation();
EnsureNotDisposed();
// Early check for cancellation
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
// Do the copy
return new CopyToStream(this, destination, bufferSize, cancellationToken).CopyFromSourceToDestinationAsync();
}
private sealed class CopyToStream : Stream
{
private readonly DeflateStream _deflateStream;
private readonly Stream _destination;
private readonly CancellationToken _cancellationToken;
private byte[] _arrayPoolBuffer;
public CopyToStream(DeflateStream deflateStream, Stream destination, int bufferSize) :
this(deflateStream, destination, bufferSize, CancellationToken.None)
{
}
public CopyToStream(DeflateStream deflateStream, Stream destination, int bufferSize, CancellationToken cancellationToken)
{
Debug.Assert(deflateStream != null);
Debug.Assert(destination != null);
Debug.Assert(bufferSize > 0);
_deflateStream = deflateStream;
_destination = destination;
_cancellationToken = cancellationToken;
_arrayPoolBuffer = ArrayPool<byte>.Shared.Rent(bufferSize);
}
public async Task CopyFromSourceToDestinationAsync()
{
_deflateStream.AsyncOperationStarting();
try
{
// Flush any existing data in the inflater to the destination stream.
while (true)
{
int bytesRead = _deflateStream._inflater.Inflate(_arrayPoolBuffer, 0, _arrayPoolBuffer.Length);
if (bytesRead > 0)
{
await _destination.WriteAsync(new ReadOnlyMemory<byte>(_arrayPoolBuffer, 0, bytesRead), _cancellationToken).ConfigureAwait(false);
}
else
{
break;
}
}
// Now, use the source stream's CopyToAsync to push directly to our inflater via this helper stream
await _deflateStream._stream.CopyToAsync(this, _arrayPoolBuffer.Length, _cancellationToken).ConfigureAwait(false);
}
finally
{
_deflateStream.AsyncOperationCompleting();
ArrayPool<byte>.Shared.Return(_arrayPoolBuffer);
_arrayPoolBuffer = null;
}
}
public void CopyFromSourceToDestination()
{
try
{
// Flush any existing data in the inflater to the destination stream.
while (true)
{
int bytesRead = _deflateStream._inflater.Inflate(_arrayPoolBuffer, 0, _arrayPoolBuffer.Length);
if (bytesRead > 0)
{
_destination.Write(_arrayPoolBuffer, 0, bytesRead);
}
else
{
break;
}
}
// Now, use the source stream's CopyToAsync to push directly to our inflater via this helper stream
_deflateStream._stream.CopyTo(this, _arrayPoolBuffer.Length);
}
finally
{
ArrayPool<byte>.Shared.Return(_arrayPoolBuffer);
_arrayPoolBuffer = null;
}
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// Validate inputs
Debug.Assert(buffer != _arrayPoolBuffer);
_deflateStream.EnsureNotDisposed();
if (count <= 0)
{
return;
}
else if (count > buffer.Length - offset)
{
// The buffer stream is either malicious or poorly implemented and returned a number of
// bytes larger than the buffer supplied to it.
throw new InvalidDataException(SR.GenericInvalidData);
}
// Feed the data from base stream into the decompression engine.
_deflateStream._inflater.SetInput(buffer, offset, count);
// While there's more decompressed data available, forward it to the buffer stream.
while (true)
{
int bytesRead = _deflateStream._inflater.Inflate(new Span<byte>(_arrayPoolBuffer));
if (bytesRead > 0)
{
await _destination.WriteAsync(new ReadOnlyMemory<byte>(_arrayPoolBuffer, 0, bytesRead), cancellationToken).ConfigureAwait(false);
}
else
{
break;
}
}
}
public override void Write(byte[] buffer, int offset, int count)
{
// Validate inputs
Debug.Assert(buffer != _arrayPoolBuffer);
_deflateStream.EnsureNotDisposed();
if (count <= 0)
{
return;
}
else if (count > buffer.Length - offset)
{
// The buffer stream is either malicious or poorly implemented and returned a number of
// bytes larger than the buffer supplied to it.
throw new InvalidDataException(SR.GenericInvalidData);
}
// Feed the data from base stream into the decompression engine.
_deflateStream._inflater.SetInput(buffer, offset, count);
// While there's more decompressed data available, forward it to the buffer stream.
while (true)
{
int bytesRead = _deflateStream._inflater.Inflate(new Span<byte>(_arrayPoolBuffer));
if (bytesRead > 0)
{
_destination.Write(_arrayPoolBuffer, 0, bytesRead);
}
else
{
break;
}
}
}
public override bool CanWrite => true;
public override void Flush() { }
public override bool CanRead => false;
public override bool CanSeek => false;
public override long Length { get { throw new NotSupportedException(); } }
public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
public override void SetLength(long value) { throw new NotSupportedException(); }
}
private bool AsyncOperationIsActive => _activeAsyncOperation != 0;
private void EnsureNoActiveAsyncOperation()
{
if (AsyncOperationIsActive)
ThrowInvalidBeginCall();
}
private void AsyncOperationStarting()
{
if (Interlocked.CompareExchange(ref _activeAsyncOperation, 1, 0) != 0)
{
ThrowInvalidBeginCall();
}
}
private void AsyncOperationCompleting()
{
int oldValue = Interlocked.CompareExchange(ref _activeAsyncOperation, 0, 1);
Debug.Assert(oldValue == 1, $"Expected {nameof(_activeAsyncOperation)} to be 1, got {oldValue}");
}
private static void ThrowInvalidBeginCall()
{
throw new InvalidOperationException(SR.InvalidBeginCall);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System.Text;
namespace NUnit.Framework.Interfaces
{
/// <summary>
/// The ResultState class represents the outcome of running a test.
/// It contains two pieces of information. The Status of the test
/// is an enum indicating whether the test passed, failed, was
/// skipped or was inconclusive. The Label provides a more
/// detailed breakdown for use by client runners.
/// </summary>
public class ResultState
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
public ResultState(TestStatus status) : this (status, string.Empty, FailureSite.Test)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="label">The label.</param>
public ResultState(TestStatus status, string label) : this (status, label, FailureSite.Test)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="site">The stage at which the result was produced</param>
public ResultState(TestStatus status, FailureSite site) : this(status, string.Empty, site)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="label">The label.</param>
/// <param name="site">The stage at which the result was produced</param>
public ResultState(TestStatus status, string label, FailureSite site)
{
Status = status;
Label = label == null ? string.Empty : label;
Site = site;
}
#endregion
#region Predefined ResultStates
/// <summary>
/// The result is inconclusive
/// </summary>
public readonly static ResultState Inconclusive = new ResultState(TestStatus.Inconclusive);
/// <summary>
/// The test has been skipped.
/// </summary>
public readonly static ResultState Skipped = new ResultState(TestStatus.Skipped);
/// <summary>
/// The test has been ignored.
/// </summary>
public readonly static ResultState Ignored = new ResultState(TestStatus.Skipped, "Ignored");
/// <summary>
/// The test was skipped because it is explicit
/// </summary>
public readonly static ResultState Explicit = new ResultState(TestStatus.Skipped, "Explicit");
/// <summary>
/// The test succeeded
/// </summary>
public readonly static ResultState Success = new ResultState(TestStatus.Passed);
/// <summary>
/// The test failed
/// </summary>
public readonly static ResultState Failure = new ResultState(TestStatus.Failed);
/// <summary>
/// The test encountered an unexpected exception
/// </summary>
public readonly static ResultState Error = new ResultState(TestStatus.Failed, "Error");
/// <summary>
/// The test was cancelled by the user
/// </summary>
public readonly static ResultState Cancelled = new ResultState(TestStatus.Failed, "Cancelled");
/// <summary>
/// The test was not runnable.
/// </summary>
public readonly static ResultState NotRunnable = new ResultState(TestStatus.Failed, "Invalid");
/// <summary>
/// A suite failed because one or more child tests failed or had errors
/// </summary>
public readonly static ResultState ChildFailure = ResultState.Failure.WithSite(FailureSite.Child);
/// <summary>
/// A suite failed in its OneTimeSetUp
/// </summary>
public readonly static ResultState SetUpFailure = ResultState.Failure.WithSite(FailureSite.SetUp);
/// <summary>
/// A suite had an unexpected exception in its OneTimeSetUp
/// </summary>
public readonly static ResultState SetUpError = ResultState.Error.WithSite(FailureSite.SetUp);
/// <summary>
/// A suite had an unexpected exception in its OneTimeDown
/// </summary>
public readonly static ResultState TearDownError = ResultState.Error.WithSite(FailureSite.TearDown);
#endregion
#region Properties
/// <summary>
/// Gets the TestStatus for the test.
/// </summary>
/// <value>The status.</value>
public TestStatus Status { get; private set; }
/// <summary>
/// Gets the label under which this test result is
/// categorized, if any.
/// </summary>
public string Label { get; private set; }
/// <summary>
/// Gets the stage of test execution in which
/// the failure or other result took place.
/// </summary>
public FailureSite Site { get; private set; }
/// <summary>
/// Get a new ResultState, which is the same as the current
/// one but with the FailureSite set to the specified value.
/// </summary>
/// <param name="site">The FailureSite to use</param>
/// <returns>A new ResultState</returns>
public ResultState WithSite(FailureSite site)
{
return new ResultState(this.Status, this.Label, site);
}
#endregion
#region Equals Override
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
var other = obj as ResultState;
if (other == null) return false;
return Status.Equals(other.Status) && Label.Equals(other.Label) && Site.Equals(other.Site);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return (int)Status << 8 + (int)Site ^ Label.GetHashCode(); ;
}
#endregion
#region ToString Override
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder(Status.ToString());
if (Label != null && Label.Length > 0)
sb.AppendFormat(":{0}", Label);
if (Site != FailureSite.Test)
sb.AppendFormat("({0})", Site.ToString());
return sb.ToString();
}
#endregion
}
/// <summary>
/// The FailureSite enum indicates the stage of a test
/// in which an error or failure occurred.
/// </summary>
public enum FailureSite
{
/// <summary>
/// Failure in the test itself
/// </summary>
Test,
/// <summary>
/// Failure in the SetUp method
/// </summary>
SetUp,
/// <summary>
/// Failure in the TearDown method
/// </summary>
TearDown,
/// <summary>
/// Failure of a parent test
/// </summary>
Parent,
/// <summary>
/// Failure of a child test
/// </summary>
Child
}
}
| |
namespace Zeta.WebSpider.Spider
{
#region Using directives.
// ----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
// ----------------------------------------------------------------------
#endregion
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Downloading a complete website.
/// </summary>
public class WebSiteDownloader :
IDisposable
{
#region Public methods.
// ------------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the <see cref="WebSiteDownloader"/>
/// class.
/// </summary>
/// <param name="options">The options.</param>
public WebSiteDownloader(
WebSiteDownloaderOptions options )
{
Trace.WriteLine(
string.Format(
@"Constructing WebSiteDownloader for URI '{0}', destination folder path '{1}'.",
options.DownloadUri,
options.DestinationFolderPath ) );
_settings = SpiderSettings.Restore( options.DestinationFolderPath );
_settings.Options = options;
}
/// <summary>
/// Performs the complete downloading (synchronously).
/// Does return only when completely finished or when an exception
/// occured.
/// </summary>
public void Process()
{
string baseUrl =
_settings.Options.DownloadUri.OriginalString.TrimEnd( '/' ).
Split( '?' )[0];
if ( _settings.Options.DownloadUri.AbsolutePath.IndexOf( '/' ) >= 0 &&
_settings.Options.DownloadUri.AbsolutePath.Length > 1 )
{
baseUrl = baseUrl.Substring( 0, baseUrl.LastIndexOf( '/' ) );
}
// --
// The URI that is configured to be the start URI.
Uri baseUri = new Uri( baseUrl, UriKind.Absolute );
// The initial seed.
DownloadedResourceInformation seedInfo =
new DownloadedResourceInformation(
_settings.Options,
@"/",
_settings.Options.DownloadUri,
baseUri,
_settings.Options.DestinationFolderPath,
_settings.Options.DestinationFolderPath,
UriType.Content );
// --
// Add the first one as the seed.
if ( !_settings.HasContinueDownloadedResourceInfos )
{
_settings.AddContinueDownloadedResourceInfos( seedInfo );
}
// 2007-07-27, Uwe Keim:
// Doing a multiple looping, to avoid stack overflows.
// Since a download-"tree" (i.e. the hierachy of all downloadable
// pages) can get _very_ deep, process one part at a time only.
// The state is already persisted, so we need to set up again at
// the previous position.
int index = 0;
while ( _settings.HasContinueDownloadedResourceInfos )
{
// Fetch one.
DownloadedResourceInformation processInfo =
_settings.PopContinueDownloadedResourceInfos();
Trace.WriteLine(
string.Format(
@"{0}. loop: Starting processing URLs from '{1}'.",
index + 1,
processInfo.AbsoluteUri.AbsoluteUri ) );
// Process the URI, add any continue URIs to start
// again, later.
ProcessUrl( processInfo, 0 );
index++;
}
Trace.WriteLine(
string.Format(
@"{0}. loop: Finished processing URLs from seed '{1}'.",
index + 1,
_settings.Options.DownloadUri ) );
}
/// <summary>
/// Performs the complete downloading (asynchronously).
/// Return immediately. Calls the ProcessCompleted event
/// upon completion.
/// </summary>
public void ProcessAsync()
{
processAsyncBackgroundWorker = new BackgroundWorker();
processAsyncBackgroundWorker.WorkerSupportsCancellation = true;
processAsyncBackgroundWorker.DoWork +=
processAsyncBackgroundWorker_DoWork;
processAsyncBackgroundWorker.RunWorkerCompleted +=
processAsyncBackgroundWorker_RunWorkerCompleted;
// Start.
processAsyncBackgroundWorker.RunWorkerAsync();
}
/// <summary>
/// Cancels a currently running asynchron processing.
/// </summary>
public void CancelProcessAsync()
{
if ( processAsyncBackgroundWorker != null )
{
processAsyncBackgroundWorker.CancelAsync();
}
}
// ------------------------------------------------------------------
#endregion
#region Public events.
// ------------------------------------------------------------------
public class ProcessingUrlEventArgs :
EventArgs
{
#region Public methods.
/// <summary>
/// Constructor.
/// </summary>
internal ProcessingUrlEventArgs(
DownloadedResourceInformation uriInfo,
int depth )
{
this.uriInfo = uriInfo;
this.depth = depth;
}
#endregion
#region Public properties.
/// <summary>
///
/// </summary>
public int Depth
{
get
{
return depth;
}
}
/// <summary>
///
/// </summary>
public DownloadedResourceInformation UriInfo
{
get
{
return uriInfo;
}
}
#endregion
#region Private variables.
private readonly DownloadedResourceInformation uriInfo;
private readonly int depth;
#endregion
}
public delegate void ProcessingUrlEventHandler(
object sender,
ProcessingUrlEventArgs e );
/// <summary>
/// Called when processing an URL.
/// </summary>
public event ProcessingUrlEventHandler ProcessingUrl;
// ------------------------------------------------------------------
#endregion
#region Asynchron processing.
// ------------------------------------------------------------------
private BackgroundWorker processAsyncBackgroundWorker = null;
void processAsyncBackgroundWorker_DoWork(
object sender,
DoWorkEventArgs e )
{
try
{
Process();
}
catch ( StopProcessingException )
{
// Do nothing, just end.
}
}
void processAsyncBackgroundWorker_RunWorkerCompleted(
object sender,
RunWorkerCompletedEventArgs e )
{
if ( ProcessCompleted != null )
{
ProcessCompleted( this, e );
}
}
public delegate void ProcessCompletedEventHandler(
object sender,
RunWorkerCompletedEventArgs e );
/// <summary>
/// Called when the asynchron processing is completed.
/// </summary>
public event ProcessCompletedEventHandler ProcessCompleted;
/// <summary>
///
/// </summary>
private class StopProcessingException :
Exception
{
}
// ------------------------------------------------------------------
#endregion
#region IDisposable members.
// ------------------------------------------------------------------
~WebSiteDownloader()
{
////settings.Persist();
}
public void Dispose()
{
////settings.Persist();
}
// ------------------------------------------------------------------
#endregion
#region Private methods.
// ------------------------------------------------------------------
/// <summary>
/// Process one single URI with a document behind (i.e. no
/// resource URI).
/// </summary>
/// <param name="uriInfo">The URI info.</param>
/// <param name="depth">The depth.</param>
private void ProcessUrl(
DownloadedResourceInformation uriInfo,
int depth )
{
Trace.WriteLine(
string.Format(
@"Processing URI '{0}', with depth {1}.",
uriInfo.AbsoluteUri.AbsoluteUri,
depth ) );
if ( _settings.Options.MaximumLinkDepth > 0 &&
depth > _settings.Options.MaximumLinkDepth )
{
Trace.WriteLine(
string.Format(
@"Depth {1} exceeds maximum configured depth. Ending recursion " +
@"at URI '{0}'.",
uriInfo.AbsoluteUri.AbsoluteUri,
depth ) );
}
else if ( depth > _maxDepth )
{
Trace.WriteLine(
string.Format(
@"Depth {1} exceeds maximum allowed recursion depth. " +
@"Ending recursion at URI '{0}' to possible continue later.",
uriInfo.AbsoluteUri.AbsoluteUri,
depth ) );
// Add myself to start there later.
// But only if not yet process, otherwise we would never finish.
if ( _settings.HasDownloadedUri( uriInfo ) )
{
Trace.WriteLine(
string.Format(
@"URI '{0}' was already downloaded. NOT continuing later.",
uriInfo.AbsoluteUri.AbsoluteUri ) );
}
else
{
_settings.AddDownloadedResourceInfo( uriInfo );
// Finished the function.
Trace.WriteLine(
string.Format(
@"Added URI '{0}' to continue later.",
uriInfo.AbsoluteUri.AbsoluteUri ) );
}
}
else
{
// If we are in asynchron mode, periodically check for stopps.
if ( processAsyncBackgroundWorker != null )
{
if ( processAsyncBackgroundWorker.CancellationPending )
{
throw new StopProcessingException();
}
}
// --
// Notify event sinks about this URL.
if ( ProcessingUrl != null )
{
ProcessingUrlEventArgs e = new ProcessingUrlEventArgs(
uriInfo,
depth );
ProcessingUrl( this, e );
}
// --
if ( uriInfo.IsProcessableUri )
{
if ( _settings.HasDownloadedUri( uriInfo ) )
{
Trace.WriteLine(
string.Format(
@"URI '{0}' was already downloaded. Skipping.",
uriInfo.AbsoluteUri.AbsoluteUri ) );
}
else
{
Trace.WriteLine(
string.Format(
@"URI '{0}' was not already downloaded. Processing.",
uriInfo.AbsoluteUri.AbsoluteUri ) );
if ( uriInfo.LinkType == UriType.Resource )
{
Trace.WriteLine(
string.Format(
@"Processing resource URI '{0}', with depth {1}.",
uriInfo.AbsoluteUri.AbsoluteUri,
depth ) );
byte[] binaryContent;
ResourceDownloader.DownloadBinary(
uriInfo.AbsoluteUri,
out binaryContent,
_settings.Options );
ResourceStorer storer =
new ResourceStorer( _settings );
storer.StoreBinary(
binaryContent,
uriInfo );
_settings.AddDownloadedResourceInfo( uriInfo );
_settings.PersistDownloadedResourceInfo( uriInfo );
}
else
{
Trace.WriteLine(
string.Format(
@"Processing content URI '{0}', with depth {1}.",
uriInfo.AbsoluteUri.AbsoluteUri,
depth ) );
string textContent;
string encodingName;
Encoding encoding;
byte[] binaryContent;
ResourceDownloader.DownloadHtml(
uriInfo.AbsoluteUri,
out textContent,
out encodingName,
out encoding,
out binaryContent,
_settings.Options );
ResourceParser parser = new ResourceParser(
_settings,
uriInfo,
textContent );
List<UriResourceInformation> linkInfos =
parser.ExtractLinks();
ResourceRewriter rewriter =
new ResourceRewriter( _settings );
textContent = rewriter.ReplaceLinks(
textContent,
uriInfo );
ResourceStorer storer =
new ResourceStorer( _settings );
storer.StoreHtml(
textContent,
encoding,
uriInfo );
// Add before parsing childs.
_settings.AddDownloadedResourceInfo( uriInfo );
foreach ( UriResourceInformation linkInfo in linkInfos )
{
DownloadedResourceInformation dlInfo =
new DownloadedResourceInformation(
linkInfo,
uriInfo.LocalFolderPath,
uriInfo.LocalBaseFolderPath );
// Recurse.
ProcessUrl( dlInfo, depth + 1 );
// Do not return or break immediately if too deep,
// because this would omit certain pages at this
// recursion level.
}
// Persist after completely parsed childs.
_settings.PersistDownloadedResourceInfo( uriInfo );
}
Trace.WriteLine(
string.Format(
@"Finished processing URI '{0}'.",
uriInfo.AbsoluteUri.AbsoluteUri ) );
}
}
else
{
Trace.WriteLine(
string.Format(
@"URI '{0}' is not processable. Skipping.",
uriInfo.AbsoluteUri.AbsoluteUri ) );
}
}
}
// ------------------------------------------------------------------
#endregion
#region Private variables.
// ------------------------------------------------------------------
private const int _maxDepth = 500;
private readonly SpiderSettings _settings = new SpiderSettings();
// ------------------------------------------------------------------
#endregion
}
/////////////////////////////////////////////////////////////////////////
}
| |
using AnimaScript;
namespace AnimaData
{
public class Seq_SC_Radar_powerOn : AnimaSeqBase
{
private static AnimaSeqBase m_seq = null;
new public static AnimaSeqBase Adquire()
{
if (m_seq == null) m_seq = PManAdd(new Seq_SC_Radar_powerOn());
return m_seq;
}
public override void DiscardStatic() { m_seq = PManRem(m_seq); }
new public static void Discard() { m_seq = PManRem(m_seq); }
protected override void PData()
{
PInit("Seq_SC_Radar_powerOn",0,60,24f,0,0);
PLocRotScale(-0f,0f,0f,-0f,0f,0f,1f,1f,1f,1f);
}
}
public class Seq_SC_Radar_Part1_powerOn : AnimaSeqBase
{
private static AnimaSeqBase m_seq = null;
new public static AnimaSeqBase Adquire()
{
if (m_seq == null) m_seq = PManAdd(new Seq_SC_Radar_Part1_powerOn());
return m_seq;
}
public override void DiscardStatic() { m_seq = PManRem(m_seq); }
new public static void Discard() { m_seq = PManRem(m_seq); }
protected override void PData()
{
PInit("Seq_SC_Radar_Part1_powerOn",0,60,24f,0,60);
PLocRotScale(-0f,0f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.052336f,0f,0.99863f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.104528f,0f,0.994522f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.156434f,0f,0.987688f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.207912f,0f,0.978148f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.258819f,0f,0.965926f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.309017f,0f,0.951057f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.358368f,0f,0.93358f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.406737f,0f,0.913545f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.453991f,0f,0.891007f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.5f,0f,0.866025f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.544639f,0f,0.838671f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.587785f,0f,0.809017f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.62932f,0f,0.777146f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.669131f,0f,0.743145f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.707107f,0f,0.707107f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.743145f,0f,0.669131f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.777146f,0f,0.62932f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.809017f,0f,0.587785f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.838671f,0f,0.544639f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.866025f,0f,0.5f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.891007f,0f,0.45399f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.913546f,0f,0.406737f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.93358f,0f,0.358368f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.951057f,0f,0.309017f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.965926f,0f,0.258819f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.978148f,0f,0.207911f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.987688f,0f,0.156434f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.994522f,0f,0.104528f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0.99863f,0f,0.0523359f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,1f,0f,0f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.99863f,0f,0.0523351f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.994522f,0f,0.104529f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.987688f,0f,0.156434f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.978148f,0f,0.207912f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.965926f,0f,0.258819f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.951057f,0f,0.309017f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.93358f,0f,0.358368f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.913545f,0f,0.406737f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.891006f,0f,0.453991f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.866025f,0f,0.5f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.83867f,0f,0.544639f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.809017f,0f,0.587785f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.777146f,0f,0.629321f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.743145f,0f,0.669131f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.707107f,0f,0.707107f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.669131f,0f,0.743145f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.62932f,0f,0.777146f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.587785f,0f,0.809017f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.544639f,0f,0.838671f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.5f,0f,0.866026f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.45399f,0f,0.891007f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.406737f,0f,0.913545f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.358368f,0f,0.933581f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.309017f,0f,0.951057f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.258819f,0f,0.965926f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.207911f,0f,0.978148f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.156434f,0f,0.987688f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.104528f,0f,0.994522f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,-0.0523358f,0f,0.99863f,1f,1f,1f);
PLocRotScale(-0f,0f,0f,-0f,0f,0f,1f,1f,1f,1f);
}
}
public class Seq_SC_Radar_Part2_powerOn : AnimaSeqBase
{
private static AnimaSeqBase m_seq = null;
new public static AnimaSeqBase Adquire()
{
if (m_seq == null) m_seq = PManAdd(new Seq_SC_Radar_Part2_powerOn());
return m_seq;
}
public override void DiscardStatic() { m_seq = PManRem(m_seq); }
new public static void Discard() { m_seq = PManRem(m_seq); }
protected override void PData()
{
PInit("Seq_SC_Radar_Part2_powerOn",0,60,24f,0,60);
PLocRotScale(-0f,0f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.005f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.01f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.015f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.02f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.025f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.03f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.035f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.04f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.045f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.05f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.055f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.06f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.065f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.07f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.075f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.08f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.085f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.09f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.095f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.1f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.105f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.11f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.115f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.12f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.125f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.13f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.135f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.14f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.145f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.15f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.155f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.16f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.165f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.17f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.175f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.18f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.185f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.19f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.195f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.2f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.205f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.21f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.215f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.22f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.225f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.23f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.235f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.24f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.245f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.25f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.255f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.26f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.265f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.27f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.275f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.28f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.285f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.29f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.295f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,0.3f,0f,-0f,0f,0f,1f,1f,1f,1f);
}
}
public class Seq_SC_Radar_Part3_powerOn : AnimaSeqBase
{
private static AnimaSeqBase m_seq = null;
new public static AnimaSeqBase Adquire()
{
if (m_seq == null) m_seq = PManAdd(new Seq_SC_Radar_Part3_powerOn());
return m_seq;
}
public override void DiscardStatic() { m_seq = PManRem(m_seq); }
new public static void Discard() { m_seq = PManRem(m_seq); }
protected override void PData()
{
PInit("Seq_SC_Radar_Part3_powerOn",0,60,24f,0,60);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0f,1f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.00654494f,0.999979f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0130896f,0.999914f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0196337f,0.999807f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.026177f,0.999657f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0327191f,0.999465f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0392598f,0.999229f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0457989f,0.998951f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.052336f,0.99863f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0588708f,0.998266f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0654031f,0.997859f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0719327f,0.99741f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0784591f,0.996917f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0849822f,0.996382f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0915016f,0.995805f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.0980172f,0.995185f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.104528f,0.994522f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.111035f,0.993816f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.117537f,0.993068f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.124034f,0.992278f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.130526f,0.991445f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.137012f,0.990569f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.143493f,0.989651f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.149967f,0.988691f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.156435f,0.987688f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.162896f,0.986643f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.16935f,0.985556f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.175796f,0.984427f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.182236f,0.983255f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.188667f,0.982041f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.19509f,0.980785f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.201505f,0.979487f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.207912f,0.978148f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.214309f,0.976766f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.220697f,0.975342f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.227076f,0.973877f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.233445f,0.97237f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.239804f,0.970821f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.246153f,0.969231f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.252492f,0.967599f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.258819f,0.965926f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.265135f,0.964211f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.271441f,0.962455f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.277734f,0.960658f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.284015f,0.95882f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.290285f,0.95694f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.296542f,0.95502f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.302786f,0.953059f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.309017f,0.951057f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.315235f,0.949014f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.32144f,0.94693f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.32763f,0.944806f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.333807f,0.942641f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.339969f,0.940437f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.346117f,0.938191f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.35225f,0.935906f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.358368f,0.93358f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.364471f,0.931215f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.370557f,0.92881f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.376629f,0.926364f,1f,1f,1f);
PLocRotScale(-0f,-0.975f,0f,-0f,0f,0.382683f,0.92388f,1f,1f,1f);
}
}
}
| |
// 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;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableSortedDictionary{TKey, TValue}.Builder"/> class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableSortedDictionary<TKey, TValue>
{
/// <summary>
/// A sorted dictionary that mutates with little or no memory allocations,
/// can produce and/or build on immutable sorted dictionary instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// This class allows multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableSortedDictionaryBuilderDebuggerProxy<,>))]
public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// The binary tree used to store the contents of the map. Contents are typically not entirely frozen.
/// </summary>
private Node _root = Node.EmptyNode;
/// <summary>
/// The key comparer.
/// </summary>
private IComparer<TKey> _keyComparer = Comparer<TKey>.Default;
/// <summary>
/// The value comparer.
/// </summary>
private IEqualityComparer<TValue> _valueComparer = EqualityComparer<TValue>.Default;
/// <summary>
/// The number of entries in the map.
/// </summary>
private int _count;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableSortedDictionary<TKey, TValue> _immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int _version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object _syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="map">A map to act as the basis for a new map.</param>
internal Builder(ImmutableSortedDictionary<TKey, TValue> map)
{
Requires.NotNull(map, nameof(map));
_root = map._root;
_keyComparer = map.KeyComparer;
_valueComparer = map.ValueComparer;
_count = map.Count;
_immutable = map;
}
#region IDictionary<TKey, TValue> Properties and Indexer
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return this.Root.Keys.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TKey> Keys
{
get { return this.Root.Keys; }
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return this.Root.Values.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TValue> Values
{
get { return this.Root.Values; }
}
/// <summary>
/// Gets the number of elements in this map.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read-only.
/// </summary>
/// <value>Always <c>false</c>.</value>
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return _version; }
}
/// <summary>
/// Gets or sets the root node that represents the data in this collection.
/// </summary>
private Node Root
{
get
{
return _root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
_version++;
if (_root != value)
{
_root = value;
// Clear any cached value for the immutable view since it is now invalidated.
_immutable = null;
}
}
}
#region IDictionary<TKey, TValue> Indexer
/// <summary>
/// Gets or sets the value for a given key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The value associated with the given key.</returns>
public TValue this[TKey key]
{
get
{
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException();
}
set
{
bool replacedExistingValue, mutated;
this.Root = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated);
if (mutated && !replacedExistingValue)
{
_count++;
}
}
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Keys
{
get { return this.Keys.ToArray(this.Count); }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Values
{
get { return this.Values.ToArray(this.Count); }
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets or sets the key comparer.
/// </summary>
/// <value>
/// The key comparer.
/// </value>
public IComparer<TKey> KeyComparer
{
get
{
return _keyComparer;
}
set
{
Requires.NotNull(value, nameof(value));
if (value != _keyComparer)
{
var newRoot = Node.EmptyNode;
int count = 0;
foreach (var item in this)
{
bool mutated;
newRoot = newRoot.Add(item.Key, item.Value, value, _valueComparer, out mutated);
if (mutated)
{
count++;
}
}
_keyComparer = value;
this.Root = newRoot;
_count = count;
}
}
}
/// <summary>
/// Gets or sets the value comparer.
/// </summary>
/// <value>
/// The value comparer.
/// </value>
public IEqualityComparer<TValue> ValueComparer
{
get
{
return _valueComparer;
}
set
{
Requires.NotNull(value, nameof(value));
if (value != _valueComparer)
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
_valueComparer = value;
_immutable = null; // invalidate cached immutable
}
}
}
#endregion
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
this.Add((TKey)key, (TValue)value);
}
/// <summary>
/// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
this.Remove((TKey)key);
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { this[(TKey)key] = (TValue)value; }
}
#endregion
#region ICollection methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int index)
{
this.Root.CopyTo(array, index, this.Count);
}
#endregion
#region IDictionary<TKey, TValue> Methods
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public void Add(TKey key, TValue value)
{
bool mutated;
this.Root = this.Root.Add(key, value, _keyComparer, _valueComparer, out mutated);
if (mutated)
{
_count++;
}
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool ContainsKey(TKey key)
{
return this.Root.ContainsKey(key, _keyComparer);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool Remove(TKey key)
{
bool mutated;
this.Root = this.Root.Remove(key, _keyComparer, out mutated);
if (mutated)
{
_count--;
}
return mutated;
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
return this.Root.TryGetValue(key, _keyComparer, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, nameof(equalKey));
return this.Root.TryGetKey(equalKey, _keyComparer, out actualKey);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public void Add(KeyValuePair<TKey, TValue> item)
{
this.Add(item.Key, item.Value);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public void Clear()
{
this.Root = ImmutableSortedDictionary<TKey, TValue>.Node.EmptyNode;
_count = 0;
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return this.Root.Contains(item, _keyComparer, _valueComparer);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
this.Root.CopyTo(array, arrayIndex, this.Count);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
if (this.Contains(item))
{
return this.Remove(item.Key);
}
return false;
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public ImmutableSortedDictionary<TKey, TValue>.Enumerator GetEnumerator()
{
return this.Root.GetEnumerator(this);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Public methods
/// <summary>
/// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
return _root.ContainsValue(value, _valueComparer);
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="items">The keys for entries to remove from the dictionary.</param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, nameof(items));
foreach (var pair in items)
{
this.Add(pair);
}
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="keys">The keys for entries to remove from the dictionary.</param>
public void RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, nameof(keys));
foreach (var key in keys)
{
this.Remove(key);
}
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>The value for the key, or the default value for type <typeparamref name="TValue"/> if no matching key was found.</returns>
[Pure]
public TValue GetValueOrDefault(TKey key)
{
return this.GetValueOrDefault(key, default(TValue));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param>
/// <returns>
/// The value for the key, or <paramref name="defaultValue"/> if no matching key was found.
/// </returns>
[Pure]
public TValue GetValueOrDefault(TKey key, TValue defaultValue)
{
Requires.NotNullAllowStructs(key, nameof(key));
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
return defaultValue;
}
/// <summary>
/// Creates an immutable sorted dictionary based on the contents of this instance.
/// </summary>
/// <returns>An immutable map.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableSortedDictionary<TKey, TValue> ToImmutable()
{
// Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (_immutable == null)
{
_immutable = Wrap(this.Root, _count, _keyComparer, _valueComparer);
}
return _immutable;
}
#endregion
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal class ImmutableSortedDictionaryBuilderDebuggerProxy<TKey, TValue>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableSortedDictionary<TKey, TValue>.Builder _map;
/// <summary>
/// The simple view of the collection.
/// </summary>
private KeyValuePair<TKey, TValue>[] _contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class.
/// </summary>
/// <param name="map">The collection to display in the debugger</param>
public ImmutableSortedDictionaryBuilderDebuggerProxy(ImmutableSortedDictionary<TKey, TValue>.Builder map)
{
Requires.NotNull(map, nameof(map));
_map = map;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (_contents == null)
{
_contents = _map.ToArray(_map.Count);
}
return _contents;
}
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
namespace NuGet.Lucene.Web
{
public class NuGetWebApiSettings : INuGetWebApiSettings
{
public const string DefaultAppSettingPrefix = "NuGet.Lucene.Web:";
public const string BlankAppSettingPrefix = "";
public const string DefaultRoutePathPrefix = "api/";
private readonly string prefix;
private readonly NameValueCollection settings;
private readonly NameValueCollection roleMappings;
public NuGetWebApiSettings()
: this(DefaultAppSettingPrefix)
{
}
public NuGetWebApiSettings(string prefix)
: this(prefix, ConfigurationManager.AppSettings, ConfigurationManager.GetSection("roleMappings") as NameValueCollection)
{
}
public NuGetWebApiSettings(string prefix, NameValueCollection settings, NameValueCollection roleMappings)
{
this.prefix = prefix;
this.settings = settings;
this.roleMappings = roleMappings ?? new NameValueCollection();
}
public bool ShowExceptionDetails
{
get { return GetFlagFromAppSetting("showExceptionDetails", false); }
}
public bool EnableCrossDomainRequests
{
get { return GetFlagFromAppSetting("enableCrossDomainRequests", false); }
}
public bool HandleLocalRequestsAsAdmin
{
get { return GetFlagFromAppSetting("handleLocalRequestsAsAdmin", false); }
}
public string LocalAdministratorApiKey
{
get
{
return GetAppSetting("localAdministratorApiKey", string.Empty);
}
}
public bool AllowAnonymousPackageChanges
{
get { return GetFlagFromAppSetting("allowAnonymousPackageChanges", false); }
}
public string RoutePathPrefix
{
get { return GetAppSetting("routePathPrefix", DefaultRoutePathPrefix); }
}
public string PackageMirrorTargetUrl
{
get { return GetAppSetting("packageMirrorTargetUrl", String.Empty); }
}
public bool AlwaysCheckMirror
{
get { return GetFlagFromAppSetting("alwaysCheckMirror", false); }
}
public TimeSpan PackageMirrorTimeout
{
get
{
var str = GetAppSetting("packageMirrorTimeout", "0:00:15");
TimeSpan ts;
return TimeSpan.TryParse(str, out ts) ? ts : TimeSpan.FromSeconds(15);
}
}
public bool RoleMappingsEnabled
{
get
{
var mappings = RoleMappings;
return mappings.AllKeys.Any(key => !String.IsNullOrWhiteSpace(mappings.Get(key)));
}
}
public NameValueCollection RoleMappings
{
get
{
return roleMappings;
}
}
public string SymbolsPath
{
get
{
return MapPathFromAppSetting("symbolsPath", "~/App_Data/Symbols");
}
}
public string ToolsPath
{
get
{
return MapPathFromAppSetting("debuggingToolsPath", "");
}
}
public bool DisablePackageHash
{
get
{
return GetFlagFromAppSetting("disablePackageHash", false);
}
}
public bool IgnorePackageFiles
{
get
{
return GetFlagFromAppSetting("ignorePackageFiles", false);
}
}
public bool SynchronizeOnStart
{
get
{
return GetFlagFromAppSetting("synchronizeOnStart", true);
}
}
public bool EnablePackageFileWatcher
{
get
{
return GetFlagFromAppSetting("enablePackageFileWatcher", true);
}
}
public bool GroupPackageFilesById
{
get
{
return GetFlagFromAppSetting("groupPackageFilesById", true);
}
}
public string LucenePackagesIndexPath
{
get
{
return MapPathFromAppSetting("lucenePath", "~/App_Data/Lucene");
}
}
public string PackagesPath
{
get
{
return MapPathFromAppSetting("packagesPath", "~/App_Data/Packages");
}
}
public PackageOverwriteMode PackageOverwriteMode
{
get { return GetEnumFromAppSetting("packageOverwriteMode", PackageOverwriteMode.Allow); }
}
public string LuceneUsersIndexPath
{
get
{
return Path.Combine(LucenePackagesIndexPath, "Users");
}
}
public int LuceneMergeFactor
{
get
{
int value;
return int.TryParse(GetAppSetting("luceneMergeFactor", "0"), out value) ? value : 0;
}
}
protected bool GetFlagFromAppSetting(string key, bool defaultValue)
{
var flag = GetAppSetting(key, String.Empty);
bool result;
return Boolean.TryParse(flag ?? String.Empty, out result) ? result : defaultValue;
}
protected virtual string MapPathFromAppSetting(string key, string defaultValue)
{
var path = GetAppSetting(key, defaultValue);
if (path.StartsWith("~/"))
{
path = Path.Combine(Environment.CurrentDirectory, path.Replace("~/", ""));
}
return path.Replace('/', Path.DirectorySeparatorChar);
}
protected virtual T GetEnumFromAppSetting<T>(string appSetting, T defaultValue) where T : struct
{
T value;
var parsed = Enum.TryParse(GetAppSetting(appSetting, defaultValue.ToString()), out value);
return parsed ? value : defaultValue;
}
protected internal virtual string GetAppSetting(string key, string defaultValue)
{
var value = settings[GetAppSettingKey(key)];
return String.IsNullOrWhiteSpace(value) ? defaultValue : value;
}
private string GetAppSettingKey(string key)
{
return prefix + key;
}
}
}
| |
/*
* 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 LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
{
public interface ILSL_Api
{
void state(string newState);
LSL_Integer llAbs(int i);
LSL_Float llAcos(double val);
void llAddToLandBanList(string avatar, double hours);
void llAddToLandPassList(string avatar, double hours);
void llAdjustSoundVolume(double volume);
void llAllowInventoryDrop(int add);
LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b);
void llApplyImpulse(LSL_Vector force, int local);
void llApplyRotationalImpulse(LSL_Vector force, int local);
LSL_Float llAsin(double val);
LSL_Float llAtan2(double x, double y);
void llAttachToAvatar(int attachment);
LSL_Key llAvatarOnSitTarget();
LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up);
LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle);
LSL_Integer llBase64ToInteger(string str);
LSL_String llBase64ToString(string str);
void llBreakAllLinks();
void llBreakLink(int linknum);
LSL_Integer llCeil(double f);
void llClearCameraParams();
void llCloseRemoteDataChannel(string channel);
LSL_Float llCloud(LSL_Vector offset);
void llCollisionFilter(string name, string id, int accept);
void llCollisionSound(string impact_sound, double impact_volume);
void llCollisionSprite(string impact_sprite);
LSL_Float llCos(double f);
void llCreateLink(string target, int parent);
LSL_List llCSV2List(string src);
LSL_List llDeleteSubList(LSL_List src, int start, int end);
LSL_String llDeleteSubString(string src, int start, int end);
void llDetachFromAvatar();
LSL_Vector llDetectedGrab(int number);
LSL_Integer llDetectedGroup(int number);
LSL_Key llDetectedKey(int number);
LSL_Integer llDetectedLinkNumber(int number);
LSL_String llDetectedName(int number);
LSL_Key llDetectedOwner(int number);
LSL_Vector llDetectedPos(int number);
LSL_Rotation llDetectedRot(int number);
LSL_Integer llDetectedType(int number);
LSL_Vector llDetectedTouchBinormal(int index);
LSL_Integer llDetectedTouchFace(int index);
LSL_Vector llDetectedTouchNormal(int index);
LSL_Vector llDetectedTouchPos(int index);
LSL_Vector llDetectedTouchST(int index);
LSL_Vector llDetectedTouchUV(int index);
LSL_Vector llDetectedVel(int number);
void llDialog(string avatar, string message, LSL_List buttons, int chat_channel);
void llDie();
LSL_String llDumpList2String(LSL_List src, string seperator);
LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir);
void llEjectFromLand(string pest);
void llEmail(string address, string subject, string message);
LSL_String llEscapeURL(string url);
LSL_Rotation llEuler2Rot(LSL_Vector v);
LSL_Float llFabs(double f);
LSL_Integer llFloor(double f);
void llForceMouselook(int mouselook);
LSL_Float llFrand(double mag);
LSL_Vector llGetAccel();
LSL_Integer llGetAgentInfo(string id);
LSL_String llGetAgentLanguage(string id);
LSL_Vector llGetAgentSize(string id);
LSL_Float llGetAlpha(int face);
LSL_Float llGetAndResetTime();
LSL_String llGetAnimation(string id);
LSL_List llGetAnimationList(string id);
LSL_Integer llGetAttached();
LSL_List llGetBoundingBox(string obj);
LSL_Vector llGetCameraPos();
LSL_Rotation llGetCameraRot();
LSL_Vector llGetCenterOfMass();
LSL_Vector llGetColor(int face);
LSL_String llGetCreator();
LSL_String llGetDate();
LSL_Float llGetEnergy();
LSL_Vector llGetForce();
LSL_Integer llGetFreeMemory();
LSL_Integer llGetFreeURLs();
LSL_Vector llGetGeometricCenter();
LSL_Float llGetGMTclock();
LSL_String llGetHTTPHeader(LSL_Key request_id, string header);
LSL_Key llGetInventoryCreator(string item);
LSL_Key llGetInventoryKey(string name);
LSL_String llGetInventoryName(int type, int number);
LSL_Integer llGetInventoryNumber(int type);
LSL_Integer llGetInventoryPermMask(string item, int mask);
LSL_Integer llGetInventoryType(string name);
LSL_Key llGetKey();
LSL_Key llGetLandOwnerAt(LSL_Vector pos);
LSL_Key llGetLinkKey(int linknum);
LSL_String llGetLinkName(int linknum);
LSL_Integer llGetLinkNumber();
LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules);
LSL_Integer llGetListEntryType(LSL_List src, int index);
LSL_Integer llGetListLength(LSL_List src);
LSL_Vector llGetLocalPos();
LSL_Rotation llGetLocalRot();
LSL_Float llGetMass();
void llGetNextEmail(string address, string subject);
LSL_String llGetNotecardLine(string name, int line);
LSL_Key llGetNumberOfNotecardLines(string name);
LSL_Integer llGetNumberOfPrims();
LSL_Integer llGetNumberOfSides();
LSL_String llGetObjectDesc();
LSL_List llGetObjectDetails(string id, LSL_List args);
LSL_Float llGetObjectMass(string id);
LSL_String llGetObjectName();
LSL_Integer llGetObjectPermMask(int mask);
LSL_Integer llGetObjectPrimCount(string object_id);
LSL_Vector llGetOmega();
LSL_Key llGetOwner();
LSL_Key llGetOwnerKey(string id);
LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param);
LSL_Integer llGetParcelFlags(LSL_Vector pos);
LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide);
LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide);
LSL_List llGetParcelPrimOwners(LSL_Vector pos);
LSL_Integer llGetPermissions();
LSL_Key llGetPermissionsKey();
LSL_Vector llGetPos();
LSL_List llGetPrimitiveParams(LSL_List rules);
LSL_Integer llGetRegionAgentCount();
LSL_Vector llGetRegionCorner();
LSL_Integer llGetRegionFlags();
LSL_Float llGetRegionFPS();
LSL_String llGetRegionName();
LSL_Float llGetRegionTimeDilation();
LSL_Vector llGetRootPosition();
LSL_Rotation llGetRootRotation();
LSL_Rotation llGetRot();
LSL_Vector llGetScale();
LSL_String llGetScriptName();
LSL_Integer llGetScriptState(string name);
LSL_String llGetSimulatorHostname();
LSL_Integer llGetStartParameter();
LSL_Integer llGetStatus(int status);
LSL_String llGetSubString(string src, int start, int end);
LSL_Vector llGetSunDirection();
LSL_String llGetTexture(int face);
LSL_Vector llGetTextureOffset(int face);
LSL_Float llGetTextureRot(int side);
LSL_Vector llGetTextureScale(int side);
LSL_Float llGetTime();
LSL_Float llGetTimeOfDay();
LSL_String llGetTimestamp();
LSL_Vector llGetTorque();
LSL_Integer llGetUnixTime();
LSL_Vector llGetVel();
LSL_Float llGetWallclock();
void llGiveInventory(string destination, string inventory);
void llGiveInventoryList(string destination, string category, LSL_List inventory);
LSL_Integer llGiveMoney(string destination, int amount);
void llGodLikeRezObject(string inventory, LSL_Vector pos);
LSL_Float llGround(LSL_Vector offset);
LSL_Vector llGroundContour(LSL_Vector offset);
LSL_Vector llGroundNormal(LSL_Vector offset);
void llGroundRepel(double height, int water, double tau);
LSL_Vector llGroundSlope(LSL_Vector offset);
LSL_String llHTTPRequest(string url, LSL_List parameters, string body);
void llHTTPResponse(LSL_Key id, int status, string body);
LSL_String llInsertString(string dst, int position, string src);
void llInstantMessage(string user, string message);
LSL_String llIntegerToBase64(int number);
LSL_String llKey2Name(string id);
void llLinkParticleSystem(int linknum, LSL_List rules);
LSL_String llList2CSV(LSL_List src);
LSL_Float llList2Float(LSL_List src, int index);
LSL_Integer llList2Integer(LSL_List src, int index);
LSL_Key llList2Key(LSL_List src, int index);
LSL_List llList2List(LSL_List src, int start, int end);
LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride);
LSL_Rotation llList2Rot(LSL_List src, int index);
LSL_String llList2String(LSL_List src, int index);
LSL_Vector llList2Vector(LSL_List src, int index);
LSL_Integer llListen(int channelID, string name, string ID, string msg);
void llListenControl(int number, int active);
void llListenRemove(int number);
LSL_Integer llListFindList(LSL_List src, LSL_List test);
LSL_List llListInsertList(LSL_List dest, LSL_List src, int start);
LSL_List llListRandomize(LSL_List src, int stride);
LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end);
LSL_List llListSort(LSL_List src, int stride, int ascending);
LSL_Float llListStatistics(int operation, LSL_List src);
void llLoadURL(string avatar_id, string message, string url);
LSL_Float llLog(double val);
LSL_Float llLog10(double val);
void llLookAt(LSL_Vector target, double strength, double damping);
void llLoopSound(string sound, double volume);
void llLoopSoundMaster(string sound, double volume);
void llLoopSoundSlave(string sound, double volume);
void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset);
void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at);
LSL_String llMD5String(string src, int nonce);
LSL_String llSHA1String(string src);
void llMessageLinked(int linknum, int num, string str, string id);
void llMinEventDelay(double delay);
void llModifyLand(int action, int brush);
LSL_Integer llModPow(int a, int b, int c);
void llMoveToTarget(LSL_Vector target, double tau);
void llOffsetTexture(double u, double v, int face);
void llOpenRemoteDataChannel();
LSL_Integer llOverMyLand(string id);
void llOwnerSay(string msg);
void llParcelMediaCommandList(LSL_List commandList);
LSL_List llParcelMediaQuery(LSL_List aList);
LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers);
LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers);
void llParticleSystem(LSL_List rules);
void llPassCollisions(int pass);
void llPassTouches(int pass);
void llPlaySound(string sound, double volume);
void llPlaySoundSlave(string sound, double volume);
void llPointAt(LSL_Vector pos);
LSL_Float llPow(double fbase, double fexponent);
void llPreloadSound(string sound);
void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local);
void llRefreshPrimURL();
void llRegionSay(int channelID, string text);
void llReleaseCamera(string avatar);
void llReleaseControls();
void llReleaseURL(string url);
void llRemoteDataReply(string channel, string message_id, string sdata, int idata);
void llRemoteDataSetRegion();
void llRemoteLoadScript(string target, string name, int running, int start_param);
void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param);
void llRemoveFromLandBanList(string avatar);
void llRemoveFromLandPassList(string avatar);
void llRemoveInventory(string item);
void llRemoveVehicleFlags(int flags);
LSL_Key llRequestAgentData(string id, int data);
LSL_Key llRequestInventoryData(string name);
void llRequestPermissions(string agent, int perm);
LSL_String llRequestSecureURL();
LSL_Key llRequestSimulatorData(string simulator, int data);
LSL_Key llRequestURL();
void llResetLandBanList();
void llResetLandPassList();
void llResetOtherScript(string name);
void llResetScript();
void llResetTime();
void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param);
void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param);
LSL_Float llRot2Angle(LSL_Rotation rot);
LSL_Vector llRot2Axis(LSL_Rotation rot);
LSL_Vector llRot2Euler(LSL_Rotation r);
LSL_Vector llRot2Fwd(LSL_Rotation r);
LSL_Vector llRot2Left(LSL_Rotation r);
LSL_Vector llRot2Up(LSL_Rotation r);
void llRotateTexture(double rotation, int face);
LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end);
void llRotLookAt(LSL_Rotation target, double strength, double damping);
LSL_Integer llRotTarget(LSL_Rotation rot, double error);
void llRotTargetRemove(int number);
LSL_Integer llRound(double f);
LSL_Integer llSameGroup(string agent);
void llSay(int channelID, string text);
void llScaleTexture(double u, double v, int face);
LSL_Integer llScriptDanger(LSL_Vector pos);
LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata);
void llSensor(string name, string id, int type, double range, double arc);
void llSensorRemove();
void llSensorRepeat(string name, string id, int type, double range, double arc, double rate);
void llSetAlpha(double alpha, int face);
void llSetBuoyancy(double buoyancy);
void llSetCameraAtOffset(LSL_Vector offset);
void llSetCameraEyeOffset(LSL_Vector offset);
void llSetCameraParams(LSL_List rules);
void llSetClickAction(int action);
void llSetColor(LSL_Vector color, int face);
void llSetDamage(double damage);
void llSetForce(LSL_Vector force, int local);
void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local);
void llSetHoverHeight(double height, int water, double tau);
void llSetInventoryPermMask(string item, int mask, int value);
void llSetLinkAlpha(int linknumber, double alpha, int face);
void llSetLinkColor(int linknumber, LSL_Vector color, int face);
void llSetLinkPrimitiveParams(int linknumber, LSL_List rules);
void llSetLinkTexture(int linknumber, string texture, int face);
void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetLocalRot(LSL_Rotation rot);
void llSetObjectDesc(string desc);
void llSetObjectName(string name);
void llSetObjectPermMask(int mask, int value);
void llSetParcelMusicURL(string url);
void llSetPayPrice(int price, LSL_List quick_pay_buttons);
void llSetPos(LSL_Vector pos);
void llSetPrimitiveParams(LSL_List rules);
void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules);
void llSetPrimURL(string url);
void llSetRemoteScriptAccessPin(int pin);
void llSetRot(LSL_Rotation rot);
void llSetScale(LSL_Vector scale);
void llSetScriptState(string name, int run);
void llSetSitText(string text);
void llSetSoundQueueing(int queue);
void llSetSoundRadius(double radius);
void llSetStatus(int status, int value);
void llSetText(string text, LSL_Vector color, double alpha);
void llSetTexture(string texture, int face);
void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetTimerEvent(double sec);
void llSetTorque(LSL_Vector torque, int local);
void llSetTouchText(string text);
void llSetVehicleFlags(int flags);
void llSetVehicleFloatParam(int param, LSL_Float value);
void llSetVehicleRotationParam(int param, LSL_Rotation rot);
void llSetVehicleType(int type);
void llSetVehicleVectorParam(int param, LSL_Vector vec);
void llShout(int channelID, string text);
LSL_Float llSin(double f);
void llSitTarget(LSL_Vector offset, LSL_Rotation rot);
void llSleep(double sec);
void llSound(string sound, double volume, int queue, int loop);
void llSoundPreload(string sound);
LSL_Float llSqrt(double f);
void llStartAnimation(string anim);
void llStopAnimation(string anim);
void llStopHover();
void llStopLookAt();
void llStopMoveToTarget();
void llStopPointAt();
void llStopSound();
LSL_Integer llStringLength(string str);
LSL_String llStringToBase64(string str);
LSL_String llStringTrim(string src, int type);
LSL_Integer llSubStringIndex(string source, string pattern);
void llTakeCamera(string avatar);
void llTakeControls(int controls, int accept, int pass_on);
LSL_Float llTan(double f);
LSL_Integer llTarget(LSL_Vector position, double range);
void llTargetOmega(LSL_Vector axis, double spinrate, double gain);
void llTargetRemove(int number);
void llTeleportAgentHome(string agent);
void llTextBox(string avatar, string message, int chat_channel);
LSL_String llToLower(string source);
LSL_String llToUpper(string source);
void llTriggerSound(string sound, double volume);
void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west);
LSL_String llUnescapeURL(string url);
void llUnSit(string id);
LSL_Float llVecDist(LSL_Vector a, LSL_Vector b);
LSL_Float llVecMag(LSL_Vector v);
LSL_Vector llVecNorm(LSL_Vector v);
void llVolumeDetect(int detect);
LSL_Float llWater(LSL_Vector offset);
void llWhisper(int channelID, string text);
LSL_Vector llWind(LSL_Vector offset);
LSL_String llXorBase64Strings(string str1, string str2);
LSL_String llXorBase64StringsCorrect(string str1, string str2);
void SetPrimitiveParamsEx(LSL_Key prim, LSL_List rules);
LSL_List GetLinkPrimitiveParamsEx(LSL_Key prim, LSL_List rules);
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A parameter of an effect.
/// </summary>
/// <remarks>
/// A parameter can be a value type that will be set to a constant buffer, or a resource type (SRV, UAV, SamplerState).
/// </remarks>
public sealed class EffectParameter : ComponentBase
{
internal readonly EffectData.Parameter ParameterDescription;
internal readonly EffectConstantBuffer buffer;
private readonly EffectResourceLinker resourceLinker;
private readonly GetMatrixDelegate GetMatrixImpl;
private readonly CopyMatrixDelegate CopyMatrix;
private readonly int matrixSize;
private int offset;
/// <summary>
/// Initializes a new instance of the <see cref="EffectParameter"/> class.
/// </summary>
internal EffectParameter(EffectData.ValueTypeParameter parameterDescription, EffectConstantBuffer buffer)
: base(parameterDescription.Name)
{
this.ParameterDescription = parameterDescription;
this.buffer = buffer;
ResourceType = EffectResourceType.None;
IsValueType = true;
ParameterClass = parameterDescription.Class;
ParameterType = parameterDescription.Type;
RowCount = parameterDescription.RowCount;
ColumnCount = parameterDescription.ColumnCount;
ElementCount = parameterDescription.Count;
Offset = parameterDescription.Offset;
Size = parameterDescription.Size;
// If the expecting Matrix is column_major or the expected size is != from Matrix, than we need to remap SharpDX.Matrix to it.
if (ParameterClass == EffectParameterClass.MatrixRows || ParameterClass == EffectParameterClass.MatrixColumns)
{
var isMatrixToMap = RowCount != 4 || ColumnCount != 4 || ParameterClass == EffectParameterClass.MatrixColumns;
matrixSize = (ParameterClass == EffectParameterClass.MatrixColumns ? ColumnCount : RowCount) * 4 * sizeof(float);
// Use the correct function for this parameter
CopyMatrix = isMatrixToMap ? (ParameterClass == EffectParameterClass.MatrixRows) ? new CopyMatrixDelegate(CopyMatrixRowMajor) : CopyMatrixColumnMajor : CopyMatrixDirect;
GetMatrixImpl = isMatrixToMap ? (ParameterClass == EffectParameterClass.MatrixRows) ? new GetMatrixDelegate(GetMatrixRowMajorFrom) : GetMatrixColumnMajorFrom : GetMatrixDirectFrom;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EffectParameter"/> class.
/// </summary>
internal EffectParameter(EffectData.ResourceParameter parameterDescription, EffectResourceType resourceType, int offset, EffectResourceLinker resourceLinker)
: base(parameterDescription.Name)
{
this.ParameterDescription = parameterDescription;
this.resourceLinker = resourceLinker;
ResourceType = resourceType;
IsValueType = false;
ParameterClass = parameterDescription.Class;
ParameterType = parameterDescription.Type;
RowCount = ColumnCount = 0;
ElementCount = parameterDescription.Count;
Offset = offset;
}
/// <summary>
/// A unique index of this parameter instance inside the <see cref="EffectParameterCollection"/> of an effect. See remarks.
/// </summary>
/// <remarks>
/// This unique index can be used between different instance of the effect with different deferred <see cref="GraphicsDevice"/>.
/// </remarks>
public int Index { get; internal set; }
/// <summary>
/// Gets the parameter class.
/// </summary>
/// <value>The parameter class.</value>
public readonly EffectParameterClass ParameterClass;
/// <summary>
/// Gets the resource type.
/// </summary>
public readonly EffectResourceType ResourceType;
/// <summary>
/// Gets the type of the parameter.
/// </summary>
/// <value>The type of the parameter.</value>
public readonly EffectParameterType ParameterType;
/// <summary>
/// Gets a boolean indicating if this parameter is a value type (true) or a resource type (false).
/// </summary>
public readonly bool IsValueType;
/// <summary>
/// Number of rows in a matrix. Otherwise a numeric type returns 1, any other type returns 0.
/// </summary>
/// <unmanaged>int Rows</unmanaged>
public readonly int RowCount;
/// <summary>
/// Number of columns in a matrix. Otherwise a numeric type returns 1, any other type returns 0.
/// </summary>
/// <unmanaged>int Columns</unmanaged>
public readonly int ColumnCount;
/// <summary>
/// Gets the collection of effect parameters.
/// </summary>
public readonly int ElementCount;
/// <summary>
/// Size in bytes of the element, only valid for value types.
/// </summary>
public readonly int Size;
/// <summary>
/// Offset of this parameter.
/// </summary>
/// <remarks>
/// For a value type, this offset is the offset in bytes inside the constant buffer.
/// For a resource type, this offset is an index to the resource linker.
/// </remarks>
public int Offset
{
get
{
return offset;
}
internal set
{
offset = value;
}
}
/// <summary>
/// Gets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name="T">The type of the value to read from the buffer.</typeparam>
/// <returns>The value of this parameter.</returns>
public T GetValue<T>() where T : struct
{
return buffer.Get<T>(offset);
}
/// <summary>
/// Gets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name="T">The type of the value to read from the buffer.</typeparam>
/// <param name="index">The index of the value (for value array).</param>
/// <returns>The value of this parameter.</returns>
public T GetValue<T>(int index) where T : struct
{
int size;
AlignedToFloat4<T>(out size);
return buffer.Get<T>(offset + index * size);
}
/// <summary>
/// Gets an array of values to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to read from the buffer.</typeparam>
/// <returns>The value of this parameter.</returns>
public T[] GetValueArray<T>(int count) where T : struct
{
int size;
if (AlignedToFloat4<T>(out size))
{
var values = new T[count];
int localOffset = offset;
for (int i = 0; i < values.Length; i++, localOffset += size)
{
buffer.Get(localOffset, out values[i]);
}
return values;
}
return buffer.GetRange<T>(offset, count);
}
/// <summary>
/// Gets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <returns>The value of this parameter.</returns>
public Matrix GetMatrix()
{
return GetMatrixImpl(offset);
}
/// <summary>
/// Gets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <returns>The value of this parameter.</returns>
public Matrix GetMatrix(int startIndex)
{
return GetMatrixImpl(offset + (startIndex * matrixSize));
}
/// <summary>
/// Gets an array of matrices to the associated parameter in the constant buffer.
/// </summary>
/// <param name="count">The count.</param>
/// <returns>Matrix[][].</returns>
/// <returns>The value of this parameter.</returns>
public Matrix[] GetMatrixArray(int count)
{
return GetMatrixArray(0, count);
}
/// <summary>
/// Gets an array of matrices to the associated parameter in the constant buffer.
/// </summary>
/// <returns>The value of this parameter.</returns>
public unsafe Matrix[] GetMatrixArray(int startIndex, int count)
{
var result = new Matrix[count];
var localOffset = offset + (startIndex * matrixSize);
// Fix the whole buffer
fixed (Matrix* pMatrix = result)
{
for (int i = 0; i < result.Length; i++, localOffset += matrixSize)
pMatrix[i] = GetMatrixImpl(localOffset);
}
buffer.IsDirty = true;
return result;
}
/// <summary>
/// Sets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name = "value">The value to write to the buffer.</param>
public void SetValue<T>(ref T value) where T : struct
{
buffer.Set(offset, ref value);
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name = "value">The value to write to the buffer.</param>
public void SetValue<T>(T value) where T : struct
{
buffer.Set(offset, value);
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single matrix value to the associated parameter in the constant buffer.
/// </summary>
/// <param name = "value">The matrix to write to the buffer.</param>
public void SetValue(ref Matrix value)
{
CopyMatrix(ref value, offset);
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single matrix value to the associated parameter in the constant buffer.
/// </summary>
/// <param name = "value">The matrix to write to the buffer.</param>
public void SetValue(Matrix value)
{
CopyMatrix(ref value, offset);
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of matrices to the associated parameter in the constant buffer.
/// </summary>
/// <param name = "values">An array of matrices to be written to the current buffer.</param>
public unsafe void SetValue(Matrix[] values)
{
var localOffset = offset;
// Fix the whole buffer
fixed (Matrix* pMatrix = values)
{
for (int i = 0; i < values.Length; i++, localOffset += matrixSize)
CopyMatrix(ref pMatrix[i], localOffset);
}
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single matrix at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <param name="index">Index of the matrix to write in element count.</param>
/// <param name = "value">The matrix to write to the buffer.</param>
public void SetValue(int index, Matrix value)
{
CopyMatrix(ref value, offset + index * matrixSize);
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of matrices to at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <param name="index">Index of the matrix to write in element count.</param>
/// <param name = "values">An array of matrices to be written to the current buffer.</param>
public unsafe void SetValue(int index, Matrix[] values)
{
var localOffset = this.offset + (index * matrixSize);
// Fix the whole buffer
fixed (Matrix* pMatrix = values)
{
for (int i = 0; i < values.Length; i++, localOffset += matrixSize)
CopyMatrix(ref pMatrix[i], localOffset);
}
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of raw values to the associated parameter in the constant buffer.
/// </summary>
/// <param name = "values">An array of values to be written to the current buffer.</param>
public void SetRawValue(byte[] values)
{
buffer.Set(offset, values);
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of values to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name = "values">An array of values to be written to the current buffer.</param>
public void SetValue<T>(T[] values) where T : struct
{
int size;
if (AlignedToFloat4<T>(out size))
{
int localOffset = offset;
for (int i = 0; i < values.Length; i++, localOffset += size)
{
buffer.Set(localOffset, ref values[i]);
}
}
else
{
buffer.Set(offset, values);
}
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single value at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name="index">Index of the value to write in typeof(T) element count.</param>
/// <param name = "value">The value to write to the buffer.</param>
public void SetValue<T>(int index, ref T value) where T : struct
{
int size;
AlignedToFloat4<T>(out size);
buffer.Set(offset + size * index, ref value);
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single value at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name="index">Index of the value to write in typeof(T) element count.</param>
/// <param name = "value">The value to write to the buffer.</param>
public void SetValue<T>(int index, T value) where T : struct
{
int size;
AlignedToFloat4<T>(out size);
buffer.Set(offset + size * index, ref value);
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of values to at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name="index">Index of the value to write in typeof(T) element count.</param>
/// <param name = "values">An array of values to be written to the current buffer.</param>
public void SetValue<T>(int index, T[] values) where T : struct
{
int size;
if (AlignedToFloat4<T>(out size))
{
int localOffset = offset + size * index;
for (int i = 0; i < values.Length; i++, localOffset += size)
{
buffer.Set(localOffset, ref values[i]);
}
}
else
{
buffer.Set(offset + size * index, values);
}
buffer.IsDirty = true;
}
/// <summary>
/// Gets the resource view set for this parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <returns>The resource view.</returns>
public T GetResource<T>() where T : class
{
return resourceLinker.GetResource<T>(offset);
}
/// <summary>
/// Sets a shader resource for the associated parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <param name="resourceView">The resource view.</param>
public void SetResource<T>(T resourceView) where T : class
{
resourceLinker.SetResource(offset, ResourceType, resourceView);
}
/// <summary>
/// Sets a shader resource for the associated parameter.
/// </summary>
/// <param name="resourceView">The resource.</param>
/// <param name="initialUAVCount">The initial count for the UAV (-1) to keep it</param>
public void SetResource(Direct3D11.UnorderedAccessView resourceView, int initialUAVCount)
{
resourceLinker.SetResource(offset, ResourceType, resourceView, initialUAVCount);
}
/// <summary>
/// Direct access to the resource pointer in order to
/// </summary>
/// <param name="resourcePointer"></param>
internal void SetResourcePointer(IntPtr resourcePointer)
{
resourceLinker.SetResourcePointer(offset, ResourceType, resourcePointer);
}
/// <summary>
/// Sets a an array of shader resource views for the associated parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <param name="resourceViewArray">The resource view array.</param>
public void SetResource<T>(params T[] resourceViewArray) where T : class
{
resourceLinker.SetResource(offset, ResourceType, resourceViewArray);
}
/// <summary>
/// Sets a an array of shader resource views for the associated parameter.
/// </summary>
/// <param name="resourceViewArray">The resource view array.</param>
/// <param name="uavCounts">Sets the initial uavCount</param>
public void SetResource(Direct3D11.UnorderedAccessView[] resourceViewArray, int[] uavCounts)
{
resourceLinker.SetResource(offset, ResourceType, resourceViewArray, uavCounts);
}
/// <summary>
/// Sets a shader resource at the specified index for the associated parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <param name="index">Index to start to set the resource views</param>
/// <param name="resourceView">The resource view.</param>
public void SetResource<T>(int index, T resourceView) where T : class
{
resourceLinker.SetResource(offset + index, ResourceType, resourceView);
}
/// <summary>
/// Sets a an array of shader resource views at the specified index for the associated parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <param name="index">Index to start to set the resource views</param>
/// <param name="resourceViewArray">The resource view array.</param>
public void SetResource<T>(int index, params T[] resourceViewArray) where T : class
{
resourceLinker.SetResource(offset + index, ResourceType, resourceViewArray);
}
/// <summary>
/// Sets a an array of shader resource views at the specified index for the associated parameter.
/// </summary>
/// <param name="index">Index to start to set the resource views</param>
/// <param name="resourceViewArray">The resource view array.</param>
/// <param name="uavCount">Sets the initial uavCount</param>
public void SetResource(int index, Direct3D11.UnorderedAccessView[] resourceViewArray, int[] uavCount)
{
resourceLinker.SetResource(offset + index, ResourceType, resourceViewArray, uavCount);
}
internal void SetDefaultValue()
{
if (IsValueType)
{
var defaultValue = ((EffectData.ValueTypeParameter) ParameterDescription).DefaultValue;
if (defaultValue != null)
{
SetRawValue(defaultValue);
}
}
}
public override string ToString()
{
return string.Format("[{0}] {1} Class: {2}, Resource: {3}, Type: {4}, IsValue: {5}, RowCount: {6}, ColumnCount: {7}, ElementCount: {8} Offset: {9}", Index, Name, ParameterClass, ResourceType, ParameterType, IsValueType, RowCount, ColumnCount, ElementCount, Offset);
}
/// <summary>
/// CopyMatrix delegate used to reorder matrix when copying from <see cref="Matrix"/>.
/// </summary>
/// <param name="matrix">The source matrix.</param>
/// <param name="offset">The offset in bytes to write to</param>
private delegate void CopyMatrixDelegate(ref Matrix matrix, int offset);
/// <summary>
/// Copy matrix in row major order.
/// </summary>
/// <param name="matrix">The source matrix.</param>
/// <param name="offset">The offset in bytes to write to</param>
private unsafe void CopyMatrixRowMajor(ref Matrix matrix, int offset)
{
var pDest = (float*)((byte*)buffer.DataPointer + offset);
fixed (void* pMatrix = &matrix)
{
var pSrc = (float*)pMatrix;
// If Matrix is row_major but expecting less columns/rows
// then copy only necessary columns/rows.
for (int i = 0; i < RowCount; i++, pSrc +=4, pDest += 4)
{
for (int j = 0; j < ColumnCount; j++)
pDest[j] = pSrc[j];
}
}
}
/// <summary>
/// Copy matrix in column major order.
/// </summary>
/// <param name="matrix">The source matrix.</param>
/// <param name="offset">The offset in bytes to write to</param>
private unsafe void CopyMatrixColumnMajor(ref Matrix matrix, int offset)
{
var pDest = (float*)((byte*)buffer.DataPointer + offset);
fixed (void* pMatrix = &matrix)
{
var pSrc = (float*)pMatrix;
// If Matrix is column_major, then we need to transpose it
for (int i = 0; i < ColumnCount; i++, pSrc++, pDest += 4)
{
for (int j = 0; j < RowCount; j++)
pDest[j] = pSrc[j * 4];
}
}
}
private static bool AlignedToFloat4<T>(out int size) where T : struct
{
size = Utilities.SizeOf<T>();
var requireAlign = (size & 0xF) != 0;
if (requireAlign) size = ((size >> 4) + 1) << 4;
return requireAlign;
}
/// <summary>
/// Straight Matrix copy, no conversion.
/// </summary>
/// <param name="matrix">The source matrix.</param>
/// <param name="offset">The offset in bytes to write to</param>
private void CopyMatrixDirect(ref Matrix matrix, int offset)
{
buffer.Set(offset, matrix);
}
/// <summary>
/// CopyMatrix delegate used to reorder matrix when copying from <see cref="Matrix"/>.
/// </summary>
/// <param name="offset">The offset in bytes to write to</param>
private delegate Matrix GetMatrixDelegate(int offset);
/// <summary>
/// Copy matrix in row major order.
/// </summary>
/// <param name="offset">The offset in bytes to write to</param>
private unsafe Matrix GetMatrixRowMajorFrom(int offset)
{
var result = default(Matrix);
var pSrc = (float*)((byte*)buffer.DataPointer + offset);
var pDest = (float*)&result;
// If Matrix is row_major but expecting less columns/rows
// then copy only necessary columns/rows.
for (int i = 0; i < RowCount; i++, pSrc += 4, pDest += 4)
{
for (int j = 0; j < ColumnCount; j++)
pDest[j] = pSrc[j];
}
return result;
}
/// <summary>
/// Copy matrix in column major order.
/// </summary>
/// <param name="offset">The offset in bytes to write to</param>
private unsafe Matrix GetMatrixColumnMajorFrom(int offset)
{
var result = default(Matrix);
var pSrc = (float*)((byte*)buffer.DataPointer + offset);
var pDest = (float*)&result;
// If Matrix is column_major, then we need to transpose it
for (int i = 0; i < ColumnCount; i++, pSrc +=4, pDest++)
{
for (int j = 0; j < RowCount; j++)
pDest[j * 4] = pSrc[j];
}
return result;
}
/// <summary>
/// Straight Matrix copy, no conversion.
/// </summary>
/// <param name="offset">The offset in bytes to write to</param>
private Matrix GetMatrixDirectFrom(int offset)
{
return buffer.GetMatrix(offset);
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Wosad 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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using Dynamo.Controls;
using Dynamo.Models;
using Dynamo.Wpf;
using ProtoCore.AST.AssociativeAST;
using Wosad.Common.CalculationLogger;
using Wosad.Dynamo.Common;
using Wosad.Loads.ASCE7.Entities;
using Wosad.Dynamo.Common.Infra.TreeItems;
using System.Xml;
using System.Windows.Input;
using System.Windows;
using Wosad.Dynamo.UI.Common.TreeItems;
using GalaSoft.MvvmLight.Command;
using WosadDynamoUI.Views.Loads.ASCE7;
using Dynamo.Nodes;
using Dynamo.Graph;
using Dynamo.Graph.Nodes;
namespace Wosad.Loads.ASCE7.Gravity.Live
{
/// <summary>
///Occupancy or use for selection of uniformly distributed loads - ASCE7-10
/// </summary>
[NodeName("Live Load occupancy selection")]
[NodeCategory("Wosad.Loads.ASCE7.Gravity.Live")]
[NodeDescription("Occupancy or use for selection of uniformly distributed loads")]
[IsDesignScriptCompatible]
public class LiveLoadOccupancySelection : UiNodeBase
{
public LiveLoadOccupancySelection()
{
ReportEntry="";
LiveLoadOccupancyId = "Office";
LiveLoadOccupancyDescription = "Office space";
//OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)"));
OutPortData.Add(new PortData("LiveLoadOccupancyId", "description of space for calculation of live loads"));
RegisterAllPorts();
//PropertyChanged += NodePropertyChanged;
}
/// <summary>
/// Gets the type of this class, to be used in base class for reflection
/// </summary>
protected override Type GetModelType()
{
return GetType();
}
#region properties
#region OutputProperties
#region LiveLoadOccupancyIdProperty
/// <summary>
/// LiveLoadOccupancyId property
/// </summary>
/// <value>description of space for calculation of live loads</value>
public string _LiveLoadOccupancyId;
public string LiveLoadOccupancyId
{
get { return _LiveLoadOccupancyId; }
set
{
_LiveLoadOccupancyId = value;
RaisePropertyChanged("LiveLoadOccupancyId");
OnNodeModified(true);
}
}
#endregion
#region LiveLoadOccupancyDescription Property
private string liveLoadOccupancyDescription;
public string LiveLoadOccupancyDescription
{
get { return liveLoadOccupancyDescription; }
set
{
liveLoadOccupancyDescription = value;
RaisePropertyChanged("LiveLoadOccupancyDescription");
}
}
#endregion
#region ReportEntryProperty
/// <summary>
/// log property
/// </summary>
/// <value>Calculation entries that can be converted into a report.</value>
public string reportEntry;
public string ReportEntry
{
get { return reportEntry; }
set
{
reportEntry = value;
RaisePropertyChanged("ReportEntry");
OnNodeModified(true);
}
}
#endregion
#endregion
#endregion
#region Serialization
/// <summary>
///Saves property values to be retained when opening the node
/// </summary>
protected override void SerializeCore(XmlElement nodeElement, SaveContext context)
{
base.SerializeCore(nodeElement, context);
nodeElement.SetAttribute("LiveLoadOccupancyId", LiveLoadOccupancyId);
}
/// <summary>
///Retrieves property values when opening the node
/// </summary>
protected override void DeserializeCore(XmlElement nodeElement, SaveContext context)
{
base.DeserializeCore(nodeElement, context);
var attrib = nodeElement.Attributes["LiveLoadOccupancyId"];
if (attrib == null)
return;
LiveLoadOccupancyId = attrib.Value;
SetOcupancyDescription();
}
public void UpdateSelectionEvents()
{
if (TreeViewControl != null)
{
TreeViewControl.SelectedItemChanged += OnTreeViewSelectionChanged;
}
}
private void OnTreeViewSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
OnSelectedItemChanged(e.NewValue);
}
private void SetOcupancyDescription()
{
Uri uri = new Uri("pack://application:,,,/WosadDynamoUI;component/Views/Loads/ASCE7/Live/LiveLoadOccupancyIdTreeData.xml");
XmlTreeHelper treeHelper = new XmlTreeHelper();
treeHelper.ExamineXmlTreeFile(uri, new EvaluateXmlNodeDelegate(FindOccupancyDescription));
}
private void FindOccupancyDescription(XmlNode node)
{
if (null != node.Attributes["Id"])
{
if (node.Attributes["Id"].Value== LiveLoadOccupancyId)
{
LiveLoadOccupancyDescription = node.Attributes["Description"].Value;
}
}
}
#endregion
#region treeView elements
public TreeView TreeViewControl { get; set; }
public void DisplayComponentUI(XTreeItem selectedComponent)
{
//TODO: Add partition allowance here
}
private XTreeItem selectedItem;
public XTreeItem SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
}
}
private void OnSelectedItemChanged(object i)
{
XmlElement item = i as XmlElement;
XTreeItem xtreeItem = new XTreeItem()
{
Header = item.GetAttribute("Header"),
Description = item.GetAttribute("Description"),
Id = item.GetAttribute("Id"),
ResourcePath = item.GetAttribute("ResourcePath"),
Tag = item.GetAttribute("Tag"),
TemplateName = item.GetAttribute("TemplateName")
};
if (item != null)
{
string id =xtreeItem.Id;
if (id != "X")
{
LiveLoadOccupancyId = xtreeItem.Id;
LiveLoadOccupancyDescription = xtreeItem.Description;
SelectedItem = xtreeItem;
DisplayComponentUI(xtreeItem);
}
}
}
#endregion
//Additional UI is a user control which is based on the user selection
// can remove this property
#region Additional UI
private UserControl additionalUI;
public UserControl AdditionalUI
{
get { return additionalUI; }
set
{
additionalUI = value;
RaisePropertyChanged("AdditionalUI");
}
}
#endregion
/// <summary>
///Customization of WPF view in Dynamo UI
/// </summary>
public class LiveLoadOccupancyIdViewCustomization : UiNodeBaseViewCustomization,
INodeViewCustomization<LiveLoadOccupancySelection>
{
public void CustomizeView(LiveLoadOccupancySelection model, NodeView nodeView)
{
base.CustomizeView(model, nodeView);
LiveLoadOccupancyIdView control = new LiveLoadOccupancyIdView();
control.DataContext = model;
//remove this part if control does not contain tree
TreeView tv = control.FindName("selectionTree") as TreeView;
if (tv!=null)
{
model.TreeViewControl = tv;
model.UpdateSelectionEvents();
}
nodeView.inputGrid.Children.Add(control);
base.CustomizeView(model, nodeView);
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using System.Text;
using Encog.App.Generate.Program;
using Encog.Engine.Network.Activation;
using Encog.ML;
using Encog.ML.Data;
using Encog.Neural.Flat;
using Encog.Neural.Networks;
using Encog.Persist;
using Encog.Util.CSV;
using Encog.Util.Simple;
namespace Encog.App.Generate.Generators.JS
{
/// <summary>
/// Generate JavaScript.
/// </summary>
public class GenerateEncogJavaScript : AbstractGenerator
{
private void EmbedNetwork(EncogProgramNode node)
{
AddBreak();
var methodFile = (FileInfo) node.Args[0].Value;
var method = (IMLMethod) EncogDirectoryPersistence
.LoadObject(methodFile);
if (!(method is IMLFactory))
{
throw new EncogError("Code generation not yet supported for: "
+ method.GetType().Name);
}
FlatNetwork flat = ((IContainsFlat) method).Flat;
// header
var line = new StringBuilder();
line.Append("public static MLMethod ");
line.Append(node.Name);
line.Append("() {");
IndentLine(line.ToString());
// create factory
line.Length = 0;
AddLine("var network = ENCOG.BasicNetwork.create( null );");
AddLine("network.inputCount = " + flat.InputCount + ";");
AddLine("network.outputCount = " + flat.OutputCount + ";");
AddLine("network.layerCounts = "
+ ToSingleLineArray(flat.LayerCounts) + ";");
AddLine("network.layerContextCount = "
+ ToSingleLineArray(flat.LayerContextCount) + ";");
AddLine("network.weightIndex = "
+ ToSingleLineArray(flat.WeightIndex) + ";");
AddLine("network.layerIndex = "
+ ToSingleLineArray(flat.LayerIndex) + ";");
AddLine("network.activationFunctions = "
+ ToSingleLineArray(flat.ActivationFunctions) + ";");
AddLine("network.layerFeedCounts = "
+ ToSingleLineArray(flat.LayerFeedCounts) + ";");
AddLine("network.contextTargetOffset = "
+ ToSingleLineArray(flat.ContextTargetOffset) + ";");
AddLine("network.contextTargetSize = "
+ ToSingleLineArray(flat.ContextTargetSize) + ";");
AddLine("network.biasActivation = "
+ ToSingleLineArray(flat.BiasActivation) + ";");
AddLine("network.beginTraining = " + flat.BeginTraining + ";");
AddLine("network.endTraining=" + flat.EndTraining + ";");
AddLine("network.weights = WEIGHTS;");
AddLine("network.layerOutput = "
+ ToSingleLineArray(flat.LayerOutput) + ";");
AddLine("network.layerSums = " + ToSingleLineArray(flat.LayerSums)
+ ";");
// return
AddLine("return network;");
UnIndentLine("}");
}
private void EmbedTraining(EncogProgramNode node)
{
var dataFile = (FileInfo) node.Args[0].Value;
IMLDataSet data = EncogUtility.LoadEGB2Memory(dataFile);
// generate the input data
IndentLine("var INPUT_DATA = [");
foreach (IMLDataPair pair in data)
{
IMLData item = pair.Input;
var line = new StringBuilder();
NumberList.ToList(CSVFormat.EgFormat, line, item);
line.Insert(0, "[ ");
line.Append(" ],");
AddLine(line.ToString());
}
UnIndentLine("];");
AddBreak();
// generate the ideal data
IndentLine("var IDEAL_DATA = [");
foreach (IMLDataPair pair in data)
{
IMLData item = pair.Ideal;
var line = new StringBuilder();
NumberList.ToList(CSVFormat.EgFormat, line, item);
line.Insert(0, "[ ");
line.Append(" ],");
AddLine(line.ToString());
}
UnIndentLine("];");
}
public override void Generate(EncogGenProgram program, bool shouldEmbed)
{
if (!shouldEmbed)
{
throw new AnalystCodeGenerationError(
"Must embed when generating Javascript");
}
GenerateForChildren(program);
}
private void GenerateArrayInit(EncogProgramNode node)
{
var line = new StringBuilder();
line.Append("var ");
line.Append(node.Name);
line.Append(" = [");
IndentLine(line.ToString());
var a = (double[]) node.Args[0].Value;
line.Length = 0;
int lineCount = 0;
for (int i = 0; i < a.Length; i++)
{
line.Append(CSVFormat.EgFormat.Format(a[i],
EncogFramework.DefaultPrecision));
if (i < (a.Length - 1))
{
line.Append(",");
}
lineCount++;
if (lineCount >= 10)
{
AddLine(line.ToString());
line.Length = 0;
lineCount = 0;
}
}
if (line.Length > 0)
{
AddLine(line.ToString());
line.Length = 0;
}
UnIndentLine("];");
}
private void GenerateClass(EncogProgramNode node)
{
AddBreak();
AddLine("<!DOCTYPE html>");
AddLine("<html>");
AddLine("<head>");
AddLine("<title>Encog Generated Javascript</title>");
AddLine("</head>");
AddLine("<body>");
AddLine("<script src=\"../encog.js\"></script>");
AddLine("<script src=\"../encog-widget.js\"></script>");
AddLine("<pre>");
AddLine("<script type=\"text/javascript\">");
GenerateForChildren(node);
AddLine("</script>");
AddLine(
"<noscript>Your browser does not support JavaScript! Note: if you are trying to view this in Encog Workbench, right-click file and choose \"Open as Text\".</noscript>");
AddLine("</pre>");
AddLine("</body>");
AddLine("</html>");
}
private void GenerateComment(EncogProgramNode commentNode)
{
AddLine("// " + commentNode.Name);
}
private void GenerateConst(EncogProgramNode node)
{
var line = new StringBuilder();
line.Append("var ");
line.Append(node.Name);
line.Append(" = \"");
line.Append(node.Args[0].Value);
line.Append("\";");
AddLine(line.ToString());
}
private void GenerateForChildren(EncogTreeNode parent)
{
foreach (EncogProgramNode node in parent.Children)
{
GenerateNode(node);
}
}
private void GenerateFunction(EncogProgramNode node)
{
AddBreak();
var line = new StringBuilder();
line.Append("function ");
line.Append(node.Name);
line.Append("() {");
IndentLine(line.ToString());
GenerateForChildren(node);
UnIndentLine("}");
}
private void GenerateFunctionCall(EncogProgramNode node)
{
AddBreak();
var line = new StringBuilder();
if (node.Args[0].Value.ToString().Length > 0)
{
line.Append("var ");
line.Append(node.Args[1].Value);
line.Append(" = ");
}
line.Append(node.Name);
line.Append("();");
AddLine(line.ToString());
}
private void GenerateMainFunction(EncogProgramNode node)
{
AddBreak();
GenerateForChildren(node);
}
private void GenerateNode(EncogProgramNode node)
{
switch (node.Type)
{
case NodeType.Comment:
GenerateComment(node);
break;
case NodeType.Class:
GenerateClass(node);
break;
case NodeType.MainFunction:
GenerateMainFunction(node);
break;
case NodeType.Const:
GenerateConst(node);
break;
case NodeType.StaticFunction:
GenerateFunction(node);
break;
case NodeType.FunctionCall:
GenerateFunctionCall(node);
break;
case NodeType.CreateNetwork:
EmbedNetwork(node);
break;
case NodeType.InitArray:
GenerateArrayInit(node);
break;
case NodeType.EmbedTraining:
EmbedTraining(node);
break;
}
}
private String ToSingleLineArray(
IActivationFunction[] activationFunctions)
{
var result = new StringBuilder();
result.Append('[');
for (int i = 0; i < activationFunctions.Length; i++)
{
if (i > 0)
{
result.Append(',');
}
IActivationFunction af = activationFunctions[i];
if (af is ActivationSigmoid)
{
result.Append("ENCOG.ActivationSigmoid.create()");
}
else if (af is ActivationTANH)
{
result.Append("ENCOG.ActivationTANH.create()");
}
else if (af is ActivationLinear)
{
result.Append("ENCOG.ActivationLinear.create()");
}
else if (af is ActivationElliott)
{
result.Append("ENCOG.ActivationElliott.create()");
}
else if (af is ActivationElliott)
{
result.Append("ENCOG.ActivationElliott.create()");
}
else
{
throw new AnalystCodeGenerationError(
"Unsupported activatoin function for code generation: "
+ af.GetType().Name);
}
}
result.Append(']');
return result.ToString();
}
private String ToSingleLineArray(double[] d)
{
var line = new StringBuilder();
line.Append("[");
for (int i = 0; i < d.Length; i++)
{
line.Append(CSVFormat.EgFormat.Format(d[i],
EncogFramework.DefaultPrecision));
if (i < (d.Length - 1))
{
line.Append(",");
}
}
line.Append("]");
return line.ToString();
}
private String ToSingleLineArray(int[] d)
{
var line = new StringBuilder();
line.Append("[");
for (int i = 0; i < d.Length; i++)
{
line.Append(d[i]);
if (i < (d.Length - 1))
{
line.Append(",");
}
}
line.Append("]");
return line.ToString();
}
}
}
| |
namespace java.nio.channels
{
[global::MonoJavaBridge.JavaClass(typeof(global::java.nio.channels.Pipe_))]
public abstract partial class Pipe : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Pipe(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass(typeof(global::java.nio.channels.Pipe.SinkChannel_))]
public abstract partial class SinkChannel : java.nio.channels.spi.AbstractSelectableChannel, WritableByteChannel, GatheringByteChannel
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected SinkChannel(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public abstract int write(java.nio.ByteBuffer arg0);
private static global::MonoJavaBridge.MethodId _m1;
public abstract long write(java.nio.ByteBuffer[] arg0, int arg1, int arg2);
private static global::MonoJavaBridge.MethodId _m2;
public abstract long write(java.nio.ByteBuffer[] arg0);
private static global::MonoJavaBridge.MethodId _m3;
public sealed override int validOps()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.channels.Pipe.SinkChannel.staticClass, "validOps", "()I", ref global::java.nio.channels.Pipe.SinkChannel._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
protected SinkChannel(java.nio.channels.spi.SelectorProvider arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.nio.channels.Pipe.SinkChannel._m4.native == global::System.IntPtr.Zero)
global::java.nio.channels.Pipe.SinkChannel._m4 = @__env.GetMethodIDNoThrow(global::java.nio.channels.Pipe.SinkChannel.staticClass, "<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.nio.channels.Pipe.SinkChannel.staticClass, global::java.nio.channels.Pipe.SinkChannel._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static SinkChannel()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.Pipe.SinkChannel.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/Pipe$SinkChannel"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.channels.Pipe.SinkChannel))]
internal sealed partial class SinkChannel_ : java.nio.channels.Pipe.SinkChannel
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal SinkChannel_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override int write(java.nio.ByteBuffer arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.channels.Pipe.SinkChannel_.staticClass, "write", "(Ljava/nio/ByteBuffer;)I", ref global::java.nio.channels.Pipe.SinkChannel_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override long write(java.nio.ByteBuffer[] arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.Pipe.SinkChannel_.staticClass, "write", "([Ljava/nio/ByteBuffer;II)J", ref global::java.nio.channels.Pipe.SinkChannel_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m2;
public override long write(java.nio.ByteBuffer[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.Pipe.SinkChannel_.staticClass, "write", "([Ljava/nio/ByteBuffer;)J", ref global::java.nio.channels.Pipe.SinkChannel_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
protected override void implCloseSelectableChannel()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.nio.channels.Pipe.SinkChannel_.staticClass, "implCloseSelectableChannel", "()V", ref global::java.nio.channels.Pipe.SinkChannel_._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
protected override void implConfigureBlocking(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.nio.channels.Pipe.SinkChannel_.staticClass, "implConfigureBlocking", "(Z)V", ref global::java.nio.channels.Pipe.SinkChannel_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static SinkChannel_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.Pipe.SinkChannel_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/Pipe$SinkChannel"));
}
}
[global::MonoJavaBridge.JavaClass(typeof(global::java.nio.channels.Pipe.SourceChannel_))]
public abstract partial class SourceChannel : java.nio.channels.spi.AbstractSelectableChannel, ReadableByteChannel, ScatteringByteChannel
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected SourceChannel(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public abstract int read(java.nio.ByteBuffer arg0);
private static global::MonoJavaBridge.MethodId _m1;
public abstract long read(java.nio.ByteBuffer[] arg0, int arg1, int arg2);
private static global::MonoJavaBridge.MethodId _m2;
public abstract long read(java.nio.ByteBuffer[] arg0);
private static global::MonoJavaBridge.MethodId _m3;
public sealed override int validOps()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.channels.Pipe.SourceChannel.staticClass, "validOps", "()I", ref global::java.nio.channels.Pipe.SourceChannel._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
protected SourceChannel(java.nio.channels.spi.SelectorProvider arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.nio.channels.Pipe.SourceChannel._m4.native == global::System.IntPtr.Zero)
global::java.nio.channels.Pipe.SourceChannel._m4 = @__env.GetMethodIDNoThrow(global::java.nio.channels.Pipe.SourceChannel.staticClass, "<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.nio.channels.Pipe.SourceChannel.staticClass, global::java.nio.channels.Pipe.SourceChannel._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static SourceChannel()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.Pipe.SourceChannel.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/Pipe$SourceChannel"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.channels.Pipe.SourceChannel))]
internal sealed partial class SourceChannel_ : java.nio.channels.Pipe.SourceChannel
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal SourceChannel_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override int read(java.nio.ByteBuffer arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.nio.channels.Pipe.SourceChannel_.staticClass, "read", "(Ljava/nio/ByteBuffer;)I", ref global::java.nio.channels.Pipe.SourceChannel_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override long read(java.nio.ByteBuffer[] arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.Pipe.SourceChannel_.staticClass, "read", "([Ljava/nio/ByteBuffer;II)J", ref global::java.nio.channels.Pipe.SourceChannel_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m2;
public override long read(java.nio.ByteBuffer[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.nio.channels.Pipe.SourceChannel_.staticClass, "read", "([Ljava/nio/ByteBuffer;)J", ref global::java.nio.channels.Pipe.SourceChannel_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
protected override void implCloseSelectableChannel()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.nio.channels.Pipe.SourceChannel_.staticClass, "implCloseSelectableChannel", "()V", ref global::java.nio.channels.Pipe.SourceChannel_._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
protected override void implConfigureBlocking(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.nio.channels.Pipe.SourceChannel_.staticClass, "implConfigureBlocking", "(Z)V", ref global::java.nio.channels.Pipe.SourceChannel_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static SourceChannel_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.Pipe.SourceChannel_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/Pipe$SourceChannel"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::java.nio.channels.Pipe open()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.nio.channels.Pipe._m0.native == global::System.IntPtr.Zero)
global::java.nio.channels.Pipe._m0 = @__env.GetStaticMethodIDNoThrow(global::java.nio.channels.Pipe.staticClass, "open", "()Ljava/nio/channels/Pipe;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.channels.Pipe.staticClass, global::java.nio.channels.Pipe._m0)) as java.nio.channels.Pipe;
}
private static global::MonoJavaBridge.MethodId _m1;
public abstract global::java.nio.channels.Pipe.SourceChannel source();
private static global::MonoJavaBridge.MethodId _m2;
public abstract global::java.nio.channels.Pipe.SinkChannel sink();
private static global::MonoJavaBridge.MethodId _m3;
protected Pipe() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.nio.channels.Pipe._m3.native == global::System.IntPtr.Zero)
global::java.nio.channels.Pipe._m3 = @__env.GetMethodIDNoThrow(global::java.nio.channels.Pipe.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.nio.channels.Pipe.staticClass, global::java.nio.channels.Pipe._m3);
Init(@__env, handle);
}
static Pipe()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.Pipe.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/Pipe"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.channels.Pipe))]
internal sealed partial class Pipe_ : java.nio.channels.Pipe
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Pipe_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::java.nio.channels.Pipe.SourceChannel source()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.channels.Pipe_.staticClass, "source", "()Ljava/nio/channels/Pipe$SourceChannel;", ref global::java.nio.channels.Pipe_._m0) as java.nio.channels.Pipe.SourceChannel;
}
private static global::MonoJavaBridge.MethodId _m1;
public override global::java.nio.channels.Pipe.SinkChannel sink()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.nio.channels.Pipe_.staticClass, "sink", "()Ljava/nio/channels/Pipe$SinkChannel;", ref global::java.nio.channels.Pipe_._m1) as java.nio.channels.Pipe.SinkChannel;
}
static Pipe_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.Pipe_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/Pipe"));
}
}
}
| |
using Assets.PostProcessing.Runtime.Utils;
using UnityEditorInternal;
using UnityEngine;
namespace UnityEditor.PostProcessing
{
public class VectorscopeMonitor : PostProcessingMonitor
{
static GUIContent s_MonitorTitle = new GUIContent("Vectorscope");
ComputeShader m_ComputeShader;
ComputeBuffer m_Buffer;
Material m_Material;
RenderTexture m_VectorscopeTexture;
Rect m_MonitorAreaRect;
public VectorscopeMonitor()
{
m_ComputeShader = EditorResources.Load<ComputeShader>("Monitors/VectorscopeCompute.compute");
}
public override void Dispose()
{
GraphicsUtils.Destroy(m_Material);
GraphicsUtils.Destroy(m_VectorscopeTexture);
if (m_Buffer != null)
m_Buffer.Release();
m_Material = null;
m_VectorscopeTexture = null;
m_Buffer = null;
}
public override bool IsSupported()
{
return m_ComputeShader != null && GraphicsUtils.supportsDX11;
}
public override GUIContent GetMonitorTitle()
{
return s_MonitorTitle;
}
public override void OnMonitorSettings()
{
EditorGUI.BeginChangeCheck();
bool refreshOnPlay = m_MonitorSettings.refreshOnPlay;
float exposure = m_MonitorSettings.vectorscopeExposure;
bool showBackground = m_MonitorSettings.vectorscopeShowBackground;
refreshOnPlay = GUILayout.Toggle(refreshOnPlay, new GUIContent(FxStyles.playIcon, "Keep refreshing the vectorscope in play mode; this may impact performances."), FxStyles.preButton);
exposure = GUILayout.HorizontalSlider(exposure, 0.05f, 0.3f, FxStyles.preSlider, FxStyles.preSliderThumb, GUILayout.Width(40f));
showBackground = GUILayout.Toggle(showBackground, new GUIContent(FxStyles.checkerIcon, "Show an YUV background in the vectorscope."), FxStyles.preButton);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(m_BaseEditor.serializedObject.targetObject, "Vectorscope Settings Changed");
m_MonitorSettings.refreshOnPlay = refreshOnPlay;
m_MonitorSettings.vectorscopeExposure = exposure;
m_MonitorSettings.vectorscopeShowBackground = showBackground;
InternalEditorUtility.RepaintAllViews();
}
}
public override void OnMonitorGUI(Rect r)
{
if (Event.current.type == EventType.Repaint)
{
// If m_MonitorAreaRect isn't set the preview was just opened so refresh the render to get the vectoscope data
if (Mathf.Approximately(m_MonitorAreaRect.width, 0) && Mathf.Approximately(m_MonitorAreaRect.height, 0))
InternalEditorUtility.RepaintAllViews();
// Sizing
float size = 0f;
if (r.width < r.height)
{
size = m_VectorscopeTexture != null
? Mathf.Min(m_VectorscopeTexture.width, r.width - 35f)
: r.width;
}
else
{
size = m_VectorscopeTexture != null
? Mathf.Min(m_VectorscopeTexture.height, r.height - 25f)
: r.height;
}
m_MonitorAreaRect = new Rect(
Mathf.Floor(r.x + r.width / 2f - size / 2f),
Mathf.Floor(r.y + r.height / 2f - size / 2f - 5f),
size, size
);
if (m_VectorscopeTexture != null)
{
m_Material.SetFloat("_Exposure", m_MonitorSettings.vectorscopeExposure);
var oldActive = RenderTexture.active;
Graphics.Blit(null, m_VectorscopeTexture, m_Material, m_MonitorSettings.vectorscopeShowBackground ? 0 : 1);
RenderTexture.active = oldActive;
Graphics.DrawTexture(m_MonitorAreaRect, m_VectorscopeTexture);
var color = Color.white;
const float kTickSize = 10f;
const int kTickCount = 24;
float radius = m_MonitorAreaRect.width / 2f;
float midX = m_MonitorAreaRect.x + radius;
float midY = m_MonitorAreaRect.y + radius;
var center = new Vector2(midX, midY);
// Cross
color.a *= 0.5f;
Handles.color = color;
Handles.DrawLine(new Vector2(midX, m_MonitorAreaRect.y), new Vector2(midX, m_MonitorAreaRect.y + m_MonitorAreaRect.height));
Handles.DrawLine(new Vector2(m_MonitorAreaRect.x, midY), new Vector2(m_MonitorAreaRect.x + m_MonitorAreaRect.width, midY));
if (m_MonitorAreaRect.width > 100f)
{
color.a = 1f;
// Ticks
Handles.color = color;
for (int i = 0; i < kTickCount; i++)
{
float a = (float)i / (float)kTickCount;
float theta = a * (Mathf.PI * 2f);
float tx = Mathf.Cos(theta + (Mathf.PI / 2f));
float ty = Mathf.Sin(theta - (Mathf.PI / 2f));
var innerVec = center + new Vector2(tx, ty) * (radius - kTickSize);
var outerVec = center + new Vector2(tx, ty) * radius;
Handles.DrawAAPolyLine(3f, innerVec, outerVec);
}
// Labels (where saturation reaches 75%)
color.a = 1f;
var oldColor = GUI.color;
GUI.color = color * 2f;
var point = new Vector2(-0.254f, -0.750f) * radius + center;
var rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
GUI.Label(rect, "[R]", FxStyles.tickStyleCenter);
point = new Vector2(-0.497f, 0.629f) * radius + center;
rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
GUI.Label(rect, "[G]", FxStyles.tickStyleCenter);
point = new Vector2(0.750f, 0.122f) * radius + center;
rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
GUI.Label(rect, "[B]", FxStyles.tickStyleCenter);
point = new Vector2(-0.750f, -0.122f) * radius + center;
rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
GUI.Label(rect, "[Y]", FxStyles.tickStyleCenter);
point = new Vector2(0.254f, 0.750f) * radius + center;
rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
GUI.Label(rect, "[C]", FxStyles.tickStyleCenter);
point = new Vector2(0.497f, -0.629f) * radius + center;
rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
GUI.Label(rect, "[M]", FxStyles.tickStyleCenter);
GUI.color = oldColor;
}
}
}
}
public override void OnFrameData(RenderTexture source)
{
if (Application.isPlaying && !m_MonitorSettings.refreshOnPlay)
return;
if (Mathf.Approximately(m_MonitorAreaRect.width, 0) || Mathf.Approximately(m_MonitorAreaRect.height, 0))
return;
float ratio = (float)source.width / (float)source.height;
int h = 384;
int w = Mathf.FloorToInt(h * ratio);
var rt = RenderTexture.GetTemporary(w, h, 0, source.format);
Graphics.Blit(source, rt);
ComputeVectorscope(rt);
m_BaseEditor.Repaint();
RenderTexture.ReleaseTemporary(rt);
}
void CreateBuffer(int width, int height)
{
m_Buffer = new ComputeBuffer(width * height, sizeof(uint));
}
void ComputeVectorscope(RenderTexture source)
{
if (m_Buffer == null)
{
CreateBuffer(source.width, source.height);
}
else if (m_Buffer.count != (source.width * source.height))
{
m_Buffer.Release();
CreateBuffer(source.width, source.height);
}
var cs = m_ComputeShader;
int kernel = cs.FindKernel("KVectorscopeClear");
cs.SetBuffer(kernel, "_Vectorscope", m_Buffer);
cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f));
cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1);
kernel = cs.FindKernel("KVectorscope");
cs.SetBuffer(kernel, "_Vectorscope", m_Buffer);
cs.SetTexture(kernel, "_Source", source);
cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0);
cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f));
cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1);
if (m_VectorscopeTexture == null || m_VectorscopeTexture.width != source.width || m_VectorscopeTexture.height != source.height)
{
GraphicsUtils.Destroy(m_VectorscopeTexture);
m_VectorscopeTexture = new RenderTexture(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.DontSave,
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear
};
}
if (m_Material == null)
m_Material = new Material(Shader.Find("Hidden/Post FX/Monitors/Vectorscope Render")) { hideFlags = HideFlags.DontSave };
m_Material.SetBuffer("_Vectorscope", m_Buffer);
m_Material.SetVector("_Size", new Vector2(m_VectorscopeTexture.width, m_VectorscopeTexture.height));
}
}
}
| |
//
// PdbHelper.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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 Mono.Cecil.Cil;
namespace Mono.Cecil.Pdb
{
class PdbHelper
{
public static string GetPdbFileName(string assemblyFileName)
{
return Path.ChangeExtension(assemblyFileName, ".pdb");
}
}
public class PdbReaderProvider : ISymbolReaderProvider
{
public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
{
return new PdbReader(File.OpenRead(PdbHelper.GetPdbFileName(fileName)));
}
public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
{
return new PdbReader(symbolStream);
}
}
public class GuidCompare : IEqualityComparer<Guid>
{
public bool Equals(Guid x, Guid y)
{
return x == y;
}
public int GetHashCode(Guid obj)
{
return obj.GetHashCode();
}
}
public class DocumentLanguageCompare : IEqualityComparer<DocumentLanguage>
{
public bool Equals(DocumentLanguage x, DocumentLanguage y)
{
return x == y;
}
public int GetHashCode(DocumentLanguage obj)
{
return obj.GetHashCode();
}
}
public class uintCompare : IEqualityComparer<uint>
{
public bool Equals(uint x, uint y)
{
return x == y;
}
public int GetHashCode(uint obj)
{
return obj.GetHashCode();
}
}
static class GuidMapping
{
static readonly Dictionary<Guid, DocumentLanguage> guid_language = new Dictionary<Guid, DocumentLanguage>(new GuidCompare());
static readonly Dictionary<DocumentLanguage, Guid> language_guid = new Dictionary<DocumentLanguage, Guid>(new DocumentLanguageCompare());
static GuidMapping()
{
AddMapping(DocumentLanguage.C, new Guid(0x63a08714, 0xfc37, 0x11d2, 0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1));
AddMapping(DocumentLanguage.Cpp, new Guid(0x3a12d0b7, 0xc26c, 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2));
AddMapping(DocumentLanguage.CSharp, new Guid(0x3f5162f8, 0x07c6, 0x11d3, 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1));
AddMapping(DocumentLanguage.Basic, new Guid(0x3a12d0b8, 0xc26c, 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2));
AddMapping(DocumentLanguage.Java, new Guid(0x3a12d0b4, 0xc26c, 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2));
AddMapping(DocumentLanguage.Cobol, new Guid(0xaf046cd1, 0xd0e1, 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc));
AddMapping(DocumentLanguage.Pascal, new Guid(0xaf046cd2, 0xd0e1, 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc));
AddMapping(DocumentLanguage.Cil, new Guid(0xaf046cd3, 0xd0e1, 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc));
AddMapping(DocumentLanguage.JScript, new Guid(0x3a12d0b6, 0xc26c, 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2));
AddMapping(DocumentLanguage.Smc, new Guid(0xd9b9f7b, 0x6611, 0x11d3, 0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd));
AddMapping(DocumentLanguage.MCpp, new Guid(0x4b35fde8, 0x07c6, 0x11d3, 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1));
//AddMapping(DocumentLanguage.FSharp, new Guid(0xab4f38c9, 0xb6e6, 0x43ba, 0xbe, 0x3b, 0x58, 0x08, 0x0b, 0x2c, 0xcc, 0xe3));
}
static void AddMapping(DocumentLanguage language, Guid guid)
{
guid_language.Add(guid, language);
language_guid.Add(language, guid);
}
static readonly Guid type_text = new Guid(0x5a869d0b, 0x6611, 0x11d3, 0xbd, 0x2a, 0x00, 0x00, 0xf8, 0x08, 0x49, 0xbd);
public static DocumentType ToType(Guid guid)
{
if (guid == type_text)
return DocumentType.Text;
return DocumentType.Other;
}
public static Guid ToGuid(DocumentType type)
{
if (type == DocumentType.Text)
return type_text;
return new Guid();
}
static readonly Guid hash_md5 = new Guid(0x406ea660, 0x64cf, 0x4c82, 0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99);
static readonly Guid hash_sha1 = new Guid(0xff1816ec, 0xaa5e, 0x4d10, 0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60);
public static DocumentHashAlgorithm ToHashAlgorithm(Guid guid)
{
if (guid == hash_md5)
return DocumentHashAlgorithm.MD5;
if (guid == hash_sha1)
return DocumentHashAlgorithm.SHA1;
return DocumentHashAlgorithm.None;
}
public static Guid ToGuid(DocumentHashAlgorithm hash_algo)
{
if (hash_algo == DocumentHashAlgorithm.MD5)
return hash_md5;
if (hash_algo == DocumentHashAlgorithm.SHA1)
return hash_sha1;
return new Guid();
}
public static DocumentLanguage ToLanguage(Guid guid)
{
DocumentLanguage language;
if (!guid_language.TryGetValue(guid, out language))
return DocumentLanguage.Other;
return language;
}
public static Guid ToGuid(DocumentLanguage language)
{
Guid guid;
if (!language_guid.TryGetValue(language, out guid))
return new Guid();
return guid;
}
static readonly Guid vendor_ms = new Guid(0x994b45c4, 0xe6e9, 0x11d2, 0x90, 0x3f, 0x00, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
public static DocumentLanguageVendor ToVendor(Guid guid)
{
if (guid == vendor_ms)
return DocumentLanguageVendor.Microsoft;
return DocumentLanguageVendor.Other;
}
public static Guid ToGuid(DocumentLanguageVendor vendor)
{
if (vendor == DocumentLanguageVendor.Microsoft)
return vendor_ms;
return new Guid();
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Census Student Validation Type Data Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SCEN_SVTDataSet : EduHubDataSet<SCEN_SVT>
{
/// <inheritdoc />
public override string Name { get { return "SCEN_SVT"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return false; } }
internal SCEN_SVTDataSet(EduHubContext Context)
: base(Context)
{
Index_ID = new Lazy<Dictionary<int, SCEN_SVT>>(() => this.ToDictionary(i => i.ID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SCEN_SVT" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SCEN_SVT" /> fields for each CSV column header</returns>
internal override Action<SCEN_SVT, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SCEN_SVT, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "ID":
mapper[i] = (e, v) => e.ID = int.Parse(v);
break;
case "VCODE":
mapper[i] = (e, v) => e.VCODE = v;
break;
case "VALIDATIONMESSAGE":
mapper[i] = (e, v) => e.VALIDATIONMESSAGE = v;
break;
case "WARNING":
mapper[i] = (e, v) => e.WARNING = v;
break;
case "PERIOD":
mapper[i] = (e, v) => e.PERIOD = v;
break;
case "DETAILEDMESSAGE":
mapper[i] = (e, v) => e.DETAILEDMESSAGE = v;
break;
case "FIELDS":
mapper[i] = (e, v) => e.FIELDS = v;
break;
case "COMMANDNAME":
mapper[i] = (e, v) => e.COMMANDNAME = v;
break;
case "ISENABLED":
mapper[i] = (e, v) => e.ISENABLED = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SCEN_SVT" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SCEN_SVT" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SCEN_SVT" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SCEN_SVT}"/> of entities</returns>
internal override IEnumerable<SCEN_SVT> ApplyDeltaEntities(IEnumerable<SCEN_SVT> Entities, List<SCEN_SVT> DeltaEntities)
{
HashSet<int> Index_ID = new HashSet<int>(DeltaEntities.Select(i => i.ID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.ID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_ID.Remove(entity.ID);
if (entity.ID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, SCEN_SVT>> Index_ID;
#endregion
#region Index Methods
/// <summary>
/// Find SCEN_SVT by ID field
/// </summary>
/// <param name="ID">ID value used to find SCEN_SVT</param>
/// <returns>Related SCEN_SVT entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SCEN_SVT FindByID(int ID)
{
return Index_ID.Value[ID];
}
/// <summary>
/// Attempt to find SCEN_SVT by ID field
/// </summary>
/// <param name="ID">ID value used to find SCEN_SVT</param>
/// <param name="Value">Related SCEN_SVT entity</param>
/// <returns>True if the related SCEN_SVT entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByID(int ID, out SCEN_SVT Value)
{
return Index_ID.Value.TryGetValue(ID, out Value);
}
/// <summary>
/// Attempt to find SCEN_SVT by ID field
/// </summary>
/// <param name="ID">ID value used to find SCEN_SVT</param>
/// <returns>Related SCEN_SVT entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SCEN_SVT TryFindByID(int ID)
{
SCEN_SVT value;
if (Index_ID.Value.TryGetValue(ID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SCEN_SVT table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SCEN_SVT]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SCEN_SVT](
[ID] int IDENTITY NOT NULL,
[VCODE] varchar(15) NULL,
[VALIDATIONMESSAGE] varchar(255) NULL,
[WARNING] varchar(1) NULL,
[PERIOD] varchar(1) NULL,
[DETAILEDMESSAGE] varchar(MAX) NULL,
[FIELDS] varchar(255) NULL,
[COMMANDNAME] varchar(255) NULL,
[ISENABLED] varchar(1) NULL,
CONSTRAINT [SCEN_SVT_Index_ID] PRIMARY KEY CLUSTERED (
[ID] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="SCEN_SVTDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="SCEN_SVTDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SCEN_SVT"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SCEN_SVT"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SCEN_SVT> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_ID = new List<int>();
foreach (var entity in Entities)
{
Index_ID.Add(entity.ID);
}
builder.AppendLine("DELETE [dbo].[SCEN_SVT] WHERE");
// Index_ID
builder.Append("[ID] IN (");
for (int index = 0; index < Index_ID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// ID
var parameterID = $"@p{parameterIndex++}";
builder.Append(parameterID);
command.Parameters.Add(parameterID, SqlDbType.Int).Value = Index_ID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SCEN_SVT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SCEN_SVT data set</returns>
public override EduHubDataSetDataReader<SCEN_SVT> GetDataSetDataReader()
{
return new SCEN_SVTDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SCEN_SVT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SCEN_SVT data set</returns>
public override EduHubDataSetDataReader<SCEN_SVT> GetDataSetDataReader(List<SCEN_SVT> Entities)
{
return new SCEN_SVTDataReader(new EduHubDataSetLoadedReader<SCEN_SVT>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SCEN_SVTDataReader : EduHubDataSetDataReader<SCEN_SVT>
{
public SCEN_SVTDataReader(IEduHubDataSetReader<SCEN_SVT> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 9; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // ID
return Current.ID;
case 1: // VCODE
return Current.VCODE;
case 2: // VALIDATIONMESSAGE
return Current.VALIDATIONMESSAGE;
case 3: // WARNING
return Current.WARNING;
case 4: // PERIOD
return Current.PERIOD;
case 5: // DETAILEDMESSAGE
return Current.DETAILEDMESSAGE;
case 6: // FIELDS
return Current.FIELDS;
case 7: // COMMANDNAME
return Current.COMMANDNAME;
case 8: // ISENABLED
return Current.ISENABLED;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // VCODE
return Current.VCODE == null;
case 2: // VALIDATIONMESSAGE
return Current.VALIDATIONMESSAGE == null;
case 3: // WARNING
return Current.WARNING == null;
case 4: // PERIOD
return Current.PERIOD == null;
case 5: // DETAILEDMESSAGE
return Current.DETAILEDMESSAGE == null;
case 6: // FIELDS
return Current.FIELDS == null;
case 7: // COMMANDNAME
return Current.COMMANDNAME == null;
case 8: // ISENABLED
return Current.ISENABLED == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // ID
return "ID";
case 1: // VCODE
return "VCODE";
case 2: // VALIDATIONMESSAGE
return "VALIDATIONMESSAGE";
case 3: // WARNING
return "WARNING";
case 4: // PERIOD
return "PERIOD";
case 5: // DETAILEDMESSAGE
return "DETAILEDMESSAGE";
case 6: // FIELDS
return "FIELDS";
case 7: // COMMANDNAME
return "COMMANDNAME";
case 8: // ISENABLED
return "ISENABLED";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "ID":
return 0;
case "VCODE":
return 1;
case "VALIDATIONMESSAGE":
return 2;
case "WARNING":
return 3;
case "PERIOD":
return 4;
case "DETAILEDMESSAGE":
return 5;
case "FIELDS":
return 6;
case "COMMANDNAME":
return 7;
case "ISENABLED":
return 8;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="StringAnimationUsingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used to animate a String property value along a set
/// of key frames.
/// </summary>
[ContentProperty("KeyFrames")]
public class StringAnimationUsingKeyFrames : StringAnimationBase, IKeyFrameAnimation, IAddChild
{
#region Data
private StringKeyFrameCollection _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
private bool _areKeyTimesValid;
#endregion
#region Constructors
/// <Summary>
/// Creates a new KeyFrameStringAnimation.
/// </Summary>
public StringAnimationUsingKeyFrames()
: base()
{
_areKeyTimesValid = true;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this KeyFrameStringAnimation.
/// </summary>
/// <returns>The copy</returns>
public new StringAnimationUsingKeyFrames Clone()
{
return (StringAnimationUsingKeyFrames)base.Clone();
}
/// <summary>
/// Returns a version of this class with all its base property values
/// set to the current animated values and removes the animations.
/// </summary>
/// <returns>
/// Since this class isn't animated, this method will always just return
/// this instance of the class.
/// </returns>
public new StringAnimationUsingKeyFrames CloneCurrentValue()
{
return (StringAnimationUsingKeyFrames)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
canFreeze &= Freezable.Freeze(_keyFrames, isChecking);
if (canFreeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return canFreeze;
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>.
/// </summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new StringAnimationUsingKeyFrames();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
StringAnimationUsingKeyFrames sourceAnimation = (StringAnimationUsingKeyFrames) sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
StringAnimationUsingKeyFrames sourceAnimation = (StringAnimationUsingKeyFrames) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
StringAnimationUsingKeyFrames sourceAnimation = (StringAnimationUsingKeyFrames) source;
base.GetAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
StringAnimationUsingKeyFrames sourceAnimation = (StringAnimationUsingKeyFrames) source;
base.GetCurrentValueAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Helper used by the four Freezable clone methods to copy the resolved key times and
/// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core
/// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here.
/// </summary>
/// <param name="sourceAnimation"></param>
/// <param name="isCurrentValueClone"></param>
private void CopyCommon(StringAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if ( _areKeyTimesValid
&& sourceAnimation._sortedResolvedKeyFrames != null)
{
// _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (StringKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = (StringKeyFrameCollection)sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
#endregion // Freezable
#region IAddChild interface
/// <summary>
/// Adds a child object to this KeyFrameAnimation.
/// </summary>
/// <param name="child">
/// The child object to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation only accepts a KeyFrame of the proper type as
/// a child.
/// </remarks>
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
/// <summary>
/// Implemented to allow KeyFrames to be direct children
/// of KeyFrameAnimations in markup.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
StringKeyFrame keyFrame = child as StringKeyFrame;
if (keyFrame != null)
{
KeyFrames.Add(keyFrame);
}
else
{
throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child");
}
}
/// <summary>
/// Adds a text string as a child of this KeyFrameAnimation.
/// </summary>
/// <param name="childText">
/// The text to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation does not accept text as a child, so this method will
/// raise an InvalididOperationException unless a derived class has
/// overridden the behavior to add text.
/// </remarks>
/// <exception cref="ArgumentNullException">The childText parameter is
/// null.</exception>
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
/// <summary>
/// This method performs the core functionality of the AddText()
/// method on the IAddChild interface. For a KeyFrameAnimation this means
/// throwing and InvalidOperationException because it doesn't
/// support adding text.
/// </summary>
/// <remarks>
/// This method is the only core implementation. It does not call
/// WritePreamble() or WritePostscript(). It also doesn't throw an
/// ArgumentNullException if the childText parameter is null. These tasks
/// are performed by the interface implementation. Therefore, it's OK
/// for a derived class to override this method and call the base
/// class implementation only if they determine that it's the right
/// course of action. The derived class can rely on KeyFrameAnimation's
/// implementation of IAddChild.AddChild or implement their own
/// following the Freezable pattern since that would be a public
/// method.
/// </remarks>
/// <param name="childText">A string representing the child text that
/// should be added. If this is a KeyFrameAnimation an exception will be
/// thrown.</param>
/// <exception cref="InvalidOperationException">Timelines have no way
/// of adding text.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren));
}
#endregion
#region StringAnimationBase
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected sealed override String GetCurrentValueCore(
String defaultOriginValue,
String defaultDestinationValue,
AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (_keyFrames == null)
{
return defaultDestinationValue;
}
// We resolved our KeyTimes when we froze, but also got notified
// of the frozen state and therefore invalidated ourselves.
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
TimeSpan currentTime = animationClock.CurrentTime.Value;
Int32 keyFrameCount = _sortedResolvedKeyFrames.Length;
Int32 maxKeyFrameIndex = keyFrameCount - 1;
String currentIterationValue;
Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames.");
Int32 currentResolvedKeyFrameIndex = 0;
// Skip all the key frames with key times lower than the current time.
// currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex
// if we are past the last key frame.
while ( currentResolvedKeyFrameIndex < keyFrameCount
&& currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
// If there are multiple key frames at the same key time, be sure to go to the last one.
while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex
&& currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
if (currentResolvedKeyFrameIndex == keyFrameCount)
{
// Past the last key frame.
currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
// Exactly on a key frame.
currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
}
else
{
// Between two key frames.
Double currentSegmentProgress = 0.0;
String fromValue;
if (currentResolvedKeyFrameIndex == 0)
{
// The current key frame is the first key frame so we have
// some special rules for determining the fromValue and an
// optimized method of calculating the currentSegmentProgress.
fromValue = defaultOriginValue;
// Current segment time divided by the segment duration.
// Note: the reason this works is that we know that we're in
// the first segment, so we can assume:
//
// currentTime.TotalMilliseconds = current segment time
// _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration
currentSegmentProgress = currentTime.TotalMilliseconds
/ _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
}
else
{
Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime;
TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
currentSegmentProgress = segmentCurrentTime.TotalMilliseconds
/ segmentDuration.TotalMilliseconds;
}
currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
}
return currentIterationValue;
}
/// <summary>
/// Provide a custom natural Duration when the Duration property is set to Automatic.
/// </summary>
/// <param name="clock">
/// The Clock whose natural duration is desired.
/// </param>
/// <returns>
/// If the last KeyFrame of this animation is a KeyTime, then this will
/// be used as the NaturalDuration; otherwise it will be one second.
/// </returns>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
#endregion
#region IKeyFrameAnimation
/// <summary>
/// Returns the StringKeyFrameCollection used by this KeyFrameStringAnimation.
/// </summary>
IList IKeyFrameAnimation.KeyFrames
{
get
{
return KeyFrames;
}
set
{
KeyFrames = (StringKeyFrameCollection)value;
}
}
/// <summary>
/// Returns the StringKeyFrameCollection used by this KeyFrameStringAnimation.
/// </summary>
public StringKeyFrameCollection KeyFrames
{
get
{
ReadPreamble();
// The reason we don't just set _keyFrames to the empty collection
// in the first place is that null tells us that the user has not
// asked for the collection yet. The first time they ask for the
// collection and we're unfrozen, policy dictates that we give
// them a new unfrozen collection. All subsequent times they will
// get whatever collection is present, whether frozen or unfrozen.
if (_keyFrames == null)
{
if (this.IsFrozen)
{
_keyFrames = StringKeyFrameCollection.Empty;
}
else
{
WritePreamble();
_keyFrames = new StringKeyFrameCollection();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (value != _keyFrames)
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
/// <summary>
/// Returns true if we should serialize the KeyFrames, property for this Animation.
/// </summary>
/// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
return _keyFrames != null
&& _keyFrames.Count > 0;
}
#endregion
#region Private Methods
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
private String GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue");
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
private StringKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame");
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
}
/// <summary>
/// Returns the largest time span specified key time from all of the key frames.
/// If there are not time span key times a time span of one second is returned
/// to match the default natural duration of the From/To/By animations.
/// </summary>
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool hasTimeSpanKeyTime = false;
TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero;
if (_keyFrames != null)
{
Int32 keyFrameCount = _keyFrames.Count;
for (int index = 0; index < keyFrameCount; index++)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
if (keyTime.Type == KeyTimeType.TimeSpan)
{
hasTimeSpanKeyTime = true;
if (keyTime.TimeSpan > largestTimeSpanKeyTime)
{
largestTimeSpanKeyTime = keyTime.TimeSpan;
}
}
}
}
if (hasTimeSpanKeyTime)
{
return largestTimeSpanKeyTime;
}
else
{
return TimeSpan.FromSeconds(1.0);
}
}
}
private void ResolveKeyTimes()
{
Debug.Assert(!_areKeyTimesValid, "KeyFrameStringAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid.");
int keyFrameCount = 0;
if (_keyFrames != null)
{
keyFrameCount = _keyFrames.Count;
}
if (keyFrameCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
return;
}
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
int index = 0;
// Initialize the _originalKeyFrameIndex.
for ( ; index < keyFrameCount; index++)
{
_sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
}
// calculationDuration represents the time span we will use to resolve
// percent key times. This is defined as the value in the following
// precedence order:
// 1. The animation's duration, but only if it is a time span, not auto or forever.
// 2. The largest time span specified key time of all the key frames.
// 3. 1 second, to match the From/To/By animations.
TimeSpan calculationDuration = TimeSpan.Zero;
Duration duration = Duration;
if (duration.HasTimeSpan)
{
calculationDuration = duration.TimeSpan;
}
else
{
calculationDuration = LargestTimeSpanKeyTime;
}
int maxKeyFrameIndex = keyFrameCount - 1;
ArrayList unspecifiedBlocks = new ArrayList();
bool hasPacedKeyTimes = false;
//
// Pass 1: Resolve Percent and Time key times.
//
index = 0;
while (index < keyFrameCount)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Percent:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(
keyTime.Percent * calculationDuration.TotalMilliseconds);
index++;
break;
case KeyTimeType.TimeSpan:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
index++;
break;
case KeyTimeType.Paced:
case KeyTimeType.Uniform:
if (index == maxKeyFrameIndex)
{
// If the last key frame doesn't have a specific time
// associated with it its resolved key time will be
// set to the calculationDuration, which is the
// defined in the comments above where it is set.
// Reason: We only want extra time at the end of the
// key frames if the user specifically states that
// the last key frame ends before the animation ends.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
index++;
}
else if ( index == 0
&& keyTime.Type == KeyTimeType.Paced)
{
// Note: It's important that this block come after
// the previous if block because of rule precendence.
// If the first key frame in a multi-frame key frame
// collection is paced, we set its resolved key time
// to 0.0 for performance reasons. If we didn't, the
// resolved key time list would be dependent on the
// base value which can change every animation frame
// in many cases.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
index++;
}
else
{
if (keyTime.Type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
KeyTimeBlock block = new KeyTimeBlock();
block.BeginIndex = index;
// NOTE: We don't want to go all the way up to the
// last frame because if it is Uniform or Paced its
// resolved key time will be set to the calculation
// duration using the logic above.
//
// This is why the logic is:
// ((++index) < maxKeyFrameIndex)
// instead of:
// ((++index) < keyFrameCount)
while ((++index) < maxKeyFrameIndex)
{
KeyTimeType type = _keyFrames[index].KeyTime.Type;
if ( type == KeyTimeType.Percent
|| type == KeyTimeType.TimeSpan)
{
break;
}
else if (type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
}
Debug.Assert(index < keyFrameCount,
"The end index for a block of unspecified key frames is out of bounds.");
block.EndIndex = index;
unspecifiedBlocks.Add(block);
}
break;
}
}
//
// Pass 2: Resolve Uniform key times.
//
for (int j = 0; j < unspecifiedBlocks.Count; j++)
{
KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j];
TimeSpan blockBeginTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
}
// The number of segments is equal to the number of key
// frames we're working on plus 1. Think about the case
// where we're working on a single key frame. There's a
// segment before it and a segment after it.
//
// Time known Uniform Time known
// ^ ^ ^
// | | |
// | (segment 1) | (segment 2) |
Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
index = block.BeginIndex;
TimeSpan resolvedTime = blockBeginTime + uniformTimeStep;
while (index < block.EndIndex)
{
_sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
resolvedTime += uniformTimeStep;
index++;
}
}
//
// Pass 3: Resolve Paced key times.
//
if (hasPacedKeyTimes)
{
ResolvePacedKeyTimes();
}
//
// Sort resolved key frame entries.
//
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
return;
}
/// <summary>
/// This should only be called from ResolveKeyTimes and only at the
/// appropriate time.
/// </summary>
private void ResolvePacedKeyTimes()
{
Debug.Assert(_keyFrames != null && _keyFrames.Count > 2,
"Caller must guard against calling this method when there are insufficient keyframes.");
// If the first key frame is paced its key time has already
// been resolved, so we start at index 1.
int index = 1;
int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
{
//
// We've found a paced key frame so this is the
// beginning of a paced block.
//
// The first paced key frame in this block.
int firstPacedBlockKeyFrameIndex = index;
// List of segment lengths for this paced block.
List<Double> segmentLengths = new List<Double>();
// The resolved key time for the key frame before this
// block which we'll use as our starting point.
TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
// The total of the segment lengths of the paced key
// frames in this block.
Double totalLength = 0.0;
// The key value of the previous key frame which will be
// used to determine the segment length of this key frame.
String prevKeyValue = _keyFrames[index - 1].Value;
do
{
String currentKeyValue = _keyFrames[index].Value;
// Determine the segment length for this key frame and
// add to the total length.
totalLength += AnimatedTypeHelpers.GetSegmentLengthString(prevKeyValue, currentKeyValue);
// Temporarily store the distance into the total length
// that this key frame represents in the resolved
// key times array to be converted to a resolved key
// time outside of this loop.
segmentLengths.Add(totalLength);
// Prepare for the next iteration.
prevKeyValue = currentKeyValue;
index++;
}
while ( index < maxKeyFrameIndex
&& _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
// index is currently set to the index of the key frame
// after the last paced key frame. This will always
// be a valid index because we limit ourselves with
// maxKeyFrameIndex.
// We need to add the distance between the last paced key
// frame and the next key frame to get the total distance
// inside the key frame block.
totalLength += AnimatedTypeHelpers.GetSegmentLengthString(prevKeyValue, _keyFrames[index].Value);
// Calculate the time available in the resolved key time space.
TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
// Convert lengths in segmentLengths list to resolved
// key times for the paced key frames in this block.
for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
{
// The resolved key time for each key frame is:
//
// The key time of the key frame before this paced block
// + ((the percentage of the way through the total length)
// * the resolved key time space available for the block)
_sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(
(segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds);
}
}
else
{
index++;
}
}
while (index < maxKeyFrameIndex);
}
#endregion
}
}
| |
using System;
using System.Linq.Expressions;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using BigTed;
using CoreGraphics;
using Foundation;
using Localizations;
using MessageUI;
using MonoTouch.Dialog;
using MusicPlayer.Api;
using MusicPlayer.Api.GoogleMusic;
using MusicPlayer.Api.iPodApi;
using MusicPlayer.Data;
using MusicPlayer.iOS.Controls;
using MusicPlayer.iOS.Helpers;
using MusicPlayer.Managers;
using MusicPlayer.Models;
using UIKit;
using Xamarin;
using MusicPlayer.Playback;
using Accounts;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
namespace MusicPlayer.iOS.ViewControllers
{
internal class SettingViewController : DialogViewController
{
readonly SettingsSwitch lastFmElement;
readonly SettingsElement addNewAccountElement;
readonly SettingsSwitch twitterScrobbleElement;
readonly StringElement songsElement;
MFMailComposeViewController mailController;
MenuHelpTextElement ratingMessage;
MenuSection accountsSection;
public SettingViewController() : base(UITableViewStyle.Plain, null)
{
Title = Strings.Settings;
accountsSection = new MenuSection (Strings.Accounts){
(addNewAccountElement = new SettingsElement(Strings.AddStreamingService,async ()=>{
try{
var vc = new ServicePickerViewController();
this.PresentModalViewController(new UINavigationController(vc),true);
var service = await vc.GetServiceTypeAsync();
await ApiManager.Shared.CreateAndLogin(service);
UpdateAccounts();
}
catch(TaskCanceledException)
{
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
})),
(lastFmElement = string.IsNullOrEmpty (ApiConstants.LastFmApiKey) ? null : new SettingsSwitch("Last.FM", Settings.LastFmEnabled)),
(twitterScrobbleElement = new SettingsSwitch(Strings.AutoTweet, Settings.TwitterEnabled)
{
Detail = Settings.TwitterDisplay
}),
new SettingsSwitch(Strings.ImportIPodMusic, Settings.IncludeIpod)
{
ValueUpdated = ToggleIPod
},
new MenuHelpTextElement(Strings.ImportIpodHint),
};
Root = new RootElement(Strings.Settings)
{
accountsSection,
new MenuSection(Strings.Playback)
{
new SettingsSwitch(Strings.EnableLikeOnTheLockScreen, Settings.ThubsUpOnLockScreen)
{
ValueUpdated = (b => {
Settings.ThubsUpOnLockScreen = b;
RemoteControlHandler.SetupThumbsUp();
})
},
new MenuHelpTextElement(Strings.EnableLikeHint),
new SettingsSwitch(Strings.EnableGaplessPlayback, Settings.EnableGaplessPlayback)
{
ValueUpdated = (b => {
Settings.EnableGaplessPlayback = b;
})
},
new MenuHelpTextElement(Strings.EnableGapplessHint),
new SettingsSwitch(Strings.PlayVideosWhenAvailable, Settings.PreferVideos)
{
ValueUpdated = (b => { Settings.PreferVideos = b; })
},
new MenuHelpTextElement(Strings.PlaysMusicVideoHint),
new SettingsSwitch(Strings.PlayCleanVersionsOfSongs,Settings.FilterExplicit)
{
ValueUpdated = (b=> { Settings.FilterExplicit = b; })
},
new MenuHelpTextElement(Strings.PlayesCleanVersionOfSongsHint),
},
new MenuSection(Strings.Streaming)
{
new SettingsSwitch (Strings.DisableAllAccess, Settings.DisableAllAccess) {
ValueUpdated = (on) => {
Settings.DisableAllAccess = on;
}
},
new MenuHelpTextElement(Strings.DisableAllAccessHint),
(CreateQualityPicker(Strings.CellularAudioQuality,Settings.MobileStreamQuality , (q)=> Settings.MobileStreamQuality = q)),
(CreateQualityPicker(Strings.WifiAudioQuality,Settings.WifiStreamQuality , (q)=> Settings.WifiStreamQuality = q)),
(CreateQualityPicker(Strings.VideoQuality,Settings.VideoStreamQuality , (q)=> Settings.VideoStreamQuality = q)),
(CreateQualityPicker(Strings.OfflineAudioQuality,Settings.DownloadStreamQuality , (q)=> Settings.DownloadStreamQuality = q)),
new MenuHelpTextElement(Strings.QualityHints)
},
new MenuSection(Strings.Feedback)
{
new SettingsElement(Strings.SendFeedback, SendFeedback)
{
TextColor = iOS.Style.DefaultStyle.MainTextColor
},
new SettingsElement($"{Strings.PleaseRate} {AppDelegate.AppName}", RateAppStore)
{
TextColor = iOS.Style.DefaultStyle.MainTextColor
},
(ratingMessage = new MenuHelpTextElement(Strings.NobodyHasRatedYet))
},
new MenuSection(Strings.Settings)
{
CreateLanguagePicker(Strings.Language),
CreateThemePicker(Strings.Theme),
new SettingsElement(Strings.ResyncDatabase, () =>
{
Database.Main.ResetDatabase();
Settings.ResetApiModes();
ApiManager.Shared.ReSync();
}),
new MenuHelpTextElement (Strings.ResyncDatabaseHint),
new SettingsSwitch(Strings.DisableAutoLock,Settings.DisableAutoLock){
ValueUpdated = (b => {
Settings.PreferVideos = b;
AutolockPowerWatcher.Shared.CheckStatus();
})
},
new MenuHelpTextElement(Strings.DisableAutoLockHelpText),
new SettingsElement(Strings.DownloadQueue,
() => NavigationController.PushViewController(new DownloadViewController(), true)),
(songsElement = new SettingsElement(Strings.SongsCount)),
new SettingsElement(Strings.Version){
Value = Device.AppVersion(),
},
new StringElement(""),
new StringElement(""),
new StringElement(""),
new StringElement(""),
}
};
if (lastFmElement != null) {
lastFmElement.ValueUpdated = async b =>
{
if (!b)
{
Settings.LastFmEnabled = false;
ScrobbleManager.Shared.LogOut();
return;
}
var success = false;
try
{
success = await ScrobbleManager.Shared.LoginToLastFm();
}
catch (TaskCanceledException ex)
{
lastFmElement.Value = Settings.LastFmEnabled = false;
TableView.ReloadData();
return;
}
Settings.LastFmEnabled = success;
if (success) return;
lastFmElement.Value = false;
ReloadData();
App.ShowAlert(string.Format(Strings.ErrorLoggingInto, "Last.FM"), Strings.PleaseTryAgain);
};
}
twitterScrobbleElement.ValueUpdated = async b =>
{
if (!b)
{
Settings.TwitterEnabled = false;
Settings.TwitterDisplay = "";
Settings.TwitterAccount = "";
twitterScrobbleElement.Detail = "";
ScrobbleManager.Shared.LogOutOfTwitter();
return;
}
var success = await ScrobbleManager.Shared.LoginToTwitter();
if (!success)
{
Settings.TwitterEnabled = false;
twitterScrobbleElement.Value = false;
ReloadData();
return;
}
Settings.TwitterEnabled = true;
twitterScrobbleElement.Detail = Settings.TwitterDisplay;
ReloadData();
};
}
UIBarButtonItem menuButton;
public override void LoadView()
{
base.LoadView();
var style = View.GetStyle();
View.TintColor = style.AccentColor;
TableView.RowHeight = 20;
TableView.TableFooterView = new UIView(new CGRect(0, 0, 320, NowPlayingViewController.TopBarHeight));
TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
TableView.EstimatedSectionFooterHeight = 0;
TableView.EstimatedSectionHeaderHeight = 0;
if (NavigationController == null)
return;
NavigationController.NavigationBar.TitleTextAttributes = new UIStringAttributes
{
ForegroundColor = style.AccentColor
};
if (NavigationController.ViewControllers.Length == 1)
{
menuButton = new UIBarButtonItem(Images.MenuImage, UIBarButtonItemStyle.Plain,
(s, e) => { NotificationManager.Shared.ProcToggleMenu(); })
{
AccessibilityIdentifier = "menu"
};
NavigationItem.LeftBarButtonItem = BaseViewController.ShouldShowMenuButton(this) ? menuButton : null;
}
//if(Device.IsIos8)
// NavigationController.HidesBarsOnSwipe = true;
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
NavigationItem.LeftBarButtonItem = BaseViewController.ShouldShowMenuButton(this) ? menuButton : null;
}
async void UpdateRatingMessage()
{
var count = await AppStore.GetRatingCount();
if (count < 0)
return;
string message = "";
if (count == 0)
{
message = Strings.NobodyHasRatedYet;
}
else if (count == 1)
{
message = Strings.OnlyOnePersonHasRatedThisVersion;
}
else if (count < 50)
{
string only = Strings.Only;
message = $"{Strings.Only} {count} {Strings.PeopleHaveRatedThisVersion}";
}
else
{
message = $"{count} {Strings.PeopleHaveRatedThisVersion}";
}
ratingMessage.Caption = message;
this.ReloadData();
}
void UpdateAccounts ()
{
var endIndex = accountsSection.Elements.IndexOf (addNewAccountElement);
var elements = accountsSection.Elements.OfType<AccountCell> ().ToList();
var newElements = new List<Element> ();
ApiManager.Shared.CurrentProviders.ToList ().ForEach ((x) => {
var element = elements.FirstOrDefault (e => e.Provider.Id == x.Id);
if (element != null)
elements.Remove (element);
else {
newElements.Add (new AccountCell (x, () => {
new AlertView (Strings.Logout, Strings.LogOutConfirmation) {
{Strings.Logout,async()=>{
await ApiManager.Shared.LogOut (x);
UpdateAccounts ();
}},
{Strings.Nevermind,null,true}
}.Show(this);
}));
}
});
if(newElements.Count > 0)
accountsSection.Insert (endIndex, newElements.ToArray());
elements.ForEach (accountsSection.Remove);
}
void setQualityValue(SettingsElement element, StreamQuality quality)
{
if (element == null)
return;
switch (quality)
{
case StreamQuality.High:
element.Value = Strings.High;
break;
case StreamQuality.Medium:
element.Value = Strings.Medium;
break;
case StreamQuality.Low:
element.Value = Strings.Low;
break;
}
element.Reload();
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
songsElement.Value = Database.Main.GetObjectCount<Song>().ToString();
TableView.ReloadData();
this.StyleViewController();
UpdateRatingMessage();
UpdateAccounts ();
NotificationManager.Shared.StyleChanged += Shared_StyleChanged;
}
void Shared_StyleChanged(object sender, EventArgs e)
{
this.StyleViewController();
TableView.ReloadData();
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
NotificationManager.Shared.StyleChanged -= Shared_StyleChanged;
}
void SendFeedback()
{
if (mailController != null)
{
mailController.Dispose();
mailController = null;
}
LogManager.Shared.Log("Tapped Feedback");
if (!MFMailComposeViewController.CanSendMail)
{
LogManager.Shared.Log("Feedback failed: No email");
new AlertView(Strings.PleaseSendAnEmailTo, "Support@youriisolutions.com").Show(this);
return;
}
mailController = new MFMailComposeViewController();
mailController.SetToRecipients(new[] {"support@youriisolutions.com"});
var tintColor = UIApplication.SharedApplication.KeyWindow.TintColor;
mailController.SetSubject(string.Format("Feedback: {0} - {1}", AppDelegate.AppName, Device.AppVersion()));
mailController.Finished += async (object s, MFComposeResultEventArgs args) =>
{
if (args.Result == MFMailComposeResult.Sent)
{
new AlertView(Strings.ThankYou, Strings.YouShouldReceiveAReplyShortly_).Show(this);
LogManager.Shared.Log("Feedback Sent");
}
else
{
LogManager.Shared.Log("Feedback failed", "Reason", args.Result.ToString());
}
await args.Controller.DismissViewControllerAsync(true);
if (tintColor != null)
UIApplication.SharedApplication.KeyWindow.TintColor = tintColor;
};
UIApplication.SharedApplication.KeyWindow.TintColor = null;
PresentViewController(mailController, true, null);
}
async void RateAppStore()
{
LogManager.Shared.Log("Rated app");
try
{
var url =
@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=" +
AppDelegate.AppId;
UIApplication.SharedApplication.OpenUrl(new NSUrl(url));
}
catch (Exception ex)
{
LogManager.Shared.Report(ex);
}
finally
{
BTProgressHUD.Dismiss();
}
}
async void ToggleIPod(bool on)
{
Settings.IncludeIpod = on;
var ipod = ApiManager.Shared.GetMusicProvider<iPodProvider>(ServiceType.iPod);
if (on)
ipod.SyncDatabase();
else
MusicProvider.RemoveApi(ipod.Id);
}
SettingsElement CreateQualityPicker(string title, StreamQuality quality,Action<StreamQuality> setQuality )
{
SettingsElement element = null;
element = new SettingsElement(title, () =>
{
new ActionSheet(title)
{
{
$"{Strings.Low} {Strings.UsesLessData}", () =>
{
setQuality(StreamQuality.Low);
setQualityValue(element, StreamQuality.Low);
}
},
{
Strings.Normal, () =>
{
setQuality(StreamQuality.Medium);
setQualityValue(element, StreamQuality.Medium);
}
},
{
$"{Strings.High} {Strings.UsesMoreData}", () =>
{
setQuality(StreamQuality.High);
setQualityValue(element, StreamQuality.High);
}
}
}.Show(this, TableView);
})
{
style = UITableViewCellStyle.Value1,
Value = quality.ToString(),
};
return element;
}
SettingsElement CreateThemePicker(string title)
{
SettingsElement element = null;
element = new SettingsElement(title, () =>
{
var sheet = new ActionSheet(Strings.Theme);
MusicPlayer.iOS.Style.AvailableStyles.ForEach(x=> sheet.Add(x.Id, () =>
{
Settings.CurrentStyle = x.Id;
element.Value = x.Id;
}));
sheet.Show(this, TableView);
})
{
style = UITableViewCellStyle.Value1,
Value = Settings.CurrentStyle,
};
return element;
}
CultureInfo[] cultures = new CultureInfo[]{
new CultureInfo("en"),
new CultureInfo("es"),
new CultureInfo("fr"),
new CultureInfo("it"),
new CultureInfo("ja"),
new CultureInfo("ko"),
new CultureInfo("ru"),
new CultureInfo("zh-Hant"),
};
SettingsElement CreateLanguagePicker(string title)
{
SettingsElement element = null;
var currentCulture = string.IsNullOrWhiteSpace(Settings.LanguageOverride) ? Strings.Default : new CultureInfo(Settings.LanguageOverride).NativeName;
element = new SettingsElement(title, () =>
{
var sheet = new ActionSheet(title);
sheet.Add(Strings.Default, () =>
{
Settings.LanguageOverride = null;
});
cultures.ForEach(x => sheet.Add(x.NativeName, () =>
{
Strings.Culture = x;
Settings.LanguageOverride = x.Name;
element.Value = x.NativeName;
}));
sheet.Show(this, TableView);
})
{
style = UITableViewCellStyle.Value1,
Value = currentCulture,
};
return element;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Windows;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using MS.Internal;
using MS.Win32;
namespace System.Windows.Automation.Peers
{
///<summary>
/// Earlier this class was returning the default value for all properties when there is no wrapper/when it is virtualized,
/// now it will throw ElementNotAvailableException (leaving some exceptions, like properties supported by container to find elements)
/// to notify the client that the full Element does not exist yet. Client may decide to use VirtualizedItemPattern to realize the full item
///</summary>
public abstract class ItemAutomationPeer : AutomationPeer, IVirtualizedItemProvider
{
///
protected ItemAutomationPeer(object item, ItemsControlAutomationPeer itemsControlAutomationPeer): base()
{
_item = item;
_itemsControlAutomationPeer = itemsControlAutomationPeer;
}
///
internal override bool AncestorsInvalid
{
get { return base.AncestorsInvalid; }
set
{
base.AncestorsInvalid = value;
if (value)
return;
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
{
wrapperPeer.AncestorsInvalid = false;
}
}
}
///
override public object GetPattern(PatternInterface patternInterface)
{
if (patternInterface == PatternInterface.VirtualizedItem)
{
if(VirtualizedItemPatternIdentifiers.Pattern != null)
{
if(GetWrapperPeer() == null)
return this;
else
{
// ItemsControlAutomationPeer can be null in case of TreeViewItems when parent TreeViewItem is also virtualized
// If the Item is in Automation Tree we consider it has Realized and need not return VirtualizeItem pattern.
if(ItemsControlAutomationPeer != null && !IsItemInAutomationTree())
{
return this;
}
if(ItemsControlAutomationPeer == null)
return this;
}
}
return null;
}
else if(patternInterface == PatternInterface.SynchronizedInput)
{
UIElementAutomationPeer peer = GetWrapperPeer() as UIElementAutomationPeer;
if(peer != null)
{
return peer.GetPattern(patternInterface);
}
}
return null;
}
internal UIElement GetWrapper()
{
UIElement wrapper = null;
ItemsControlAutomationPeer itemsControlAutomationPeer = ItemsControlAutomationPeer;
if (itemsControlAutomationPeer != null)
{
ItemsControl owner = (ItemsControl)(itemsControlAutomationPeer.Owner);
if (owner != null)
{
if (((MS.Internal.Controls.IGeneratorHost)owner).IsItemItsOwnContainer(_item))
wrapper = _item as UIElement;
else
wrapper = owner.ItemContainerGenerator.ContainerFromItem(_item) as UIElement;
}
}
return wrapper;
}
virtual internal AutomationPeer GetWrapperPeer()
{
AutomationPeer wrapperPeer = null;
UIElement wrapper = GetWrapper();
if(wrapper != null)
{
wrapperPeer = UIElementAutomationPeer.CreatePeerForElement(wrapper);
if(wrapperPeer == null) //fall back to default peer if there is no specific one
{
if(wrapper is FrameworkElement)
wrapperPeer = new FrameworkElementAutomationPeer((FrameworkElement)wrapper);
else
wrapperPeer = new UIElementAutomationPeer(wrapper);
}
}
return wrapperPeer;
}
/// <summary>
internal void ThrowElementNotAvailableException()
{
// To avoid the situation on legacy systems which may not have new unmanaged core. this check with old unmanaged core
// avoids throwing exception and provide older behavior returning default values for items which are virtualized rather than throwing exception.
if (VirtualizedItemPatternIdentifiers.Pattern != null && !(this is GridViewItemAutomationPeer) && !IsItemInAutomationTree())
throw new ElementNotAvailableException(SR.Get(SRID.VirtualizedElement));
}
private bool IsItemInAutomationTree()
{
AutomationPeer parent = this.GetParent();
if(this.Index != -1 && parent != null && parent.Children != null && this.Index < parent.Children.Count && parent.Children[this.Index] == this)
return true;
else return false;
}
override internal bool IsDataItemAutomationPeer()
{
return true;
}
override internal void AddToParentProxyWeakRefCache()
{
ItemsControlAutomationPeer itemsControlAutomationPeer = ItemsControlAutomationPeer;
if(itemsControlAutomationPeer != null)
{
itemsControlAutomationPeer.AddProxyToWeakRefStorage(this.ElementProxyWeakReference, this);
}
}
/// <summary>
override internal Rect GetVisibleBoundingRectCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
{
return wrapperPeer.GetVisibleBoundingRectCore();
}
return GetBoundingRectangle();
}
///
override protected string GetItemTypeCore()
{
return string.Empty;
}
///
protected override List<AutomationPeer> GetChildrenCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
{
// The children needs to be updated before GetChildren call as ChildrenValid flag would already be true and GetChildren call won't update the children list.
wrapperPeer.ForceEnsureChildren();
List<AutomationPeer> children = wrapperPeer.GetChildren();
return children;
}
return null;
}
///
protected override Rect GetBoundingRectangleCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
{
return wrapperPeer.GetBoundingRectangle();
}
else
ThrowElementNotAvailableException();
return new Rect();
}
///
protected override bool IsOffscreenCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.IsOffscreen();
else
ThrowElementNotAvailableException();
return true;
}
///
protected override AutomationOrientation GetOrientationCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.GetOrientation();
else
ThrowElementNotAvailableException();
return AutomationOrientation.None;
}
///
protected override string GetItemStatusCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.GetItemStatus();
else
ThrowElementNotAvailableException();
return string.Empty;
}
///
protected override bool IsRequiredForFormCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.IsRequiredForForm();
else
ThrowElementNotAvailableException();
return false;
}
///
protected override bool IsKeyboardFocusableCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.IsKeyboardFocusable();
else
ThrowElementNotAvailableException();
return false;
}
///
protected override bool HasKeyboardFocusCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.HasKeyboardFocus();
else
ThrowElementNotAvailableException();
return false;
}
///
protected override bool IsEnabledCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.IsEnabled();
else
ThrowElementNotAvailableException();
return false;
}
///
protected override bool IsPasswordCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.IsPassword();
else
ThrowElementNotAvailableException();
return false;
}
///
protected override string GetAutomationIdCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
string id = null;
if (wrapperPeer != null)
{
id = wrapperPeer.GetAutomationId();
}
else if (_item != null)
{
using (RecyclableWrapper recyclableWrapper = ItemsControlAutomationPeer.GetRecyclableWrapperPeer(_item))
{
id = recyclableWrapper.Peer.GetAutomationId();
}
}
return id;
}
///
protected override string GetNameCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
string name = null;
if (wrapperPeer != null)
{
name = wrapperPeer.GetName();
}
else if (_item != null)
{
using (RecyclableWrapper recyclableWrapper = ItemsControlAutomationPeer.GetRecyclableWrapperPeer(_item))
{
name = recyclableWrapper.Peer.GetName();
}
}
if (string.IsNullOrEmpty(name) && _item != null)
{
// For FE we can't use ToString as that provides extraneous information than just the plain text
FrameworkElement fe = _item as FrameworkElement;
if(fe != null)
name = fe.GetPlainText();
if(string.IsNullOrEmpty(name))
name = _item.ToString();
}
return name;
}
///
protected override bool IsContentElementCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.IsContentElement();
return true;
}
///
protected override bool IsControlElementCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.IsControlElement();
return true;
}
///
protected override AutomationPeer GetLabeledByCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.GetLabeledBy();
else
ThrowElementNotAvailableException();
return null;
}
///
protected override string GetHelpTextCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.GetHelpText();
else
ThrowElementNotAvailableException();
return string.Empty;
}
///
protected override string GetAcceleratorKeyCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.GetAcceleratorKey();
else
ThrowElementNotAvailableException();
return string.Empty;
}
///
protected override string GetAccessKeyCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.GetAccessKey();
else
ThrowElementNotAvailableException();
return string.Empty;
}
///
protected override Point GetClickablePointCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
return wrapperPeer.GetClickablePoint();
else
ThrowElementNotAvailableException();
return new Point(double.NaN, double.NaN);
}
///
protected override void SetFocusCore()
{
AutomationPeer wrapperPeer = GetWrapperPeer();
if (wrapperPeer != null)
wrapperPeer.SetFocus();
else
ThrowElementNotAvailableException();
}
virtual internal ItemsControlAutomationPeer GetItemsControlAutomationPeer()
{
return _itemsControlAutomationPeer;
}
///
public object Item
{
get
{
return _item;
}
}
///
public ItemsControlAutomationPeer ItemsControlAutomationPeer
{
get
{
return GetItemsControlAutomationPeer();
}
internal set
{
_itemsControlAutomationPeer = value;
}
}
///
void IVirtualizedItemProvider.Realize()
{
RealizeCore();
}
virtual internal void RealizeCore()
{
ItemsControlAutomationPeer itemsControlAutomationPeer = ItemsControlAutomationPeer;
if (itemsControlAutomationPeer != null)
{
ItemsControl parent = itemsControlAutomationPeer.Owner as ItemsControl;
if (parent != null)
{
if (parent.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
// Please note that this action must happen before the OnBringItemIntoView call because
// that is a call that synchronously flushes out layout and we want these realized peers
// cached before the UpdateSubtree kicks in OnLayoutUpdated.
if (VirtualizingPanel.GetIsVirtualizingWhenGrouping(parent))
{
itemsControlAutomationPeer.RecentlyRealizedPeers.Add(this);
}
parent.OnBringItemIntoView(Item);
}
else
{
// The items aren't generated, try at a later time
Dispatcher.BeginInvoke(DispatcherPriority.Loaded,
(DispatcherOperationCallback)delegate(object arg)
{
// Please note that this action must happen before the OnBringItemIntoView call because
// that is a call that synchronously flushes out layout and we want these realized peers
// cached before the UpdateSubtree kicks in OnLayoutUpdated.
if (VirtualizingPanel.GetIsVirtualizingWhenGrouping(parent))
{
itemsControlAutomationPeer.RecentlyRealizedPeers.Add(this);
}
parent.OnBringItemIntoView(arg);
return null;
}, Item);
}
}
}
}
private object _item;
private ItemsControlAutomationPeer _itemsControlAutomationPeer;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime;
using System.Runtime.InteropServices;
using System.ServiceModel.Security;
using System.ServiceModel.Channels.ConnectionHelpers;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
internal abstract class FramingDuplexSessionChannel : TransportDuplexSessionChannel
{
private static EndpointAddress s_anonymousEndpointAddress = new EndpointAddress(EndpointAddress.AnonymousUri, new AddressHeader[0]);
private IConnection _connection;
private bool _exposeConnectionProperty;
private FramingDuplexSessionChannel(ChannelManagerBase manager, IConnectionOrientedTransportFactorySettings settings,
EndpointAddress localAddress, Uri localVia, EndpointAddress remoteAddress, Uri via, bool exposeConnectionProperty)
: base(manager, settings, localAddress, localVia, remoteAddress, via)
{
_exposeConnectionProperty = exposeConnectionProperty;
}
protected FramingDuplexSessionChannel(ChannelManagerBase factory, IConnectionOrientedTransportFactorySettings settings,
EndpointAddress remoteAddress, Uri via, bool exposeConnectionProperty)
: this(factory, settings, s_anonymousEndpointAddress, settings.MessageVersion.Addressing == AddressingVersion.None ? null : new Uri("http://www.w3.org/2005/08/addressing/anonymous"),
remoteAddress, via, exposeConnectionProperty)
{
this.Session = FramingConnectionDuplexSession.CreateSession(this, settings.Upgrade);
}
protected IConnection Connection
{
get
{
return _connection;
}
set
{
_connection = value;
}
}
protected override bool IsStreamedOutput
{
get { return false; }
}
protected override void CloseOutputSessionCore(TimeSpan timeout)
{
Connection.Write(SessionEncoder.EndBytes, 0, SessionEncoder.EndBytes.Length, true, timeout);
}
protected override Task CloseOutputSessionCoreAsync(TimeSpan timeout)
{
return Connection.WriteAsync(SessionEncoder.EndBytes, 0, SessionEncoder.EndBytes.Length, true, timeout);
}
protected override void CompleteClose(TimeSpan timeout)
{
this.ReturnConnectionIfNecessary(false, timeout);
}
protected override void PrepareMessage(Message message)
{
if (_exposeConnectionProperty)
{
message.Properties[ConnectionMessageProperty.Name] = _connection;
}
base.PrepareMessage(message);
}
protected override void OnSendCore(Message message, TimeSpan timeout)
{
bool allowOutputBatching;
ArraySegment<byte> messageData;
allowOutputBatching = message.Properties.AllowOutputBatching;
messageData = this.EncodeMessage(message);
this.Connection.Write(messageData.Array, messageData.Offset, messageData.Count, !allowOutputBatching,
timeout, this.BufferManager);
}
protected override AsyncCompletionResult BeginCloseOutput(TimeSpan timeout, Action<object> callback, object state)
{
return this.Connection.BeginWrite(SessionEncoder.EndBytes, 0, SessionEncoder.EndBytes.Length,
true, timeout, callback, state);
}
protected override void FinishWritingMessage()
{
this.Connection.EndWrite();
}
protected override AsyncCompletionResult StartWritingBufferedMessage(Message message, ArraySegment<byte> messageData, bool allowOutputBatching, TimeSpan timeout, Action<object> callback, object state)
{
return this.Connection.BeginWrite(messageData.Array, messageData.Offset, messageData.Count,
!allowOutputBatching, timeout, callback, state);
}
protected override AsyncCompletionResult StartWritingStreamedMessage(Message message, TimeSpan timeout, Action<object> callback, object state)
{
Contract.Assert(false, "Streamed output should never be called in this channel.");
throw new InvalidOperationException();
}
protected override ArraySegment<byte> EncodeMessage(Message message)
{
ArraySegment<byte> messageData = MessageEncoder.WriteMessage(message,
int.MaxValue, this.BufferManager, SessionEncoder.MaxMessageFrameSize);
messageData = SessionEncoder.EncodeMessageFrame(messageData);
return messageData;
}
internal class FramingConnectionDuplexSession : ConnectionDuplexSession
{
private FramingConnectionDuplexSession(FramingDuplexSessionChannel channel)
: base(channel)
{
}
public static FramingConnectionDuplexSession CreateSession(FramingDuplexSessionChannel channel,
StreamUpgradeProvider upgrade)
{
StreamSecurityUpgradeProvider security = upgrade as StreamSecurityUpgradeProvider;
if (security == null)
{
return new FramingConnectionDuplexSession(channel);
}
else
{
return new SecureConnectionDuplexSession(channel);
}
}
private class SecureConnectionDuplexSession : FramingConnectionDuplexSession, ISecuritySession
{
private EndpointIdentity _remoteIdentity;
public SecureConnectionDuplexSession(FramingDuplexSessionChannel channel)
: base(channel)
{
// empty
}
EndpointIdentity ISecuritySession.RemoteIdentity
{
get
{
if (_remoteIdentity == null)
{
SecurityMessageProperty security = this.Channel.RemoteSecurity;
if (security != null && security.ServiceSecurityContext != null &&
security.ServiceSecurityContext.IdentityClaim != null &&
security.ServiceSecurityContext.PrimaryIdentity != null)
{
_remoteIdentity = EndpointIdentity.CreateIdentity(
security.ServiceSecurityContext.IdentityClaim);
}
}
return _remoteIdentity;
}
}
}
}
}
internal class ClientFramingDuplexSessionChannel : FramingDuplexSessionChannel
{
private IConnectionOrientedTransportChannelFactorySettings _settings;
private ClientDuplexDecoder _decoder;
private StreamUpgradeProvider _upgrade;
private ConnectionPoolHelper _connectionPoolHelper;
private bool _flowIdentity;
public ClientFramingDuplexSessionChannel(ChannelManagerBase factory, IConnectionOrientedTransportChannelFactorySettings settings,
EndpointAddress remoteAddress, Uri via, IConnectionInitiator connectionInitiator, ConnectionPool connectionPool,
bool exposeConnectionProperty, bool flowIdentity)
: base(factory, settings, remoteAddress, via, exposeConnectionProperty)
{
_settings = settings;
this.MessageEncoder = settings.MessageEncoderFactory.CreateSessionEncoder();
_upgrade = settings.Upgrade;
_flowIdentity = flowIdentity;
_connectionPoolHelper = new DuplexConnectionPoolHelper(this, connectionPool, connectionInitiator);
}
private ArraySegment<byte> CreatePreamble()
{
EncodedVia encodedVia = new EncodedVia(this.Via.AbsoluteUri);
EncodedContentType encodedContentType = EncodedContentType.Create(this.MessageEncoder.ContentType);
// calculate preamble length
int startSize = ClientDuplexEncoder.ModeBytes.Length + SessionEncoder.CalcStartSize(encodedVia, encodedContentType);
int preambleEndOffset = 0;
if (_upgrade == null)
{
preambleEndOffset = startSize;
startSize += ClientDuplexEncoder.PreambleEndBytes.Length;
}
byte[] startBytes = Fx.AllocateByteArray(startSize);
Buffer.BlockCopy(ClientDuplexEncoder.ModeBytes, 0, startBytes, 0, ClientDuplexEncoder.ModeBytes.Length);
SessionEncoder.EncodeStart(startBytes, ClientDuplexEncoder.ModeBytes.Length, encodedVia, encodedContentType);
if (preambleEndOffset > 0)
{
Buffer.BlockCopy(ClientDuplexEncoder.PreambleEndBytes, 0, startBytes, preambleEndOffset, ClientDuplexEncoder.PreambleEndBytes.Length);
}
return new ArraySegment<byte>(startBytes, 0, startSize);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
public override T GetProperty<T>()
{
T result = base.GetProperty<T>();
if (result == null && _upgrade != null)
{
result = _upgrade.GetProperty<T>();
}
return result;
}
private async Task<IConnection> SendPreambleAsync(IConnection connection, ArraySegment<byte> preamble, TimeSpan timeout)
{
var timeoutHelper = new TimeoutHelper(timeout);
// initialize a new decoder
_decoder = new ClientDuplexDecoder(0);
byte[] ackBuffer = new byte[1];
if (!await SendLock.WaitAsync(TimeoutHelper.ToMilliseconds(timeout)))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(
SR.Format(SR.CloseTimedOut, timeout),
TimeoutHelper.CreateEnterTimedOutException(timeout)));
}
try
{
await connection.WriteAsync(preamble.Array, preamble.Offset, preamble.Count, true, timeoutHelper.RemainingTime());
if (_upgrade != null)
{
StreamUpgradeInitiator upgradeInitiator = _upgrade.CreateUpgradeInitiator(this.RemoteAddress, this.Via);
await upgradeInitiator.OpenAsync(timeoutHelper.RemainingTime());
var connectionWrapper = new OutWrapper<IConnection>();
connectionWrapper.Value = connection;
bool upgradeInitiated = await ConnectionUpgradeHelper.InitiateUpgradeAsync(upgradeInitiator, connectionWrapper, _decoder, this, timeoutHelper.RemainingTime());
connection = connectionWrapper.Value;
if (!upgradeInitiated)
{
await ConnectionUpgradeHelper.DecodeFramingFaultAsync(_decoder, connection, this.Via, MessageEncoder.ContentType, timeoutHelper.RemainingTime());
}
SetRemoteSecurity(upgradeInitiator);
await upgradeInitiator.CloseAsync(timeoutHelper.RemainingTime());
await connection.WriteAsync(ClientDuplexEncoder.PreambleEndBytes, 0, ClientDuplexEncoder.PreambleEndBytes.Length, true, timeoutHelper.RemainingTime());
}
int ackBytesRead = await connection.ReadAsync(ackBuffer, 0, ackBuffer.Length, timeoutHelper.RemainingTime());
if (!ConnectionUpgradeHelper.ValidatePreambleResponse(ackBuffer, ackBytesRead, _decoder, Via))
{
await ConnectionUpgradeHelper.DecodeFramingFaultAsync(_decoder, connection, Via,
MessageEncoder.ContentType, timeoutHelper.RemainingTime());
}
return connection;
}
finally
{
SendLock.Release();
}
}
private IConnection SendPreamble(IConnection connection, ArraySegment<byte> preamble, ref TimeoutHelper timeoutHelper)
{
TimeSpan timeout = timeoutHelper.RemainingTime();
if (!SendLock.Wait(TimeoutHelper.ToMilliseconds(timeout)))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(
SR.Format(SR.CloseTimedOut, timeout),
TimeoutHelper.CreateEnterTimedOutException(timeout)));
}
try
{
// initialize a new decoder
_decoder = new ClientDuplexDecoder(0);
byte[] ackBuffer = new byte[1];
connection.Write(preamble.Array, preamble.Offset, preamble.Count, true, timeoutHelper.RemainingTime());
if (_upgrade != null)
{
StreamUpgradeInitiator upgradeInitiator = _upgrade.CreateUpgradeInitiator(this.RemoteAddress, this.Via);
upgradeInitiator.Open(timeoutHelper.RemainingTime());
if (!ConnectionUpgradeHelper.InitiateUpgrade(upgradeInitiator, ref connection, _decoder, this, ref timeoutHelper))
{
ConnectionUpgradeHelper.DecodeFramingFault(_decoder, connection, this.Via, MessageEncoder.ContentType, ref timeoutHelper);
}
SetRemoteSecurity(upgradeInitiator);
upgradeInitiator.Close(timeoutHelper.RemainingTime());
connection.Write(ClientDuplexEncoder.PreambleEndBytes, 0, ClientDuplexEncoder.PreambleEndBytes.Length, true, timeoutHelper.RemainingTime());
}
// read ACK
int ackBytesRead = connection.Read(ackBuffer, 0, ackBuffer.Length, timeoutHelper.RemainingTime());
if (!ConnectionUpgradeHelper.ValidatePreambleResponse(ackBuffer, ackBytesRead, _decoder, Via))
{
ConnectionUpgradeHelper.DecodeFramingFault(_decoder, connection, Via,
MessageEncoder.ContentType, ref timeoutHelper);
}
return connection;
}
finally
{
SendLock.Release();
}
}
protected internal override async Task OnOpenAsync(TimeSpan timeout)
{
IConnection connection;
try
{
connection = await _connectionPoolHelper.EstablishConnectionAsync(timeout);
}
catch (TimeoutException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TimeoutException(SR.Format(SR.TimeoutOnOpen, timeout), exception));
}
bool connectionAccepted = false;
try
{
AcceptConnection(connection);
connectionAccepted = true;
}
finally
{
if (!connectionAccepted)
{
_connectionPoolHelper.Abort();
}
}
}
protected override void OnOpen(TimeSpan timeout)
{
IConnection connection;
try
{
connection = _connectionPoolHelper.EstablishConnection(timeout);
}
catch (TimeoutException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TimeoutException(SR.Format(SR.TimeoutOnOpen, timeout), exception));
}
bool connectionAccepted = false;
try
{
AcceptConnection(connection);
connectionAccepted = true;
}
finally
{
if (!connectionAccepted)
{
_connectionPoolHelper.Abort();
}
}
}
protected override void ReturnConnectionIfNecessary(bool abort, TimeSpan timeout)
{
lock (ThisLock)
{
if (abort)
{
_connectionPoolHelper.Abort();
}
else
{
_connectionPoolHelper.Close(timeout);
}
}
}
private void AcceptConnection(IConnection connection)
{
base.SetMessageSource(new ClientDuplexConnectionReader(this, connection, _decoder, _settings, MessageEncoder));
lock (ThisLock)
{
if (this.State != CommunicationState.Opening)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new CommunicationObjectAbortedException(SR.Format(SR.DuplexChannelAbortedDuringOpen, this.Via)));
}
this.Connection = connection;
}
}
private void SetRemoteSecurity(StreamUpgradeInitiator upgradeInitiator)
{
this.RemoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(upgradeInitiator);
}
protected override void PrepareMessage(Message message)
{
base.PrepareMessage(message);
}
internal class DuplexConnectionPoolHelper : ConnectionPoolHelper
{
private ClientFramingDuplexSessionChannel _channel;
private ArraySegment<byte> _preamble;
public DuplexConnectionPoolHelper(ClientFramingDuplexSessionChannel channel,
ConnectionPool connectionPool, IConnectionInitiator connectionInitiator)
: base(connectionPool, connectionInitiator, channel.Via)
{
_channel = channel;
_preamble = channel.CreatePreamble();
}
protected override TimeoutException CreateNewConnectionTimeoutException(TimeSpan timeout, TimeoutException innerException)
{
return new TimeoutException(SR.Format(SR.OpenTimedOutEstablishingTransportSession,
timeout, _channel.Via.AbsoluteUri), innerException);
}
protected override IConnection AcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper)
{
return _channel.SendPreamble(connection, _preamble, ref timeoutHelper);
}
protected override Task<IConnection> AcceptPooledConnectionAsync(IConnection connection, ref TimeoutHelper timeoutHelper)
{
return _channel.SendPreambleAsync(connection, _preamble, timeoutHelper.RemainingTime());
}
}
}
// used by StreamedFramingRequestChannel and ClientFramingDuplexSessionChannel
internal class ConnectionUpgradeHelper
{
public static async Task DecodeFramingFaultAsync(ClientFramingDecoder decoder, IConnection connection,
Uri via, string contentType, TimeSpan timeout)
{
var timeoutHelper = new TimeoutHelper(timeout);
ValidateReadingFaultString(decoder);
int size = await connection.ReadAsync(0,
Math.Min(FaultStringDecoder.FaultSizeQuota, connection.AsyncReadBufferSize),
timeoutHelper.RemainingTime());
int offset = 0;
while (size > 0)
{
int bytesDecoded = decoder.Decode(connection.AsyncReadBuffer, offset, size);
offset += bytesDecoded;
size -= bytesDecoded;
if (decoder.CurrentState == ClientFramingDecoderState.Fault)
{
ConnectionUtilities.CloseNoThrow(connection, timeoutHelper.RemainingTime());
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
FaultStringDecoder.GetFaultException(decoder.Fault, via.ToString(), contentType));
}
else
{
if (decoder.CurrentState != ClientFramingDecoderState.ReadingFaultString)
{
throw new Exception("invalid framing client state machine");
}
if (size == 0)
{
offset = 0;
size = await connection.ReadAsync(0,
Math.Min(FaultStringDecoder.FaultSizeQuota, connection.AsyncReadBufferSize),
timeoutHelper.RemainingTime());
}
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
}
public static void DecodeFramingFault(ClientFramingDecoder decoder, IConnection connection,
Uri via, string contentType, ref TimeoutHelper timeoutHelper)
{
ValidateReadingFaultString(decoder);
int offset = 0;
byte[] faultBuffer = Fx.AllocateByteArray(FaultStringDecoder.FaultSizeQuota);
int size = connection.Read(faultBuffer, offset, faultBuffer.Length, timeoutHelper.RemainingTime());
while (size > 0)
{
int bytesDecoded = decoder.Decode(faultBuffer, offset, size);
offset += bytesDecoded;
size -= bytesDecoded;
if (decoder.CurrentState == ClientFramingDecoderState.Fault)
{
ConnectionUtilities.CloseNoThrow(connection, timeoutHelper.RemainingTime());
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
FaultStringDecoder.GetFaultException(decoder.Fault, via.ToString(), contentType));
}
else
{
if (decoder.CurrentState != ClientFramingDecoderState.ReadingFaultString)
{
throw new Exception("invalid framing client state machine");
}
if (size == 0)
{
offset = 0;
size = connection.Read(faultBuffer, offset, faultBuffer.Length, timeoutHelper.RemainingTime());
}
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
}
public static bool InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, ref IConnection connection,
ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, ref TimeoutHelper timeoutHelper)
{
string upgradeContentType = upgradeInitiator.GetNextUpgrade();
while (upgradeContentType != null)
{
EncodedUpgrade encodedUpgrade = new EncodedUpgrade(upgradeContentType);
// write upgrade request framing for synchronization
connection.Write(encodedUpgrade.EncodedBytes, 0, encodedUpgrade.EncodedBytes.Length, true, timeoutHelper.RemainingTime());
byte[] buffer = new byte[1];
// read upgrade response framing
int size = connection.Read(buffer, 0, buffer.Length, timeoutHelper.RemainingTime());
if (!ValidateUpgradeResponse(buffer, size, decoder)) // we have a problem
{
return false;
}
// initiate wire upgrade
ConnectionStream connectionStream = new ConnectionStream(connection, defaultTimeouts);
Stream upgradedStream = upgradeInitiator.InitiateUpgrade(connectionStream);
// and re-wrap connection
connection = new StreamConnection(upgradedStream, connectionStream);
upgradeContentType = upgradeInitiator.GetNextUpgrade();
}
return true;
}
public static async Task<bool> InitiateUpgradeAsync(StreamUpgradeInitiator upgradeInitiator, OutWrapper<IConnection> connectionWrapper,
ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, TimeSpan timeout)
{
IConnection connection = connectionWrapper.Value;
string upgradeContentType = upgradeInitiator.GetNextUpgrade();
while (upgradeContentType != null)
{
EncodedUpgrade encodedUpgrade = new EncodedUpgrade(upgradeContentType);
// write upgrade request framing for synchronization
await connection.WriteAsync(encodedUpgrade.EncodedBytes, 0, encodedUpgrade.EncodedBytes.Length, true, timeout);
byte[] buffer = new byte[1];
// read upgrade response framing
int size = await connection.ReadAsync(buffer, 0, buffer.Length, timeout);
if (!ValidateUpgradeResponse(buffer, size, decoder)) // we have a problem
{
return false;
}
// initiate wire upgrade
ConnectionStream connectionStream = new ConnectionStream(connection, defaultTimeouts);
Stream upgradedStream = await upgradeInitiator.InitiateUpgradeAsync(connectionStream);
// and re-wrap connection
connection = new StreamConnection(upgradedStream, connectionStream);
connectionWrapper.Value = connection;
upgradeContentType = upgradeInitiator.GetNextUpgrade();
}
return true;
}
private static void ValidateReadingFaultString(ClientFramingDecoder decoder)
{
if (decoder.CurrentState != ClientFramingDecoderState.ReadingFaultString)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new System.ServiceModel.Security.MessageSecurityException(
SR.ServerRejectedUpgradeRequest));
}
}
public static bool ValidatePreambleResponse(byte[] buffer, int count, ClientFramingDecoder decoder, Uri via)
{
if (count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.ServerRejectedSessionPreamble, via),
decoder.CreatePrematureEOFException()));
}
// decode until the framing byte has been processed (it always will be)
while (decoder.Decode(buffer, 0, count) == 0)
{
// do nothing
}
if (decoder.CurrentState != ClientFramingDecoderState.Start) // we have a problem
{
return false;
}
return true;
}
private static bool ValidateUpgradeResponse(byte[] buffer, int count, ClientFramingDecoder decoder)
{
if (count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.ServerRejectedUpgradeRequest, decoder.CreatePrematureEOFException()));
}
// decode until the framing byte has been processed (it always will be)
while (decoder.Decode(buffer, 0, count) == 0)
{
// do nothing
}
if (decoder.CurrentState != ClientFramingDecoderState.UpgradeResponse) // we have a problem
{
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.Globalization;
using System.Net.Internals;
using System.Net.Sockets;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
/// <devdoc>
/// <para>Provides simple
/// domain name resolution functionality.</para>
/// </devdoc>
public static class Dns
{
// Host names any longer than this automatically fail at the winsock level.
// If the host name is 255 chars, the last char must be a dot.
private const int MaxHostName = 255;
[Obsolete("GetHostByName is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByName(string hostName)
{
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostName == null)
{
throw new ArgumentNullException(nameof(hostName));
}
// See if it's an IP Address.
IPAddress address;
if (IPAddress.TryParse(hostName, out address))
{
return NameResolutionUtilities.GetUnresolvedAnswer(address);
}
return InternalGetHostByName(hostName);
}
private static void ValidateHostName(string hostName)
{
if (hostName.Length > MaxHostName // If 255 chars, the last one must be a dot.
|| hostName.Length == MaxHostName && hostName[MaxHostName - 1] != '.')
{
throw new ArgumentOutOfRangeException(nameof(hostName), SR.Format(SR.net_toolong,
nameof(hostName), MaxHostName.ToString(NumberFormatInfo.CurrentInfo)));
}
}
private static IPHostEntry InternalGetHostByName(string hostName)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
IPHostEntry ipHostEntry = null;
ValidateHostName(hostName);
int nativeErrorCode;
SocketError errorCode = NameResolutionPal.TryGetAddrInfo(hostName, out ipHostEntry, out nativeErrorCode);
if (errorCode != SocketError.Success)
{
throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostByName
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(string address)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(IPAddress.Parse(address));
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostByAddress
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(IPAddress address)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(address);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostByAddress
// Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods).
private static IPHostEntry InternalGetHostByAddress(IPAddress address)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, address);
//
// Try to get the data for the host from it's address
//
// We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string
// will only return that address and not the full list.
// Do a reverse lookup to get the host name.
SocketError errorCode;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(address, out errorCode, out nativeErrorCode);
if (errorCode == SocketError.Success)
{
// Do the forward lookup to get the IPs for that host name
IPHostEntry hostEntry;
errorCode = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode);
if (errorCode == SocketError.Success)
{
return hostEntry;
}
if (NetEventSource.IsEnabled) NetEventSource.Error(null, SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode));
// One of two things happened:
// 1. There was a ptr record in dns, but not a corollary A/AAA record.
// 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix.
// - Workaround, Check "Use this connection's dns suffix in dns registration" on that network
// adapter's advanced dns settings.
// Just return the resolved host name and no IPs.
return hostEntry;
}
throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode);
} // InternalGetHostByAddress
/*****************************************************************************
Function : gethostname
Abstract: Queries the hostname from DNS
Input Parameters:
Returns: String
******************************************************************************/
/// <devdoc>
/// <para>Gets the host name of the local machine.</para>
/// </devdoc>
public static string GetHostName()
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, null);
NameResolutionPal.EnsureSocketsAreInitialized();
return NameResolutionPal.GetHostName();
}
[Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry Resolve(string hostName)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostName == null)
{
throw new ArgumentNullException(nameof(hostName));
}
// See if it's an IP Address.
IPAddress address;
IPHostEntry ipHostEntry;
if (IPAddress.TryParse(hostName, out address) && (address.AddressFamily != AddressFamily.InterNetworkV6 || SocketProtocolSupportPal.OSSupportsIPv6))
{
try
{
ipHostEntry = InternalGetHostByAddress(address);
}
catch (SocketException ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
}
}
else
{
ipHostEntry = InternalGetHostByName(hostName);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
}
private static void ResolveCallback(object context)
{
DnsResolveAsyncResult result = (DnsResolveAsyncResult)context;
IPHostEntry hostEntry;
try
{
if (result.IpAddress != null)
{
hostEntry = InternalGetHostByAddress(result.IpAddress);
}
else
{
hostEntry = InternalGetHostByName(result.HostName);
}
}
catch (OutOfMemoryException)
{
throw;
}
catch (Exception exception)
{
result.InvokeCallback(exception);
return;
}
result.InvokeCallback(hostEntry);
}
// Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical
// If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the original address is returned.
private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, bool throwOnIIPAny, AsyncCallback requestCallback, object state)
{
if (hostName == null)
{
throw new ArgumentNullException(nameof(hostName));
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, hostName);
// See if it's an IP Address.
IPAddress ipAddress;
DnsResolveAsyncResult asyncResult;
if (IPAddress.TryParse(hostName, out ipAddress))
{
if (throwOnIIPAny && (ipAddress.Equals(IPAddress.Any) || ipAddress.Equals(IPAddress.IPv6Any)))
{
throw new ArgumentException(SR.net_invalid_ip_addr, nameof(hostName));
}
asyncResult = new DnsResolveAsyncResult(ipAddress, null, state, requestCallback);
if (justReturnParsedIp)
{
IPHostEntry hostEntry = NameResolutionUtilities.GetUnresolvedAnswer(ipAddress);
asyncResult.StartPostingAsyncOp(false);
asyncResult.InvokeCallback(hostEntry);
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
}
else
{
asyncResult = new DnsResolveAsyncResult(hostName, null, state, requestCallback);
}
// Set up the context, possibly flow.
asyncResult.StartPostingAsyncOp(false);
// If the OS supports it and 'hostName' is not an IP Address, resolve the name asynchronously
// instead of calling the synchronous version in the ThreadPool.
if (NameResolutionPal.SupportsGetAddrInfoAsync && ipAddress == null)
{
ValidateHostName(hostName);
NameResolutionPal.GetAddrInfoAsync(asyncResult);
}
else
{
// Start the resolve.
Task.Factory.StartNew(
s => ResolveCallback(s),
asyncResult,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
}
// Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above.
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
private static IAsyncResult HostResolutionBeginHelper(IPAddress address, bool flowContext, AsyncCallback requestCallback, object state)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address));
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, address);
// Set up the context, possibly flow.
DnsResolveAsyncResult asyncResult = new DnsResolveAsyncResult(address, null, state, requestCallback);
if (flowContext)
{
asyncResult.StartPostingAsyncOp(false);
}
// Start the resolve.
Task.Factory.StartNew(
s => ResolveCallback(s),
asyncResult,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
// Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above.
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
private static IPHostEntry HostResolutionEndHelper(IAsyncResult asyncResult)
{
//
// parameter validation
//
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
DnsResolveAsyncResult castedResult = asyncResult as DnsResolveAsyncResult;
if (castedResult == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndResolve)));
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null);
castedResult.InternalWaitForCompletion();
castedResult.EndCalled = true;
Exception exception = castedResult.Result as Exception;
if (exception != null)
{
ExceptionDispatchInfo.Throw(exception);
}
return (IPHostEntry)castedResult.Result;
}
[Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback requestCallback, object stateObject)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, true, true, requestCallback, stateObject);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginGetHostByName
[Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
NameResolutionPal.EnsureSocketsAreInitialized();
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // EndGetHostByName()
public static IPHostEntry GetHostEntry(string hostNameOrAddress)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress == null)
{
throw new ArgumentNullException(nameof(hostNameOrAddress));
}
// See if it's an IP Address.
IPAddress address;
IPHostEntry ipHostEntry;
if (IPAddress.TryParse(hostNameOrAddress, out address))
{
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(hostNameOrAddress)));
}
ipHostEntry = InternalGetHostByAddress(address);
}
else
{
ipHostEntry = InternalGetHostByName(hostNameOrAddress);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
}
public static IPHostEntry GetHostEntry(IPAddress address)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(address)));
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(address);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // GetHostEntry
public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress == null)
{
throw new ArgumentNullException(nameof(hostNameOrAddress));
}
// See if it's an IP Address.
IPAddress address;
IPAddress[] addresses;
if (IPAddress.TryParse(hostNameOrAddress, out address))
{
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(hostNameOrAddress)));
}
addresses = new IPAddress[] { address };
}
else
{
// InternalGetHostByName works with IP addresses (and avoids a reverse-lookup), but we need
// explicit handling in order to do the ArgumentException and guarantee the behavior.
addresses = InternalGetHostByName(hostNameOrAddress).AddressList;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, addresses);
return addresses;
}
public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, false, true, requestCallback, stateObject);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(address, true, requestCallback, stateObject);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // EndResolve()
public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, true, true, requestCallback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry.AddressList;
} // EndResolveToAddresses
[Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginResolve(string hostName, AsyncCallback requestCallback, object stateObject)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, false, false, requestCallback, stateObject);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
return asyncResult;
} // BeginResolve
[Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndResolve(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
IPHostEntry ipHostEntry;
try
{
ipHostEntry = HostResolutionEndHelper(asyncResult);
}
catch (SocketException ex)
{
IPAddress address = ((DnsResolveAsyncResult)asyncResult).IpAddress;
if (address == null)
throw; // BeginResolve was called with a HostName, not an IPAddress
if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
} // EndResolve()
//************* Task-based async public methods *************************
public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress)
{
NameResolutionPal.EnsureSocketsAreInitialized();
return Task<IPAddress[]>.Factory.FromAsync(
(arg, requestCallback, stateObject) => BeginGetHostAddresses(arg, requestCallback, stateObject),
asyncResult => EndGetHostAddresses(asyncResult),
hostNameOrAddress,
null);
}
public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address)
{
NameResolutionPal.EnsureSocketsAreInitialized();
return Task<IPHostEntry>.Factory.FromAsync(
(arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject),
asyncResult => EndGetHostEntry(asyncResult),
address,
null);
}
public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress)
{
NameResolutionPal.EnsureSocketsAreInitialized();
return Task<IPHostEntry>.Factory.FromAsync(
(arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject),
asyncResult => EndGetHostEntry(asyncResult),
hostNameOrAddress,
null);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace Medo.Security.Cryptography.PasswordSafe {
/// <summary>
/// Password policy definition.
/// </summary>
[DebuggerDisplay("{Name}")]
public class NamedPasswordPolicy {
/// <summary>
/// Create a new policy.
/// </summary>
/// <param name="name">Policy name.</param>
/// <param name="passwordLength">Password length.</param>
public NamedPasswordPolicy(string name, int passwordLength) {
Name = name;
TotalPasswordLength = passwordLength;
}
internal NamedPasswordPolicy(NamedPasswordPolicyCollection owner, string name, PasswordPolicyStyle style, int totalPasswordLength, int minimumLowercaseCount, int minimumUppercaseCount, int minimumDigitCount, int minimumSymbolCount, char[] specialSymbolSet) {
Name = name;
Style = style;
TotalPasswordLength = totalPasswordLength;
MinimumLowercaseCount = minimumLowercaseCount;
MinimumUppercaseCount = minimumUppercaseCount;
MinimumDigitCount = minimumDigitCount;
MinimumSymbolCount = minimumSymbolCount;
SetSpecialSymbolSet(specialSymbolSet);
Owner = owner;
}
private readonly NamedPasswordPolicyCollection Owner;
/// <summary>
/// Used to mark document as changed.
/// </summary>
protected void MarkAsChanged() {
if (Owner != null) { Owner.MarkAsChanged(); }
}
private string _name;
/// <summary>
/// Gets/sets name of the policy.
/// </summary>
/// <exception cref="ArgumentNullException">Name cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Name cannot be empty. -or- Name cannot be longer than 255 characters.</exception>
public string Name {
get { return _name; }
set {
if (value == null) { throw new ArgumentNullException(nameof(value), "Name cannot be null."); }
if (string.IsNullOrEmpty(value)) { throw new ArgumentOutOfRangeException(nameof(value), "Name cannot be empty."); }
if (value.Length > 255) { throw new ArgumentOutOfRangeException(nameof(value), "Name cannot be longer than 255 characters."); }
_name = value;
MarkAsChanged();
}
}
private PasswordPolicyStyle _style;
/// <summary>
/// Gets/sets style of password policy.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Value cannot be wider than 16-bit.</exception>
public PasswordPolicyStyle Style {
get { return _style; }
set {
if (((int)value & 0xFFFF0000) != 0) { throw new ArgumentOutOfRangeException(nameof(value), "Value cannot be wider than 16-bit."); }
if ((value & PasswordPolicyStyle.UseHexDigits) == 0) {
_style = value;
} else { //force hex values only
_style = PasswordPolicyStyle.UseHexDigits;
}
MarkAsChanged();
}
}
private int _totalPasswordLength;
/// <summary>
/// Gets/sets total password length.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Count must be between 1 and 4095.</exception>
public int TotalPasswordLength {
get { return _totalPasswordLength; }
set {
if ((value < 1) || (value > 4095)) { throw new ArgumentOutOfRangeException(nameof(value), "Length must be between 1 and 4095."); }
_totalPasswordLength = value;
MarkAsChanged();
}
}
private int _minimumLowercaseCount;
/// <summary>
/// Gets/sets minimum lowercase count.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Count must be between 0 and 4095.</exception>
public int MinimumLowercaseCount {
get { return _minimumLowercaseCount; }
set {
if ((value < 0) || (value > 4095)) { throw new ArgumentOutOfRangeException(nameof(value), "Count must be between 0 and 4095."); }
_minimumLowercaseCount = value;
MarkAsChanged();
}
}
private int _minimumUppercaseCount;
/// <summary>
/// Gets/sets minimum uppercase count.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Count must be between 0 and 4095.</exception>
public int MinimumUppercaseCount {
get { return _minimumUppercaseCount; }
set {
if ((value < 0) || (value > 4095)) { throw new ArgumentOutOfRangeException(nameof(value), "Count must be between 0 and 4095."); }
_minimumUppercaseCount = value;
MarkAsChanged();
}
}
private int _minimumDigitCount;
/// <summary>
/// Gets/sets minimum digit count.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Count must be between 0 and 4095.</exception>
public int MinimumDigitCount {
get { return _minimumDigitCount; }
set {
if ((value < 0) || (value > 4095)) { throw new ArgumentOutOfRangeException(nameof(value), "Count must be between 0 and 4095."); }
_minimumDigitCount = value;
MarkAsChanged();
}
}
private int _minimumSymbolCount;
/// <summary>
/// Gets/sets minimum symbol count.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Count must be between 0 and 4095.</exception>
public int MinimumSymbolCount {
get { return _minimumSymbolCount; }
set {
if ((value < 0) || (value > 4095)) { throw new ArgumentOutOfRangeException(nameof(value), "Count must be between 0 and 4095."); }
_minimumSymbolCount = value;
MarkAsChanged();
}
}
private char[] _specialSymbolSet = new char[] { };
/// <summary>
/// Returns special symbols that are allowed in the password.
/// </summary>
public char[] GetSpecialSymbolSet() {
return _specialSymbolSet;
}
/// <summary>
/// Sets which special characters are allowed.
/// </summary>
/// <param name="specialSymbols"></param>
/// <exception cref="ArgumentNullException">Value cannot be null.</exception>
public void SetSpecialSymbolSet(params char[] specialSymbols) {
if (specialSymbols == null) { throw new ArgumentNullException(nameof(specialSymbols), "Value cannot be null."); }
//filter the same
var symbols = new List<char>(specialSymbols);
if (symbols.Count > 1) {
symbols.Sort();
var prevCh = symbols[symbols.Count - 1];
for (var i = symbols.Count - 2; i >= 0; i--) {
var currCh = symbols[i];
if (currCh == prevCh) {
symbols.RemoveAt(i);
} else {
prevCh = currCh;
}
}
}
_specialSymbolSet = symbols.ToArray();
MarkAsChanged();
}
/// <summary>
/// Returns true if objects are equal.
/// </summary>
/// <param name="obj">Other object.</param>
public override bool Equals(object obj) {
if (obj is NamedPasswordPolicy other) {
return string.Equals(ToString(), other.ToString(), StringComparison.Ordinal);
}
return false;
}
/// <summary>
/// Returns hash code.
/// </summary>
public override int GetHashCode() {
return Name.GetHashCode() ^ Style.GetHashCode();
}
/// <summary>
/// Returns text representing this policy.
/// </summary>
/// <returns></returns>
public override string ToString() {
return Name;
}
}
}
| |
/***************************************************************************
* PodcastFeedPropertiesDialog.cs
*
* Written by Mike Urbanski <michael.c.urbanski@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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 Mono.Unix;
using Gtk;
using Pango;
using Migo.Syndication;
using Banshee.Base;
using Banshee.Podcasting.Data;
namespace Banshee.Podcasting.Gui
{
internal class PodcastFeedPropertiesDialog : Dialog
{
private PodcastSource source;
private Feed feed;
private SyncPreferenceComboBox new_episode_option_combo;
private Entry name_entry;
public PodcastFeedPropertiesDialog (PodcastSource source, Feed feed)
{
this.source = source;
this.feed = feed;
Title = feed.Title;
//IconThemeUtils.SetWindowIcon (this);
BuildWindow ();
}
private void BuildWindow()
{
BorderWidth = 6;
VBox.Spacing = 12;
HasSeparator = false;
HBox box = new HBox();
box.BorderWidth = 6;
box.Spacing = 12;
Button save_button = new Button("gtk-save");
save_button.CanDefault = true;
save_button.Show();
// For later additions to the dialog. (I.E. Feed art)
HBox content_box = new HBox();
content_box.Spacing = 12;
Table table = new Table (2, 4, false);
table.RowSpacing = 6;
table.ColumnSpacing = 12;
Label description_label = new Label (Catalog.GetString ("Description:"));
description_label.SetAlignment (0f, 0f);
description_label.Justify = Justification.Left;
Label last_updated_label = new Label (Catalog.GetString ("Last updated:"));
last_updated_label.SetAlignment (0f, 0f);
last_updated_label.Justify = Justification.Left;
Label name_label = new Label (Catalog.GetString ("Podcast Name:"));
name_label.SetAlignment (0f, 0f);
name_label.Justify = Justification.Left;
name_entry = new Entry ();
name_entry.Text = feed.Title;
name_entry.Changed += delegate {
save_button.Sensitive = !String.IsNullOrEmpty (name_entry.Text);
};
Label feed_url_label = new Label (Catalog.GetString ("URL:"));
feed_url_label.SetAlignment (0f, 0f);
feed_url_label.Justify = Justification.Left;
Label new_episode_option_label = new Label (Catalog.GetString ("When feed is updated:"));
new_episode_option_label.SetAlignment (0f, 0.5f);
new_episode_option_label.Justify = Justification.Left;
Label last_updated_text = new Label (feed.LastDownloadTime.ToString ("f"));
last_updated_text.Justify = Justification.Left;
last_updated_text.SetAlignment (0f, 0f);
Label feed_url_text = new Label (feed.Url.ToString ());
feed_url_text.Wrap = false;
feed_url_text.Selectable = true;
feed_url_text.SetAlignment (0f, 0f);
feed_url_text.Justify = Justification.Left;
feed_url_text.Ellipsize = Pango.EllipsizeMode.End;
string description_string = String.IsNullOrEmpty (feed.Description) ?
Catalog.GetString ("No description available") :
feed.Description;
Label descrition_text = new Label (description_string);
descrition_text.Justify = Justification.Left;
descrition_text.SetAlignment (0f, 0f);
descrition_text.Wrap = true;
descrition_text.Selectable = true;
Viewport description_viewport = new Viewport();
description_viewport.SetSizeRequest(-1, 150);
description_viewport.ShadowType = ShadowType.None;
ScrolledWindow description_scroller = new ScrolledWindow ();
description_scroller.HscrollbarPolicy = PolicyType.Never;
description_scroller.VscrollbarPolicy = PolicyType.Automatic;
description_viewport.Add (descrition_text);
description_scroller.Add (description_viewport);
new_episode_option_combo = new SyncPreferenceComboBox (feed.AutoDownload);
// First column
uint i = 0;
table.Attach (
name_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
feed_url_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
last_updated_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
new_episode_option_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
description_label, 0, 1, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
// Second column
i = 0;
table.Attach (
name_entry, 1, 2, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
feed_url_text, 1, 2, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
last_updated_text, 1, 2, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (
new_episode_option_combo, 1, 2, i, ++i,
AttachOptions.Fill, AttachOptions.Fill, 0, 0
);
table.Attach (description_scroller, 1, 2, i, ++i,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Expand | AttachOptions.Fill, 0, 0
);
content_box.PackStart (table, true, true, 0);
box.PackStart (content_box, true, true, 0);
Button cancel_button = new Button("gtk-cancel");
cancel_button.CanDefault = true;
cancel_button.Show();
AddActionWidget (cancel_button, ResponseType.Cancel);
AddActionWidget (save_button, ResponseType.Ok);
DefaultResponse = Gtk.ResponseType.Cancel;
ActionArea.Layout = Gtk.ButtonBoxStyle.End;
box.ShowAll ();
VBox.Add (box);
Response += OnResponse;
}
private void OnResponse (object sender, ResponseArgs args)
{
if (args.ResponseId == Gtk.ResponseType.Ok) {
FeedAutoDownload new_sync_pref = new_episode_option_combo.ActiveSyncPreference;
bool changed = false;
if (feed.AutoDownload != new_sync_pref) {
feed.AutoDownload = new_sync_pref;
changed = true;
}
if (feed.Title != name_entry.Text) {
feed.Title = name_entry.Text;
source.Reload ();
changed = true;
}
if (changed) {
feed.Save ();
}
}
(sender as Dialog).Response -= OnResponse;
(sender as Dialog).Destroy();
}
}
}
| |
// Copyright 2009-2012 Matvei Stefarov <me@matvei.org>
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using JetBrains.Annotations;
namespace fCraft.MapConversion
{
public sealed class MapDat : IMapConverter
{
static readonly byte[] Mapping = new byte[256];
static MapDat()
{
Mapping[50] = (byte)Block.CobbleSlab;// torch
Mapping[51] = (byte)Block.Rope; // fire
Mapping[52] = (byte)Block.Sandstone;// spawner
Mapping[53] = (byte)Block.Snow; // wood stairs
Mapping[54] = (byte)Block.Fire; // chest
Mapping[55] = (byte)Block.LightPink;// redstone wire
Mapping[56] = (byte)Block.DarkGreen;// diamond ore
Mapping[57] = (byte)Block.Brown; // diamond block
Mapping[58] = (byte)Block.DarkBlue; // workbench
Mapping[59] = (byte)Block.Turquoise;// crops
Mapping[60] = (byte)Block.Ice; // soil
Mapping[61] = (byte)Block.Tile; // furnace
Mapping[62] = (byte)Block.Magma; // burning furnance
Mapping[63] = (byte)Block.Pillar; // sign post
Mapping[64] = (byte)Block.Crate; // wooden door
Mapping[65] = (byte)Block.StoneBrick;// ladder
Mapping[66] = (byte)Block.Air; // rails
Mapping[67] = (byte)Block.Stair; // cobblestone stairs
Mapping[68] = (byte)Block.Air; // wall sign
Mapping[69] = (byte)Block.Air; // lever
Mapping[70] = (byte)Block.Air; // pressure plate
Mapping[71] = (byte)Block.Air; // iron door
Mapping[72] = (byte)Block.Air; // wooden pressure plate
Mapping[73] = (byte)Block.IronOre; // redstone ore
Mapping[74] = (byte)Block.IronOre; // glowing redstone ore
Mapping[75] = (byte)Block.Air; // redstone torch (off)
Mapping[76] = (byte)Block.Air; // redstone torch (on)
Mapping[77] = (byte)Block.Air; // stone button
Mapping[78] = (byte)Block.Air; // snow
Mapping[79] = (byte)Block.Glass; // ice
Mapping[80] = (byte)Block.White; // snow block
Mapping[81] = (byte)Block.Leaves; // cactus
Mapping[82] = (byte)Block.Gray; // clay
Mapping[83] = (byte)Block.Leaves; // reed
Mapping[84] = (byte)Block.Log; // jukebox
Mapping[85] = (byte)Block.Wood; // fence
Mapping[86] = (byte)Block.Orange; // pumpkin
Mapping[87] = (byte)Block.Dirt; // netherstone
Mapping[88] = (byte)Block.Gravel; // slow sand
Mapping[89] = (byte)Block.Sand; // lightstone
Mapping[90] = (byte)Block.Violet; // portal
Mapping[91] = (byte)Block.Orange; // jack-o-lantern
// all others default to 0/air
}
public string ServerName
{
get { return "Creative/Vanilla"; }
}
public MapStorageType StorageType
{
get { return MapStorageType.SingleFile; }
}
public MapFormat Format
{
get { return MapFormat.Creative; }
}
public bool ClaimsName([NotNull] string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
return fileName.EndsWith(".dat", StringComparison.OrdinalIgnoreCase) ||
fileName.EndsWith(".mine", StringComparison.OrdinalIgnoreCase);
}
public bool Claims([NotNull] string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
try
{
using (FileStream mapStream = File.OpenRead(fileName))
{
byte[] temp = new byte[8];
mapStream.Seek(-4, SeekOrigin.End);
mapStream.Read(temp, 0, 4);
mapStream.Seek(0, SeekOrigin.Begin);
int length = BitConverter.ToInt32(temp, 0);
byte[] data = new byte[length];
using (GZipStream reader = new GZipStream(mapStream, CompressionMode.Decompress, true))
{
reader.Read(data, 0, length);
}
for (int i = 0; i < length - 1; i++)
{
if (data[i] == 0xAC && data[i + 1] == 0xED)
{
return true;
}
}
return false;
}
}
catch (Exception)
{
return false;
}
}
public Map LoadHeader([NotNull] string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
Map map = Load(fileName);
map.Blocks = null;
return map;
}
public static byte MapBlock(byte block)
{
return Mapping[block];
}
public static Block MapBlock(Block block)
{
return (Block)Mapping[(byte)block];
}
public Map Load([NotNull] string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
using (FileStream mapStream = File.OpenRead(fileName))
{
byte[] temp = new byte[8];
Map map = null;
mapStream.Seek(-4, SeekOrigin.End);
mapStream.Read(temp, 0, 4);
mapStream.Seek(0, SeekOrigin.Begin);
int uncompressedLength = BitConverter.ToInt32(temp, 0);
byte[] data = new byte[uncompressedLength];
using (GZipStream reader = new GZipStream(mapStream, CompressionMode.Decompress, true))
{
reader.Read(data, 0, uncompressedLength);
}
for (int i = 0; i < uncompressedLength - 1; i++)
{
if (data[i] != 0xAC || data[i + 1] != 0xED) continue;
// bypassing the header crap
int pointer = i + 6;
Array.Copy(data, pointer, temp, 0, 2);
pointer += IPAddress.HostToNetworkOrder(BitConverter.ToInt16(temp, 0));
pointer += 13;
int headerEnd;
// find the end of serialization listing
for (headerEnd = pointer; headerEnd < data.Length - 1; headerEnd++)
{
if (data[headerEnd] == 0x78 && data[headerEnd + 1] == 0x70)
{
headerEnd += 2;
break;
}
}
// start parsing serialization listing
int offset = 0;
int width = 0, length = 0, height = 0;
Position spawn = new Position();
while (pointer < headerEnd)
{
switch ((char)data[pointer])
{
case 'Z':
offset++;
break;
case 'F':
case 'I':
offset += 4;
break;
case 'J':
offset += 8;
break;
}
pointer += 1;
Array.Copy(data, pointer, temp, 0, 2);
short skip = IPAddress.HostToNetworkOrder(BitConverter.ToInt16(temp, 0));
pointer += 2;
// look for relevant variables
Array.Copy(data, headerEnd + offset - 4, temp, 0, 4);
if (MemCmp(data, pointer, "width"))
{
width = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0));
}
else if (MemCmp(data, pointer, "depth"))
{
height = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0));
}
else if (MemCmp(data, pointer, "height"))
{
length = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0));
}
else if (MemCmp(data, pointer, "xSpawn"))
{
spawn.X = (short)(IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0)) * 32 + 16);
}
else if (MemCmp(data, pointer, "ySpawn"))
{
spawn.Z = (short)(IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0)) * 32 + 16);
}
else if (MemCmp(data, pointer, "zSpawn"))
{
spawn.Y = (short)(IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0)) * 32 + 16);
}
pointer += skip;
}
map = new Map(null, width, length, height, false) { Spawn = spawn };
if (!map.ValidateHeader())
{
throw new MapFormatException("One or more of the map dimensions are invalid.");
}
// find the start of the block array
bool foundBlockArray = false;
offset = Array.IndexOf<byte>(data, 0x00, headerEnd);
while (offset != -1 && offset < data.Length - 2)
{
if (data[offset] == 0x00 && data[offset + 1] == 0x78 && data[offset + 2] == 0x70)
{
foundBlockArray = true;
pointer = offset + 7;
}
offset = Array.IndexOf<byte>(data, 0x00, offset + 1);
}
// copy the block array... or fail
if (foundBlockArray)
{
map.Blocks = new byte[map.Volume];
Array.Copy(data, pointer, map.Blocks, 0, map.Blocks.Length);
map.ConvertBlockTypes(Mapping);
}
else
{
throw new MapFormatException("Could not locate block array.");
}
break;
}
return map;
}
}
public bool Save([NotNull] Map mapToSave, [NotNull] string fileName)
{
if (mapToSave == null) throw new ArgumentNullException("mapToSave");
if (fileName == null) throw new ArgumentNullException("fileName");
throw new NotImplementedException();
}
static bool MemCmp([NotNull] IList<byte> data, int offset, [NotNull] string value)
{
if (data == null) throw new ArgumentNullException("data");
if (value == null) throw new ArgumentNullException("value");
// ReSharper disable LoopCanBeConvertedToQuery
for (int i = 0; i < value.Length; i++)
{
if (offset + i >= data.Count || data[offset + i] != value[i]) return false;
}
// ReSharper restore LoopCanBeConvertedToQuery
return true;
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using VR = UnityEngine.VR;
using System.Collections;
/// <summary>
/// Shows the Oculus plaform UI.
/// </summary>
public class OVRPlatformMenu : MonoBehaviour
{
/// <summary>
/// A timer that appears at the gaze cursor before a platform UI transition.
/// </summary>
public GameObject cursorTimer;
/// <summary>
/// The current color of the cursor timer.
/// </summary>
public Color cursorTimerColor = new Color(0.0f, 0.643f, 1.0f, 1.0f); // set default color to same as native cursor timer
/// <summary>
/// The distance at which the cursor timer appears.
/// </summary>
public float fixedDepth = 3.0f;
private GameObject instantiatedCursorTimer = null;
private Material cursorTimerMaterial = null;
private float doubleTapDelay = 0.25f;
private float shortPressDelay = 0.25f;
private float longPressDelay = 0.75f;
enum eBackButtonAction
{
NONE,
DOUBLE_TAP,
SHORT_PRESS,
LONG_PRESS
};
private int downCount = 0;
private int upCount = 0;
private float initialDownTime = -1.0f;
private bool waitForUp = false;
eBackButtonAction ResetAndSendAction( eBackButtonAction action )
{
print( "ResetAndSendAction( " + action + " );" );
downCount = 0;
upCount = 0;
initialDownTime = -1.0f;
waitForUp = false;
ResetCursor();
if ( action == eBackButtonAction.LONG_PRESS )
{
// since a long press triggers off of time and not an up,
// wait for an up to happen before handling any more key state.
waitForUp = true;
}
return action;
}
eBackButtonAction HandleBackButtonState()
{
if ( waitForUp )
{
if ( !Input.GetKeyDown( KeyCode.Escape ) && !Input.GetKey( KeyCode.Escape ) )
{
waitForUp = false;
}
else
{
return eBackButtonAction.NONE;
}
}
if ( Input.GetKeyDown( KeyCode.Escape ) )
{
// just came down
downCount++;
if ( downCount == 1 )
{
initialDownTime = Time.realtimeSinceStartup;
}
}
else if ( downCount > 0 )
{
if ( Input.GetKey( KeyCode.Escape ) )
{
if ( downCount <= upCount )
{
// just went down
downCount++;
}
float timeSinceFirstDown = Time.realtimeSinceStartup - initialDownTime;
if ( timeSinceFirstDown > shortPressDelay )
{
// The gaze cursor timer should start unfilled once short-press time is exceeded
// then fill up completely, so offset the times by the short-press delay.
float t = ( timeSinceFirstDown - shortPressDelay ) / ( longPressDelay - shortPressDelay );
UpdateCursor( t );
}
if ( timeSinceFirstDown > longPressDelay )
{
return ResetAndSendAction( eBackButtonAction.LONG_PRESS );
}
}
else
{
bool started = initialDownTime >= 0.0f;
if ( started )
{
if ( upCount < downCount )
{
// just came up
upCount++;
}
float timeSinceFirstDown = Time.realtimeSinceStartup - initialDownTime;
if ( timeSinceFirstDown < doubleTapDelay )
{
if ( downCount == 2 && upCount == 2 )
{
return ResetAndSendAction( eBackButtonAction.DOUBLE_TAP );
}
}
else if ( timeSinceFirstDown > shortPressDelay )
{
if ( downCount == 1 && upCount == 1 )
{
return ResetAndSendAction( eBackButtonAction.SHORT_PRESS );
}
}
else if ( timeSinceFirstDown < longPressDelay )
{
// this is an abort of a long press after short-press delay has passed
return ResetAndSendAction( eBackButtonAction.NONE );
}
}
}
}
// down reset, but perform no action
return eBackButtonAction.NONE;
}
/// <summary>
/// Instantiate the cursor timer
/// </summary>
void Awake()
{
if (!OVRManager.isHmdPresent)
{
enabled = false;
return;
}
if ((cursorTimer != null) && (instantiatedCursorTimer == null))
{
//Debug.Log("Instantiating CursorTimer");
instantiatedCursorTimer = Instantiate(cursorTimer) as GameObject;
if (instantiatedCursorTimer != null)
{
cursorTimerMaterial = instantiatedCursorTimer.GetComponent<Renderer>().material;
cursorTimerMaterial.SetColor ( "_Color", cursorTimerColor );
instantiatedCursorTimer.GetComponent<Renderer>().enabled = false;
}
}
}
/// <summary>
/// Destroy the cloned material
/// </summary>
void OnDestroy()
{
if (cursorTimerMaterial != null)
{
Destroy(cursorTimerMaterial);
}
}
/// <summary>
/// Reset when resuming
/// </summary>
void OnApplicationFocus( bool focusState )
{
//Input.ResetInputAxes();
//ResetAndSendAction( eBackButtonAction.LONG_PRESS );
}
/// <summary>
/// Reset when resuming
/// </summary>
void OnApplicationPause( bool pauseStatus )
{
if ( !pauseStatus )
{
Input.ResetInputAxes();
}
//ResetAndSendAction( eBackButtonAction.LONG_PRESS );
}
/// <summary>
/// Show the confirm quit menu
/// </summary>
void ShowConfirmQuitMenu()
{
#if UNITY_ANDROID && !UNITY_EDITOR
Debug.Log("[PlatformUI-ConfirmQuit] Showing @ " + Time.time);
OVRManager.PlatformUIConfirmQuit();
#endif
}
/// <summary>
/// Show the platform UI global menu
/// </summary>
void ShowGlobalMenu()
{
#if UNITY_ANDROID && !UNITY_EDITOR
Debug.Log("[PlatformUI-Global] Showing @ " + Time.time);
OVRManager.PlatformUIGlobalMenu();
#endif
}
/// <summary>
/// Tests for long-press and activates global platform menu when detected.
/// as per the Unity integration doc, the back button responds to "mouse 1" button down/up/etc
/// </summary>
void Update()
{
#if UNITY_ANDROID
eBackButtonAction action = HandleBackButtonState();
if ( action == eBackButtonAction.DOUBLE_TAP )
{
ResetCursor();
}
else if ( action == eBackButtonAction.SHORT_PRESS )
{
ResetCursor();
ShowConfirmQuitMenu();
}
else if ( action == eBackButtonAction.LONG_PRESS )
{
ShowGlobalMenu();
}
#endif
}
/// <summary>
/// Update the cursor based on how long the back button is pressed
/// </summary>
void UpdateCursor(float timerRotateRatio)
{
timerRotateRatio = Mathf.Clamp( timerRotateRatio, 0.0f, 1.0f );
if (instantiatedCursorTimer != null)
{
instantiatedCursorTimer.GetComponent<Renderer>().enabled = true;
// Clamp the rotation ratio to avoid rendering artifacts
float rampOffset = Mathf.Clamp(1.0f - timerRotateRatio, 0.0f, 1.0f);
cursorTimerMaterial.SetFloat ( "_ColorRampOffset", rampOffset );
//print( "alphaAmount = " + alphaAmount );
// Draw timer at fixed distance in front of camera
// cursor positions itself based on camera forward and draws at a fixed depth
Vector3 cameraForward = Camera.main.transform.forward;
Vector3 cameraPos = Camera.main.transform.position;
instantiatedCursorTimer.transform.position = cameraPos + (cameraForward * fixedDepth);
instantiatedCursorTimer.transform.forward = cameraForward;
}
}
void ResetCursor()
{
if (instantiatedCursorTimer != null)
{
cursorTimerMaterial.SetFloat("_ColorRampOffset", 1.0f);
instantiatedCursorTimer.GetComponent<Renderer>().enabled = false;
//print( "ResetCursor" );
}
}
}
| |
// 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 Internal.Cryptography.Pal;
using System.Diagnostics;
using System.Globalization;
namespace System.Security.Cryptography.X509Certificates
{
public sealed class X509Store : IDisposable
{
internal const string RootStoreName = "Root";
internal const string IntermediateCAStoreName = "CA";
internal const string DisallowedStoreName = "Disallowed";
private IStorePal _storePal;
public X509Store()
: this("MY", StoreLocation.CurrentUser)
{
}
public X509Store(string storeName)
: this(storeName, StoreLocation.CurrentUser)
{
}
public X509Store(StoreName storeName)
: this(storeName, StoreLocation.CurrentUser)
{
}
public X509Store(StoreLocation storeLocation)
: this("MY", storeLocation)
{
}
public X509Store(StoreName storeName, StoreLocation storeLocation)
{
if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(storeLocation)));
switch (storeName)
{
case StoreName.AddressBook:
Name = "AddressBook";
break;
case StoreName.AuthRoot:
Name = "AuthRoot";
break;
case StoreName.CertificateAuthority:
Name = IntermediateCAStoreName;
break;
case StoreName.Disallowed:
Name = DisallowedStoreName;
break;
case StoreName.My:
Name = "My";
break;
case StoreName.Root:
Name = RootStoreName;
break;
case StoreName.TrustedPeople:
Name = "TrustedPeople";
break;
case StoreName.TrustedPublisher:
Name = "TrustedPublisher";
break;
default:
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(storeName)));
}
Location = storeLocation;
}
public X509Store(StoreName storeName, StoreLocation storeLocation, OpenFlags flags)
: this(storeName, storeLocation)
{
Open(flags);
}
public X509Store(string storeName, StoreLocation storeLocation)
{
if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(storeLocation)));
Location = storeLocation;
Name = storeName;
}
public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags)
: this(storeName, storeLocation)
{
Open(flags);
}
public X509Store(IntPtr storeHandle)
{
_storePal = StorePal.FromHandle(storeHandle);
Debug.Assert(_storePal != null);
}
public IntPtr StoreHandle
{
get
{
if (_storePal == null)
throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen);
// The Pal layer may return null (Unix) or throw exception (Windows)
if (_storePal.SafeHandle == null)
return IntPtr.Zero;
return _storePal.SafeHandle.DangerousGetHandle();
}
}
public StoreLocation Location { get; private set; }
public string Name { get; private set; }
public void Open(OpenFlags flags)
{
Close();
_storePal = StorePal.FromSystemStore(Name, Location, flags);
}
public X509Certificate2Collection Certificates
{
get
{
X509Certificate2Collection certificates = new X509Certificate2Collection();
if (_storePal != null)
{
_storePal.CloneTo(certificates);
}
return certificates;
}
}
public bool IsOpen
{
get { return _storePal != null; }
}
public void Add(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException(nameof(certificate));
if (_storePal == null)
throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen);
if (certificate.Pal == null)
throw new CryptographicException(SR.Cryptography_InvalidHandle, "pCertContext");
_storePal.Add(certificate.Pal);
}
public void AddRange(X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException(nameof(certificates));
int i = 0;
try
{
foreach (X509Certificate2 certificate in certificates)
{
Add(certificate);
i++;
}
}
catch
{
// For desktop compat, we keep the exception semantics even though they are not ideal
// because an exception may cause certs to be removed even if they weren't there before.
for (int j = 0; j < i; j++)
{
Remove(certificates[j]);
}
throw;
}
}
public void Remove(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException(nameof(certificate));
if (_storePal == null)
throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen);
if (certificate.Pal == null)
return;
_storePal.Remove(certificate.Pal);
}
public void RemoveRange(X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException(nameof(certificates));
int i = 0;
try
{
foreach (X509Certificate2 certificate in certificates)
{
Remove(certificate);
i++;
}
}
catch
{
// For desktop compat, we keep the exception semantics even though they are not ideal
// because an exception above may cause certs to be added even if they weren't there before
// and an exception here may cause certs not to be re-added.
for (int j = 0; j < i; j++)
{
Add(certificates[j]);
}
throw;
}
}
public void Dispose()
{
Close();
}
public void Close()
{
IStorePal storePal = _storePal;
_storePal = null;
if (storePal != null)
{
storePal.Dispose();
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using RecordsViewer.Portable;
using RecordsViewer.ViewModels;
using Accela.WindowsStoreSDK;
using RecordsViewer.Portable.Resources;
namespace RecordsViewer
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public static PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Accela SDK initialization
InitializeSDK();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Handle reset requests for clearing the backstack
RootFrame.Navigated += CheckForResetNavigation;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
private void CheckForResetNavigation(object sender, NavigationEventArgs e)
{
// If the app has received a 'reset' navigation, then we need to check
// on the next navigation to see if the page stack should be reset
if (e.NavigationMode == NavigationMode.Reset)
RootFrame.Navigated += ClearBackStackAfterReset;
}
private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
{
// Unregister the event so it doesn't get called again
RootFrame.Navigated -= ClearBackStackAfterReset;
// Only clear the stack for 'new' (forward) and 'refresh' navigations
if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
return;
// For UI consistency, clear the entire page stack
while (RootFrame.RemoveBackEntry() != null)
{
; // do nothing
}
}
#endregion
// Initialize the app's font and flow direction as defined in its localized resource strings.
//
// To ensure that the font of your application is aligned with its supported languages and that the
// FlowDirection for each of those languages follows its traditional direction, ResourceLanguage
// and ResourceFlowDirection should be initialized in each resx file to match these values with that
// file's culture. For example:
//
// AppResources.es-ES.resx
// ResourceLanguage's value should be "es-ES"
// ResourceFlowDirection's value should be "LeftToRight"
//
// AppResources.ar-SA.resx
// ResourceLanguage's value should be "ar-SA"
// ResourceFlowDirection's value should be "RightToLeft"
//
// For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072.
//
private void InitializeLanguage()
{
try
{
// Set the font to match the display language defined by the
// ResourceLanguage resource string for each supported language.
//
// Fall back to the font of the neutral language if the Display
// language of the phone is not supported.
//
// If a compiler error is hit then ResourceLanguage is missing from
// the resource file.
RootFrame.Language = XmlLanguage.GetLanguage(Strings.ResourceLanguage);
// Set the FlowDirection of all elements under the root frame based
// on the ResourceFlowDirection resource string for each
// supported language.
//
// If a compiler error is hit then ResourceFlowDirection is missing from
// the resource file.
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), Strings.ResourceFlowDirection);
RootFrame.FlowDirection = flow;
}
catch
{
// If an exception is caught here it is most likely due to either
// ResourceLangauge not being correctly set to a supported language
// code or ResourceFlowDirection is set to a value other than LeftToRight
// or RightToLeft.
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
#region AccelaSDK
/// <summary>
/// Provides easy access to the Accela SDK of the Phone Application.
/// </summary>
public static AccelaSDK SharedSDK { get; private set; }
public static string[] ApiPermissions = { "records" };
private void InitializeSDK()
{
string appid = "635436839797855367";
string appsecret = "761e60d9e9224b278d99cf27c99de1f8";
SharedSDK = new AccelaSDK(appid, appsecret);
SharedSDK.SessionChanged += SharedSDK_SessionChanged;
}
void SharedSDK_SessionChanged(object sender, AccelaSessionEventArgs e)
{
switch (e.SessionStatus)
{
case AccelaSessionStatus.InvalidSession:
// todo: invalid session handle
break;
case AccelaSessionStatus.LoginCancelled:
// todo: login cancelled handle
break;
case AccelaSessionStatus.LoginFailed:
// todo: login failed handle
break;
case AccelaSessionStatus.LoginSucceeded:
// todo: login succeeded handle
break;
case AccelaSessionStatus.LogoutSucceeded:
// todo: logout succeeded handle
break;
default:
break;
}
}
#endregion
#region Service
private static ILoginService _loginService;
public static ILoginService LoginService
{
get
{
lock (typeof(App))
{
if (_loginService == null)
{
_loginService = new LoginService();
}
}
return _loginService;
}
}
private static IRecordService _recordService;
public static IRecordService RecordService
{
get
{
lock (typeof(App))
{
if (_recordService == null)
{
_recordService = new RecordService();
}
}
return _recordService;
}
}
#endregion
#region ViewModel
private static RecordsViewModel _recordsViewModel;
public static RecordsViewModel RecordsViewModel
{
get
{
lock (typeof(App))
{
if (_recordsViewModel == null)
{
_recordsViewModel = new RecordsViewModel(RecordService);
}
}
return _recordsViewModel;
}
}
private static LoginViewModel _loginViewModel;
public static LoginViewModel LoginViewModel
{
get
{
lock (typeof(App))
{
if (_loginViewModel == null)
{
_loginViewModel = new LoginViewModel(LoginService);
}
}
return _loginViewModel;
}
}
private static SettingsViewModel _settingsViewModel;
public static SettingsViewModel SettingsViewModel
{
get
{
lock (typeof(App))
{
if (_settingsViewModel == null)
{
_settingsViewModel = new SettingsViewModel();
}
}
return _settingsViewModel;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableHashSetBuilderTest : ImmutablesTestBase
{
[Fact]
public void CreateBuilder()
{
var builder = ImmutableHashSet.CreateBuilder<string>();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableHashSet<int>.Empty.ToBuilder();
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set = builder.ToImmutable();
Assert.Equal(builder.Count, set.Count);
Assert.True(builder.Add(8));
Assert.Equal(3, builder.Count);
Assert.Equal(2, set.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
}
[Fact]
public void BuilderFromSet()
{
var set = ImmutableHashSet<int>.Empty.Add(1);
var builder = set.ToBuilder();
Assert.True(builder.Contains(1));
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set2 = builder.ToImmutable();
Assert.Equal(builder.Count, set2.Count);
Assert.True(set2.Contains(1));
Assert.True(builder.Add(8));
Assert.Equal(4, builder.Count);
Assert.Equal(3, set2.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
Assert.False(set2.Contains(8));
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableHashSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder();
CollectionAssertAreEquivalent(Enumerable.Range(1, 10).ToArray(), builder.ToArray());
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray());
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray());
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableHashSet<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void EnumeratorTest()
{
var builder = ImmutableHashSet.Create(1).ToBuilder();
ManuallyEnumerateTest(new[] { 1 }, ((IEnumerable<int>)builder).GetEnumerator());
}
[Fact]
public void Clear()
{
var set = ImmutableHashSet.Create(1);
var builder = set.ToBuilder();
builder.Clear();
Assert.Equal(0, builder.Count);
}
[Fact]
public void KeyComparer()
{
var builder = ImmutableHashSet.Create("a", "B").ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
Assert.True(builder.Contains("a"));
Assert.False(builder.Contains("A"));
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains("a"));
Assert.True(builder.Contains("A"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void KeyComparerCollisions()
{
var builder = ImmutableHashSet.Create("a", "A").ToBuilder();
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Equal(1, builder.Count);
Assert.True(builder.Contains("a"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.Equal(1, set.Count);
Assert.True(set.Contains("a"));
}
[Fact]
public void KeyComparerEmptyCollection()
{
var builder = ImmutableHashSet.Create<string>().ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void UnionWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.UnionWith(null));
builder.UnionWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void ExceptWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.ExceptWith(null));
builder.ExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1 }, builder);
}
[Fact]
public void SymmetricExceptWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.SymmetricExceptWith(null));
builder.SymmetricExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 4 }, builder);
}
[Fact]
public void IntersectWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.IntersectWith(null));
builder.IntersectWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 2, 3 }, builder);
}
[Fact]
public void IsProperSubsetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.IsProperSubsetOf(null));
Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsProperSupersetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.IsProperSupersetOf(null));
Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void IsSubsetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.IsSubsetOf(null));
Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsSupersetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.IsSupersetOf(null));
Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void Overlaps()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.Overlaps(null));
Assert.True(builder.Overlaps(Enumerable.Range(3, 2)));
Assert.False(builder.Overlaps(Enumerable.Range(4, 3)));
}
[Fact]
public void Remove()
{
var builder = ImmutableHashSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>("item", () => builder.Remove(null));
Assert.False(builder.Remove("b"));
Assert.True(builder.Remove("a"));
}
[Fact]
public void SetEquals()
{
var builder = ImmutableHashSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>("other", () => builder.SetEquals(null));
Assert.False(builder.SetEquals(new[] { "b" }));
Assert.True(builder.SetEquals(new[] { "a" }));
Assert.True(builder.SetEquals(builder));
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> builder = ImmutableHashSet.Create("a").ToBuilder();
builder.Add("b");
Assert.True(builder.Contains("b"));
var array = new string[3];
builder.CopyTo(array, 1);
Assert.Null(array[0]);
CollectionAssertAreEquivalent(new[] { null, "a", "b" }, array);
Assert.False(builder.IsReadOnly);
CollectionAssertAreEquivalent(new[] { "a", "b" }, builder.ToArray()); // tests enumerator
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.CreateBuilder<int>());
}
}
}
| |
using System.Collections;
using UnityEngine;
public class Door : MonoBehaviour
{
// INSPECTOR SETTINGS
[Header("Rotation Settings")]
[Tooltip("The initial angle of the door/window.")]
public float InitialAngle = 0.0F;
[Tooltip("The amount of degrees the door/window rotates.")]
public float RotationAngle = 90.0F;
public enum SideOfRotation { Left, Right }
public SideOfRotation RotationSide;
[Tooltip("Rotating speed of the door/window.")]
public float Speed = 3F;
[Tooltip("0 = infinite times")]
public int TimesMoveable = 0;
public enum TypeOfHinge { Centered, CorrectlyPositioned }
[Header("Hinge Settings")]
public TypeOfHinge HingeType;
public enum PositionOfHinge { Left, Right }
[ConditionalHide("HingeType", true, false)]
public PositionOfHinge HingePosition;
// PRIVATE SETTINGS - NOT VISIBLE FOR THE USER
int TimesRotated = 0;
[HideInInspector] public bool RotationPending = false; // Needs to be public because Detection.cs has to access it
// DEBUG SETTINGS
[Header("Debug Settings")]
[Tooltip("Visualizes the position of the hinge in-game by a colored cube.")]
public bool VisualizeHinge = false;
[Tooltip("The color of the visualization of the hinge.")]
public Color HingeColor = Color.yellow;
// Define an initial and final rotation
Quaternion FinalRot, InitialRot;
int State;
// Create a hinge
GameObject hinge;
// An offset to take into account the original rotation of a 3rd party door
Quaternion RotationOffset;
void Start()
{
// Give the object the name "Door" for future reference
gameObject.tag = "Door";
RotationOffset = transform.rotation;
if (HingeType == TypeOfHinge.Centered)
{
// Create a hinge
hinge = new GameObject("hinge");
// Calculate sine/cosine of initial angle (needed for hinge positioning)
float CosDeg = Mathf.Cos((transform.eulerAngles.y * Mathf.PI) / 180);
float SinDeg = Mathf.Sin((transform.eulerAngles.y * Mathf.PI) / 180);
// Read transform (position/rotation/scale) of the door
float PosDoorX = transform.position.x;
float PosDoorY = transform.position.y;
float PosDoorZ = transform.position.z;
float RotDoorX = transform.localEulerAngles.x;
float RotDoorZ = transform.localEulerAngles.z;
float ScaleDoorX = transform.localScale.x;
float ScaleDoorZ = transform.localScale.z;
// Create a placeholder/temporary object of the hinge's position/rotation
Vector3 HingePosCopy = hinge.transform.position;
Vector3 HingeRotCopy = hinge.transform.localEulerAngles;
if (HingePosition == PositionOfHinge.Left)
{
if (transform.localScale.x > transform.localScale.z)
{
HingePosCopy.x = (PosDoorX - (ScaleDoorX / 2 * CosDeg));
HingePosCopy.z = (PosDoorZ + (ScaleDoorX / 2 * SinDeg));
HingePosCopy.y = PosDoorY;
HingeRotCopy.x = RotDoorX;
HingeRotCopy.y = -InitialAngle;
HingeRotCopy.z = RotDoorZ;
}
else
{
HingePosCopy.x = (PosDoorX + (ScaleDoorZ / 2 * SinDeg));
HingePosCopy.z = (PosDoorZ + (ScaleDoorZ / 2 * CosDeg));
HingePosCopy.y = PosDoorY;
HingeRotCopy.x = RotDoorX;
HingeRotCopy.y = -InitialAngle;
HingeRotCopy.z = RotDoorZ;
}
}
if (HingePosition == PositionOfHinge.Right)
{
if (transform.localScale.x > transform.localScale.z)
{
HingePosCopy.x = (PosDoorX + (ScaleDoorX / 2 * CosDeg));
HingePosCopy.z = (PosDoorZ - (ScaleDoorX / 2 * SinDeg));
HingePosCopy.y = PosDoorY;
HingeRotCopy.x = RotDoorX;
HingeRotCopy.y = -InitialAngle;
HingeRotCopy.z = RotDoorZ;
}
else
{
HingePosCopy.x = (PosDoorX - (ScaleDoorZ / 2 * SinDeg));
HingePosCopy.z = (PosDoorZ - (ScaleDoorZ / 2 * CosDeg));
HingePosCopy.y = PosDoorY;
HingeRotCopy.x = RotDoorX;
HingeRotCopy.y = -InitialAngle;
HingeRotCopy.z = RotDoorZ;
}
}
// HINGE POSITIONING
hinge.transform.position = HingePosCopy;
transform.parent = hinge.transform;
hinge.transform.localEulerAngles = HingeRotCopy;
// DEBUGGING
if (VisualizeHinge == true)
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = HingePosCopy;
cube.transform.localScale = new Vector3(0.25f, 0.25f, 0.25f);
cube.GetComponent<Renderer>().material.color = HingeColor;
}
}
}
// MOVE FUNCTION
public IEnumerator Move()
{
// ANGLES
if (RotationSide == SideOfRotation.Left)
{
InitialRot = Quaternion.Euler(0, -InitialAngle, 0);
FinalRot = Quaternion.Euler(0, -InitialAngle - RotationAngle, 0);
}
if (RotationSide == SideOfRotation.Right)
{
InitialRot = Quaternion.Euler(0, -InitialAngle, 0);
FinalRot = Quaternion.Euler(0, -InitialAngle + RotationAngle, 0);
}
if (TimesRotated < TimesMoveable || TimesMoveable == 0)
{
if (HingeType == TypeOfHinge.Centered)
{
// Change state from 1 to 0 and back ( = alternate between FinalRot and InitialRot)
if (hinge.transform.rotation == (State == 0 ? FinalRot : InitialRot)) State ^= 1;
// Set 'FinalRotation' to 'FinalRot' when moving and to 'InitialRot' when moving back
Quaternion FinalRotation = ((State == 0) ? FinalRot : InitialRot);
// Make the door/window rotate until it is fully opened/closed
while (Mathf.Abs(Quaternion.Angle(FinalRotation, hinge.transform.rotation)) > 0.01f)
{
RotationPending = true;
hinge.transform.rotation = Quaternion.Lerp(hinge.transform.rotation, FinalRotation, Time.deltaTime * Speed);
yield return new WaitForEndOfFrame();
}
RotationPending = false;
if (TimesMoveable == 0) TimesRotated = 0;
else TimesRotated++;
}
else
{
// Change state from 1 to 0 and back (= alternate between FinalRot and InitialRot)
if (transform.rotation == (State == 0 ? FinalRot * RotationOffset : InitialRot * RotationOffset)) State ^= 1;
// Set 'FinalRotation' to 'FinalRot' when moving and to 'InitialRot' when moving back
Quaternion FinalRotation = ((State == 0) ? FinalRot * RotationOffset : InitialRot * RotationOffset);
// Make the door/window rotate until it is fully opened/closed
while (Mathf.Abs(Quaternion.Angle(FinalRotation, transform.rotation)) > 0.01f)
{
RotationPending = true;
transform.rotation = Quaternion.Lerp(transform.rotation, FinalRotation, Time.deltaTime * Speed);
yield return new WaitForEndOfFrame();
}
RotationPending = false;
if (TimesMoveable == 0) TimesRotated = 0;
else TimesRotated++;
}
}
}
}
| |
using System;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Rocks;
using Mono.Cecil.Cil;
using System.Collections.Generic;
public class ModuleWeaver
{
public Action<String> LogInfo { get; set; }
public ModuleDefinition ModuleDefinition { get; set; }
public ModuleWeaver()
{
LogInfo = m => { };
}
public class PropertyInformation
{
public PropertyDefinition Property { get; set; }
public FieldDefinition Field { get; set; }
public TypeDefinition AccessorType { get; set; }
}
const MethodAttributes PublicImplementationAttributes
= MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public
| MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.NewSlot;
public class Cache
{
ModuleWeaver self;
public Cache(ModuleWeaver self)
{
this.self = self;
}
public Boolean HasWeaveTypeAttribute(TypeReference potential, out CustomAttribute baseAttribute, Int32 nesting = 0)
{
if (weaveTypeAttributeCache.TryGetValue(potential, out baseAttribute))
return baseAttribute != null;
if (nesting > 5)
{
weaveTypeAttributeCache[potential] = baseAttribute = null;
return false;
}
foreach (var attribute in potential.Resolve().CustomAttributes)
{
if (attribute.AttributeType.Name == "AttributeUsageAttribute") continue;
if (attribute.AttributeType.Name == "WeaveClassAttribute")
{
weaveTypeAttributeCache[potential] = baseAttribute = attribute;
return true;
}
if (HasWeaveTypeAttribute(attribute.AttributeType, out baseAttribute, nesting = nesting + 1))
return baseAttribute != null;
}
weaveTypeAttributeCache[potential] = null;
return false;
}
Dictionary<TypeReference, CustomAttribute> weaveTypeAttributeCache
= new Dictionary<TypeReference, CustomAttribute>();
public TypeReference GetAccessorInterface(ModuleDefinition module)
{
if (accessorInterface != null)
{
return accessorInterface;
}
foreach (var type in module.Types)
{
if (type.Name == "IAccessor`2")
{
accessorInterface = type;
return type;
}
}
throw new Exception("Can't find type IAccessor`2");
}
TypeReference accessorInterface;
}
Cache cache;
public void Execute()
{
cache = new Cache(this);
var types = ModuleDefinition.GetTypes();
foreach (var type in types)
PotentiallyWeaveType(type);
LogInfo("done.");
}
void PotentiallyWeaveType(TypeDefinition @class)
{
if (@class.Name.EndsWith("Attribute")) return;
if (cache.HasWeaveTypeAttribute(@class, out var baseAttribute))
{
WeaveType(@class, baseAttribute);
}
}
void WeaveType(TypeDefinition @class, CustomAttribute weaveTypeAttribute)
{
var propertyInformation = new PropertyInformation[@class.Properties.Count];
var arguments = weaveTypeAttribute.ConstructorArguments.ToList();
var propertyImplementationGenericType = arguments[1].Value as TypeDefinition;
// Methods and events are taken from the MixIn's type directly rather than, as
// would be more appropriate, the interfaces it implements. That's because that way
// we don't need to resolve the interface's type.
WeaveMixInWithEventDelegations(@class, weaveTypeAttribute, out var mixInType, out var mixInField);
WeavePropertyDelegations(@class, mixInField, propertyImplementationGenericType, propertyInformation);
WeaveMethodDelegations(@class, mixInType, mixInField, propertyImplementationGenericType, propertyInformation, weaveTypeAttribute);
}
void WeavePropertyDelegations(
TypeDefinition @class, FieldDefinition mixInField,
TypeDefinition propertyImplementationGenericType, PropertyInformation[] propertyInformation)
{
for (int i = 0; i < @class.Properties.Count; ++i)
{
propertyInformation[i]
= WeaveProperty(@class, mixInField, propertyImplementationGenericType, i, @class.Properties[i]);
}
}
PropertyInformation WeaveProperty(TypeDefinition @class, FieldDefinition mixInField, TypeDefinition propertyImplementationTemplate, Int32 index, PropertyDefinition property)
{
var accessorInterface = cache.GetAccessorInterface(propertyImplementationTemplate.Module);
var oldGetMethod = new MethodDefinition($"old{property.GetMethod.Name}", property.GetMethod.Attributes, property.GetMethod.ReturnType);
oldGetMethod.Body = property.GetMethod.Body;
@class.Methods.Add(oldGetMethod);
var oldSetMethod = new MethodDefinition($"old{property.SetMethod.Name}", property.SetMethod.Attributes, property.SetMethod.ReturnType);
oldSetMethod.Body = property.SetMethod.Body;
oldSetMethod.Parameters.AddRange(property.SetMethod.Parameters);
@class.Methods.Add(oldSetMethod);
var accessorType = new TypeDefinition($"", $"{property.Name}Accessor", TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.SequentialLayout | TypeAttributes.BeforeFieldInit);
accessorType.BaseType = propertyImplementationTemplate.BaseType; // just because it's a value type
var accessorConcreteImplementationInterface = new InterfaceImplementation(accessorInterface.MakeGenericType(property.PropertyType, @class));
accessorType.Interfaces.Add(accessorConcreteImplementationInterface);
var getPropertyNameMethod = new MethodDefinition("GetPropertyName", PublicImplementationAttributes, ModuleDefinition.TypeSystem.String);
getPropertyNameMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, property.Name));
getPropertyNameMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
accessorType.Methods.Add(getPropertyNameMethod);
var getIndexMethod = new MethodDefinition("GetIndex", PublicImplementationAttributes, ModuleDefinition.TypeSystem.Int32);
getIndexMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, index));
getIndexMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
accessorType.Methods.Add(getIndexMethod);
var isVariableMethod = new MethodDefinition("IsVariable", PublicImplementationAttributes, ModuleDefinition.TypeSystem.Boolean);
isVariableMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1));
isVariableMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
accessorType.Methods.Add(isVariableMethod);
var getMethod = new MethodDefinition($"Get", PublicImplementationAttributes, property.PropertyType);
getMethod.Parameters.Add(new ParameterDefinition("container", ParameterAttributes.None, @class));
getMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_1));
getMethod.Body.Instructions.Add(
Instruction.Create(property.GetMethod.IsVirtual
? OpCodes.Callvirt : OpCodes.Call, oldGetMethod));
getMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
accessorType.Methods.Add(getMethod);
var setMethod = new MethodDefinition($"Set", PublicImplementationAttributes, ModuleDefinition.TypeSystem.Void);
setMethod.Parameters.Add(new ParameterDefinition("container", ParameterAttributes.None, @class));
setMethod.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, property.PropertyType));
setMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_1));
setMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_2));
setMethod.Body.Instructions.Add(
Instruction.Create(property.SetMethod.IsVirtual
? OpCodes.Callvirt : OpCodes.Call, oldSetMethod));
setMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
accessorType.Methods.Add(setMethod);
var propertyImplementationType =
propertyImplementationTemplate.MakeGenericType(
property.PropertyType, @class, accessorType);
var getImplementationTemplate = propertyImplementationTemplate.Methods.Single(m => m.Name == "Get");
var setImplementationTemplate = propertyImplementationTemplate.Methods.Single(m => m.Name == "Set");
// The methods don't appear to be generic themselves, but they're defined on the property implementation
// generic type, which has three generic parameters.
var getImplementation = getImplementationTemplate.MakeGeneric(property.PropertyType, @class, accessorType);
var setImplementation = setImplementationTemplate.MakeGeneric(property.PropertyType, @class, accessorType);
var implementationField = new FieldDefinition($"_{property.Name}Implementation", FieldAttributes.Private, propertyImplementationType);
@class.Fields.Add(implementationField);
property.GetMethod.Body = new MethodBody(property.GetMethod);
var getMethodInstructions = property.GetMethod.Body.Instructions;
getMethodInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
getMethodInstructions.Add(Instruction.Create(OpCodes.Ldflda, implementationField));
getMethodInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
getMethodInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
getMethodInstructions.Add(Instruction.Create(OpCodes.Ldflda, mixInField));
getMethodInstructions.Add(Instruction.Create(OpCodes.Call, getImplementation));
getMethodInstructions.Add(Instruction.Create(OpCodes.Ret));
property.SetMethod.Body = new MethodBody(property.SetMethod);
var setMethodInstructions = property.SetMethod.Body.Instructions;
setMethodInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
setMethodInstructions.Add(Instruction.Create(OpCodes.Ldflda, implementationField));
setMethodInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
setMethodInstructions.Add(Instruction.Create(OpCodes.Ldarg_0));
setMethodInstructions.Add(Instruction.Create(OpCodes.Ldflda, mixInField));
setMethodInstructions.Add(Instruction.Create(OpCodes.Ldarg_1));
setMethodInstructions.Add(Instruction.Create(OpCodes.Call, setImplementation));
setMethodInstructions.Add(Instruction.Create(OpCodes.Ret));
@class.NestedTypes.Add(accessorType);
return new PropertyInformation
{
Property = property,
Field = implementationField,
AccessorType = accessorType
};
}
void WeaveMixInWithEventDelegations(TypeDefinition @class, CustomAttribute weaveTypeAttribute,
out TypeDefinition mixInType, out FieldDefinition mixInField)
{
var arguments = weaveTypeAttribute.ConstructorArguments.ToList();
LogInfo("a: " + arguments.Count);
var mixInGenericType = arguments[0].Value as TypeDefinition;
if (mixInGenericType.GenericParameters.Count == 0)
throw new Exception($"Type {mixInGenericType} has no generic parameters.");
var containerParameter = mixInGenericType.GenericParameters[0];
var mixInTypeInstance = mixInGenericType.MakeGenericInstanceType(@class);
mixInType = mixInTypeInstance.Resolve();
foreach (var i in mixInType.Interfaces)
@class.Interfaces.Add(i);
mixInField = new FieldDefinition($"mixInField", FieldAttributes.Public | FieldAttributes.SpecialName, mixInTypeInstance);
@class.Fields.Add(mixInField);
// Other methods may also be useful:
//foreach (var method in mixInGenericType.Methods)
//{
// WeaveDelegate(@class, containerParameter, mixInField, method);
//}
foreach (var @event in mixInType.Events)
{
WeaveEvent(@class, containerParameter, mixInField, @event);
}
}
void WeaveEvent(TypeDefinition @class, GenericParameter containerParameter, FieldDefinition mixInField, EventDefinition @event)
{
var delegateEvent = new EventDefinition(@event.Name, EventAttributes.None, @event.EventType);
delegateEvent.AddMethod = WeaveDelegate(@class, containerParameter, mixInField, @event.AddMethod);
delegateEvent.RemoveMethod = WeaveDelegate(@class, containerParameter, mixInField, @event.RemoveMethod);
@class.Events.Add(delegateEvent);
}
MethodDefinition WeaveDelegate(TypeDefinition @class, GenericParameter containerParameter, FieldDefinition mixInField, MethodDefinition method)
{
var delegateMethod = new MethodDefinition(method.Name, PublicImplementationAttributes, method.ReturnType);
var parameters = new List<ParameterDefinition>();
foreach (var parameter in method.Parameters)
{
if (parameter.ParameterType == containerParameter)
parameters.Add(new ParameterDefinition("self", ParameterAttributes.None, @class));
else
parameters.Add(new ParameterDefinition(parameter.Name, parameter.Attributes, parameter.ParameterType));
}
foreach (var parameter in parameters)
delegateMethod.Parameters.Add(parameter);
var processor = delegateMethod.Body.GetILProcessor();
processor.Append(Instruction.Create(OpCodes.Nop));
processor.Append(Instruction.Create(OpCodes.Ldarg_0));
processor.Append(Instruction.Create(OpCodes.Ldflda, mixInField));
for (int i = 1; i <= parameters.Count; ++i)
{
processor.Append(GetLda(i));
}
// method is on the MixIn type, which is a generic type with one type parameter (the container)
processor.Append(Instruction.Create(OpCodes.Call, method.MakeGeneric(@class)));
processor.Append(Instruction.Create(OpCodes.Nop));
processor.Append(Instruction.Create(OpCodes.Ret));
@class.Methods.Add(delegateMethod);
return delegateMethod;
}
void WeaveMethodDelegations(
TypeDefinition @class, TypeDefinition mixInType, FieldDefinition mixInField,
TypeDefinition propertyImplementationTemplate, PropertyInformation[] propertyInformation,
CustomAttribute loomAttribute)
{
foreach (var method in mixInType.Methods)
{
WeaveDelegateToProperties
(@class, mixInField, propertyImplementationTemplate, propertyInformation, method);
}
}
void WeaveDelegateToProperties(
TypeDefinition @class,
FieldDefinition mixInField,
TypeDefinition propertyImplementationTemplate,
PropertyInformation[] propertyInformation,
MethodDefinition method)
{
var targetMethodOnProperties
= propertyImplementationTemplate.Methods.FirstOrDefault(m => m.Name == method.Name);
if (targetMethodOnProperties == null) return;
if (method.ReturnType != targetMethodOnProperties.ReturnType)
throw new Exception($"Property delegation method {method.Name} has different return types between the mixin and the property implementation.");
if (method.Parameters.Count != targetMethodOnProperties.Parameters.Count - 1)
throw new Exception($"Property delegation method {method.Name} is expected to have one less parameter on the mixin than on the property implementation.");
if (method.Parameters.Count == 0)
throw new Exception($"Property delegation method {method.Name} lacks the index parameter on the mixin.");
if (method.Parameters[0].ParameterType.FullName != "System.Int32")
throw new Exception($"Property delegation method {method.Name} is expected to have Int32 as its first parameter on the mixin, but got {method.Parameters[0].ParameterType} instead.");
// Those checks are more sophisticated than I thought: We're not checking against the concrete types but template parameter types.
//if (targetMethodOnProperties.Parameters[0].ParameterType != @class)
// throw new Exception($"Property delegation method {method.Name} is expected to have {@class.Name} as its first parameter on the property implementation, but it has {targetMethodOnProperties.Parameters[0].ParameterType}");
//var mixInByReference = mixInField.FieldType.MakeByReferenceType();
//if (targetMethodOnProperties.Parameters[1].ParameterType != mixInByReference)
// throw new Exception($"Property delegation method {method.Name} is expected to have {mixInByReference} as its second parameter on the property implementation.");
for (int i = 1; i < method.Parameters.Count; ++i)
{
// The type comparison here fails when the types are derived from generics.
var lhs = method.Parameters[i].ParameterType;
var rhs = targetMethodOnProperties.Parameters[i + 1].ParameterType;
if (lhs != rhs)
throw new Exception($"Property delegation method {method.Name}'s parameter #{i}/#{i + 1} is different between the mixin and the property implementation. ({lhs} vs {rhs})");
}
var newMethod = new MethodDefinition(method.Name, method.Attributes, method.ReturnType);
var parameters = new List<ParameterDefinition>();
for (int i = 0; i < method.Parameters.Count; ++i)
{
var p = method.Parameters[i];
newMethod.Parameters.Add(new ParameterDefinition(p.Name, p.Attributes, p.ParameterType));
}
@class.Methods.Add(newMethod);
var processor = newMethod.Body.GetILProcessor();
processor.Emit(OpCodes.Ldarg_1);
var switchInstruction = processor.AppendAndReturn(Instruction.Create(OpCodes.Switch, new Instruction[0]));
processor.Emit(OpCodes.Ldarg_0);
processor.Emit(OpCodes.Ldflda, mixInField);
for (int ai = 1; ai <= method.Parameters.Count; ++ai)
processor.Append(GetLda(ai));
processor.Emit(OpCodes.Call, method.MakeGeneric(@class));
processor.Emit(OpCodes.Ret);
var callsites = new List<Instruction>();
for (int pic = 0; pic < propertyInformation.Length; ++pic)
{
var info = propertyInformation[pic];
var head = processor.AppendAndReturn(Instruction.Create(OpCodes.Ldarg_0));
processor.Append(Instruction.Create(OpCodes.Ldflda, info.Field));
processor.Append(Instruction.Create(OpCodes.Ldarg_0));
processor.Append(Instruction.Create(OpCodes.Ldarg_0));
processor.Append(Instruction.Create(OpCodes.Ldflda, mixInField));
for (int ai = 2; ai <= method.Parameters.Count; ++ai)
processor.Append(GetLda(ai));
// The methods don't appear to be generic themselves, but they're defined on the property implementation
// generic type, which has three generic parameters.
var concreteTargetMethodOnProperties
= targetMethodOnProperties.MakeGeneric(info.Property.PropertyType, @class, info.AccessorType);
processor.Append(Instruction.Create(OpCodes.Call, concreteTargetMethodOnProperties));
processor.Append(Instruction.Create(OpCodes.Ret));
callsites.Add(head);
}
switchInstruction.Operand = callsites.ToArray();
}
Instruction GetLda(Int32 i)
{
switch (i)
{
case 0: return Instruction.Create(OpCodes.Ldarg_0);
case 1: return Instruction.Create(OpCodes.Ldarg_1);
case 2: return Instruction.Create(OpCodes.Ldarg_2);
case 3: return Instruction.Create(OpCodes.Ldarg_3);
default:
return Instruction.Create(OpCodes.Ldarg_S, (Byte)i);
}
}
}
public static class Extensions
{
public static TypeReference MakeGenericType(this TypeReference self, params TypeReference[] arguments)
{
if (self.GenericParameters.Count != arguments.Length)
throw new ArgumentException();
var instance = new GenericInstanceType(self);
foreach (var argument in arguments)
instance.GenericArguments.Add(argument);
return instance;
}
public static MethodReference MakeGeneric(this MethodReference self, params TypeReference[] arguments)
{
var reference = new MethodReference(self.Name, self.ReturnType)
{
DeclaringType = self.DeclaringType.MakeGenericInstanceType(arguments),
HasThis = self.HasThis,
ExplicitThis = self.ExplicitThis,
CallingConvention = self.CallingConvention,
};
foreach (var parameter in self.Parameters)
reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));
foreach (var generic_parameter in self.GenericParameters)
reference.GenericParameters.Add(new GenericParameter(generic_parameter.Name, reference));
return reference;
}
public static void AddRange<T>(this Mono.Collections.Generic.Collection<T> self, IEnumerable<T> range)
{
foreach (var item in range)
self.Add(item);
}
public static T Single<T>(this IEnumerable<T> list, String msg)
{
try
{
return list.Single();
}
catch (Exception)
{
throw new WeavingException(msg);
}
}
public static Instruction AppendAndReturn(this ILProcessor processor, Instruction instruction)
{
processor.Append(instruction);
return instruction;
}
public static IEnumerable<TypeReference> GetSelfAndBases(this TypeReference reference)
{
while (reference != null)
{
yield return reference;
reference = reference.Resolve().BaseType;
}
}
}
public class WeavingException : Exception
{
public WeavingException(string message) : base(message)
{
}
}
| |
namespace System.Collections.Generic {
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
#if !SILVERLIGHT
using System.Runtime.Serialization;
#endif
using System.Security.Permissions;
[System.Runtime.InteropServices.ComVisible(false)]
[DebuggerTypeProxy(typeof(System_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
#if SILVERLIGHT
public class LinkedList<T>: ICollection<T>, System.Collections.ICollection
#else
[Serializable()]
public class LinkedList<T>: ICollection<T>, System.Collections.ICollection
,ISerializable, IDeserializationCallback
#endif
{
// This LinkedList is a doubly-Linked circular list.
internal LinkedListNode<T> head;
internal int count;
internal int version;
private Object _syncRoot;
#if !SILVERLIGHT
private SerializationInfo siInfo; //A temporary variable which we need during deserialization.
#endif
// names for serialization
const String VersionName = "Version";
const String CountName = "Count";
const String ValuesName = "Data";
public LinkedList() {
}
public LinkedList(IEnumerable<T> collection) {
if (collection==null) {
throw new ArgumentNullException("collection");
}
foreach( T item in collection) {
AddLast(item);
}
}
#if !SILVERLIGHT
protected LinkedList(SerializationInfo info, StreamingContext context) {
siInfo = info;
}
#endif
public int Count {
get { return count;}
}
public LinkedListNode<T> First {
get { return head;}
}
public LinkedListNode<T> Last {
get { return head == null? null: head.prev;}
}
bool ICollection<T>.IsReadOnly {
get { return false; }
}
void ICollection<T>.Add(T value) {
AddLast(value);
}
public LinkedListNode<T> AddAfter(LinkedListNode<T> node, T value) {
ValidateNode(node);
LinkedListNode<T> result = new LinkedListNode<T>(node.list, value);
InternalInsertNodeBefore(node.next, result);
return result;
}
public void AddAfter(LinkedListNode<T> node, LinkedListNode<T> newNode) {
ValidateNode(node);
ValidateNewNode(newNode);
InternalInsertNodeBefore(node.next, newNode);
newNode.list = this;
}
public LinkedListNode<T> AddBefore(LinkedListNode<T> node, T value) {
ValidateNode(node);
LinkedListNode<T> result = new LinkedListNode<T>(node.list, value);
InternalInsertNodeBefore(node, result);
if ( node == head) {
head = result;
}
return result;
}
public void AddBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) {
ValidateNode(node);
ValidateNewNode(newNode);
InternalInsertNodeBefore(node, newNode);
newNode.list = this;
if ( node == head) {
head = newNode;
}
}
public LinkedListNode<T> AddFirst(T value) {
LinkedListNode<T> result = new LinkedListNode<T>(this, value);
if (head == null) {
InternalInsertNodeToEmptyList(result);
}
else {
InternalInsertNodeBefore( head, result);
head = result;
}
return result;
}
public void AddFirst(LinkedListNode<T> node) {
ValidateNewNode(node);
if (head == null) {
InternalInsertNodeToEmptyList(node);
}
else {
InternalInsertNodeBefore( head, node);
head = node;
}
node.list = this;
}
public LinkedListNode<T> AddLast(T value) {
LinkedListNode<T> result = new LinkedListNode<T>(this, value);
if (head== null) {
InternalInsertNodeToEmptyList(result);
}
else {
InternalInsertNodeBefore( head, result);
}
return result;
}
public void AddLast(LinkedListNode<T> node) {
ValidateNewNode(node);
if (head == null) {
InternalInsertNodeToEmptyList(node);
}
else {
InternalInsertNodeBefore( head, node);
}
node.list = this;
}
public void Clear() {
LinkedListNode<T> current = head;
while (current != null ) {
LinkedListNode<T> temp = current;
current = current.Next; // use Next the instead of "next", otherwise it will loop forever
temp.Invalidate();
}
head = null;
count = 0;
version++;
}
public bool Contains(T value) {
return Find(value) != null;
}
public void CopyTo( T[] array, int index) {
if (array == null) {
throw new ArgumentNullException("array");
}
if(index < 0 || index > array.Length) {
throw new ArgumentOutOfRangeException("index",SR.GetString(SR.IndexOutOfRange, index) );
}
if (array.Length - index < Count) {
throw new ArgumentException(SR.GetString(SR.Arg_InsufficientSpace));
}
LinkedListNode<T> node = head;
if (node != null) {
do {
array[index++] = node.item;
node = node.next;
} while (node != head);
}
}
public LinkedListNode<T> Find(T value) {
LinkedListNode<T> node = head;
EqualityComparer<T> c = EqualityComparer<T>.Default;
if (node != null) {
if (value != null) {
do {
if (c.Equals(node.item, value)) {
return node;
}
node = node.next;
} while (node != head);
}
else {
do {
if (node.item == null) {
return node;
}
node = node.next;
} while (node != head);
}
}
return null;
}
public LinkedListNode<T> FindLast(T value) {
if ( head == null) return null;
LinkedListNode<T> last = head.prev;
LinkedListNode<T> node = last;
EqualityComparer<T> c = EqualityComparer<T>.Default;
if (node != null) {
if (value != null) {
do {
if (c.Equals(node.item, value)) {
return node;
}
node = node.prev;
} while (node != last);
}
else {
do {
if (node.item == null) {
return node;
}
node = node.prev;
} while (node != last);
}
}
return null;
}
public Enumerator GetEnumerator() {
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return GetEnumerator();
}
public bool Remove(T value) {
LinkedListNode<T> node = Find(value);
if (node != null) {
InternalRemoveNode(node);
return true;
}
return false;
}
public void Remove(LinkedListNode<T> node) {
ValidateNode(node);
InternalRemoveNode(node);
}
public void RemoveFirst() {
if ( head == null) { throw new InvalidOperationException(SR.GetString(SR.LinkedListEmpty)); }
InternalRemoveNode(head);
}
public void RemoveLast() {
if ( head == null) { throw new InvalidOperationException(SR.GetString(SR.LinkedListEmpty)); }
InternalRemoveNode(head.prev);
}
#if !SILVERLIGHT
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
// Customized serialization for LinkedList.
// We need to do this because it will be too expensive to Serialize each node.
// This will give us the flexiblility to change internal implementation freely in future.
if (info==null) {
throw new ArgumentNullException("info");
}
info.AddValue(VersionName, version);
info.AddValue(CountName, count); //This is the length of the bucket array.
if ( count != 0) {
T[] array = new T[Count];
CopyTo(array, 0);
info.AddValue(ValuesName, array, typeof(T[]));
}
}
public virtual void OnDeserialization(Object sender) {
if (siInfo==null) {
return; //Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it.
}
int realVersion = siInfo.GetInt32(VersionName);
int count = siInfo.GetInt32(CountName);
if ( count != 0) {
T[] array = (T[]) siInfo.GetValue(ValuesName, typeof(T[]));
if (array==null) {
throw new SerializationException(SR.GetString(SR.Serialization_MissingValues));
}
for ( int i = 0; i < array.Length; i++) {
AddLast(array[i]);
}
}
else {
head = null;
}
version = realVersion;
siInfo=null;
}
#endif
private void InternalInsertNodeBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) {
newNode.next = node;
newNode.prev = node.prev;
node.prev.next = newNode;
node.prev = newNode;
version++;
count++;
}
private void InternalInsertNodeToEmptyList(LinkedListNode<T> newNode) {
Debug.Assert( head == null && count == 0, "LinkedList must be empty when this method is called!");
newNode.next = newNode;
newNode.prev = newNode;
head = newNode;
version++;
count++;
}
internal void InternalRemoveNode(LinkedListNode<T> node) {
Debug.Assert( node.list == this, "Deleting the node from another list!");
Debug.Assert( head != null, "This method shouldn't be called on empty list!");
if ( node.next == node) {
Debug.Assert(count == 1 && head == node, "this should only be true for a list with only one node");
head = null;
}
else {
node.next.prev = node.prev;
node.prev.next = node.next;
if ( head == node) {
head = node.next;
}
}
node.Invalidate();
count--;
version++;
}
internal void ValidateNewNode(LinkedListNode<T> node) {
if (node == null) {
throw new ArgumentNullException("node");
}
if ( node.list != null) {
throw new InvalidOperationException(SR.GetString(SR.LinkedListNodeIsAttached));
}
}
internal void ValidateNode(LinkedListNode<T> node) {
if (node == null) {
throw new ArgumentNullException("node");
}
if ( node.list != this) {
throw new InvalidOperationException(SR.GetString(SR.ExternalLinkedListNode));
}
}
bool System.Collections.ICollection.IsSynchronized {
get { return false;}
}
object System.Collections.ICollection.SyncRoot {
get {
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
void System.Collections.ICollection.CopyTo(Array array, int index) {
if (array == null) {
throw new ArgumentNullException("array");
}
if (array.Rank != 1) {
throw new ArgumentException(SR.GetString(SR.Arg_MultiRank));
}
if( array.GetLowerBound(0) != 0 ) {
throw new ArgumentException(SR.GetString(SR.Arg_NonZeroLowerBound));
}
if (index < 0) {
throw new ArgumentOutOfRangeException("index",SR.GetString(SR.IndexOutOfRange, index) );
}
if (array.Length - index < Count) {
throw new ArgumentException(SR.GetString(SR.Arg_InsufficientSpace));
}
T[] tArray = array as T[];
if (tArray != null) {
CopyTo(tArray, index);
}
else {
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
throw new ArgumentException(SR.GetString(SR.Invalid_Array_Type));
}
object[] objects = array as object[];
if (objects == null) {
throw new ArgumentException(SR.GetString(SR.Invalid_Array_Type));
}
LinkedListNode<T> node = head;
try {
if (node != null) {
do {
objects[index++] = node.item;
node = node.next;
} while (node != head);
}
}
catch(ArrayTypeMismatchException) {
throw new ArgumentException(SR.GetString(SR.Invalid_Array_Type));
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return GetEnumerator();
}
#if !SILVERLIGHT
[Serializable()]
#endif
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
#if !SILVERLIGHT
, ISerializable, IDeserializationCallback
#endif
{
private LinkedList<T> list;
private LinkedListNode<T> node;
private int version;
private T current;
private int index;
#if !SILVERLIGHT
private SerializationInfo siInfo; //A temporary variable which we need during deserialization.
#endif
const string LinkedListName = "LinkedList";
const string CurrentValueName = "Current";
const string VersionName = "Version";
const string IndexName = "Index";
internal Enumerator(LinkedList<T> list) {
this.list = list;
version = list.version;
node = list.head;
current = default(T);
index = 0;
#if !SILVERLIGHT
siInfo = null;
#endif
}
#if !SILVERLIGHT
internal Enumerator(SerializationInfo info, StreamingContext context) {
siInfo = info;
list = null;
version = 0;
node = null;
current = default(T);
index = 0;
}
#endif
public T Current {
get { return current;}
}
object System.Collections.IEnumerator.Current {
get {
if( index == 0 || (index == list.Count + 1)) {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
return current;
}
}
public bool MoveNext() {
if (version != list.version) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
}
if (node == null) {
index = list.Count + 1;
return false;
}
++index;
current = node.item;
node = node.next;
if (node == list.head) {
node = null;
}
return true;
}
void System.Collections.IEnumerator.Reset() {
if (version != list.version) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
}
current = default(T);
node = list.head;
index = 0;
}
public void Dispose() {
}
#if !SILVERLIGHT
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException("info");
}
info.AddValue(LinkedListName, list);
info.AddValue(VersionName, version);
info.AddValue(CurrentValueName, current);
info.AddValue(IndexName, index);
}
void IDeserializationCallback.OnDeserialization(Object sender) {
if (list != null) {
return; //Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it.
}
if (siInfo==null) {
throw new SerializationException(SR.GetString(SR.Serialization_InvalidOnDeser));
}
list = (LinkedList<T>)siInfo.GetValue(LinkedListName, typeof(LinkedList<T>));
version = siInfo.GetInt32(VersionName);
current = (T)siInfo.GetValue(CurrentValueName, typeof(T));
index = siInfo.GetInt32(IndexName);
if( list.siInfo != null) {
list.OnDeserialization(sender);
}
if( index == list.Count + 1) { // end of enumeration
node = null;
}
else {
node = list.First;
// We don't care if we can point to the correct node if the LinkedList was changed
// MoveNext will throw upon next call and Current has the correct value.
if( node != null && index != 0) {
for(int i =0; i< index; i++) {
node = node.next;
}
if( node == list.First) {
node = null;
}
}
}
siInfo=null;
}
#endif
}
}
// Note following class is not serializable since we customized the serialization of LinkedList.
[System.Runtime.InteropServices.ComVisible(false)]
public sealed class LinkedListNode<T> {
internal LinkedList<T> list;
internal LinkedListNode<T> next;
internal LinkedListNode<T> prev;
internal T item;
public LinkedListNode( T value) {
this.item = value;
}
internal LinkedListNode(LinkedList<T> list, T value) {
this.list = list;
this.item = value;
}
public LinkedList<T> List {
get { return list;}
}
public LinkedListNode<T> Next {
get { return next == null || next == list.head? null: next;}
}
public LinkedListNode<T> Previous {
get { return prev == null || this == list.head? null: prev;}
}
public T Value {
get { return item;}
set { item = value;}
}
internal void Invalidate() {
list = null;
next = null;
prev = null;
}
}
}
| |
#region Copyright (c) Roni Schuetz - All Rights Reserved
// * --------------------------------------------------------------------- *
// * Roni Schuetz *
// * Copyright (c) 2008 All Rights reserved *
// * *
// * Shared Cache high-performance, distributed caching and *
// * replicated caching system, generic in nature, but intended to *
// * speeding up dynamic web and / or win applications by alleviating *
// * database load. *
// * *
// * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) *
// * *
// * 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., 59 Temple Place, Suite 330, *
// * Boston, MA 02111-1307 USA *
// * *
// * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
// * --------------------------------------------------------------------- *
#endregion
// *************************************************************************
//
// Name: IndexusServerSharedCacheProvider.cs
//
// Created: 31-12-2007 SharedCache.com, rschuetz
// Modified: 31-12-2007 SharedCache.com, rschuetz : Creation
// Modified: 31-12-2007 SharedCache.com, rschuetz : same as the client but element names are differnt
// Modified: 13-01-2008 SharedCache.com, rschuetz : implemented count method
// Modified: 24-02-2008 SharedCache.com, rschuetz : updated logging part for tracking, instead of using appsetting we use precompiler definition #if TRACE
// Modified: 28-01-2010 SharedCache.com, chrisme : clean up code
// *************************************************************************
using System;
using System.Collections.Generic;
using COM = SharedCache.WinServiceCommon;
namespace SharedCache.WinServiceCommon.Provider.Server
{
/// <summary>
/// Implementing a provider for Shared Cache based on
/// Microsofts Provider model.
/// </summary>
public class IndexusServerSharedCacheProvider : IndexusServerProviderBase
{
/// <summary>
/// Initializes a new instance of the <see cref="IndexusServerSharedCacheProvider"/> class.
/// </summary>
public IndexusServerSharedCacheProvider()
{
CacheUtil.SetContext(false);
}
#region Properties
/// <summary>
/// Gets the count.
/// </summary>
/// <value>The count.</value>
public override long Count
{
[System.Diagnostics.DebuggerStepThrough]
get {
if (this.Servers != null && this.Servers.Length > 0)
return (long)this.Servers.Length;
else
return 0;
}
}
/// <summary>
/// Retriving a list of all available servers
/// </summary>
/// <value>An <see cref="string"/> array with all servers.</value>
public override string[] Servers
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (serverListArray == null)
{
serverListArray = new List<string>();
foreach (COM.Configuration.Server.IndexusServerSetting configEntry in ServersList)
{
serverListArray.Add(configEntry.IpAddress);
}
}
return serverListArray.ToArray();
}
}
private static List<string> serverListArray;
private static List<COM.Configuration.Server.IndexusServerSetting> serverList;
/// <summary>
/// Retriving a list of all available servers
/// </summary>
/// <value>The servers list.</value>
public override List<COM.Configuration.Server.IndexusServerSetting> ServersList
{
get
{
if (serverList == null)
{
serverList = new List<COM.Configuration.Server.IndexusServerSetting>();
foreach (COM.Configuration.Server.IndexusServerSetting server in COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.Servers)
{
serverList.Add(server);
}
}
return serverList;
}
}
#endregion Properties
/// <summary>
/// Distributes the specified to other server nodes.
/// </summary>
/// <param name="msg">The MSG <see cref="IndexusMessage"/></param>
public override void Distribute(IndexusMessage msg)
{
#region Access Log
#if TRACE
{
COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
// very important because if this is not set explizit to
// server mode it will try to access wrong configuration providers
msg.ClientContext = false;
switch (msg.Action)
{
case IndexusMessage.ActionValue.Add:
COM.CacheUtil.Add(msg);
break;
case IndexusMessage.ActionValue.Remove:
COM.CacheUtil.Remove(msg);
break;
//case IndexusMessage.ActionValue.Get:
//case IndexusMessage.ActionValue.GetAllKeys:
//case IndexusMessage.ActionValue.Statistic:
//case IndexusMessage.ActionValue.Error:
//case IndexusMessage.ActionValue.Successful:
//case IndexusMessage.ActionValue.Ping:
//case IndexusMessage.ActionValue.RemoveAll:
//case IndexusMessage.ActionValue.MultiAdd:
//case IndexusMessage.ActionValue.MultiDelete:
//case IndexusMessage.ActionValue.MultiGet:
default:
Handler.LogHandler.Fatal(string.Format("Distribute option '{0}' is not supported!!", msg.Action));
#if DEBUG
Console.WriteLine("Distribute option '{0}' is not supported!!", msg.Action);
#endif
break;
}
}
/// <summary>
/// Pings the specified host.
/// </summary>
/// <param name="host">The host.</param>
/// <returns>
/// if the server is available then it returns true otherwise false.
/// </returns>
public override bool Ping(string host)
{
#region Access Log
#if TRACE
{
COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
try
{
return CacheUtil.Ping(host);
}
catch (Exception)
{
Handler.LogHandler.Fatal(string.Format("Exception: Could not Ping host: '{0}'!!", host));
#if DEBUG
Console.WriteLine("Exception: Could not Ping host: '{0}'!!", host);
#endif
return false;
}
}
/// <summary>
/// Retrieve a list with all key which are available on all cofnigured server nodes.
/// </summary>
/// <param name="host">The host represents the ip address of a server node.</param>
/// <returns>
/// A <see cref="List{T}"/> of strings with all available keys.
/// </returns>
public override List<string> GetAllKeys(string host)
{
#region Access Log
#if TRACE
{
COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
try
{
return CacheUtil.GetAllKeys(host);
}
catch (Exception)
{
Handler.LogHandler.Fatal(string.Format("Exception: Could not run 'GetAllKeys' on host: '{0}'!!", host));
#if DEBUG
Console.WriteLine("Exception: Could not run 'GetAllKeys' on host: '{0}'!!", host);
#endif
return null;
}
}
/// <summary>
/// Based on a list of key's the client receives a dictonary with
/// all available data depending on the keys.
/// </summary>
/// <param name="keys">A List of <see cref="string"/> with all requested keys.</param>
/// <param name="host">The host to request the key's from</param>
/// <returns>
/// A <see cref="IDictionary{TKey,TValue}"/> with <see cref="string"/> and <see cref="byte"/> array element.
/// </returns>
public override IDictionary<string, byte[]> MultiGet(List<string> keys, string host)
{
var result = new Dictionary<string, byte[]>();
using (var msg = new IndexusMessage())
{
msg.Hostname = host;
msg.Key = "MultiGetKeyServerNode2ServerNode";
msg.Action = IndexusMessage.ActionValue.MultiGet;
msg.Payload = Formatters.Serialization.BinarySerialize(keys);
if (CacheUtil.Get(msg) && msg.Payload != null)
{
var partialResult = Formatters.Serialization.BinaryDeSerialize<IDictionary<string, byte[]>>(msg.Payload);
foreach (KeyValuePair<string, byte[]> item in partialResult)
{
result.Add(item.Key, item.Value);
}
}
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IdentityModel.Policy;
using System.Runtime;
using System.Security;
using System.Security.Principal;
using System.ServiceModel;
namespace System.IdentityModel.Claims
{
public class WindowsClaimSet : ClaimSet, IIdentityInfo, IDisposable
{
internal const bool DefaultIncludeWindowsGroups = true;
private WindowsIdentity _windowsIdentity;
private DateTime _expirationTime;
private bool _includeWindowsGroups;
private IList<Claim> _claims;
private bool _disposed = false;
private string _authenticationType;
public WindowsClaimSet(WindowsIdentity windowsIdentity)
: this(windowsIdentity, DefaultIncludeWindowsGroups)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups)
: this(windowsIdentity, includeWindowsGroups, DateTime.UtcNow.AddHours(10))
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, DateTime expirationTime)
: this(windowsIdentity, DefaultIncludeWindowsGroups, expirationTime)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, bool includeWindowsGroups, DateTime expirationTime)
: this(windowsIdentity, null, includeWindowsGroups, expirationTime, true)
{
}
public WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime)
: this(windowsIdentity, authenticationType, includeWindowsGroups, expirationTime, true)
{
}
internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, bool clone)
: this(windowsIdentity, authenticationType, includeWindowsGroups, DateTime.UtcNow.AddHours(10), clone)
{
}
internal WindowsClaimSet(WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime, bool clone)
{
if (windowsIdentity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity");
_windowsIdentity = clone ? SecurityUtils.CloneWindowsIdentityIfNecessary(windowsIdentity, authenticationType) : windowsIdentity;
_includeWindowsGroups = includeWindowsGroups;
_expirationTime = expirationTime;
_authenticationType = authenticationType;
}
private WindowsClaimSet(WindowsClaimSet from)
: this(from.WindowsIdentity, from._authenticationType, from._includeWindowsGroups, from._expirationTime, true)
{
}
public override Claim this[int index]
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims[index];
}
}
public override int Count
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims.Count;
}
}
IIdentity IIdentityInfo.Identity
{
get
{
ThrowIfDisposed();
return _windowsIdentity;
}
}
public WindowsIdentity WindowsIdentity
{
get
{
ThrowIfDisposed();
return _windowsIdentity;
}
}
public override ClaimSet Issuer
{
get { return ClaimSet.Windows; }
}
public DateTime ExpirationTime
{
get { return _expirationTime; }
}
internal WindowsClaimSet Clone()
{
ThrowIfDisposed();
return new WindowsClaimSet(this);
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
_windowsIdentity.Dispose();
}
}
private IList<Claim> InitializeClaimsCore()
{
if (_windowsIdentity.AccessToken == null)
return new List<Claim>();
List<Claim> claims = new List<Claim>(3);
claims.Add(new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity));
Claim claim;
if (TryCreateWindowsSidClaim(_windowsIdentity, out claim))
{
claims.Add(claim);
}
claims.Add(Claim.CreateNameClaim(_windowsIdentity.Name));
if (_includeWindowsGroups)
{
// claims.AddRange(Groups);
}
return claims;
}
private void EnsureClaims()
{
if (_claims != null)
return;
_claims = InitializeClaimsCore();
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
private static bool SupportedClaimType(string claimType)
{
return claimType == null ||
ClaimTypes.Sid == claimType ||
ClaimTypes.DenyOnlySid == claimType ||
ClaimTypes.Name == claimType;
}
// Note: null string represents any.
public override IEnumerable<Claim> FindClaims(string claimType, string right)
{
ThrowIfDisposed();
if (!SupportedClaimType(claimType) || !ClaimSet.SupportedRight(right))
{
yield break;
}
else if (_claims == null && (ClaimTypes.Sid == claimType || ClaimTypes.DenyOnlySid == claimType))
{
if (ClaimTypes.Sid == claimType)
{
if (right == null || Rights.Identity == right)
{
yield return new Claim(ClaimTypes.Sid, _windowsIdentity.User, Rights.Identity);
}
}
if (right == null || Rights.PossessProperty == right)
{
Claim sid;
if (TryCreateWindowsSidClaim(_windowsIdentity, out sid))
{
if (claimType == sid.ClaimType)
{
yield return sid;
}
}
}
if (_includeWindowsGroups && (right == null || Rights.PossessProperty == right))
{
// Not sure yet if GroupSidClaimCollections are necessary in .NET Core, but default
// _includeWindowsGroups is true; don't throw here or we bust the default case on UWP/.NET Core
}
}
else
{
EnsureClaims();
bool anyClaimType = (claimType == null);
bool anyRight = (right == null);
for (int i = 0; i < _claims.Count; ++i)
{
Claim claim = _claims[i];
if ((claim != null) &&
(anyClaimType || claimType == claim.ClaimType) &&
(anyRight || right == claim.Right))
{
yield return claim;
}
}
}
}
public override IEnumerator<Claim> GetEnumerator()
{
ThrowIfDisposed();
EnsureClaims();
return _claims.GetEnumerator();
}
public override string ToString()
{
return _disposed ? base.ToString() : SecurityUtils.ClaimSetToString(this);
}
public static bool TryCreateWindowsSidClaim(WindowsIdentity windowsIdentity, out Claim claim)
{
throw ExceptionHelper.PlatformNotSupported("CreateWindowsSidClaim is not yet supported");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using EasyGenerator.Studio.DbHelper.Info;
using EasyGenerator.Studio.Model;
using EasyGenerator.Studio.Model.DB;
using System.Dynamic;
namespace EasyGenerator.Studio.DbHelper.MSSQL
{
public class MSSQLSchemaExtractor : ISchemaExtractor
{
private Hashtable dataTypeMapping = new Hashtable(30);
public MSSQLSchemaExtractor(Driver driver)
: base(driver)
{
dataTypeMapping.Add("bigint", SqlType.BigInt);
dataTypeMapping.Add("varbinary", SqlType.VarBinary);
dataTypeMapping.Add("binary", SqlType.VarBinary);
dataTypeMapping.Add("bit", SqlType.Bit);
dataTypeMapping.Add("char", SqlType.Char);
dataTypeMapping.Add("date", SqlType.Date);
dataTypeMapping.Add("datetime", SqlType.DateTime);
dataTypeMapping.Add("datetime2", SqlType.DateTime2);
dataTypeMapping.Add("datetimeoffset", SqlType.DateTimeOffset);
dataTypeMapping.Add("decimal", SqlType.Decimal);
dataTypeMapping.Add("varbinary(max)", SqlType.VarBinary);
dataTypeMapping.Add("float", SqlType.Float);
dataTypeMapping.Add("image", SqlType.Binary);
dataTypeMapping.Add("int", SqlType.Int);
dataTypeMapping.Add("money", SqlType.Money);
dataTypeMapping.Add("nchar", SqlType.NChar);
dataTypeMapping.Add("ntext", SqlType.NText);
dataTypeMapping.Add("numeric", SqlType.Decimal);
dataTypeMapping.Add("varchar", SqlType.VarChar);
dataTypeMapping.Add("nvarchar", SqlType.NVarChar);
dataTypeMapping.Add("real", SqlType.Real);
dataTypeMapping.Add("rowversion", SqlType.Timestamp);
dataTypeMapping.Add("smalldatetime", SqlType.DateTime);
dataTypeMapping.Add("smallint", SqlType.SmallInt);
dataTypeMapping.Add("smallmoney", SqlType.SmallMoney);
dataTypeMapping.Add("sql_variant", SqlType.Variant);
dataTypeMapping.Add("text", SqlType.Text);
dataTypeMapping.Add("time", SqlType.Time);
dataTypeMapping.Add("timestamp", SqlType.Timestamp);
}
public override IDictionary<string, EntityModel> GetAllTables()
{
IDictionary<string, EntityModel> entities = new Dictionary<string, EntityModel>(0);
IDbCommand cmd = this.driver.CreateCommand();
cmd.Connection.Open();
cmd.CommandText = "SELECT TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_SCHEMA,TABLE_NAME";
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string owner = reader["TABLE_CATALOG"].ToString();
if (owner.Equals("INFORMATION_SCHEMA", StringComparison.CurrentCultureIgnoreCase) || owner.Equals("sys", StringComparison.CurrentCultureIgnoreCase))
{
continue;
}
entities.Add(reader["TABLE_NAME"].ToString(), new EntityModel() { TableName = reader["TABLE_NAME"].ToString(), TableCatalog = reader["TABLE_CATALOG"].ToString(), TableSchema = reader["TABLE_SCHEMA"].ToString() });
}
}
return entities;
}
public override IDictionary<string, EntityModel> GetAllViews()
{
IDictionary<string, EntityModel> entities = new Dictionary<string, EntityModel>(0);
IDbCommand cmd = this.driver.CreateCommand();
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
}
cmd.CommandText = "SELECT TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'VIEW' ORDER BY TABLE_SCHEMA,TABLE_NAME";
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string owner = reader["TABLE_CATALOG"].ToString();
if (owner.Equals("INFORMATION_SCHEMA", StringComparison.CurrentCultureIgnoreCase) || owner.Equals("sys", StringComparison.CurrentCultureIgnoreCase))
{
continue;
}
entities.Add(reader["TABLE_NAME"].ToString(), new EntityModel() { TableName = reader["TABLE_NAME"].ToString(), TableCatalog = reader["TABLE_CATALOG"].ToString(), TableSchema = reader["TABLE_SCHEMA"].ToString() });
}
}
return entities;
}
public override IDictionary<string, ColumnModel> GetColumns()
{
IDictionary<string, ColumnModel> entities = new Dictionary<string, ColumnModel>();
IDbCommand cmd = this.driver.CreateCommand();
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
}
cmd.CommandText = "Select COLUMN_NAME, DATA_TYPE, IS_NULLABLE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, CHARACTER_SET_NAME, COLLATION_NAME, TABLE_NAME, COLUMNPROPERTY(OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity') as IS_IDENTITY " +
" from INFORMATION_SCHEMA.COLUMNS "+
" order by ORDINAL_POSITION";
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
ColumnModel model = new ColumnModel();
model.ColumnName = reader["COLUMN_NAME"].ToString();
model.DataType = (SqlType)dataTypeMapping[reader["DATA_TYPE"].ToString()];
model.Nullable = reader["IS_NULLABLE"].ToString() == "YES";
model.Length = (reader["CHARACTER_MAXIMUM_LENGTH"].GetType() == typeof(DBNull)) ? 0 : int.Parse(reader["CHARACTER_MAXIMUM_LENGTH"].ToString());
model.Precision = (reader["NUMERIC_PRECISION"].GetType() == typeof(DBNull)) ? 0 : int.Parse(reader["NUMERIC_PRECISION"].ToString());
model.Scale = (reader["NUMERIC_SCALE"].GetType() == typeof(DBNull)) ? 0 : int.Parse(reader["NUMERIC_SCALE"].ToString());
model.TableName = reader["TABLE_NAME"].ToString();
model.IsIdentity = (int)reader["IS_IDENTITY"]==1;
entities.Add(reader["COLUMN_NAME"].ToString() + "-" + reader["TABLE_NAME"].ToString(), model);
}
}
return entities;
}
public override IDictionary<string, ForgeinKeyModel> GetAllForeignKeys()
{
IDictionary<string, ForgeinKeyModel> entities = new Dictionary<string, ForgeinKeyModel>();
IDbCommand cmd = this.driver.CreateCommand();
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
}
cmd.CommandText = "select "+
"INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE.CONSTRAINT_NAME,"+
"INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE.TABLE_NAME,"+
"INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE.COLUMN_NAME,"+
"INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME as REFERECING_TABLE_NAME," +
"unique_usage.COLUMN_NAME AS REFERENCING_COLUMN_NAME " +
"from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE "+
"inner join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS "+
"on "+
"INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE.CONSTRAINT_NAME = "+
"INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS.CONSTRAINT_NAME "+
"inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS "+
"on "+
"INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME = "+
"INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS.UNIQUE_CONSTRAINT_NAME "+
"inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE unique_usage "+
"on "+
"INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME = "+
"unique_usage.CONSTRAINT_NAME";
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string constraintName = reader["CONSTRAINT_NAME"].ToString();
string tableName = reader["TABLE_NAME"].ToString();
string columnName = reader["COLUMN_NAME"].ToString();
string referecingTableName = reader["REFERECING_TABLE_NAME"].ToString();
string referencingColumnName = reader["REFERENCING_COLUMN_NAME"].ToString();
entities.Add(constraintName, new ForgeinKeyModel { ConstraintName = constraintName, ColumnName = columnName, TableName = tableName, ReferecingTableName = referecingTableName, ReferencingColumnName = referencingColumnName });
}
}
return entities;
}
public override IDictionary<string,PrimaryKeyModel> GetAllPrimaryKeys()
{
IDictionary<string, PrimaryKeyModel> entities = new Dictionary<string,PrimaryKeyModel>();
IDbCommand cmd = this.driver.CreateCommand();
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
}
cmd.CommandText = "select kcu.TABLE_SCHEMA, kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, tc.CONSTRAINT_TYPE, kcu.COLUMN_NAME, kcu.ORDINAL_POSITION " +
" from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc " +
" join INFORMATION_SCHEMA.KEY_COLUMN_USAGE as kcu " +
" on kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA " +
" and kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME " +
" and kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA " +
" and kcu.TABLE_NAME = tc.TABLE_NAME " +
" where tc.CONSTRAINT_TYPE in ( 'PRIMARY KEY') " +
" order by kcu.TABLE_SCHEMA, kcu.TABLE_NAME, tc.CONSTRAINT_TYPE, kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION";
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string constraintName = reader["CONSTRAINT_NAME"].ToString();
string tableName = reader["TABLE_NAME"].ToString();
string columnName = reader["COLUMN_NAME"].ToString();
entities.Add(constraintName + "-" + columnName, new PrimaryKeyModel { ConstraintName = constraintName, ColumnName = columnName, TableName = tableName });
}
}
return entities;
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Tpu.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedTpuClientTest
{
[xunit::FactAttribute]
public void GetNodeRequestObject()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeRequest request = new GetNodeRequest
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
};
Node expectedResponse = new Node
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
Description = "description2cf9da67",
AcceleratorType = "accelerator_type68a25f42",
#pragma warning disable CS0612
IpAddress = "ip_address46a72553",
#pragma warning restore CS0612
State = Node.Types.State.Restarting,
HealthDescription = "health_descriptionb522cddb",
TensorflowVersion = "tensorflow_version878dc75b",
Network = "networkd22ce091",
CidrBlock = "cidr_block0fc04814",
#pragma warning disable CS0612
Port = "portfb551590",
#pragma warning restore CS0612
ServiceAccount = "service_accounta3c1b923",
CreateTime = new wkt::Timestamp(),
SchedulingConfig = new SchedulingConfig(),
NetworkEndpoints =
{
new NetworkEndpoint(),
},
Health = Node.Types.Health.UnhealthyMaintenance,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
UseServiceNetworking = true,
ApiVersion = Node.Types.ApiVersion.V2Alpha1,
Symptoms = { new Symptom(), },
};
mockGrpcClient.Setup(x => x.GetNode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
Node response = client.GetNode(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetNodeRequestObjectAsync()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeRequest request = new GetNodeRequest
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
};
Node expectedResponse = new Node
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
Description = "description2cf9da67",
AcceleratorType = "accelerator_type68a25f42",
#pragma warning disable CS0612
IpAddress = "ip_address46a72553",
#pragma warning restore CS0612
State = Node.Types.State.Restarting,
HealthDescription = "health_descriptionb522cddb",
TensorflowVersion = "tensorflow_version878dc75b",
Network = "networkd22ce091",
CidrBlock = "cidr_block0fc04814",
#pragma warning disable CS0612
Port = "portfb551590",
#pragma warning restore CS0612
ServiceAccount = "service_accounta3c1b923",
CreateTime = new wkt::Timestamp(),
SchedulingConfig = new SchedulingConfig(),
NetworkEndpoints =
{
new NetworkEndpoint(),
},
Health = Node.Types.Health.UnhealthyMaintenance,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
UseServiceNetworking = true,
ApiVersion = Node.Types.ApiVersion.V2Alpha1,
Symptoms = { new Symptom(), },
};
mockGrpcClient.Setup(x => x.GetNodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Node>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
Node responseCallSettings = await client.GetNodeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Node responseCancellationToken = await client.GetNodeAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetNode()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeRequest request = new GetNodeRequest
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
};
Node expectedResponse = new Node
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
Description = "description2cf9da67",
AcceleratorType = "accelerator_type68a25f42",
#pragma warning disable CS0612
IpAddress = "ip_address46a72553",
#pragma warning restore CS0612
State = Node.Types.State.Restarting,
HealthDescription = "health_descriptionb522cddb",
TensorflowVersion = "tensorflow_version878dc75b",
Network = "networkd22ce091",
CidrBlock = "cidr_block0fc04814",
#pragma warning disable CS0612
Port = "portfb551590",
#pragma warning restore CS0612
ServiceAccount = "service_accounta3c1b923",
CreateTime = new wkt::Timestamp(),
SchedulingConfig = new SchedulingConfig(),
NetworkEndpoints =
{
new NetworkEndpoint(),
},
Health = Node.Types.Health.UnhealthyMaintenance,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
UseServiceNetworking = true,
ApiVersion = Node.Types.ApiVersion.V2Alpha1,
Symptoms = { new Symptom(), },
};
mockGrpcClient.Setup(x => x.GetNode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
Node response = client.GetNode(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetNodeAsync()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeRequest request = new GetNodeRequest
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
};
Node expectedResponse = new Node
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
Description = "description2cf9da67",
AcceleratorType = "accelerator_type68a25f42",
#pragma warning disable CS0612
IpAddress = "ip_address46a72553",
#pragma warning restore CS0612
State = Node.Types.State.Restarting,
HealthDescription = "health_descriptionb522cddb",
TensorflowVersion = "tensorflow_version878dc75b",
Network = "networkd22ce091",
CidrBlock = "cidr_block0fc04814",
#pragma warning disable CS0612
Port = "portfb551590",
#pragma warning restore CS0612
ServiceAccount = "service_accounta3c1b923",
CreateTime = new wkt::Timestamp(),
SchedulingConfig = new SchedulingConfig(),
NetworkEndpoints =
{
new NetworkEndpoint(),
},
Health = Node.Types.Health.UnhealthyMaintenance,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
UseServiceNetworking = true,
ApiVersion = Node.Types.ApiVersion.V2Alpha1,
Symptoms = { new Symptom(), },
};
mockGrpcClient.Setup(x => x.GetNodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Node>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
Node responseCallSettings = await client.GetNodeAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Node responseCancellationToken = await client.GetNodeAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetNodeResourceNames()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeRequest request = new GetNodeRequest
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
};
Node expectedResponse = new Node
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
Description = "description2cf9da67",
AcceleratorType = "accelerator_type68a25f42",
#pragma warning disable CS0612
IpAddress = "ip_address46a72553",
#pragma warning restore CS0612
State = Node.Types.State.Restarting,
HealthDescription = "health_descriptionb522cddb",
TensorflowVersion = "tensorflow_version878dc75b",
Network = "networkd22ce091",
CidrBlock = "cidr_block0fc04814",
#pragma warning disable CS0612
Port = "portfb551590",
#pragma warning restore CS0612
ServiceAccount = "service_accounta3c1b923",
CreateTime = new wkt::Timestamp(),
SchedulingConfig = new SchedulingConfig(),
NetworkEndpoints =
{
new NetworkEndpoint(),
},
Health = Node.Types.Health.UnhealthyMaintenance,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
UseServiceNetworking = true,
ApiVersion = Node.Types.ApiVersion.V2Alpha1,
Symptoms = { new Symptom(), },
};
mockGrpcClient.Setup(x => x.GetNode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
Node response = client.GetNode(request.NodeName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetNodeResourceNamesAsync()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNodeRequest request = new GetNodeRequest
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
};
Node expectedResponse = new Node
{
NodeName = NodeName.FromProjectLocationNode("[PROJECT]", "[LOCATION]", "[NODE]"),
Description = "description2cf9da67",
AcceleratorType = "accelerator_type68a25f42",
#pragma warning disable CS0612
IpAddress = "ip_address46a72553",
#pragma warning restore CS0612
State = Node.Types.State.Restarting,
HealthDescription = "health_descriptionb522cddb",
TensorflowVersion = "tensorflow_version878dc75b",
Network = "networkd22ce091",
CidrBlock = "cidr_block0fc04814",
#pragma warning disable CS0612
Port = "portfb551590",
#pragma warning restore CS0612
ServiceAccount = "service_accounta3c1b923",
CreateTime = new wkt::Timestamp(),
SchedulingConfig = new SchedulingConfig(),
NetworkEndpoints =
{
new NetworkEndpoint(),
},
Health = Node.Types.Health.UnhealthyMaintenance,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
UseServiceNetworking = true,
ApiVersion = Node.Types.ApiVersion.V2Alpha1,
Symptoms = { new Symptom(), },
};
mockGrpcClient.Setup(x => x.GetNodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Node>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
Node responseCallSettings = await client.GetNodeAsync(request.NodeName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Node responseCancellationToken = await client.GetNodeAsync(request.NodeName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTensorFlowVersionRequestObject()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTensorFlowVersionRequest request = new GetTensorFlowVersionRequest
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
};
TensorFlowVersion expectedResponse = new TensorFlowVersion
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTensorFlowVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
TensorFlowVersion response = client.GetTensorFlowVersion(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTensorFlowVersionRequestObjectAsync()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTensorFlowVersionRequest request = new GetTensorFlowVersionRequest
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
};
TensorFlowVersion expectedResponse = new TensorFlowVersion
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTensorFlowVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TensorFlowVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
TensorFlowVersion responseCallSettings = await client.GetTensorFlowVersionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TensorFlowVersion responseCancellationToken = await client.GetTensorFlowVersionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTensorFlowVersion()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTensorFlowVersionRequest request = new GetTensorFlowVersionRequest
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
};
TensorFlowVersion expectedResponse = new TensorFlowVersion
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTensorFlowVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
TensorFlowVersion response = client.GetTensorFlowVersion(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTensorFlowVersionAsync()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTensorFlowVersionRequest request = new GetTensorFlowVersionRequest
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
};
TensorFlowVersion expectedResponse = new TensorFlowVersion
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTensorFlowVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TensorFlowVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
TensorFlowVersion responseCallSettings = await client.GetTensorFlowVersionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TensorFlowVersion responseCancellationToken = await client.GetTensorFlowVersionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTensorFlowVersionResourceNames()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTensorFlowVersionRequest request = new GetTensorFlowVersionRequest
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
};
TensorFlowVersion expectedResponse = new TensorFlowVersion
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTensorFlowVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
TensorFlowVersion response = client.GetTensorFlowVersion(request.TensorFlowVersionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTensorFlowVersionResourceNamesAsync()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTensorFlowVersionRequest request = new GetTensorFlowVersionRequest
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
};
TensorFlowVersion expectedResponse = new TensorFlowVersion
{
TensorFlowVersionName = TensorFlowVersionName.FromProjectLocationTensorFlowVersion("[PROJECT]", "[LOCATION]", "[TENSOR_FLOW_VERSION]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTensorFlowVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TensorFlowVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
TensorFlowVersion responseCallSettings = await client.GetTensorFlowVersionAsync(request.TensorFlowVersionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TensorFlowVersion responseCancellationToken = await client.GetTensorFlowVersionAsync(request.TensorFlowVersionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAcceleratorTypeRequestObject()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAcceleratorTypeRequest request = new GetAcceleratorTypeRequest
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
};
AcceleratorType expectedResponse = new AcceleratorType
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
Type = "typee2cc9d59",
};
mockGrpcClient.Setup(x => x.GetAcceleratorType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
AcceleratorType response = client.GetAcceleratorType(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAcceleratorTypeRequestObjectAsync()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAcceleratorTypeRequest request = new GetAcceleratorTypeRequest
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
};
AcceleratorType expectedResponse = new AcceleratorType
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
Type = "typee2cc9d59",
};
mockGrpcClient.Setup(x => x.GetAcceleratorTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AcceleratorType>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
AcceleratorType responseCallSettings = await client.GetAcceleratorTypeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AcceleratorType responseCancellationToken = await client.GetAcceleratorTypeAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAcceleratorType()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAcceleratorTypeRequest request = new GetAcceleratorTypeRequest
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
};
AcceleratorType expectedResponse = new AcceleratorType
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
Type = "typee2cc9d59",
};
mockGrpcClient.Setup(x => x.GetAcceleratorType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
AcceleratorType response = client.GetAcceleratorType(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAcceleratorTypeAsync()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAcceleratorTypeRequest request = new GetAcceleratorTypeRequest
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
};
AcceleratorType expectedResponse = new AcceleratorType
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
Type = "typee2cc9d59",
};
mockGrpcClient.Setup(x => x.GetAcceleratorTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AcceleratorType>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
AcceleratorType responseCallSettings = await client.GetAcceleratorTypeAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AcceleratorType responseCancellationToken = await client.GetAcceleratorTypeAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAcceleratorTypeResourceNames()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAcceleratorTypeRequest request = new GetAcceleratorTypeRequest
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
};
AcceleratorType expectedResponse = new AcceleratorType
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
Type = "typee2cc9d59",
};
mockGrpcClient.Setup(x => x.GetAcceleratorType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
AcceleratorType response = client.GetAcceleratorType(request.AcceleratorTypeName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAcceleratorTypeResourceNamesAsync()
{
moq::Mock<Tpu.TpuClient> mockGrpcClient = new moq::Mock<Tpu.TpuClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetAcceleratorTypeRequest request = new GetAcceleratorTypeRequest
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
};
AcceleratorType expectedResponse = new AcceleratorType
{
AcceleratorTypeName = AcceleratorTypeName.FromProjectLocationAcceleratorType("[PROJECT]", "[LOCATION]", "[ACCELERATOR_TYPE]"),
Type = "typee2cc9d59",
};
mockGrpcClient.Setup(x => x.GetAcceleratorTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AcceleratorType>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TpuClient client = new TpuClientImpl(mockGrpcClient.Object, null);
AcceleratorType responseCallSettings = await client.GetAcceleratorTypeAsync(request.AcceleratorTypeName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AcceleratorType responseCancellationToken = await client.GetAcceleratorTypeAsync(request.AcceleratorTypeName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
namespace System.Net.NetworkInformation {
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using Microsoft.Win32.SafeHandles;
internal class IpHelperErrors {
internal const uint Success = 0;
internal const uint ErrorInvalidFunction = 1;
internal const uint ErrorNoSuchDevice = 2;
internal const uint ErrorInvalidData= 13;
internal const uint ErrorInvalidParameter = 87;
internal const uint ErrorBufferOverflow = 111;
internal const uint ErrorInsufficientBuffer = 122;
internal const uint ErrorNoData= 232;
internal const uint Pending = 997;
internal const uint ErrorNotFound = 1168;
}
//
// Per-adapter Flags
//
[Flags]
internal enum AdapterFlags {
DnsEnabled= 0x01,
RegisterAdapterSuffix= 0x02,
DhcpEnabled = 0x04,
ReceiveOnly = 0x08,
NoMulticast= 0x10,
Ipv6OtherStatefulConfig= 0x20,
// Vista+
NetBiosOverTcp = 0x40,
IPv4Enabled = 0x80,
IPv6Enabled = 0x100,
IPv6ManagedAddressConfigurationSupported = 0x200,
};
[Flags]
internal enum AdapterAddressFlags{
DnsEligible = 0x1,
Transient = 0x2
}
internal enum OldOperationalStatus{
NonOperational =0,
Unreachable =1,
Disconnected =2,
Connecting =3,
Connected =4,
Operational =5
}
[Flags]
internal enum GetAdaptersAddressesFlags
{
SkipUnicast = 0x0001,
SkipAnycast = 0x0002,
SkipMulticast = 0x0004,
SkipDnsServer = 0x0008,
IncludePrefix = 0x0010,
SkipFriendlyName = 0x0020,
IncludeWins = 0x0040,
IncludeGateways = 0x0080,
IncludeAllInterfaces = 0x0100,
IncludeAllCompartments = 0x0200,
IncludeTunnelBindingOrder = 0x0400,
}
/// <summary>
/// IpAddressList - store an IP address with its corresponding subnet mask,
/// both as dotted decimal strings
/// </summary>
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
internal struct IpAddrString {
internal IntPtr Next; /* struct _IpAddressList* */
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=16)]
internal string IpAddress;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=16)]
internal string IpMask;
internal uint Context;
};
/// <summary>
/// Core network information.
/// </summary>
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
internal struct FIXED_INFO {
internal const int MAX_HOSTNAME_LEN = 128;
internal const int MAX_DOMAIN_NAME_LEN = 128;
internal const int MAX_SCOPE_ID_LEN = 256;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=MAX_HOSTNAME_LEN + 4)]
internal string hostName;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=MAX_DOMAIN_NAME_LEN + 4)]
internal string domainName;
internal uint currentDnsServer; /* IpAddressList* */
internal IpAddrString DnsServerList;
internal NetBiosNodeType nodeType;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=MAX_SCOPE_ID_LEN + 4)]
internal string scopeId;
internal bool enableRouting;
internal bool enableProxy;
internal bool enableDns;
};
[StructLayout(LayoutKind.Sequential)]
internal struct IpSocketAddress {
internal IntPtr address;
internal int addressLength;
internal IPAddress MarshalIPAddress() {
// Determine the address family used to create the IPAddress
AddressFamily family = (addressLength > SocketAddress.IPv4AddressSize)
? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
SocketAddress sockAddress = new SocketAddress(family, addressLength);
Marshal.Copy(address, sockAddress.m_Buffer, 0, addressLength);
return sockAddress.GetIPAddress();
}
}
// IP_ADAPTER_ANYCAST_ADDRESS
// IP_ADAPTER_MULTICAST_ADDRESS
// IP_ADAPTER_DNS_SERVER_ADDRESS
// IP_ADAPTER_WINS_SERVER_ADDRESS
// IP_ADAPTER_GATEWAY_ADDRESS
[StructLayout(LayoutKind.Sequential)]
internal struct IpAdapterAddress {
internal uint length;
internal AdapterAddressFlags flags;
internal IntPtr next;
internal IpSocketAddress address;
internal static IPAddressCollection MarshalIpAddressCollection(IntPtr ptr) {
IPAddressCollection addressList = new IPAddressCollection();
while (ptr != IntPtr.Zero) {
IpAdapterAddress addressStructure =
(IpAdapterAddress)Marshal.PtrToStructure(ptr, typeof(IpAdapterAddress));
IPAddress address = addressStructure.address.MarshalIPAddress();
addressList.InternalAdd(address);
ptr = addressStructure.next;
}
return addressList;
}
internal static IPAddressInformationCollection MarshalIpAddressInformationCollection(IntPtr ptr) {
IPAddressInformationCollection addressList = new IPAddressInformationCollection();
while (ptr != IntPtr.Zero) {
IpAdapterAddress addressStructure =
(IpAdapterAddress)Marshal.PtrToStructure(ptr, typeof(IpAdapterAddress));
IPAddress address = addressStructure.address.MarshalIPAddress();
addressList.InternalAdd(new SystemIPAddressInformation(address, addressStructure.flags));
ptr = addressStructure.next;
}
return addressList;
}
}
// Vista+
[StructLayout(LayoutKind.Sequential)]
internal struct IpAdapterUnicastAddress {
internal uint length;
internal AdapterAddressFlags flags;
internal IntPtr next;
internal IpSocketAddress address;
internal PrefixOrigin prefixOrigin;
internal SuffixOrigin suffixOrigin;
internal DuplicateAddressDetectionState dadState;
internal uint validLifetime;
internal uint preferredLifetime;
internal uint leaseLifetime;
internal byte prefixLength;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct IpAdapterAddresses {
internal const int MAX_ADAPTER_ADDRESS_LENGTH = 8;
internal uint length;
internal uint index;
internal IntPtr next;
// Needs to be ANSI
[MarshalAs(UnmanagedType.LPStr)]
internal string AdapterName;
internal IntPtr firstUnicastAddress;
internal IntPtr firstAnycastAddress;
internal IntPtr firstMulticastAddress;
internal IntPtr firstDnsServerAddress;
internal string dnsSuffix;
internal string description;
internal string friendlyName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_ADAPTER_ADDRESS_LENGTH)]
internal byte[] address;
internal uint addressLength;
internal AdapterFlags flags;
internal uint mtu;
internal NetworkInterfaceType type;
internal OperationalStatus operStatus;
internal uint ipv6Index;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
internal uint[] zoneIndices;
internal IntPtr firstPrefix;
/* Vista+ */
internal UInt64 transmitLinkSpeed;
internal UInt64 receiveLinkSpeed;
internal IntPtr firstWinsServerAddress;
internal IntPtr firstGatewayAddress;
internal UInt32 ipv4Metric;
internal UInt32 ipv6Metric;
internal UInt64 luid;
internal IpSocketAddress dhcpv4Server;
internal UInt32 compartmentId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
internal byte[] networkGuid;
internal InterfaceConnectionType connectionType;
internal InterfaceTunnelType tunnelType;
internal IpSocketAddress dhcpv6Server; // Never available in Windows.
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 130)]
internal byte[] dhcpv6ClientDuid;
internal UInt32 dhcpv6ClientDuidLength;
internal UInt32 dhcpV6Iaid;
/* Windows 2008 +
PIP_ADAPTER_DNS_SUFFIX FirstDnsSuffix;
* */
}
internal enum InterfaceConnectionType : int {
Dedicated = 1,
Passive = 2,
Demand = 3,
Maximum = 4,
}
internal enum InterfaceTunnelType : int {
None = 0,
Other = 1,
Direct = 2,
SixToFour = 11,
Isatap = 13,
Teredo = 14,
IpHttps = 15,
}
/// <summary>
/// IP_PER_ADAPTER_INFO - per-adapter IP information such as DNS server list.
/// </summary>
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
internal struct IpPerAdapterInfo {
internal bool autoconfigEnabled;
internal bool autoconfigActive;
internal IntPtr currentDnsServer; /* IpAddressList* */
internal IpAddrString dnsServerList;
};
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]
internal struct MibIfRow2 // MIB_IF_ROW2
{
private const int GuidLength = 16;
private const int IfMaxStringSize = 256;
private const int IfMaxPhysAddressLength = 32;
internal UInt64 interfaceLuid;
internal UInt32 interfaceIndex;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GuidLength)]
internal byte[] interfaceGuid;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxStringSize + 1)]
internal char[] alias; // Null terminated string
[MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxStringSize + 1)]
internal char[] description; // Null terminated string
internal UInt32 physicalAddressLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxPhysAddressLength)]
internal byte[] physicalAddress; // ANSI
[MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxPhysAddressLength)]
internal byte[] permanentPhysicalAddress; // ANSI
internal UInt32 mtu;
internal NetworkInterfaceType type;
internal InterfaceTunnelType tunnelType;
internal UInt32 mediaType; // Enum
internal UInt32 physicalMediumType; // Enum
internal UInt32 accessType; // Enum
internal UInt32 directionType; // Enum
internal byte interfaceAndOperStatusFlags; // Flags Enum
internal OperationalStatus operStatus;
internal UInt32 adminStatus; // Enum
internal UInt32 mediaConnectState; // Enum
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GuidLength)]
internal byte[] networkGuid;
internal InterfaceConnectionType connectionType;
internal UInt64 transmitLinkSpeed;
internal UInt64 receiveLinkSpeed;
internal UInt64 inOctets;
internal UInt64 inUcastPkts;
internal UInt64 inNUcastPkts;
internal UInt64 inDiscards;
internal UInt64 inErrors;
internal UInt64 inUnknownProtos;
internal UInt64 inUcastOctets;
internal UInt64 inMulticastOctets;
internal UInt64 inBroadcastOctets;
internal UInt64 outOctets;
internal UInt64 outUcastPkts;
internal UInt64 outNUcastPkts;
internal UInt64 outDiscards;
internal UInt64 outErrors;
internal UInt64 outUcastOctets;
internal UInt64 outMulticastOctets;
internal UInt64 outBroadcastOctets;
internal UInt64 outQLen;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibUdpStats {
internal uint datagramsReceived;
internal uint incomingDatagramsDiscarded;
internal uint incomingDatagramsWithErrors;
internal uint datagramsSent;
internal uint udpListeners;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibTcpStats {
internal uint reTransmissionAlgorithm;
internal uint minimumRetransmissionTimeOut;
internal uint maximumRetransmissionTimeOut;
internal uint maximumConnections;
internal uint activeOpens;
internal uint passiveOpens;
internal uint failedConnectionAttempts;
internal uint resetConnections;
internal uint currentConnections;
internal uint segmentsReceived;
internal uint segmentsSent;
internal uint segmentsResent;
internal uint errorsReceived;
internal uint segmentsSentWithReset;
internal uint cumulativeConnections;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibIpStats {
internal bool forwardingEnabled;
internal uint defaultTtl;
internal uint packetsReceived;
internal uint receivedPacketsWithHeaderErrors;
internal uint receivedPacketsWithAddressErrors;
internal uint packetsForwarded;
internal uint receivedPacketsWithUnknownProtocols;
internal uint receivedPacketsDiscarded;
internal uint receivedPacketsDelivered;
internal uint packetOutputRequests;
internal uint outputPacketRoutingDiscards;
internal uint outputPacketsDiscarded;
internal uint outputPacketsWithNoRoute;
internal uint packetReassemblyTimeout;
internal uint packetsReassemblyRequired;
internal uint packetsReassembled;
internal uint packetsReassemblyFailed;
internal uint packetsFragmented;
internal uint packetsFragmentFailed;
internal uint packetsFragmentCreated;
internal uint interfaces;
internal uint ipAddresses;
internal uint routes;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibIcmpInfo {
internal MibIcmpStats inStats;
internal MibIcmpStats outStats;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibIcmpStats {
internal uint messages;
internal uint errors;
internal uint destinationUnreachables;
internal uint timeExceeds;
internal uint parameterProblems;
internal uint sourceQuenches;
internal uint redirects;
internal uint echoRequests;
internal uint echoReplies;
internal uint timestampRequests;
internal uint timestampReplies;
internal uint addressMaskRequests;
internal uint addressMaskReplies;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibIcmpInfoEx {
internal MibIcmpStatsEx inStats;
internal MibIcmpStatsEx outStats;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibIcmpStatsEx {
internal uint dwMsgs;
internal uint dwErrors;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=256)]
internal uint[] rgdwTypeCount;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibTcpTable {
internal uint numberOfEntries;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibTcpRow {
internal TcpState state;
internal uint localAddr;
internal byte localPort1;
internal byte localPort2;
// Ports are only 16 bit values (in network WORD order, 3,4,1,2).
// There are reports where the high order bytes have garbage in them.
internal byte ignoreLocalPort3;
internal byte ignoreLocalPort4;
internal uint remoteAddr;
internal byte remotePort1;
internal byte remotePort2;
// Ports are only 16 bit values (in network WORD order, 3,4,1,2).
// There are reports where the high order bytes have garbage in them.
internal byte ignoreRemotePort3;
internal byte ignoreRemotePort4;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibTcp6TableOwnerPid {
internal uint numberOfEntries;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibTcp6RowOwnerPid {
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
internal byte[] localAddr;
internal uint localScopeId;
internal byte localPort1;
internal byte localPort2;
// Ports are only 16 bit values (in network WORD order, 3,4,1,2).
// There are reports where the high order bytes have garbage in them.
internal byte ignoreLocalPort3;
internal byte ignoreLocalPort4;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
internal byte[] remoteAddr;
internal uint remoteScopeId;
internal byte remotePort1;
internal byte remotePort2;
// Ports are only 16 bit values (in network WORD order, 3,4,1,2).
// There are reports where the high order bytes have garbage in them.
internal byte ignoreRemotePort3;
internal byte ignoreRemotePort4;
internal TcpState state;
internal uint owningPid;
}
internal enum TcpTableClass {
TcpTableBasicListener = 0,
TcpTableBasicConnections = 1,
TcpTableBasicAll = 2,
TcpTableOwnerPidListener = 3,
TcpTableOwnerPidConnections = 4,
TcpTableOwnerPidAll = 5,
TcpTableOwnerModuleListener = 6,
TcpTableOwnerModuleConnections = 7,
TcpTableOwnerModuleAll = 8
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibUdpTable {
internal uint numberOfEntries;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibUdpRow {
internal uint localAddr;
internal byte localPort1;
internal byte localPort2;
// Ports are only 16 bit values (in network WORD order, 3,4,1,2).
// There are reports where the high order bytes have garbage in them.
internal byte ignoreLocalPort3;
internal byte ignoreLocalPort4;
}
internal enum UdpTableClass {
UdpTableBasic = 0,
UdpTableOwnerPid = 1,
UdpTableOwnerModule = 2
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibUdp6TableOwnerPid {
internal uint numberOfEntries;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MibUdp6RowOwnerPid {
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
internal byte[] localAddr;
internal uint localScopeId;
internal byte localPort1;
internal byte localPort2;
// Ports are only 16 bit values (in network WORD order, 3,4,1,2).
// There are reports where the high order bytes have garbage in them.
internal byte ignoreLocalPort3;
internal byte ignoreLocalPort4;
internal uint owningPid;
}
[StructLayout(LayoutKind.Sequential)]
internal struct IPOptions {
internal byte ttl;
internal byte tos;
internal byte flags;
internal byte optionsSize;
internal IntPtr optionsData;
internal IPOptions (PingOptions options)
{
ttl = 128;
tos = 0;
flags = 0;
optionsSize = 0;
optionsData = IntPtr.Zero;
if (options != null) {
this.ttl = (byte)options.Ttl;
if (options.DontFragment){
flags = 2;
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct IcmpEchoReply {
internal uint address;
internal uint status;
internal uint roundTripTime;
internal ushort dataSize;
internal ushort reserved;
internal IntPtr data;
internal IPOptions options;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
internal struct Ipv6Address {
[MarshalAs(UnmanagedType.ByValArray,SizeConst=6)]
internal byte[] Goo;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=16)]
internal byte[] Address; // Replying address.
internal uint ScopeID;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Icmp6EchoReply {
internal Ipv6Address Address;
internal uint Status; // Reply IP_STATUS.
internal uint RoundTripTime; // RTT in milliseconds.
internal IntPtr data;
// internal IPOptions options;
// internal IntPtr data; data os after tjos
}
internal delegate void StableUnicastIpAddressTableDelegate(IntPtr context, IntPtr table);
/// <summary>
/// Wrapper for API's in iphlpapi.dll
/// </summary>
[
System.Security.SuppressUnmanagedCodeSecurityAttribute()
]
internal static class UnsafeNetInfoNativeMethods {
private const string IPHLPAPI = "iphlpapi.dll";
[DllImport(IPHLPAPI)]
internal extern static uint GetAdaptersAddresses(
AddressFamily family,
uint flags,
IntPtr pReserved,
SafeLocalFree adapterAddresses,
ref uint outBufLen);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
"CA2118:ReviewSuppressUnmanagedCodeSecurityUsage",
Justification = "This operation is Read-Only and does not access restricted information")]
[DllImport(IPHLPAPI)]
internal extern static uint GetBestInterfaceEx(byte[] ipAddress, out int index);
[DllImport(IPHLPAPI)]
internal extern static uint GetIfEntry2(ref MibIfRow2 pIfRow);
[DllImport(IPHLPAPI)]
internal extern static uint GetIpStatisticsEx(out MibIpStats statistics, AddressFamily family);
[DllImport(IPHLPAPI)]
internal extern static uint GetTcpStatisticsEx(out MibTcpStats statistics, AddressFamily family);
[DllImport(IPHLPAPI)]
internal extern static uint GetUdpStatisticsEx(out MibUdpStats statistics, AddressFamily family);
[DllImport(IPHLPAPI)]
internal extern static uint GetIcmpStatistics(out MibIcmpInfo statistics);
[DllImport(IPHLPAPI)]
internal extern static uint GetIcmpStatisticsEx(out MibIcmpInfoEx statistics,AddressFamily family);
[DllImport(IPHLPAPI)]
internal extern static uint GetTcpTable(SafeLocalFree pTcpTable, ref uint dwOutBufLen, bool order);
[DllImport(IPHLPAPI)]
internal extern static uint GetExtendedTcpTable(SafeLocalFree pTcpTable, ref uint dwOutBufLen, bool order,
uint IPVersion, TcpTableClass tableClass, uint reserved);
[DllImport(IPHLPAPI)]
internal extern static uint GetUdpTable(SafeLocalFree pUdpTable, ref uint dwOutBufLen, bool order);
[DllImport(IPHLPAPI)]
internal extern static uint GetExtendedUdpTable(SafeLocalFree pUdpTable, ref uint dwOutBufLen, bool order,
uint IPVersion, UdpTableClass tableClass, uint reserved);
[DllImport(IPHLPAPI)]
internal extern static uint GetNetworkParams(SafeLocalFree pFixedInfo,ref uint pOutBufLen);
[DllImport(IPHLPAPI)]
internal extern static uint GetPerAdapterInfo(uint IfIndex,SafeLocalFree pPerAdapterInfo,ref uint pOutBufLen);
[DllImport(IPHLPAPI, SetLastError=true)]
internal extern static SafeCloseIcmpHandle IcmpCreateFile();
[DllImport (IPHLPAPI, SetLastError=true)]
internal extern static SafeCloseIcmpHandle Icmp6CreateFile ();
[DllImport (IPHLPAPI, SetLastError=true)]
internal extern static bool IcmpCloseHandle(IntPtr handle);
[DllImport (IPHLPAPI, SetLastError=true)]
internal extern static uint IcmpSendEcho2 (SafeCloseIcmpHandle icmpHandle, SafeWaitHandle Event, IntPtr apcRoutine, IntPtr apcContext,
uint ipAddress, [In] SafeLocalFree data, ushort dataSize, ref IPOptions options, SafeLocalFree replyBuffer, uint replySize, uint timeout);
[DllImport (IPHLPAPI, SetLastError=true)]
internal extern static uint IcmpSendEcho2 (SafeCloseIcmpHandle icmpHandle, IntPtr Event, IntPtr apcRoutine, IntPtr apcContext,
uint ipAddress, [In] SafeLocalFree data, ushort dataSize, ref IPOptions options, SafeLocalFree replyBuffer, uint replySize, uint timeout);
[DllImport (IPHLPAPI, SetLastError=true)]
internal extern static uint Icmp6SendEcho2 (SafeCloseIcmpHandle icmpHandle, SafeWaitHandle Event, IntPtr apcRoutine, IntPtr apcContext,
byte[] sourceSocketAddress, byte[] destSocketAddress, [In] SafeLocalFree data, ushort dataSize, ref IPOptions options, SafeLocalFree replyBuffer, uint replySize, uint timeout);
[DllImport (IPHLPAPI, SetLastError=true)]
internal extern static uint Icmp6SendEcho2 (SafeCloseIcmpHandle icmpHandle, IntPtr Event, IntPtr apcRoutine, IntPtr apcContext,
byte[] sourceSocketAddress, byte[] destSocketAddress, [In] SafeLocalFree data, ushort dataSize, ref IPOptions options, SafeLocalFree replyBuffer, uint replySize, uint timeout);
[DllImport(IPHLPAPI)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern void FreeMibTable(IntPtr handle);
[DllImport(IPHLPAPI)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern uint CancelMibChangeNotify2(IntPtr notificationHandle);
[DllImport(IPHLPAPI)]
internal static extern uint NotifyStableUnicastIpAddressTable(
[In] AddressFamily addressFamily,
[Out] out SafeFreeMibTable table,
[MarshalAs(UnmanagedType.FunctionPtr)][In] StableUnicastIpAddressTableDelegate callback,
[In] IntPtr context,
[Out] out SafeCancelMibChangeNotify notificationHandle);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace PlatformAPI.GDIPlus
{
public class Matrix
{
Matrix()
{
GpMatrix matrix;
lastResult = NativeMethods.GdipCreateMatrix(out matrix);
SetNativeMatrix(matrix);
}
Matrix(float m11,
float m12,
float m21,
float m22,
float dx,
float dy)
{
GpMatrix matrix;
lastResult = NativeMethods.GdipCreateMatrix2(m11, m12, m21, m22,
dx, dy, out matrix);
SetNativeMatrix(matrix);
}
Matrix( GpRectF rect,
GpPointF[] dstplg)
{
GpMatrix matrix;
lastResult = NativeMethods.GdipCreateMatrix3(rect,
dstplg,
out matrix);
SetNativeMatrix(matrix);
}
~Matrix()
{
NativeMethods.GdipDeleteMatrix(nativeMatrix);
}
GpStatus GetElements(float[] m)
{
return SetStatus(NativeMethods.GdipGetMatrixElements(nativeMatrix, m));
}
GpStatus SetElements(float m11,
float m12,
float m21,
float m22,
float dx,
float dy)
{
return SetStatus(NativeMethods.GdipSetMatrixElements(nativeMatrix,
m11, m12, m21, m22, dx, dy));
}
float OffsetX()
{
float[] elements = new float [6];
if (GetElements(elements) == GpStatus.Ok)
return elements[4];
else
return 0.0f;
}
float OffsetY()
{
float[] elements = new float [6];
if (GetElements(elements) == GpStatus.Ok)
return elements[5];
else
return 0.0f;
}
GpStatus Reset()
{
// set identity matrix elements
return SetStatus(NativeMethods.GdipSetMatrixElements(nativeMatrix,
1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
}
/*
Status Multiply( Matrix matrix,
MatrixOrder order )
{
return SetStatus(NativeMethods.GdipMultiplyMatrix(nativeMatrix,
matrix.nativeMatrix,
order));
}
Status Translate(float offsetX,
float offsetY,
MatrixOrder order )
{
return SetStatus(NativeMethods.GdipTranslateMatrix(nativeMatrix, offsetX,
offsetY, order));
}
Status Scale(float scaleX,
float scaleY,
MatrixOrder order )
{
return SetStatus(NativeMethods.GdipScaleMatrix(nativeMatrix, scaleX,
scaleY, order));
}
Status Rotate(float angle,
MatrixOrder order)
{
return SetStatus(NativeMethods.GdipRotateMatrix(nativeMatrix, angle,
order));
}
Status RotateAt(float angle,
PointF center,
MatrixOrder order )
{
if(order == MatrixOrderPrepend)
{
SetStatus(NativeMethods.GdipTranslateMatrix(nativeMatrix, center.X,
center.Y, order));
SetStatus(NativeMethods.GdipRotateMatrix(nativeMatrix, angle,
order));
return SetStatus(NativeMethods.GdipTranslateMatrix(nativeMatrix,
-center.X,
-center.Y,
order));
}
else
{
SetStatus(NativeMethods.GdipTranslateMatrix(nativeMatrix,
- center.X,
- center.Y,
order));
SetStatus(NativeMethods.GdipRotateMatrix(nativeMatrix, angle,
order));
return SetStatus(NativeMethods.GdipTranslateMatrix(nativeMatrix,
center.X,
center.Y,
order));
}
}
Status Shear(float shearX,
float shearY,
MatrixOrder order = MatrixOrderPrepend)
{
return SetStatus(NativeMethods.GdipShearMatrix(nativeMatrix, shearX,
shearY, order));
}
Status Invert()
{
return SetStatus(NativeMethods.GdipInvertMatrix(nativeMatrix));
}
// float version
Status TransformPoints(PointF[] pts)
{
return SetStatus(NativeMethods.GdipTransformMatrixPoints(nativeMatrix,
pts, count));
}
Status TransformPoints(Point[] pts)
{
return SetStatus(NativeMethods.GdipTransformMatrixPointsI(nativeMatrix,
pts,
count));
}
Status TransformVectors(OUT PointF* pts,
INT count = 1)
{
return SetStatus(NativeMethods.GdipVectorTransformMatrixPoints(
nativeMatrix, pts, count));
}
Status TransformVectors(OUT Point* pts,
INT count = 1)
{
return SetStatus(NativeMethods.GdipVectorTransformMatrixPointsI(
nativeMatrix,
pts,
count));
}
BOOL IsInvertible()
{
BOOL result = FALSE;
SetStatus(NativeMethods.GdipIsMatrixInvertible(nativeMatrix, &result));
return result;
}
BOOL IsIdentity()
{
BOOL result = FALSE;
SetStatus(NativeMethods.GdipIsMatrixIdentity(nativeMatrix, &result));
return result;
}
*/
bool Equals( Matrix matrix)
{
float []points1 = new float[6], points2 = new float[6];
GetElements(points1);
matrix.GetElements(points2);
for(int i = 0; i < 6; i++ )
if ( points1[i] != points2[i] )
return false;
return true;
}
GpStatus GetLastStatus()
{
GpStatus lastStatus = lastResult;
lastResult = GpStatus.Ok;
return lastStatus;
}
private Matrix( Matrix m)
{
float[] points = new float[6];
m.GetElements(points);
SetElements(points[0], points[2], points[3], points[4], points[5], points[6]);
}
protected Matrix(GpMatrix nativeMatrix)
{
lastResult = GpStatus.Ok;
SetNativeMatrix(nativeMatrix);
}
void SetNativeMatrix(GpMatrix nativeMatrix)
{
this.nativeMatrix = nativeMatrix;
}
GpStatus SetStatus(GpStatus status)
{
if (status != GpStatus.Ok)
return (lastResult = status);
else
return status;
}
internal GpMatrix nativeMatrix;
protected GpStatus lastResult;
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
namespace Svg
{
/// <summary>
/// Converts string representations of colours into <see cref="Color"/> objects.
/// </summary>
public class SvgColourConverter : System.Drawing.ColorConverter
{
/// <summary>
/// Converts the given object to the converter's native type.
/// </summary>
/// <param name="context">A <see cref="T:System.ComponentModel.TypeDescriptor"/> that provides a format context. You can use this object to get additional information about the environment from which this converter is being invoked.</param>
/// <param name="culture">A <see cref="T:System.Globalization.CultureInfo"/> that specifies the culture to represent the color.</param>
/// <param name="value">The object to convert.</param>
/// <returns>
/// An <see cref="T:System.Object"/> representing the converted value.
/// </returns>
/// <exception cref="T:System.ArgumentException">The conversion cannot be performed.</exception>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/>
/// </PermissionSet>
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string colour = value as string;
if (colour != null)
{
var oldCulture = Thread.CurrentThread.CurrentCulture;
try {
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
colour = colour.Trim();
if (colour.StartsWith("rgb"))
{
try
{
int start = colour.IndexOf("(") + 1;
//get the values from the RGB string
string[] values = colour.Substring(start, colour.IndexOf(")") - start).Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
//determine the alpha value if this is an RGBA (it will be the 4th value if there is one)
int alphaValue = 255;
if (values.Length > 3)
{
//the alpha portion of the rgba is not an int 0-255 it is a decimal between 0 and 1
//so we have to determine the corosponding byte value
var alphastring = values[3];
if (alphastring.StartsWith("."))
{
alphastring = "0" + alphastring;
}
var alphaDecimal = decimal.Parse(alphastring);
if (alphaDecimal <= 1)
{
alphaValue = (int)Math.Round(alphaDecimal * 255);
}
else
{
alphaValue = (int)Math.Round(alphaDecimal);
}
}
Color colorpart;
if (values[0].Trim().EndsWith("%"))
{
colorpart = System.Drawing.Color.FromArgb(alphaValue, (int)Math.Round(255 * float.Parse(values[0].Trim().TrimEnd('%')) / 100f),
(int)Math.Round(255 * float.Parse(values[1].Trim().TrimEnd('%')) / 100f),
(int)Math.Round(255 * float.Parse(values[2].Trim().TrimEnd('%')) / 100f));
}
else
{
colorpart = System.Drawing.Color.FromArgb(alphaValue, int.Parse(values[0]), int.Parse(values[1]), int.Parse(values[2]));
}
return colorpart;
}
catch
{
throw new SvgException("Colour is in an invalid format: '" + colour + "'");
}
}
// HSL support
else if (colour.StartsWith("hsl")) {
try
{
int start = colour.IndexOf("(") + 1;
//get the values from the RGB string
string[] values = colour.Substring(start, colour.IndexOf(")") - start).Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (values[1].EndsWith("%"))
{
values[1] = values[1].TrimEnd('%');
}
if (values[2].EndsWith("%"))
{
values[2] = values[2].TrimEnd('%');
}
// Get the HSL values in a range from 0 to 1.
double h = double.Parse(values[0]) / 360.0;
double s = double.Parse(values[1]) / 100.0;
double l = double.Parse(values[2]) / 100.0;
// Convert the HSL color to an RGB color
Color colorpart = Hsl2Rgb(h, s, l);
return colorpart;
}
catch
{
throw new SvgException("Colour is in an invalid format: '" + colour + "'");
}
}
else if (colour.StartsWith("#") && colour.Length == 4)
{
colour = string.Format(culture, "#{0}{0}{1}{1}{2}{2}", colour[1], colour[2], colour[3]);
return base.ConvertFrom(context, culture, colour);
}
switch (colour.ToLowerInvariant())
{
case "activeborder": return SystemColors.ActiveBorder;
case "activecaption": return SystemColors.ActiveCaption;
case "appworkspace": return SystemColors.AppWorkspace;
case "background": return SystemColors.Desktop;
case "buttonface": return SystemColors.Control;
case "buttonhighlight": return SystemColors.ControlLightLight;
case "buttonshadow": return SystemColors.ControlDark;
case "buttontext": return SystemColors.ControlText;
case "captiontext": return SystemColors.ActiveCaptionText;
case "graytext": return SystemColors.GrayText;
case "highlight": return SystemColors.Highlight;
case "highlighttext": return SystemColors.HighlightText;
case "inactiveborder": return SystemColors.InactiveBorder;
case "inactivecaption": return SystemColors.InactiveCaption;
case "inactivecaptiontext": return SystemColors.InactiveCaptionText;
case "infobackground": return SystemColors.Info;
case "infotext": return SystemColors.InfoText;
case "menu": return SystemColors.Menu;
case "menutext": return SystemColors.MenuText;
case "scrollbar": return SystemColors.ScrollBar;
case "threeddarkshadow": return SystemColors.ControlDarkDark;
case "threedface": return SystemColors.Control;
case "threedhighlight": return SystemColors.ControlLight;
case "threedlightshadow": return SystemColors.ControlLightLight;
case "window": return SystemColors.Window;
case "windowframe": return SystemColors.WindowFrame;
case "windowtext": return SystemColors.WindowText;
}
int number;
if (Int32.TryParse(colour, out number))
{
// numbers are handled as colors by System.Drawing.ColorConverter - we
// have to prevent this and ignore the color instead (see #342)
return SvgColourServer.NotSet;
}
}
finally
{
// Make sure to set back the old culture even an error occurred.
Thread.CurrentThread.CurrentCulture = oldCulture;
}
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
var colour = (Color)value;
return ColorTranslator.ToHtml(colour);
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <summary>
/// Converts HSL color (with HSL specified from 0 to 1) to RGB color.
/// Taken from http://www.geekymonkey.com/Programming/CSharp/RGB2HSL_HSL2RGB.htm
/// </summary>
/// <param name="h"></param>
/// <param name="sl"></param>
/// <param name="l"></param>
/// <returns></returns>
private static Color Hsl2Rgb( double h, double sl, double l ) {
double r = l; // default to gray
double g = l;
double b = l;
double v = (l <= 0.5) ? (l * (1.0 + sl)) : (l + sl - l * sl);
if (v > 0)
{
double m;
double sv;
int sextant;
double fract, vsf, mid1, mid2;
m = l + l - v;
sv = (v - m ) / v;
h *= 6.0;
sextant = (int)h;
fract = h - sextant;
vsf = v * sv * fract;
mid1 = m + vsf;
mid2 = v - vsf;
switch (sextant)
{
case 0:
r = v;
g = mid1;
b = m;
break;
case 1:
r = mid2;
g = v;
b = m;
break;
case 2:
r = m;
g = v;
b = mid1;
break;
case 3:
r = m;
g = mid2;
b = v;
break;
case 4:
r = mid1;
g = m;
b = v;
break;
case 5:
r = v;
g = m;
b = mid2;
break;
}
}
Color rgb = Color.FromArgb( (int)Math.Round( r * 255.0 ), (int)Math.Round( g * 255.0 ), (int)Math.Round( b * 255.0 ) );
return rgb;
}
}
}
| |
namespace Microsoft.Azure.Management.Dns
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ZonesOperations operations.
/// </summary>
internal partial class ZonesOperations : IServiceOperations<DnsManagementClient>, IZonesOperations
{
/// <summary>
/// Initializes a new instance of the ZonesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ZonesOperations(DnsManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DnsManagementClient
/// </summary>
public DnsManagementClient Client { get; private set; }
/// <summary>
/// Creates or Updates a DNS zone within a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Zone>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, Zone parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Zone>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Zone>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Zone>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Removes a DNS zone from a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='ifMatch'>
/// Defines the If-Match condition. The delete operation will be performed
/// only if the ETag of the zone on the server matches this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. The delete operation will be
/// performed only if the ETag of the zone on the server does not match this
/// value.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ZoneDeleteResult>> DeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse<ZoneDeleteResult> _response = await BeginDeleteWithHttpMessagesAsync(
resourceGroupName, zoneName, ifMatch, ifNoneMatch, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Removes a DNS zone from a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='ifMatch'>
/// Defines the If-Match condition. The delete operation will be performed
/// only if the ETag of the zone on the server matches this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. The delete operation will be
/// performed only if the ETag of the zone on the server does not match this
/// value.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ZoneDeleteResult>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ZoneDeleteResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ZoneDeleteResult>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Zone>> GetWithHttpMessagesAsync(string resourceGroupName, string zoneName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Zone>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Zone>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Zone>>> ListInResourceGroupWithHttpMessagesAsync(string resourceGroupName, string top = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListInResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", Uri.EscapeDataString(top)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Zone>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Zone>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Zone>>> ListInSubscriptionWithHttpMessagesAsync(string top = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListInSubscription", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", Uri.EscapeDataString(top)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Zone>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Zone>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Zone>>> ListInResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListInResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Zone>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Zone>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Zone>>> ListInSubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListInSubscriptionNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Zone>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Zone>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2008 Rusty Howell, Thomas Wiest
*
* 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.
*******************************************************************************/
// Authors:
// Thomas Wiest twiest@users.sourceforge.net
// Rusty Howell rhowell@users.sourceforge.net
using System;
using System.Collections.Generic;
using System.Text;
using UvsChess;
namespace ExampleAI
{
public class ExampleAI : IChessAI
{
#region IChessAI Members that are implemented by the Student
/// <summary>
/// The name of your AI
/// </summary>
public string Name
{
#if DEBUG
get { return "ExampleAI (Debug)"; }
#else
get { return "ExampleAI"; }
#endif
}
/// <summary>
/// Evaluates the chess board and decided which move to make. This is the main method of the AI.
/// The framework will call this method when it's your turn.
/// </summary>
/// <param name="board">Current chess board</param>
/// <param name="yourColor">Your color</param>
/// <returns> Returns the best chess move the player has for the given chess board</returns>
public ChessMove GetNextMove(ChessBoard board, ChessColor myColor)
{
#if DEBUG
//For more information about using the profiler, visit http://code.google.com/p/uvschess/wiki/ProfilerHowTo
// This is how you setup the profiler. This should be done in GetNextMove.
Profiler.TagNames = Enum.GetNames(typeof(ExampleAIProfilerTags));
// In order for the profiler to calculate the AI's nodes/sec value,
// I need to tell the profiler which method key's are for MiniMax.
// In this case our mini and max methods are the same,
// but usually they are not.
Profiler.MinisProfilerTag = (int)ExampleAIProfilerTags.GetAllMoves;
Profiler.MaxsProfilerTag = (int)ExampleAIProfilerTags.GetAllMoves;
// This increments the method call count by 1 for GetNextMove in the profiler
Profiler.IncrementTagCount((int)ExampleAIProfilerTags.GetNextMove);
#endif
ChessMove myNextMove = null;
while (! IsMyTurnOver())
{
if (myNextMove == null)
{
myNextMove = MoveAPawn(board, myColor);
this.Log(myColor.ToString() + " (" + this.Name + ") just moved.");
this.Log(string.Empty);
// Since I have a move, break out of loop
break;
}
}
Profiler.SetDepthReachedDuringThisTurn(2);
return myNextMove;
}
/// <summary>
/// Validates a move. The framework uses this to validate the opponents move.
/// </summary>
/// <param name="boardBeforeMove">The board as it currently is _before_ the move.</param>
/// <param name="moveToCheck">This is the move that needs to be checked to see if it's valid.</param>
/// <param name="colorOfPlayerMoving">This is the color of the player who's making the move.</param>
/// <returns>Returns true if the move was valid</returns>
public bool IsValidMove(ChessBoard boardBeforeMove, ChessMove moveToCheck, ChessColor colorOfPlayerMoving)
{
#if DEBUG
Profiler.IncrementTagCount((int)ExampleAIProfilerTags.IsValidMove);
#endif
// This AI isn't sophisticated enough to validate moves, therefore
// just tell UvsChess that all moves are valid.
return true;
}
#endregion
#region My AI Logic
/// <summary>
/// This method generates a ChessMove to move a pawn.
/// </summary>
/// <param name="currentBoard">This is the current board to generate the move for.</param>
/// <param name="myColor">This is the color of the player that should generate the move.</param>
/// <returns>A chess move.</returns>
ChessMove MoveAPawn(ChessBoard currentBoard, ChessColor myColor)
{
#if DEBUG
Profiler.IncrementTagCount((int)ExampleAIProfilerTags.MoveAPawn);
#endif
List<ChessMove> allMyMoves = GetAllMoves(currentBoard, myColor);
ChessMove myChosenMove = null;
Random random = new Random();
int myChosenMoveNumber = random.Next(allMyMoves.Count);
if (allMyMoves.Count == 0)
{
// If I couldn't find a valid move easily,
// I'll just create an empty move and flag a stalemate.
myChosenMove = new ChessMove(null, null);
myChosenMove.Flag = ChessFlag.Stalemate;
}
else
{
myChosenMove = allMyMoves[myChosenMoveNumber];
AddAllPossibleMovesToDecisionTree(allMyMoves, myChosenMove, currentBoard.Clone(), myColor);
}
return myChosenMove;
}
/// <summary>
/// This method generates all valid moves for myColor based on the currentBoard
/// </summary>
/// <param name="currentBoard">This is the current board to generate the moves for.</param>
/// <param name="myColor">This is the color of the player to generate the moves for.</param>
/// <returns>List of ChessMoves</returns>
List<ChessMove> GetAllMoves(ChessBoard currentBoard, ChessColor myColor)
{
#if DEBUG
Profiler.IncrementTagCount((int)ExampleAIProfilerTags.GetAllMoves);
#endif
// This method only generates moves for pawns to move one space forward.
// It does not generate moves for any other pieces.
List<ChessMove> allMoves = new List<ChessMove>();
// Got through the entire board one tile at a time looking for pawns I can move
for (int Y = 1; Y < ChessBoard.NumberOfRows - 1; Y++)
{
for (int X = 0; X < ChessBoard.NumberOfColumns; X++)
{
if (myColor == ChessColor.White)
{
if ((currentBoard[X, Y-1] == ChessPiece.Empty) &&
(currentBoard[X, Y] == ChessPiece.WhitePawn))
{
// Generate a move to move my pawn 1 tile forward
allMoves.Add(new ChessMove(new ChessLocation(X, Y), new ChessLocation(X, Y - 1)));
}
}
else // myColor is black
{
if ((currentBoard[X, Y+1] == ChessPiece.Empty) &&
(currentBoard[X, Y] == ChessPiece.BlackPawn))
{
// Generate a move to move my pawn 1 tile forward
allMoves.Add(new ChessMove(new ChessLocation(X, Y), new ChessLocation(X, Y + 1)));
}
}
}
}
return allMoves;
}
public void AddAllPossibleMovesToDecisionTree(List<ChessMove> allMyMoves, ChessMove myChosenMove,
ChessBoard currentBoard, ChessColor myColor)
{
#if DEBUG
Profiler.IncrementTagCount((int)ExampleAIProfilerTags.AddAllPossibleMovesToDecisionTree);
#endif
Random random = new Random();
// Create the decision tree object
DecisionTree dt = new DecisionTree(currentBoard);
// Tell UvsChess about the decision tree object
SetDecisionTree(dt);
dt.BestChildMove = myChosenMove;
// Go through all of my moves, add them to the decision tree
// Then go through each of these moves and generate all of my
// opponents moves and add those to the decision tree as well.
for (int ix = 0; ix < allMyMoves.Count; ix++)
{
ChessMove myCurMove = allMyMoves[ix];
ChessBoard boardAfterMyCurMove = currentBoard.Clone();
boardAfterMyCurMove.MakeMove(myCurMove);
// Add the new move and board to the decision tree
dt.AddChild(boardAfterMyCurMove, myCurMove);
// Descend the decision tree to the last child added so we can
// add all of the opponents response moves to our move.
dt = dt.LastChild;
// Get all of the opponents response moves to my move
ChessColor oppColor = (myColor == ChessColor.White ? ChessColor.Black : ChessColor.White);
List<ChessMove> allOppMoves = GetAllMoves(boardAfterMyCurMove, oppColor);
// Go through all of my opponent moves and add them to the decision tree
foreach (ChessMove oppCurMove in allOppMoves)
{
ChessBoard boardAfterOppCurMove = boardAfterMyCurMove.Clone();
boardAfterOppCurMove.MakeMove(oppCurMove);
dt.AddChild(boardAfterOppCurMove, oppCurMove);
// Setting all of the opponents eventual move values to 0 (see below).
dt.LastChild.EventualMoveValue = "0";
}
if (allOppMoves.Count > 0)
{
// Tell the decision tree which move we think our opponent will choose.
int chosenOppMoveNumber = random.Next(allOppMoves.Count);
dt.BestChildMove = allOppMoves[chosenOppMoveNumber];
}
// Tell the decision tree what this moves eventual value will be.
// Since this AI can't evaulate anything, I'm just going to set this
// value to 0.
dt.EventualMoveValue = "0";
// All of the opponents response moves have been added to this childs move,
// so return to the parent so we can do the loop again for our next move.
dt = dt.Parent;
}
}
#endregion
#region IChessAI Members that should be implemented as automatic properties and should NEVER be touched by students.
/// <summary>
/// This will return false when the framework starts running your AI. When the AI's time has run out,
/// then this method will return true. Once this method returns true, your AI should return a
/// move immediately.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
public AIIsMyTurnOverCallback IsMyTurnOver { get; set; }
/// <summary>
/// Call this method to print out debug information. The framework subscribes to this event
/// and will provide a log window for your debug messages.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
/// <param name="message"></param>
public AILoggerCallback Log { get; set; }
/// <summary>
/// Call this method to catch profiling information. The framework subscribes to this event
/// and will print out the profiling stats in your log window.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
/// <param name="key"></param>
public AIProfiler Profiler { get; set; }
/// <summary>
/// Call this method to tell the framework what decision print out debug information. The framework subscribes to this event
/// and will provide a debug window for your decision tree.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
/// <param name="message"></param>
public AISetDecisionTreeCallback SetDecisionTree { get; set; }
#endregion
#if DEBUG
private enum ExampleAIProfilerTags
{
AddAllPossibleMovesToDecisionTree,
GetAllMoves,
GetNextMove,
IsValidMove,
MoveAPawn
}
#endif
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Swashbuckle.SwaggerGen.Annotations;
using SchoolBusAPI.Models;
using SchoolBusAPI.ViewModels;
using SchoolBusAPI.Services;
using SchoolBusAPI.Authorization;
namespace SchoolBusAPI.Controllers
{
/// <summary>
///
/// </summary>
public partial class SchoolBusController : Controller
{
private readonly ISchoolBusService _service;
/// <summary>
/// Create a controller and set the service
/// </summary>
public SchoolBusController(ISchoolBusService service)
{
_service = service;
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">SchoolBus created</response>
[HttpPost]
[Route("/api/schoolbuses/bulk")]
[SwaggerOperation("SchoolbusesBulkPost")]
[RequiresPermission(Permission.ADMIN)]
public virtual IActionResult SchoolbusesBulkPost([FromBody]SchoolBus[] items)
{
return this._service.SchoolbusesBulkPostAsync(items);
}
/// <summary>
///
/// </summary>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses")]
[SwaggerOperation("SchoolbusesGet")]
[SwaggerResponse(200, type: typeof(List<SchoolBus>))]
public virtual IActionResult SchoolbusesGet()
{
return this._service.SchoolbusesGetAsync();
}
/// <summary>
///
/// </summary>
/// <remarks>Returns attachments for a particular SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch attachments for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/attachments")]
[SwaggerOperation("SchoolbusesIdAttachmentsGet")]
[SwaggerResponse(200, type: typeof(List<AttachmentViewModel>))]
public virtual IActionResult SchoolbusesIdAttachmentsGet([FromRoute]int id)
{
return this._service.SchoolbusesIdAttachmentsGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns CCWData for a particular Schoolbus</remarks>
/// <param name="id">id of SchoolBus to fetch CCWData for</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/ccwdata")]
[SwaggerOperation("SchoolbusesIdCcwdataGet")]
[SwaggerResponse(200, type: typeof(CCWData))]
public virtual IActionResult SchoolbusesIdCcwdataGet([FromRoute]int id)
{
return this._service.SchoolbusesIdCcwdataGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to delete</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpPost]
[Route("/api/schoolbuses/{id}/delete")]
[SwaggerOperation("SchoolbusesIdDeletePost")]
public virtual IActionResult SchoolbusesIdDeletePost([FromRoute]int id)
{
return this._service.SchoolbusesIdDeletePostAsync(id);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpGet]
[Route("/api/schoolbuses/{id}")]
[SwaggerOperation("SchoolbusesIdGet")]
[SwaggerResponse(200, type: typeof(SchoolBus))]
public virtual IActionResult SchoolbusesIdGet([FromRoute]int id)
{
return this._service.SchoolbusesIdGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns History for a particular SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch History for</param>
/// <param name="offset">offset for records that are returned</param>
/// <param name="limit">limits the number of records returned.</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/history")]
[SwaggerOperation("SchoolbusesIdHistoryGet")]
[SwaggerResponse(200, type: typeof(List<HistoryViewModel>))]
public virtual IActionResult SchoolbusesIdHistoryGet([FromRoute]int id, [FromQuery]int? offset, [FromQuery]int? limit)
{
return this._service.SchoolbusesIdHistoryGetAsync(id, offset, limit);
}
/// <summary>
///
/// </summary>
/// <remarks>Add a History record to the SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch History for</param>
/// <param name="item"></param>
/// <response code="201">History created</response>
[HttpPost]
[Route("/api/schoolbuses/{id}/history")]
[SwaggerOperation("SchoolbusesIdHistoryPost")]
[SwaggerResponse(200, type: typeof(History))]
public virtual IActionResult SchoolbusesIdHistoryPost([FromRoute]int id, [FromBody]History item)
{
return this._service.SchoolbusesIdHistoryPostAsync(id, item);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to fetch Inspections for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/inspections")]
[SwaggerOperation("SchoolbusesIdInspectionsGet")]
[SwaggerResponse(200, type: typeof(List<Inspection>))]
public virtual IActionResult SchoolbusesIdInspectionsGet([FromRoute]int id)
{
return this._service.SchoolbusesIdInspectionsGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Obtains a new permit number for the indicated Schoolbus. Returns the updated SchoolBus record.</remarks>
/// <param name="id">id of SchoolBus to obtain a new permit number for</param>
/// <response code="200">OK</response>
[HttpPut]
[Route("/api/schoolbuses/{id}/newpermit")]
[SwaggerOperation("SchoolbusesIdNewpermitPut")]
[SwaggerResponse(200, type: typeof(SchoolBus))]
public virtual IActionResult SchoolbusesIdNewpermitPut([FromRoute]int id)
{
return this._service.SchoolbusesIdNewpermitPutAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns notes for a particular SchoolBus.</remarks>
/// <param name="id">id of SchoolBus to fetch notes for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/notes")]
[SwaggerOperation("SchoolbusesIdNotesGet")]
[SwaggerResponse(200, type: typeof(List<Note>))]
public virtual IActionResult SchoolbusesIdNotesGet([FromRoute]int id)
{
return this._service.SchoolbusesIdNotesGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a PDF version of the permit for the selected Schoolbus</remarks>
/// <param name="id">id of SchoolBus to obtain the PDF permit for</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/pdfpermit")]
[SwaggerOperation("SchoolbusesIdPdfpermitGet")]
public virtual IActionResult SchoolbusesIdPdfpermitGet([FromRoute]int id)
{
return this._service.SchoolbusesIdPdfpermitGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to fetch</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpPut]
[Route("/api/schoolbuses/{id}")]
[SwaggerOperation("SchoolbusesIdPut")]
[SwaggerResponse(200, type: typeof(SchoolBus))]
public virtual IActionResult SchoolbusesIdPut([FromRoute]int id, [FromBody]SchoolBus item)
{
return this._service.SchoolbusesIdPutAsync(id, item);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">SchoolBus created</response>
[HttpPost]
[Route("/api/schoolbuses")]
[SwaggerOperation("SchoolbusesPost")]
[SwaggerResponse(200, type: typeof(SchoolBus))]
public virtual IActionResult SchoolbusesPost([FromBody]SchoolBus item)
{
return this._service.SchoolbusesPostAsync(item);
}
/// <summary>
/// Searches school buses
/// </summary>
/// <remarks>Used for the search schoolbus page.</remarks>
/// <param name="districts">Districts (array of id numbers)</param>
/// <param name="inspectors">Assigned School Bus Inspectors (array of id numbers)</param>
/// <param name="cities">Cities (array of id numbers)</param>
/// <param name="schooldistricts">School Districts (array of id numbers)</param>
/// <param name="owner"></param>
/// <param name="regi">e Regi Number</param>
/// <param name="vin">VIN</param>
/// <param name="plate">License Plate String</param>
/// <param name="includeInactive">True if Inactive schoolbuses will be returned</param>
/// <param name="onlyReInspections">If true, only buses that need a re-inspection will be returned</param>
/// <param name="startDate">Inspection start date</param>
/// <param name="endDate">Inspection end date</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses/search")]
[SwaggerOperation("SchoolbusesSearchGet")]
[SwaggerResponse(200, type: typeof(List<SchoolBus>))]
public virtual IActionResult SchoolbusesSearchGet([FromQuery]int?[] districts, [FromQuery]int?[] inspectors, [FromQuery]int?[] cities, [FromQuery]int?[] schooldistricts, [FromQuery]int? owner, [FromQuery]string regi, [FromQuery]string vin, [FromQuery]string plate, [FromQuery]bool? includeInactive, [FromQuery]bool? onlyReInspections, [FromQuery]DateTime? startDate, [FromQuery]DateTime? endDate)
{
return this._service.SchoolbusesSearchGetAsync(districts, inspectors, cities, schooldistricts, owner, regi, vin, plate, includeInactive, onlyReInspections, startDate, endDate);
}
}
}
| |
using System;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;
using NUnit.Framework;
namespace SIL.WritingSystems.Tests
{
[TestFixture]
public class AddSortKeysToXmlTests
{
private XPathNavigator _document;
private string _xpathSortKeySource;
private string _xpathElementToPutSortKeyAttributeIn;
private string _attribute;
private string _prefix;
private string _uri;
private AddSortKeysToXml.SortKeyGenerator _sortKeyGenerator;
[SetUp]
public void Setup()
{
XmlDocument document = new XmlDocument();
document.LoadXml(
@"<test>
<node>z</node>
<node>a</node>
<node>b</node>
<node>q</node>
</test>");
this._document = document.CreateNavigator();
this._xpathSortKeySource = "//node";
this._xpathElementToPutSortKeyAttributeIn = "self::*";
this._attribute = "sort-key";
this._prefix = "sil";
this._uri = "http://sil.org/sort-key";
_sortKeyGenerator = CultureInfo.InvariantCulture.CompareInfo.GetSortKey;
}
[Test]
public void AddSortKeys()
{
AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_attribute);
string expectedXml = "<test>\r\n <node sort-key=\"1QKG20810400\">z</node>\r\n <node sort-key=\"1O1020810400\">a</node>\r\n <node sort-key=\"1O4G20810400\">b</node>\r\n <node sort-key=\"1Q4G20810400\">q</node>\r\n</test>";
Assert.AreEqual(NormalizeLineBreaks(expectedXml),
NormalizeLineBreaks(_document.OuterXml));
}
[Test]
public void AddSortKeys_EmptyDocument()
{
XmlDocument document = new XmlDocument();
XPathNavigator navigator = document.CreateNavigator();
AddSortKeysToXml.AddSortKeys(navigator,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_attribute);
Assert.AreEqual(string.Empty, navigator.OuterXml);
}
[Test]
public void AddSortKeys_DocumentNull_Throws()
{
Assert.Throws<ArgumentNullException>(
() => AddSortKeysToXml.AddSortKeys(null,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_attribute));
}
[Test]
public void AddSortKeys_XPathSourceNull_Throws()
{
Assert.Throws<ArgumentNullException>(
() => AddSortKeysToXml.AddSortKeys(_document,
null,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_attribute));
}
[Test]
public void AddSortKeys_XPathSourceEmpty_Throws()
{
Assert.Throws<XPathException>(
() => AddSortKeysToXml.AddSortKeys(_document,
string.Empty,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_attribute));
}
[Test]
public void AddSortKeys_XPathDestinationNull_Throws()
{
Assert.Throws<ArgumentNullException>(
() => AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
null,
_attribute));
}
[Test]
public void AddSortKeys_XPathDestinationEmpty_Throws()
{
Assert.Throws<XPathException>(
() => AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
string.Empty,
_attribute));
}
[Test]
public void AddSortKeys_AttributeNull_Throws()
{
Assert.Throws<ArgumentNullException>(
() => AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
null));
}
[Test]
public void AddSortKeys_AttributeEmpty_Throws()
{
Assert.Throws<ArgumentException>(
() => AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
string.Empty));
}
[Test]
public void AddSortKeys_PrefixNull_Throws()
{
Assert.Throws<ArgumentNullException>(
() => AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
null,
_attribute,
_uri));
}
[Test]
public void AddSortKeys_PrefixEmpty_Throws()
{
Assert.Throws<ArgumentException>(
() => AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
string.Empty,
_attribute,
_uri));
}
[Test]
public void AddSortKeys_PrefixInvalidCharacter_Throws()
{
Assert.Throws<ArgumentException>(
() => AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
"1",
_attribute,
_uri));
}
[Test]
public void AddSortKeys_UriNull_Throws()
{
Assert.Throws<ArgumentNullException>(
() => AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_prefix,
_attribute,
null));
}
[Test]
public void AddSortKeys_UriEmpty_Throws()
{
Assert.Throws<ArgumentException>(
() => AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_prefix,
_attribute,
string.Empty));
}
[Test]
public void AddSortKeysWithNamespace()
{
AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_prefix,
_attribute,
_uri);
string expectedXml = "<test>\r\n <node sil:sort-key=\"1QKG20810400\" xmlns:sil=\""+ _uri +
"\">z</node>\r\n <node sil:sort-key=\"1O1020810400\" xmlns:sil=\""+ _uri +
"\">a</node>\r\n <node sil:sort-key=\"1O4G20810400\" xmlns:sil=\""+ _uri +
"\">b</node>\r\n <node sil:sort-key=\"1Q4G20810400\" xmlns:sil=\""+ _uri +
"\">q</node>\r\n</test>";
Assert.AreEqual(NormalizeLineBreaks(expectedXml),
NormalizeLineBreaks(_document.OuterXml));
}
[Test]
public void AddSortKeys_AlreadyHasSortKeys()
{
AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_attribute);
AddSortKeysToXml.AddSortKeys(_document,
_xpathSortKeySource,
_sortKeyGenerator,
_xpathElementToPutSortKeyAttributeIn,
_attribute);
string expectedXml = "<test>\r\n <node sort-key=\"1QKG20810400\">z</node>\r\n <node sort-key=\"1O1020810400\">a</node>\r\n <node sort-key=\"1O4G20810400\">b</node>\r\n <node sort-key=\"1Q4G20810400\">q</node>\r\n</test>";
Assert.AreEqual(NormalizeLineBreaks(expectedXml),
NormalizeLineBreaks(_document.OuterXml));
}
private string NormalizeLineBreaks(string s)
{
return s.Replace("\r\n", "\n");
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Threading.Tasks;
using Xunit;
using FluentAssertions;
using System.Net;
using System.Collections.Generic;
using IdentityServer4.Models;
using System.Security.Claims;
using IdentityServer4.IntegrationTests.Common;
using IdentityServer4.Test;
using System.Net.Http;
using IdentityModel;
using System;
namespace IdentityServer4.IntegrationTests.Endpoints.Authorize
{
public class AuthorizeTests
{
private const string Category = "Authorize endpoint";
private IdentityServerPipeline _mockPipeline = new IdentityServerPipeline();
private Client _client1;
public AuthorizeTests()
{
_mockPipeline.Clients.AddRange(new Client[] {
_client1 = new Client
{
ClientId = "client1",
AllowedGrantTypes = GrantTypes.Implicit,
RequireConsent = false,
AllowedScopes = new List<string> { "openid", "profile" },
RedirectUris = new List<string> { "https://client1/callback" },
AllowAccessTokensViaBrowser = true
},
new Client
{
ClientId = "client2",
AllowedGrantTypes = GrantTypes.Implicit,
RequireConsent = true,
AllowedScopes = new List<string> { "openid", "profile", "api1", "api2" },
RedirectUris = new List<string> { "https://client2/callback" },
AllowAccessTokensViaBrowser = true
},
new Client
{
ClientId = "client3",
AllowedGrantTypes = GrantTypes.Implicit,
RequireConsent = false,
AllowedScopes = new List<string> { "openid", "profile", "api1", "api2" },
RedirectUris = new List<string> { "https://client3/callback" },
AllowAccessTokensViaBrowser = true,
EnableLocalLogin = false,
IdentityProviderRestrictions = new List<string> { "google" }
}
});
_mockPipeline.Users.Add(new TestUser
{
SubjectId = "bob",
Username = "bob",
Claims = new Claim[]
{
new Claim("name", "Bob Loblaw"),
new Claim("email", "bob@loblaw.com"),
new Claim("role", "Attorney")
}
});
_mockPipeline.IdentityScopes.AddRange(new IdentityResource[] {
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email()
});
_mockPipeline.ApiScopes.AddRange(new ApiResource[] {
new ApiResource
{
Name = "api",
Scopes =
{
new Scope
{
Name = "api1"
},
new Scope
{
Name = "api2"
}
}
}
});
_mockPipeline.Initialize();
}
[Fact]
[Trait("Category", Category)]
public async Task get_request_should_not_return_404()
{
var response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.AuthorizeEndpoint);
response.StatusCode.Should().NotBe(HttpStatusCode.NotFound);
}
[Fact]
[Trait("Category", Category)]
public async Task post_request_without_form_should_return_415()
{
var response = await _mockPipeline.BrowserClient.PostAsync(IdentityServerPipeline.AuthorizeEndpoint, new StringContent("foo"));
response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType);
}
[Fact]
[Trait("Category", Category)]
public async Task post_request_should_return_200()
{
var response = await _mockPipeline.BrowserClient.PostAsync(IdentityServerPipeline.AuthorizeEndpoint,
new FormUrlEncodedContent(
new Dictionary<string, string> { }));
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
[Trait("Category", Category)]
public async Task get_request_should_not_return_500()
{
var response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.AuthorizeEndpoint);
((int)response.StatusCode).Should().BeLessThan(500);
}
[Fact]
[Trait("Category", Category)]
public async Task anonymous_user_should_be_redirected_to_login_page()
{
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.LoginWasCalled.Should().BeTrue();
}
[Fact]
[Trait("Category", Category)]
public async Task signin_request_should_have_authorization_params()
{
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce",
loginHint: "login_hint_value",
acrValues: "acr_1 acr_2 tenant:tenant_value idp:idp_value",
extra: new
{
display = "popup", // must use a valid value from the spec for display
ui_locales = "ui_locale_value",
custom_foo = "foo_value"
});
var response = await _mockPipeline.BrowserClient.GetAsync(url + "&foo=bar");
_mockPipeline.LoginRequest.Should().NotBeNull();
_mockPipeline.LoginRequest.ClientId.Should().Be("client1");
_mockPipeline.LoginRequest.DisplayMode.Should().Be("popup");
_mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value");
_mockPipeline.LoginRequest.IdP.Should().Be("idp_value");
_mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value");
_mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value");
_mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" });
_mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo");
_mockPipeline.LoginRequest.Parameters["foo"].Should().Be("bar");
}
[Fact]
[Trait("Category", Category)]
public async Task signin_response_should_allow_successful_authorization_response()
{
_mockPipeline.Subject = new IdentityServerUser("bob").CreatePrincipal();
_mockPipeline.BrowserClient.StopRedirectingAfter = 2;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
response.StatusCode.Should().Be(HttpStatusCode.Redirect);
response.Headers.Location.ToString().Should().StartWith("https://client1/callback");
var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
authorization.IsError.Should().BeFalse();
authorization.IdentityToken.Should().NotBeNull();
authorization.State.Should().Be("123_state");
}
[Fact]
[Trait("Category", Category)]
public async Task authenticated_user_with_valid_request_should_receive_authorization_response()
{
await _mockPipeline.LoginAsync("bob");
_mockPipeline.BrowserClient.AllowAutoRedirect = false;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
response.StatusCode.Should().Be(HttpStatusCode.Redirect);
response.Headers.Location.ToString().Should().StartWith("https://client1/callback");
var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
authorization.IsError.Should().BeFalse();
authorization.IdentityToken.Should().NotBeNull();
authorization.State.Should().Be("123_state");
}
[Fact]
[Trait("Category", Category)]
public async Task login_response_and_consent_response_should_receive_authorization_response()
{
_mockPipeline.Subject = new IdentityServerUser("bob").CreatePrincipal();
_mockPipeline.ConsentResponse = new ConsentResponse()
{
ScopesConsented = new string[] { "openid", "api1", "profile" }
};
_mockPipeline.BrowserClient.StopRedirectingAfter = 4;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client2",
responseType: "id_token token",
scope: "openid profile api1 api2",
redirectUri: "https://client2/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
response.StatusCode.Should().Be(HttpStatusCode.Redirect);
response.Headers.Location.ToString().Should().StartWith("https://client2/callback");
var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
authorization.IsError.Should().BeFalse();
authorization.IdentityToken.Should().NotBeNull();
authorization.State.Should().Be("123_state");
var scopes = authorization.Scope.Split(' ');
scopes.Should().BeEquivalentTo(new string[] { "profile", "api1", "openid" });
}
[Fact]
[Trait("Category", Category)]
public async Task idp_should_be_passed_to_login_page()
{
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client3",
responseType: "id_token",
scope: "openid profile",
redirectUri: "https://client3/callback",
state: "123_state",
nonce: "123_nonce",
acrValues: "idp:google");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.LoginWasCalled.Should().BeTrue();
_mockPipeline.LoginRequest.IdP.Should().Be("google");
}
[Fact]
[Trait("Category", Category)]
public async Task idp_not_allowed_by_client_should_not_be_passed_to_login_page()
{
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client3",
responseType: "id_token",
scope: "openid profile",
redirectUri: "https://client3/callback",
state: "123_state",
nonce: "123_nonce",
acrValues: "idp:facebook");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.LoginWasCalled.Should().BeTrue();
_mockPipeline.LoginRequest.IdP.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public async Task user_idp_not_allowed_by_client_should_cause_login_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client3",
responseType: "id_token",
scope: "openid profile",
redirectUri: "https://client3/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.LoginWasCalled.Should().BeTrue();
_mockPipeline.LoginRequest.IdP.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_redirect_uri_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://invalid",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("redirect_uri");
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_redirect_uri_should_not_pass_return_url_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://invalid",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().BeNull();
_mockPipeline.ErrorMessage.ResponseMode.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_client_id_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1_invalid",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient);
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_client_id_should_not_pass_return_url_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1_invalid",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().BeNull();
_mockPipeline.ErrorMessage.ResponseMode.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public async Task missing_redirect_uri_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1_invalid",
responseType: "id_token",
scope: "openid",
//redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("redirect_uri");
}
[Fact]
[Trait("Category", Category)]
public async Task missing_redirect_uri_should_not_pass_return_url_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1_invalid",
responseType: "id_token",
scope: "openid",
//redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().BeNull();
_mockPipeline.ErrorMessage.ResponseMode.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public async Task malformed_redirect_uri_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1_invalid",
responseType: "id_token",
scope: "openid",
redirectUri: "invalid-uri",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("redirect_uri");
}
[Fact]
[Trait("Category", Category)]
public async Task disabled_client_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
_client1.Enabled = false;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient);
}
[Fact]
[Trait("Category", Category)]
public async Task disabled_client_should_not_pass_return_url_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
_client1.Enabled = false;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().BeNull();
_mockPipeline.ErrorMessage.ResponseMode.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_protocol_for_client_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
_client1.ProtocolType = "invalid";
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("protocol");
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_protocol_for_client_should_not_pass_return_url_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
_client1.ProtocolType = "invalid";
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().BeNull();
_mockPipeline.ErrorMessage.ResponseMode.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_response_type_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "invalid",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnsupportedResponseType);
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_response_type_should_not_pass_return_url_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "invalid",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().BeNull();
_mockPipeline.ErrorMessage.ResponseMode.Should().BeNull();
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_response_mode_for_flow_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
responseMode: "query",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnsupportedResponseType);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("response_mode");
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_response_mode_for_flow_should_pass_return_url_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
responseMode: "query",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_response_mode_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
responseMode: "invalid",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnsupportedResponseType);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("response_mode");
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_response_mode_should_pass_return_url_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
responseMode: "invalid",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task missing_scope_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
//scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("scope");
}
[Fact]
[Trait("Category", Category)]
public async Task missing_scope_should_pass_return_url_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
//scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task explicit_response_mode_should_be_passed_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
responseMode: "form_post",
//scope: "openid", // this will cause the error
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("form_post");
}
[Fact]
[Trait("Category", Category)]
public async Task scope_too_long_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: new string('x', 500),
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("scope");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task missing_openid_scope_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "profile",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("scope");
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("openid");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task client_not_allowed_access_to_scope_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid email",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("scope");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task missing_nonce_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state"
//nonce: "123_nonce"
);
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("nonce");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task nonce_too_long_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: new string('x', 500));
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("nonce");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task locale_too_long_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce",
extra: new { ui_locales = new string('x', 500) });
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("ui_locales");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_max_age_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce",
extra: new { max_age = "invalid" });
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("max_age");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task negative_max_age_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce",
extra: new { max_age = "-10" });
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("max_age");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task login_hint_too_long_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce",
loginHint: new string('x', 500));
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("login_hint");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task acr_values_too_long_should_show_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce",
acrValues: new string('x', 500));
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest);
_mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("acr_values");
_mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback");
_mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment");
}
[Fact]
[Trait("Category", Category)]
public async Task overlapping_identity_scopes_and_api_scopes_should_show_error_page()
{
_mockPipeline.IdentityScopes.Add(new IdentityResource("foo", "Foo", new string[] { "name" }));
_mockPipeline.IdentityScopes.Add(new IdentityResource("bar", "Bar", new string[] { "name" }));
_mockPipeline.ApiScopes.Add(new ApiResource("foo", "Foo"));
_mockPipeline.ApiScopes.Add(new ApiResource("bar", "Bar"));
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid foo bar",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce");
Func<Task> a = () => _mockPipeline.BrowserClient.GetAsync(url);
a.Should().Throw<Exception>();
}
[Fact]
[Trait("Category", Category)]
public async Task ui_locales_should_be_passed_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce",
acrValues: new string('x', 500),
extra: new { ui_locales = "fr-FR" });
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.UiLocales.Should().Be("fr-FR");
}
[Fact]
[Trait("Category", Category)]
public async Task display_mode_should_be_passed_to_error_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client1/callback",
state: "123_state",
nonce: "123_nonce",
acrValues: new string('x', 500),
extra: new { display = "popup" });
await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ErrorWasCalled.Should().BeTrue();
_mockPipeline.ErrorMessage.DisplayMode.Should().Be("popup");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class CastNullableTests
{
#region Test methods
[Fact]
public static void CheckNullableEnumCastEnumTypeTest()
{
E?[] array = new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableEnumCastEnumType(array[i]);
}
}
[Fact]
public static void CheckNullableEnumCastObjectTest()
{
E?[] array = new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableEnumCastObject(array[i]);
}
}
[Fact]
public static void CheckNullableIntCastObjectTest()
{
int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableIntCastObject(array[i]);
}
}
[Fact]
public static void CheckNullableIntCastValueTypeTest()
{
int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableIntCastValueType(array[i]);
}
}
[Fact]
public static void CheckNullableStructCastIEquatableOfStructTest()
{
S?[] array = new S?[] { null, default(S), new S() };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableStructCastIEquatableOfStruct(array[i]);
}
}
[Fact]
public static void CheckNullableStructCastObjectTest()
{
S?[] array = new S?[] { null, default(S), new S() };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableStructCastObject(array[i]);
}
}
[Fact]
public static void CheckNullableStructCastValueTypeTest()
{
S?[] array = new S?[] { null, default(S), new S() };
for (int i = 0; i < array.Length; i++)
{
VerifyNullableStructCastValueType(array[i]);
}
}
[Fact]
public static void ConvertGenericWithStructRestrictionCastObjectAsEnum()
{
CheckGenericWithStructRestrictionCastObjectHelper<E>();
}
[Fact]
public static void ConvertGenericWithStructRestrictionCastObjectAsStruct()
{
CheckGenericWithStructRestrictionCastObjectHelper<S>();
}
[Fact]
public static void ConvertGenericWithStructRestrictionCastObjectAsStructWithStringAndField()
{
CheckGenericWithStructRestrictionCastObjectHelper<Scs>();
}
[Fact]
public static void ConvertGenericWithStructRestrictionCastValueTypeAsEnum()
{
CheckGenericWithStructRestrictionCastValueTypeHelper<E>();
}
[Fact]
public static void ConvertGenericWithStructRestrictionCastValueTypeAsStruct()
{
CheckGenericWithStructRestrictionCastValueTypeHelper<S>();
}
[Fact]
public static void ConvertGenericWithStructRestrictionCastValueTypeAsStructWithStringAndField()
{
CheckGenericWithStructRestrictionCastValueTypeHelper<Scs>();
}
#endregion
#region Generic helpers
private static void CheckGenericWithStructRestrictionCastObjectHelper<Ts>() where Ts : struct
{
Ts[] array = new Ts[] { default(Ts), new Ts() };
for (int i = 0; i < array.Length; i++)
{
VerifyGenericWithStructRestrictionCastObject<Ts>(array[i]);
}
}
private static void CheckGenericWithStructRestrictionCastValueTypeHelper<Ts>() where Ts : struct
{
Ts[] array = new Ts[] { default(Ts), new Ts() };
for (int i = 0; i < array.Length; i++)
{
VerifyGenericWithStructRestrictionCastValueType<Ts>(array[i]);
}
}
#endregion
#region Test verifiers
private static void VerifyNullableEnumCastEnumType(E? value)
{
Expression<Func<Enum>> e =
Expression.Lambda<Func<Enum>>(
Expression.Convert(Expression.Constant(value, typeof(E?)), typeof(Enum)),
Enumerable.Empty<ParameterExpression>());
Func<Enum> f = e.Compile();
// compute the value with the expression tree
Enum etResult = default(Enum);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute the value with regular IL
Enum csResult = default(Enum);
Exception csException = null;
try
{
csResult = (Enum)value;
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableEnumCastObject(E? value)
{
Expression<Func<object>> e =
Expression.Lambda<Func<object>>(
Expression.Convert(Expression.Constant(value, typeof(E?)), typeof(object)),
Enumerable.Empty<ParameterExpression>());
Func<object> f = e.Compile();
// compute the value with the expression tree
object etResult = default(object);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute the value with regular IL
object csResult = default(object);
Exception csException = null;
try
{
csResult = (object)value;
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableIntCastObject(int? value)
{
Expression<Func<object>> e =
Expression.Lambda<Func<object>>(
Expression.Convert(Expression.Constant(value, typeof(int?)), typeof(object)),
Enumerable.Empty<ParameterExpression>());
Func<object> f = e.Compile();
// compute the value with the expression tree
object etResult = default(object);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute the value with regular IL
object csResult = default(object);
Exception csException = null;
try
{
csResult = (object)value;
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableIntCastValueType(int? value)
{
Expression<Func<ValueType>> e =
Expression.Lambda<Func<ValueType>>(
Expression.Convert(Expression.Constant(value, typeof(int?)), typeof(ValueType)),
Enumerable.Empty<ParameterExpression>());
Func<ValueType> f = e.Compile();
// compute the value with the expression tree
ValueType etResult = default(ValueType);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute the value with regular IL
ValueType csResult = default(ValueType);
Exception csException = null;
try
{
csResult = (ValueType)value;
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableStructCastIEquatableOfStruct(S? value)
{
Expression<Func<IEquatable<S>>> e =
Expression.Lambda<Func<IEquatable<S>>>(
Expression.Convert(Expression.Constant(value, typeof(S?)), typeof(IEquatable<S>)),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<S>> f = e.Compile();
// compute the value with the expression tree
IEquatable<S> etResult = default(IEquatable<S>);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute the value with regular IL
IEquatable<S> csResult = default(IEquatable<S>);
Exception csException = null;
try
{
csResult = (IEquatable<S>)value;
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableStructCastObject(S? value)
{
Expression<Func<object>> e =
Expression.Lambda<Func<object>>(
Expression.Convert(Expression.Constant(value, typeof(S?)), typeof(object)),
Enumerable.Empty<ParameterExpression>());
Func<object> f = e.Compile();
// compute the value with the expression tree
object etResult = default(object);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute the value with regular IL
object csResult = default(object);
Exception csException = null;
try
{
csResult = (object)value;
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableStructCastValueType(S? value)
{
Expression<Func<ValueType>> e =
Expression.Lambda<Func<ValueType>>(
Expression.Convert(Expression.Constant(value, typeof(S?)), typeof(ValueType)),
Enumerable.Empty<ParameterExpression>());
Func<ValueType> f = e.Compile();
// compute the value with the expression tree
ValueType etResult = default(ValueType);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute the value with regular IL
ValueType csResult = default(ValueType);
Exception csException = null;
try
{
csResult = (ValueType)value;
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyGenericWithStructRestrictionCastObject<Ts>(Ts value) where Ts : struct
{
Expression<Func<object>> e =
Expression.Lambda<Func<object>>(
Expression.Convert(Expression.Constant(value, typeof(Ts)), typeof(object)),
Enumerable.Empty<ParameterExpression>());
Func<object> f = e.Compile();
// compute the value with the expression tree
object etResult = default(object);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute the value with regular IL
object csResult = default(object);
Exception csException = null;
try
{
csResult = (object)value;
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyGenericWithStructRestrictionCastValueType<Ts>(Ts value) where Ts : struct
{
Expression<Func<ValueType>> e =
Expression.Lambda<Func<ValueType>>(
Expression.Convert(Expression.Constant(value, typeof(Ts)), typeof(ValueType)),
Enumerable.Empty<ParameterExpression>());
Func<ValueType> f = e.Compile();
// compute the value with the expression tree
ValueType etResult = default(ValueType);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute the value with regular IL
ValueType csResult = default(ValueType);
Exception csException = null;
try
{
csResult = (ValueType)value;
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using HetsApi.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Swashbuckle.AspNetCore.Annotations;
using HetsApi.Helpers;
using HetsData.Helpers;
using HetsData.Model;
namespace HetsApi.Controllers
{
/// <summary>
/// Attachment Upload Controller
/// </summary>
[Route("api")]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public class AttachmentUploadController : Controller
{
private readonly DbAppContext _context;
public AttachmentUploadController(DbAppContext context, IHttpContextAccessor httpContextAccessor)
{
_context = context;
// set context data
HetUser user = UserAccountHelper.GetUser(context, httpContextAccessor.HttpContext);
_context.SmUserId = user.SmUserId;
_context.DirectoryName = user.SmAuthorizationDirectory;
_context.SmUserGuid = user.Guid;
}
/// <summary>
/// Associate an attachment with a piece of equipment
/// </summary>
/// <param name="id"></param>
/// <param name="files"></param>
[HttpPost]
[Route("equipment/{id}/attachments")]
[SwaggerOperation("EquipmentIdAttachmentsPost")]
[SwaggerResponse(200, type: typeof(List<HetDigitalFile>))]
[RequiresPermission(HetPermission.Login)]
public virtual IActionResult EquipmentIdAttachmentsPost([FromRoute] int id, [FromForm]IList<IFormFile> files)
{
// validate the id
bool exists = _context.HetEquipment.Any(a => a.EquipmentId == id);
if (!exists) return new StatusCodeResult(404);
HetEquipment equipment = _context.HetEquipment
.Include(x => x.HetDigitalFile)
.First(a => a.EquipmentId == id);
foreach (IFormFile file in files)
{
if (file.Length > 0)
{
HetDigitalFile attachment = new HetDigitalFile();
// strip out extra info in the file name
if (!string.IsNullOrEmpty(file.FileName))
{
attachment.FileName = Path.GetFileName(file.FileName);
}
// allocate storage for the file and create a memory stream
attachment.FileContents = new byte[file.Length];
using (MemoryStream fileStream = new MemoryStream(attachment.FileContents))
{
file.CopyTo(fileStream);
}
attachment.Type = GetType(attachment.FileName);
// set the mime type id
string mimeType = GetMimeType(attachment.Type);
int? mimeTypeId = StatusHelper.GetMimeTypeId(mimeType, _context);
if (mimeTypeId == null)
{
throw new DataException("Mime Type Id cannot be null");
}
attachment.MimeTypeId = (int)mimeTypeId;
equipment.HetDigitalFile.Add(attachment);
}
}
_context.SaveChanges();
return new ObjectResult(equipment.HetDigitalFile);
}
/// <summary>
/// Get attachments associated with a piece of equipment
/// </summary>
/// <param name="id"></param>
[HttpGet]
[Route("equipment/{id}/attachmentsForm")]
[Produces("text/html")]
public virtual IActionResult EquipmentIdAttachmentsFormGet([FromRoute] int id)
{
return new ObjectResult("<html><body><form method=\"post\" action=\"/api/equipment/" + id + "/attachments\" enctype=\"multipart/form-data\"><input type=\"file\" name = \"files\" multiple /><input type = \"submit\" value = \"Upload\" /></body></html>");
}
/// <summary>
/// Associate an attachment with a project
/// </summary>
/// <param name="id"></param>
/// <param name="files"></param>
[HttpPost]
[Route("projects/{id}/attachments")]
[SwaggerOperation("ProjectIdAttachmentsPost")]
[SwaggerResponse(200, type: typeof(List<HetDigitalFile>))]
[RequiresPermission(HetPermission.Login)]
public virtual IActionResult ProjectIdAttachmentsPost([FromRoute] int id, [FromForm] IList<IFormFile> files)
{
// validate the id
bool exists = _context.HetProject.Any(a => a.ProjectId == id);
if (!exists) return new StatusCodeResult(404);
HetProject project = _context.HetProject
.Include(x => x.HetDigitalFile)
.First(a => a.ProjectId == id);
foreach (IFormFile file in files)
{
if (file.Length > 0)
{
HetDigitalFile attachment = new HetDigitalFile();
// strip out extra info in the file name
if (!string.IsNullOrEmpty(file.FileName))
{
attachment.FileName = Path.GetFileName(file.FileName);
}
// allocate storage for the file and create a memory stream
attachment.FileContents = new byte[file.Length];
using (MemoryStream fileStream = new MemoryStream(attachment.FileContents))
{
file.CopyTo(fileStream);
}
attachment.Type = GetType(attachment.FileName);
// set the mime type id
string mimeType = GetMimeType(attachment.Type);
int? mimeTypeId = StatusHelper.GetMimeTypeId(mimeType, _context);
if (mimeTypeId == null)
{
throw new DataException("Mime Type Id cannot be null");
}
attachment.MimeTypeId = (int)mimeTypeId;
project.HetDigitalFile.Add(attachment);
}
}
_context.SaveChanges();
return new ObjectResult(project.HetDigitalFile);
}
/// <summary>
/// Get attachments associated with a project
/// </summary>
/// <param name="id"></param>
[HttpGet]
[Route("projects/{id}/attachmentsForm")]
[Produces("text/html")]
[RequiresPermission(HetPermission.Login)]
public virtual IActionResult ProjectIdAttachmentsFormGet([FromRoute] int id)
{
return new ObjectResult("<html><body><form method=\"post\" action=\"/api/projects/" + id + "/attachments\" enctype=\"multipart/form-data\"><input type=\"file\" name = \"files\" multiple /><input type = \"submit\" value = \"Upload\" /></body></html>");
}
/// <summary>
/// Associate an owner with an attachment
/// </summary>
/// <param name="id"></param>
/// <param name="files"></param>
[HttpPost]
[Route("owners/{id}/attachments")]
[SwaggerOperation("OwnerIdAttachmentsPost")]
[SwaggerResponse(200, type: typeof(List<HetDigitalFile>))]
[RequiresPermission(HetPermission.Login)]
public virtual IActionResult OwnerIdAttachmentsPost([FromRoute] int id, [FromForm] IList<IFormFile> files)
{
// validate the id
bool exists = _context.HetOwner.Any(a => a.OwnerId == id);
if (!exists) return new StatusCodeResult(404);
HetOwner owner = _context.HetOwner
.Include(x => x.HetDigitalFile)
.First(a => a.OwnerId == id);
foreach (IFormFile file in files)
{
if (file.Length > 0)
{
HetDigitalFile attachment = new HetDigitalFile();
// strip out extra info in the file name
if (!string.IsNullOrEmpty(file.FileName))
{
attachment.FileName = Path.GetFileName(file.FileName);
}
// allocate storage for the file and create a memory stream
attachment.FileContents = new byte[file.Length];
using (MemoryStream fileStream = new MemoryStream(attachment.FileContents))
{
file.CopyTo(fileStream);
}
attachment.Type = GetType(attachment.FileName);
// set the mime type id
string mimeType = GetMimeType(attachment.Type);
int? mimeTypeId = StatusHelper.GetMimeTypeId(mimeType, _context);
if (mimeTypeId == null)
{
throw new DataException("Mime Type Id cannot be null");
}
attachment.MimeTypeId = (int)mimeTypeId;
owner.HetDigitalFile.Add(attachment);
}
}
_context.SaveChanges();
return new ObjectResult(owner.HetDigitalFile);
}
/// <summary>
/// Get attachments associated with an owner
/// </summary>
/// <param name="id"></param>
[HttpGet]
[Route("owners/{id}/attachmentsForm")]
[Produces("text/html")]
[RequiresPermission(HetPermission.Login)]
public virtual IActionResult OwnerIdAttachmentsFormGet([FromRoute] int id)
{
return new ObjectResult("<html><body><form method=\"post\" action=\"/api/owners/" + id + "/attachments\" enctype=\"multipart/form-data\"><input type=\"file\" name = \"files\" multiple /><input type = \"submit\" value = \"Upload\" /></body></html>");
}
/// <summary>
/// Associate an attachment with a rental request
/// </summary>
/// <param name="id"></param>
/// <param name="files"></param>
[HttpPost]
[Route("rentalRequests/{id}/attachments")]
[SwaggerOperation("RentalRequestIdAttachmentsPost")]
[SwaggerResponse(200, type: typeof(List<HetDigitalFile>))]
[RequiresPermission(HetPermission.Login)]
public virtual IActionResult RentalRequestIdAttachmentsPost([FromRoute] int id, [FromForm] IList<IFormFile> files)
{
// validate the id
bool exists = _context.HetRentalRequest.Any(a => a.RentalRequestId == id);
if (!exists) return new StatusCodeResult(404);
HetRentalRequest rentalRequest = _context.HetRentalRequest
.Include(x => x.HetDigitalFile)
.First(a => a.RentalRequestId == id);
foreach (IFormFile file in files)
{
if (file.Length > 0)
{
HetDigitalFile attachment = new HetDigitalFile();
// strip out extra info in the file name
if (!string.IsNullOrEmpty(file.FileName))
{
attachment.FileName = Path.GetFileName(file.FileName);
}
// allocate storage for the file and create a memory stream
attachment.FileContents = new byte[file.Length];
using (MemoryStream fileStream = new MemoryStream(attachment.FileContents))
{
file.CopyTo(fileStream);
}
attachment.Type = GetType(attachment.FileName);
// set the mime type id
string mimeType = GetMimeType(attachment.Type);
int? mimeTypeId = StatusHelper.GetMimeTypeId(mimeType, _context);
if (mimeTypeId == null)
{
throw new DataException("Mime Type Id cannot be null");
}
attachment.MimeTypeId = (int)mimeTypeId;
rentalRequest.HetDigitalFile.Add(attachment);
}
}
_context.SaveChanges();
return new ObjectResult(rentalRequest.HetDigitalFile);
}
/// <summary>
/// Get attachments associated with rental request
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
[Route("rentalRequests/{id}/attachmentsForm")]
[Produces("text/html")]
[RequiresPermission(HetPermission.Login)]
public virtual IActionResult RentalRequestIdAttachmentsFormGet([FromRoute] int id)
{
return new ObjectResult("<html><body><form method=\"post\" action=\"/api/rentalRequests/" + id + "/attachments\" enctype=\"multipart/form-data\"><input type=\"file\" name = \"files\" multiple /><input type = \"submit\" value = \"Upload\" /></body></html>");
}
#region Get File Extension / Mime Type
private string GetType(string fileName)
{
// get extension
int extStart = fileName.LastIndexOf('.');
if (extStart > 0)
{
return fileName.Substring(extStart + 1).ToLower();
}
return "";
}
private string GetMimeType(string extension)
{
switch (extension.ToLower())
{
case "txt":
return "text/plain";
case "png":
return "image/png";
case "jpeg":
return "image/jpeg";
case "jpg":
return "image/jpeg";
case "gif":
return "image/gif";
case "tif":
return "image/tiff";
case "tiff":
return "image/tiff";
case "pdf":
return "application/pdf";
case "doc":
return "application/msword";
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "xls":
return "application/vnd.ms-excel";
case "xlsx":
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
return "";
}
#endregion
}
}
| |
using Articulate.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Http;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Persistence;
using Umbraco.Core.Services;
using Umbraco.Web;
using Umbraco.Web.Actions;
using Umbraco.Web.Composing;
using Umbraco.Web.WebApi;
using File = System.IO.File;
namespace Articulate.Controllers
{
/// <summary>
/// Controller for handling the a-new mardown editor endpoint for creating blog posts
/// </summary>
public class MardownEditorApiController : UmbracoAuthorizedApiController
{
private readonly IMediaFileSystem _mediaFileSystem;
public MardownEditorApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper, IMediaFileSystem mediaFileSystem) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper)
{
_mediaFileSystem = mediaFileSystem;
}
public class ParseImageResponse
{
public string BodyText { get; set; }
public string FirstImage { get; set; }
}
public async Task<HttpResponseMessage> PostNew()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var str = IOHelper.MapPath("~/App_Data/TEMP/FileUploads");
Directory.CreateDirectory(str);
var provider = new MultipartFormDataStreamProvider(str);
var multiPartRequest = await Request.Content.ReadAsMultipartAsync(provider);
if (multiPartRequest.FormData["model"] == null)
{
CleanFiles(multiPartRequest);
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The request was not formatted correctly and is missing the 'model' parameter"));
}
var model = JsonConvert.DeserializeObject<MardownEditorModel>(multiPartRequest.FormData["model"]);
if (model.ArticulateNodeId.HasValue == false)
{
CleanFiles(multiPartRequest);
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No id specified"));
}
if (!ModelState.IsValid)
{
CleanFiles(multiPartRequest);
throw new HttpResponseException(Request.CreateValidationErrorResponse(ModelState));
}
var articulateNode = Services.ContentService.GetById(model.ArticulateNodeId.Value);
if (articulateNode == null)
{
CleanFiles(multiPartRequest);
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Articulate node found with the specified id"));
}
var extractFirstImageAsProperty = true;
if (articulateNode.HasProperty("extractFirstImage"))
{
extractFirstImageAsProperty = articulateNode.GetValue<bool>("extractFirstImage");
}
var archive = Services.ContentService.GetPagedChildren(model.ArticulateNodeId.Value, 0, int.MaxValue, out long totalArchiveNodes)
.FirstOrDefault(x => x.ContentType.Alias.InvariantEquals(ArticulateConstants.ArticulateArchiveContentTypeAlias));
if (archive == null)
{
CleanFiles(multiPartRequest);
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Articulate Archive node found for the specified id"));
}
var list = new List<char> { ActionNew.ActionLetter, ActionUpdate.ActionLetter };
var hasPermission = CheckPermissions(Security.CurrentUser, Services.UserService, list.ToArray(), archive);
if (hasPermission == false)
{
CleanFiles(multiPartRequest);
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Cannot create content at this level"));
}
//parse out the images, we may be posting more than is in the body
var parsedImageResponse = ParseImages(model.Body, multiPartRequest, extractFirstImageAsProperty);
model.Body = parsedImageResponse.BodyText;
var contentType = Services.ContentTypeService.Get("ArticulateMarkdown");
if (contentType == null)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No ArticulateMarkdown content type found"));
}
var content = Services.ContentService.CreateWithInvariantOrDefaultCultureName(
model.Title,
archive,
contentType,
Services.LocalizationService,
UmbracoContext.Security.GetUserId().Result);
content.SetInvariantOrDefaultCultureValue("markdown", model.Body, contentType, Services.LocalizationService);
if (!string.IsNullOrEmpty(parsedImageResponse.FirstImage))
{
content.SetInvariantOrDefaultCultureValue("postImage", parsedImageResponse.FirstImage, contentType, Services.LocalizationService);
}
if (model.Excerpt.IsNullOrWhiteSpace() == false)
{
content.SetInvariantOrDefaultCultureValue("excerpt", model.Excerpt, contentType, Services.LocalizationService);
}
if (model.Tags.IsNullOrWhiteSpace() == false)
{
var tags = model.Tags.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
content.AssignInvariantOrDefaultCultureTags("tags", tags, contentType, Services.LocalizationService);
}
if (model.Categories.IsNullOrWhiteSpace() == false)
{
var cats = model.Categories.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
content.AssignInvariantOrDefaultCultureTags("categories", cats, contentType, Services.LocalizationService);
}
if (model.Slug.IsNullOrWhiteSpace() == false)
{
content.SetInvariantOrDefaultCultureValue("umbracoUrlName", model.Slug, contentType, Services.LocalizationService);
}
//author is required
content.SetInvariantOrDefaultCultureValue("author", UmbracoContext?.Security?.CurrentUser?.Name ?? "Unknown", contentType, Services.LocalizationService);
var status = Services.ContentService.SaveAndPublish(content, userId: UmbracoContext.Security.GetUserId().Result);
if (status.Success == false)
{
CleanFiles(multiPartRequest);
ModelState.AddModelError("server", "Publishing failed: " + status.Result);
//probably need to send back more info than that...
throw new HttpResponseException(Request.CreateValidationErrorResponse(ModelState));
}
var published = Umbraco.Content(content.Id);
CleanFiles(multiPartRequest);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(published.Url, Encoding.UTF8, "text/html");
return response;
}
private static void CleanFiles(MultipartFileStreamProvider multiPartRequest)
{
foreach (var f in multiPartRequest.FileData)
{
File.Delete(f.LocalFileName);
}
}
private ParseImageResponse ParseImages(string body, MultipartFileStreamProvider multiPartRequest, bool extractFirstImageAsProperty)
{
var firstImage = string.Empty;
var bodyText = Regex.Replace(body, @"\[i:(\d+)\:(.*?)]", m =>
{
var index = m.Groups[1].Value.TryConvertTo<int>();
if (index)
{
//get the file at this index
var file = multiPartRequest.FileData[index.Result];
var rndId = Guid.NewGuid().ToString("N");
using (var stream = File.OpenRead(file.LocalFileName))
{
var fileUrl = "articulate/" + rndId + "/" + file.Headers.ContentDisposition.FileName.TrimStart("\"").TrimEnd("\"");
_mediaFileSystem.AddFile(fileUrl, stream);
var result = string.Format("",
fileUrl,
fileUrl
);
if (extractFirstImageAsProperty && string.IsNullOrEmpty(firstImage))
{
firstImage = fileUrl;
//in this case, we've extracted the image, we don't want it to be displayed
// in the content too so don't return it.
return string.Empty;
}
return result;
}
}
return m.Value;
});
return new ParseImageResponse { BodyText = bodyText, FirstImage = firstImage };
}
private static bool CheckPermissions(IUser user, IUserService userService, char[] permissionsToCheck, IContent contentItem)
{
if (permissionsToCheck == null || !permissionsToCheck.Any()) return true;
var entityPermission = userService.GetPermissions(user, new[] { contentItem.Id }).FirstOrDefault();
var flag = true;
foreach (var ch in permissionsToCheck)
{
if (entityPermission == null || !entityPermission.AssignedPermissions.Contains(ch.ToString(CultureInfo.InvariantCulture)))
flag = false;
}
return flag;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.Data.Common;
using System.IO;
using System.Linq;
using ASC.Common.Data;
using ASC.Common.Logging;
using ASC.Core.Tenants;
using ASC.Data.Backup.Extensions;
using ASC.Data.Backup.Tasks.Modules;
using ASC.Data.Storage;
namespace ASC.Data.Backup.Tasks
{
public class TransferPortalTask : PortalTaskBase
{
public const string DefaultDirectoryName = "backup";
public string ToConfigPath { get; private set; }
public string BackupDirectory { get; set; }
public bool DeleteBackupFileAfterCompletion { get; set; }
public bool BlockOldPortalAfterStart { get; set; }
public bool DeleteOldPortalAfterCompletion { get; set; }
public int Limit { get; private set; }
public int ToTenantId { get; private set; }
public TransferPortalTask(ILog logger, int tenantId, string fromConfigPath, string toConfigPath, int limit)
: base(logger, tenantId, fromConfigPath)
{
if (toConfigPath == null)
throw new ArgumentNullException("toConfigPath");
ToConfigPath = toConfigPath;
DeleteBackupFileAfterCompletion = true;
BlockOldPortalAfterStart = true;
DeleteOldPortalAfterCompletion = true;
Limit = limit;
}
public override void RunJob()
{
Logger.DebugFormat("begin transfer {0}", TenantId);
var fromDbFactory = new DbFactory(ConfigPath);
var toDbFactory = new DbFactory(ToConfigPath);
string tenantAlias = GetTenantAlias(fromDbFactory);
string backupFilePath = GetBackupFilePath(tenantAlias);
var columnMapper = new ColumnMapper();
try
{
//target db can have error tenant from the previous attempts
SaveTenant(toDbFactory, tenantAlias, TenantStatus.RemovePending, tenantAlias + "_error", "status = " + TenantStatus.Restoring.ToString("d"));
if (BlockOldPortalAfterStart)
{
SaveTenant(fromDbFactory, tenantAlias, TenantStatus.Transfering);
}
SetStepsCount(ProcessStorage ? 3 : 2);
//save db data to temporary file
var backupTask = new BackupPortalTask(Logger, TenantId, ConfigPath, backupFilePath, Limit) { ProcessStorage = false };
backupTask.ProgressChanged += (sender, args) => SetCurrentStepProgress(args.Progress);
foreach (var moduleName in IgnoredModules)
{
backupTask.IgnoreModule(moduleName);
}
backupTask.RunJob();
//restore db data from temporary file
var restoreTask = new RestorePortalTask(Logger, ToConfigPath, backupFilePath, columnMapper) { ProcessStorage = false };
restoreTask.ProgressChanged += (sender, args) => SetCurrentStepProgress(args.Progress);
foreach (var moduleName in IgnoredModules)
{
restoreTask.IgnoreModule(moduleName);
}
restoreTask.RunJob();
//transfer files
if (ProcessStorage)
{
DoTransferStorage(columnMapper);
}
SaveTenant(toDbFactory, tenantAlias, TenantStatus.Active);
if (DeleteOldPortalAfterCompletion)
{
SaveTenant(fromDbFactory, tenantAlias, TenantStatus.RemovePending, tenantAlias + "_deleted");
}
else if (BlockOldPortalAfterStart)
{
SaveTenant(fromDbFactory, tenantAlias, TenantStatus.Active);
}
ToTenantId = columnMapper.GetTenantMapping();
}
catch
{
SaveTenant(fromDbFactory, tenantAlias, TenantStatus.Active);
if (columnMapper.GetTenantMapping() > 0)
{
SaveTenant(toDbFactory, tenantAlias, TenantStatus.RemovePending, tenantAlias + "_error");
}
throw;
}
finally
{
if (DeleteBackupFileAfterCompletion)
{
File.Delete(backupFilePath);
}
Logger.DebugFormat("end transfer {0}", TenantId);
}
}
private void DoTransferStorage(ColumnMapper columnMapper)
{
Logger.Debug("begin transfer storage");
var fileGroups = GetFilesToProcess(TenantId).GroupBy(file => file.Module).ToList();
int groupsProcessed = 0;
foreach (var group in fileGroups)
{
var baseStorage = StorageFactory.GetStorage(ConfigPath, TenantId.ToString(), group.Key);
var destStorage = StorageFactory.GetStorage(ToConfigPath, columnMapper.GetTenantMapping().ToString(), group.Key);
var utility = new CrossModuleTransferUtility(baseStorage, destStorage);
foreach (BackupFileInfo file in group)
{
string adjustedPath = file.Path;
IModuleSpecifics module = ModuleProvider.GetByStorageModule(file.Module, file.Domain);
if (module == null || module.TryAdjustFilePath(false, columnMapper, ref adjustedPath))
{
try
{
utility.CopyFile(file.Domain, file.Path, file.Domain, adjustedPath);
}
catch (Exception error)
{
Logger.WarnFormat("Can't copy file ({0}:{1}): {2}", file.Module, file.Path, error);
}
}
else
{
Logger.WarnFormat("Can't adjust file path \"{0}\".", file.Path);
}
}
SetCurrentStepProgress((int)(++groupsProcessed * 100 / (double)fileGroups.Count));
}
if (fileGroups.Count == 0)
SetStepCompleted();
Logger.Debug("end transfer storage");
}
private void SaveTenant(DbFactory dbFactory, string alias, TenantStatus status, string newAlias = null, string whereCondition = null)
{
using (var connection = dbFactory.OpenConnection())
{
if (newAlias == null)
{
newAlias = alias;
}
else if (newAlias != alias)
{
newAlias = GetUniqAlias(connection, newAlias);
}
var commandText = string.Format(
"update tenants_tenants " +
"set " +
" status={0}, " +
" alias = '{1}', " +
" last_modified='{2}', " +
" statuschanged='{2}' " +
"where alias = '{3}'",
status.ToString("d"),
newAlias,
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"),
alias);
if (!string.IsNullOrEmpty(whereCondition))
commandText += (" and " + whereCondition);
connection.CreateCommand(commandText).WithTimeout(120).ExecuteNonQuery();
}
}
private string GetTenantAlias(DbFactory dbFactory)
{
using (var connection = dbFactory.OpenConnection())
{
var commandText = "select alias from tenants_tenants where id = " + TenantId;
return connection.CreateCommand(commandText).WithTimeout(120).ExecuteScalar<string>();
}
}
private static string GetUniqAlias(DbConnection connection, string alias)
{
return alias + connection.CreateCommand("select count(*) from tenants_tenants where alias like '" + alias + "%'")
.WithTimeout(120)
.ExecuteScalar<int>();
}
private string GetBackupFilePath(string tenantAlias)
{
if (!Directory.Exists(BackupDirectory ?? DefaultDirectoryName))
Directory.CreateDirectory(BackupDirectory ?? DefaultDirectoryName);
return Path.Combine(BackupDirectory ?? DefaultDirectoryName, tenantAlias + DateTime.UtcNow.ToString("(yyyy-MM-dd HH-mm-ss)") + ".backup");
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryMultiplyTests
{
#region Test methods
[Fact]
public static void CheckByteMultiplyTest()
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteMultiply(array[i], array[j]);
}
}
}
[Fact]
public static void CheckSByteMultiplyTest()
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteMultiply(array[i], array[j]);
}
}
}
[Fact]
public static void CheckUShortMultiplyTest()
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortMultiply(array[i], array[j]);
VerifyUShortMultiplyOvf(array[i], array[j]);
}
}
}
[Fact]
public static void CheckShortMultiplyTest()
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortMultiply(array[i], array[j]);
VerifyShortMultiplyOvf(array[i], array[j]);
}
}
}
[Fact]
public static void CheckUIntMultiplyTest()
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntMultiply(array[i], array[j]);
VerifyUIntMultiplyOvf(array[i], array[j]);
}
}
}
[Fact]
public static void CheckIntMultiplyTest()
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntMultiply(array[i], array[j]);
VerifyIntMultiplyOvf(array[i], array[j]);
}
}
}
[Fact]
public static void CheckULongMultiplyTest()
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongMultiply(array[i], array[j]);
VerifyULongMultiplyOvf(array[i], array[j]);
}
}
}
[Fact]
public static void CheckLongMultiplyTest()
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongMultiply(array[i], array[j]);
// we are not calling VerifyLongMultiplyOvf here
// because it currently fails on Linux
}
}
}
[Fact]
public static void CheckLongMultiplyTestOvf()
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongMultiplyOvf(array[i], array[j]);
}
}
}
[Fact]
public static void CheckFloatMultiplyTest()
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyFloatMultiply(array[i], array[j]);
}
}
}
[Fact]
public static void CheckDoubleMultiplyTest()
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDoubleMultiply(array[i], array[j]);
}
}
}
[Fact]
public static void CheckDecimalMultiplyTest()
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDecimalMultiply(array[i], array[j]);
}
}
}
[Fact]
public static void CheckCharMultiplyTest()
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharMultiply(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteMultiply(byte a, byte b)
{
Expression aExp = Expression.Constant(a, typeof(byte));
Expression bExp = Expression.Constant(b, typeof(byte));
Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp));
}
private static void VerifySByteMultiply(sbyte a, sbyte b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte));
Expression bExp = Expression.Constant(b, typeof(sbyte));
Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp));
}
private static void VerifyUShortMultiply(ushort a, ushort b)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Multiply(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile();
// add with expression tree
ushort etResult = default(ushort);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
ushort csResult = default(ushort);
Exception csException = null;
try
{
csResult = (ushort)(a * b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyUShortMultiplyOvf(ushort a, ushort b)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile();
// add with expression tree
ushort etResult = default(ushort);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
ushort csResult = default(ushort);
Exception csException = null;
try
{
csResult = checked((ushort)(a * b));
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyShortMultiply(short a, short b)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Multiply(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile();
// add with expression tree
short etResult = default(short);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
short csResult = default(short);
Exception csException = null;
try
{
csResult = (short)(a * b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyShortMultiplyOvf(short a, short b)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile();
// add with expression tree
short etResult = default(short);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
short csResult = default(short);
Exception csException = null;
try
{
csResult = checked((short)(a * b));
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyUIntMultiply(uint a, uint b)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Multiply(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile();
// add with expression tree
uint etResult = default(uint);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
uint csResult = default(uint);
Exception csException = null;
try
{
csResult = (uint)(a * b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyUIntMultiplyOvf(uint a, uint b)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile();
// add with expression tree
uint etResult = default(uint);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
uint csResult = default(uint);
Exception csException = null;
try
{
csResult = checked((uint)(a * b));
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyIntMultiply(int a, int b)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Multiply(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
// add with expression tree
int etResult = default(int);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
int csResult = default(int);
Exception csException = null;
try
{
csResult = (int)(a * b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyIntMultiplyOvf(int a, int b)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
// add with expression tree
int etResult = default(int);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
int csResult = default(int);
Exception csException = null;
try
{
csResult = checked((int)(a * b));
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyULongMultiply(ulong a, ulong b)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Multiply(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile();
// add with expression tree
ulong etResult = default(ulong);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
ulong csResult = default(ulong);
Exception csException = null;
try
{
csResult = (ulong)(a * b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyULongMultiplyOvf(ulong a, ulong b)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile();
// add with expression tree
ulong etResult = default(ulong);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
ulong csResult = default(ulong);
Exception csException = null;
try
{
csResult = checked((ulong)(a * b));
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyLongMultiply(long a, long b)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Multiply(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile();
// add with expression tree
long etResult = default(long);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
long csResult = default(long);
Exception csException = null;
try
{
csResult = (long)(a * b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyLongMultiplyOvf(long a, long b)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile();
// add with expression tree
long etResult = default(long);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
long csResult = default(long);
Exception csException = null;
try
{
csResult = checked((long)(a * b));
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyFloatMultiply(float a, float b)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Multiply(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile();
// add with expression tree
float etResult = default(float);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
float csResult = default(float);
Exception csException = null;
try
{
csResult = (float)(a * b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyDoubleMultiply(double a, double b)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Multiply(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile();
// add with expression tree
double etResult = default(double);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
double csResult = default(double);
Exception csException = null;
try
{
csResult = (double)(a * b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyDecimalMultiply(decimal a, decimal b)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Multiply(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile();
// add with expression tree
decimal etResult = default(decimal);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// add with real IL
decimal csResult = default(decimal);
Exception csException = null;
try
{
csResult = (decimal)(a * b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyCharMultiply(char a, char b)
{
Expression aExp = Expression.Constant(a, typeof(char));
Expression bExp = Expression.Constant(b, typeof(char));
Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp));
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Multiply(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void CannotReduceChecked()
{
Expression exp = Expression.MultiplyChecked(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.Multiply(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.Multiply(Expression.Constant(""), null));
}
[Fact]
public static void CheckedThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.MultiplyChecked(null, Expression.Constant("")));
}
[Fact]
public static void CheckedThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.MultiplyChecked(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.Multiply(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.Multiply(Expression.Constant(1), value));
}
[Fact]
public static void CheckedThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.MultiplyChecked(value, Expression.Constant(1)));
}
[Fact]
public static void CheckedThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.MultiplyChecked(Expression.Constant(1), value));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
public partial class ThreadPoolBoundHandleTests
{
[Fact]
public unsafe void SingleOperationOverSingleHandle()
{
const int DATA_SIZE = 2;
SafeHandle handle = HandleFactory.CreateAsyncFileHandleForWrite(@"SingleOverlappedOverSingleHandle.tmp");
ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle);
OverlappedContext result = new OverlappedContext();
byte[] data = new byte[DATA_SIZE];
data[0] = (byte)'A';
data[1] = (byte)'B';
NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result, data);
fixed (byte* p = data)
{
int retval = DllImport.WriteFile(boundHandle.Handle, p, DATA_SIZE, IntPtr.Zero, overlapped);
if (retval == 0)
{
Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error());
}
// Wait for overlapped operation to complete
result.Event.WaitOne();
}
boundHandle.FreeNativeOverlapped(overlapped);
boundHandle.Dispose();
handle.Dispose();
Assert.Equal(0, result.ErrorCode);
Assert.Equal(DATA_SIZE, result.BytesWritten);
}
[Fact]
public unsafe void MultipleOperationsOverSingleHandle()
{
const int DATA_SIZE = 2;
SafeHandle handle = HandleFactory.CreateAsyncFileHandleForWrite(@"MultipleOperationsOverSingleHandle.tmp");
ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle);
OverlappedContext result1 = new OverlappedContext();
OverlappedContext result2 = new OverlappedContext();
byte[] data1 = new byte[DATA_SIZE];
data1[0] = (byte)'A';
data1[1] = (byte)'B';
byte[] data2 = new byte[DATA_SIZE];
data2[0] = (byte)'C';
data2[1] = (byte)'D';
NativeOverlapped* overlapped1 = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result1, data1);
NativeOverlapped* overlapped2 = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result2, data2);
fixed (byte* p1 = data1, p2 = data2)
{
int retval = DllImport.WriteFile(boundHandle.Handle, p1, DATA_SIZE, IntPtr.Zero, overlapped1);
if (retval == 0)
{
Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error());
}
// Start the offset after the above write, so that it doesn't overwrite the previous write
overlapped2->OffsetLow = DATA_SIZE;
retval = DllImport.WriteFile(boundHandle.Handle, p2, DATA_SIZE, IntPtr.Zero, overlapped2);
if (retval == 0)
{
Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error());
}
// Wait for overlapped operations to complete
WaitHandle.WaitAll(new WaitHandle[] { result1.Event, result2.Event });
}
boundHandle.FreeNativeOverlapped(overlapped1);
boundHandle.FreeNativeOverlapped(overlapped2);
boundHandle.Dispose();
handle.Dispose();
Assert.Equal(0, result1.ErrorCode);
Assert.Equal(0, result2.ErrorCode);
Assert.Equal(DATA_SIZE, result1.BytesWritten);
Assert.Equal(DATA_SIZE, result2.BytesWritten);
}
[Fact]
public unsafe void MultipleOperationsOverMultipleHandles()
{
const int DATA_SIZE = 2;
SafeHandle handle1 = HandleFactory.CreateAsyncFileHandleForWrite(@"MultipleOperationsOverMultipleHandle1.tmp");
SafeHandle handle2 = HandleFactory.CreateAsyncFileHandleForWrite(@"MultipleOperationsOverMultipleHandle2.tmp");
ThreadPoolBoundHandle boundHandle1 = ThreadPoolBoundHandle.BindHandle(handle1);
ThreadPoolBoundHandle boundHandle2 = ThreadPoolBoundHandle.BindHandle(handle2);
OverlappedContext result1 = new OverlappedContext();
OverlappedContext result2 = new OverlappedContext();
byte[] data1 = new byte[DATA_SIZE];
data1[0] = (byte)'A';
data1[1] = (byte)'B';
byte[] data2 = new byte[DATA_SIZE];
data2[0] = (byte)'C';
data2[1] = (byte)'D';
PreAllocatedOverlapped preAlloc1 = new PreAllocatedOverlapped(OnOverlappedOperationCompleted, result1, data1);
PreAllocatedOverlapped preAlloc2 = new PreAllocatedOverlapped(OnOverlappedOperationCompleted, result2, data2);
for (int i = 0; i < 10; i++)
{
NativeOverlapped* overlapped1 = boundHandle1.AllocateNativeOverlapped(preAlloc1);
NativeOverlapped* overlapped2 = boundHandle2.AllocateNativeOverlapped(preAlloc2);
fixed (byte* p1 = data1, p2 = data2)
{
int retval = DllImport.WriteFile(boundHandle1.Handle, p1, DATA_SIZE, IntPtr.Zero, overlapped1);
if (retval == 0)
{
Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error());
}
retval = DllImport.WriteFile(boundHandle2.Handle, p2, DATA_SIZE, IntPtr.Zero, overlapped2);
if (retval == 0)
{
Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error());
}
// Wait for overlapped operations to complete
WaitHandle.WaitAll(new WaitHandle[] { result1.Event, result2.Event });
}
boundHandle1.FreeNativeOverlapped(overlapped1);
boundHandle2.FreeNativeOverlapped(overlapped2);
result1.Event.Reset();
result2.Event.Reset();
Assert.Equal(0, result1.ErrorCode);
Assert.Equal(0, result2.ErrorCode);
Assert.Equal(DATA_SIZE, result1.BytesWritten);
Assert.Equal(DATA_SIZE, result2.BytesWritten);
}
boundHandle1.Dispose();
boundHandle2.Dispose();
preAlloc1.Dispose();
preAlloc2.Dispose();
handle1.Dispose();
handle2.Dispose();
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Active Issue dotnet/corefx#13343")]
public unsafe void FlowsAsyncLocalsToCallback()
{ // Makes sure that we flow async locals to callback
const int DATA_SIZE = 2;
SafeHandle handle = HandleFactory.CreateAsyncFileHandleForWrite(@"AsyncLocal.tmp");
ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle);
OverlappedContext context = new OverlappedContext();
byte[] data = new byte[DATA_SIZE];
AsyncLocal<int> asyncLocal = new AsyncLocal<int>();
asyncLocal.Value = 10;
int? result = null;
IOCompletionCallback callback = (_, __, ___) => {
result = asyncLocal.Value;
OnOverlappedOperationCompleted(_, __, ___);
};
NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped(callback, context, data);
fixed (byte* p = data)
{
int retval = DllImport.WriteFile(boundHandle.Handle, p, DATA_SIZE, IntPtr.Zero, overlapped);
if (retval == 0)
{
Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error());
}
// Wait for overlapped operation to complete
context.Event.WaitOne();
}
boundHandle.FreeNativeOverlapped(overlapped);
boundHandle.Dispose();
handle.Dispose();
Assert.Equal(10, result);
}
private static unsafe void OnOverlappedOperationCompleted(uint errorCode, uint numBytes, NativeOverlapped* overlapped)
{
OverlappedContext result = (OverlappedContext)ThreadPoolBoundHandle.GetNativeOverlappedState(overlapped);
result.ErrorCode = (int)errorCode;
result.BytesWritten = (int)numBytes;
// Signal original thread to indicate overlapped completed
result.Event.Set();
}
private class OverlappedContext
{
public readonly ManualResetEvent Event = new ManualResetEvent(false);
public int ErrorCode;
public int BytesWritten;
}
}
| |
using System;
using System.Threading;
namespace Orleans.Runtime
{
internal abstract class AsynchAgent : IDisposable
{
public enum FaultBehavior
{
CrashOnFault, // Crash the process if the agent faults
RestartOnFault, // Restart the agent if it faults
IgnoreFault // Allow the agent to stop if it faults, but take no other action (other than logging)
}
private Thread t;
protected CancellationTokenSource Cts;
protected object Lockable;
protected Logger Log;
private readonly string type;
protected FaultBehavior OnFault;
#if TRACK_DETAILED_STATS
internal protected ThreadTrackingStatistic threadTracking;
#endif
public ThreadState State { get; private set; }
internal string Name { get; private set; }
internal int ManagedThreadId { get { return t==null ? -1 : t.ManagedThreadId; } }
protected AsynchAgent(string nameSuffix)
{
Cts = new CancellationTokenSource();
var thisType = GetType();
type = thisType.Namespace + "." + thisType.Name;
if (type.StartsWith("Orleans.", StringComparison.Ordinal))
{
type = type.Substring(8);
}
if (!string.IsNullOrEmpty(nameSuffix))
{
Name = type + "/" + nameSuffix;
}
else
{
Name = type;
}
Lockable = new object();
State = ThreadState.Unstarted;
OnFault = FaultBehavior.IgnoreFault;
Log = LogManager.GetLogger(Name, LoggerType.Runtime);
#if !NETSTANDARD
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
#endif
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking = new ThreadTrackingStatistic(Name);
}
#endif
t = new Thread(AgentThreadProc) { IsBackground = true, Name = this.Name };
}
protected AsynchAgent()
: this(null)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
try
{
if (State != ThreadState.Stopped)
{
Stop();
}
}
catch (Exception exc)
{
// ignore. Just make sure DomainUnload handler does not throw.
Log.Verbose("Ignoring error during Stop: {0}", exc);
}
}
public virtual void Start()
{
lock (Lockable)
{
if (State == ThreadState.Running)
{
return;
}
if (State == ThreadState.Stopped)
{
Cts = new CancellationTokenSource();
t = new Thread(AgentThreadProc) { IsBackground = true, Name = this.Name };
}
t.Start(this);
State = ThreadState.Running;
}
if(Log.IsVerbose) Log.Verbose("Started asynch agent " + this.Name);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public virtual void Stop()
{
try
{
lock (Lockable)
{
if (State == ThreadState.Running)
{
State = ThreadState.StopRequested;
Cts.Cancel();
State = ThreadState.Stopped;
}
}
#if !NETSTANDARD
AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload;
#endif
}
catch (Exception exc)
{
// ignore. Just make sure stop does not throw.
Log.Verbose("Ignoring error during Stop: {0}", exc);
}
Log.Verbose("Stopped agent");
}
#if !NETSTANDARD
public void Abort(object stateInfo)
{
if(t!=null)
t.Abort(stateInfo);
}
#endif
public void Join(TimeSpan timeout)
{
try
{
var agentThread = t;
if (agentThread != null)
{
bool joined = agentThread.Join((int)timeout.TotalMilliseconds);
Log.Verbose("{0} the agent thread {1} after {2} time.", joined ? "Joined" : "Did not join", Name, timeout);
}
}catch(Exception exc)
{
// ignore. Just make sure Join does not throw.
Log.Verbose("Ignoring error during Join: {0}", exc);
}
}
protected abstract void Run();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void AgentThreadProc(Object obj)
{
var agent = obj as AsynchAgent;
if (agent == null)
{
var log = LogManager.GetLogger("RuntimeCore.AsynchAgent");
log.Error(ErrorCode.Runtime_Error_100022, "Agent thread started with incorrect parameter type");
return;
}
try
{
LogStatus(agent.Log, "Starting AsyncAgent {0} on managed thread {1}", agent.Name, Thread.CurrentThread.ManagedThreadId);
CounterStatistic.SetOrleansManagedThread(); // do it before using CounterStatistic.
CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.RUNTIME_THREADS_ASYNC_AGENT_PERAGENTTYPE, agent.type)).Increment();
CounterStatistic.FindOrCreate(StatisticNames.RUNTIME_THREADS_ASYNC_AGENT_TOTAL_THREADS_CREATED).Increment();
agent.Run();
}
catch (Exception exc)
{
if (agent.State == ThreadState.Running) // If we're stopping, ignore exceptions
{
var log = agent.Log;
switch (agent.OnFault)
{
case FaultBehavior.CrashOnFault:
Console.WriteLine(
"The {0} agent has thrown an unhandled exception, {1}. The process will be terminated.",
agent.Name, exc);
log.Error(ErrorCode.Runtime_Error_100023,
"AsynchAgent Run method has thrown an unhandled exception. The process will be terminated.",
exc);
log.Fail(ErrorCode.Runtime_Error_100024, "Terminating process because of an unhandled exception caught in AsynchAgent.Run.");
break;
case FaultBehavior.IgnoreFault:
log.Error(ErrorCode.Runtime_Error_100025, "AsynchAgent Run method has thrown an unhandled exception. The agent will exit.",
exc);
agent.State = ThreadState.Stopped;
break;
case FaultBehavior.RestartOnFault:
log.Error(ErrorCode.Runtime_Error_100026,
"AsynchAgent Run method has thrown an unhandled exception. The agent will be restarted.",
exc);
agent.State = ThreadState.Stopped;
try
{
agent.Start();
}
catch (Exception ex)
{
log.Error(ErrorCode.Runtime_Error_100027, "Unable to restart AsynchAgent", ex);
agent.State = ThreadState.Stopped;
}
break;
}
}
}
finally
{
CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.RUNTIME_THREADS_ASYNC_AGENT_PERAGENTTYPE, agent.type)).DecrementBy(1);
agent.Log.Info(ErrorCode.Runtime_Error_100328, "Stopping AsyncAgent {0} that runs on managed thread {1}", agent.Name, Thread.CurrentThread.ManagedThreadId);
}
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing) return;
if (Cts != null)
{
Cts.Dispose();
Cts = null;
}
}
#endregion
public override string ToString()
{
return Name;
}
internal static bool IsStarting { get; set; }
private static void LogStatus(Logger log, string msg, params object[] args)
{
if (IsStarting)
{
// Reduce log noise during silo startup
if (log.IsVerbose) log.Verbose(msg, args);
}
else
{
// Changes in agent threads during all operations aside for initial creation are usually important diag events.
log.Info(msg, args);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Imaging
{
using System.Runtime.InteropServices;
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader"]/*' />
/// <devdoc>
/// Contains attributes of an
/// associated <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
[StructLayout(LayoutKind.Sequential)]
public sealed class MetafileHeader
{
// determine which to use by nullity
internal MetafileHeaderWmf wmf;
internal MetafileHeaderEmf emf;
internal MetafileHeader()
{
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.Type"]/*' />
/// <devdoc>
/// Gets the type of the associated <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
public MetafileType Type
{
get
{
return IsWmf() ? wmf.type : emf.type;
}
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.MetafileSize"]/*' />
/// <devdoc>
/// <para>
/// Gets the size, in bytes, of the associated
/// <see cref='System.Drawing.Imaging.Metafile'/>.
/// </para>
/// </devdoc>
public int MetafileSize
{
get
{
return IsWmf() ? wmf.size : emf.size;
}
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.Version"]/*' />
/// <devdoc>
/// Gets the version number of the associated
/// <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
public int Version
{
get
{
return IsWmf() ? wmf.version : emf.version;
}
}
/* FxCop rule 'AvoidBuildingNonCallableCode' - Left here in case it is needed in the future.
private EmfPlusFlags EmfPlusFlags
{
get
{
return IsWmf() ? wmf.emfPlusFlags : emf.emfPlusFlags;
}
}
*/
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.DpiX"]/*' />
/// <devdoc>
/// Gets the horizontal resolution, in
/// dots-per-inch, of the associated <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
public float DpiX
{
get
{
return IsWmf() ? wmf.dpiX : emf.dpiX;
}
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.DpiY"]/*' />
/// <devdoc>
/// Gets the vertical resolution, in
/// dots-per-inch, of the associated <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
public float DpiY
{
get
{
return IsWmf() ? wmf.dpiY : emf.dpiY;
}
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.Bounds"]/*' />
/// <devdoc>
/// Gets a <see cref='System.Drawing.Rectangle'/> that bounds the associated
/// <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
public Rectangle Bounds
{
get
{
return IsWmf() ?
new Rectangle(wmf.X, wmf.Y, wmf.Width, wmf.Height) :
new Rectangle(emf.X, emf.Y, emf.Width, emf.Height);
}
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.IsWmf"]/*' />
/// <devdoc>
/// Returns a value indicating whether the
/// associated <see cref='System.Drawing.Imaging.Metafile'/> is in the Windows metafile
/// format.
/// </devdoc>
public bool IsWmf()
{
if ((wmf == null) && (emf == null))
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
if ((wmf != null) &&
((wmf.type == MetafileType.Wmf) ||
(wmf.type == MetafileType.WmfPlaceable)))
return true;
else
return false;
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.IsWmfPlaceable"]/*' />
/// <devdoc>
/// <para>
/// Returns a value indicating whether the
/// associated <see cref='System.Drawing.Imaging.Metafile'/> is in the Windows Placeable metafile
/// format.
/// </para>
/// </devdoc>
public bool IsWmfPlaceable()
{
if (wmf == null && emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return ((wmf != null) && (wmf.type == MetafileType.WmfPlaceable));
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.IsEmf"]/*' />
/// <devdoc>
/// Returns a value indicating whether the
/// associated <see cref='System.Drawing.Imaging.Metafile'/> is in the Windows enhanced metafile
/// format.
/// </devdoc>
public bool IsEmf()
{
if (wmf == null && emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return ((emf != null) && (emf.type == MetafileType.Emf));
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.IsEmfOrEmfPlus"]/*' />
/// <devdoc>
/// Returns a value indicating whether the
/// associated <see cref='System.Drawing.Imaging.Metafile'/> is in the Windows enhanced metafile
/// format or the Windows enhanced metafile plus.
/// </devdoc>
public bool IsEmfOrEmfPlus()
{
if (wmf == null && emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return ((emf != null) && (emf.type >= MetafileType.Emf));
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.IsEmfPlus"]/*' />
/// <devdoc>
/// Returns a value indicating whether the
/// associated <see cref='System.Drawing.Imaging.Metafile'/> is in the Windows enhanced metafile
/// plus format.
/// </devdoc>
public bool IsEmfPlus()
{
if (wmf == null && emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return ((emf != null) && (emf.type >= MetafileType.EmfPlusOnly));
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.IsEmfPlusDual"]/*' />
/// <devdoc>
/// Returns a value indicating whether the
/// associated <see cref='System.Drawing.Imaging.Metafile'/> is in the Dual enhanced
/// metafile format. This format supports both the enhanced and the enhanced
/// plus format.
/// </devdoc>
public bool IsEmfPlusDual()
{
if (wmf == null && emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return ((emf != null) && (emf.type == MetafileType.EmfPlusDual));
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.IsEmfPlusOnly"]/*' />
/// <devdoc>
/// <para>
/// Returns a value indicating whether the associated <see cref='System.Drawing.Imaging.Metafile'/> supports only the Windows
/// enhanced metafile plus format.
/// </para>
/// </devdoc>
public bool IsEmfPlusOnly()
{
if (wmf == null && emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return ((emf != null) && (emf.type == MetafileType.EmfPlusOnly));
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.IsDisplay"]/*' />
/// <devdoc>
/// <para>
/// Returns a value indicating whether the associated <see cref='System.Drawing.Imaging.Metafile'/> is device-dependent.
/// </para>
/// </devdoc>
public bool IsDisplay()
{
return IsEmfPlus() &&
(((unchecked((int)emf.emfPlusFlags)) & ((int)EmfPlusFlags.Display)) != 0);
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.WmfHeader"]/*' />
/// <devdoc>
/// Gets the WMF header file for the associated
/// <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
public MetaHeader WmfHeader
{
get
{
if (wmf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return wmf.WmfHeader;
}
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.EmfHeader"]/*' />
/// <devdoc>
/// <para>
/// Gets the WMF header file for the associated <see cref='System.Drawing.Imaging.Metafile'/>.
/// </para>
/// </devdoc>
/* FxCop rule 'AvoidBuildingNonCallableCode' - Left here in case it is needed in the future.
internal SafeNativeMethods.ENHMETAHEADER EmfHeader
{
get
{
if (emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return emf.EmfHeader;
}
}
*/
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.EmfPlusHeaderSize"]/*' />
/// <devdoc>
/// Gets the size, in bytes, of the
/// enhanced metafile plus header file.
/// </devdoc>
public int EmfPlusHeaderSize
{
get
{
if (wmf == null && emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return IsWmf() ? wmf.EmfPlusHeaderSize : emf.EmfPlusHeaderSize;
}
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.LogicalDpiX"]/*' />
/// <devdoc>
/// <para>
/// Gets the logical horizontal resolution, in
/// dots-per-inch, of the associated <see cref='System.Drawing.Imaging.Metafile'/>.
/// </para>
/// </devdoc>
public int LogicalDpiX
{
get
{
if (wmf == null && emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return IsWmf() ? wmf.LogicalDpiX : emf.LogicalDpiX;
}
}
/// <include file='doc\MetafileHeader.uex' path='docs/doc[@for="MetafileHeader.LogicalDpiY"]/*' />
/// <devdoc>
/// Gets the logical vertical resolution, in
/// dots-per-inch, of the associated <see cref='System.Drawing.Imaging.Metafile'/>.
/// </devdoc>
public int LogicalDpiY
{
get
{
if (wmf == null && emf == null)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
return IsWmf() ? wmf.LogicalDpiY : emf.LogicalDpiX;
}
}
}
}
| |
// 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 ShiftRightLogicalUInt3232()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt3232();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalUInt3232
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar;
private Vector128<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogicalUInt3232()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogicalUInt3232()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.ShiftRightLogical(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.ShiftRightLogical(
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.ShiftRightLogical(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.ShiftRightLogical(
_clsVar,
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt3232();
var result = Sse2.ShiftRightLogical(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.ShiftRightLogical(_fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
if (0 != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0!= result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<UInt32>(Vector128<UInt32><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
/// <summary>
/// char.IsLetterOrDigit(string, int)
/// Indicates whether the character at the specified position in a specified string is categorized
/// as a letter or decimal digit character.
/// </summary>
public class CharIsLetterOrDigit
{
private const int c_MIN_STR_LEN = 2;
private const int c_MAX_STR_LEN = 256;
private static readonly char[] r_decimalDigits =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
public static int Main()
{
CharIsLetterOrDigit testObj = new CharIsLetterOrDigit();
TestLibrary.TestFramework.BeginTestCase("for method: char.IsLetterOrDigit(string, int)");
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;
TestLibrary.TestFramework.LogInformation("[Negaitive]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
//Generate the character for validate
char ch = 'a';
return this.DoTest("PosTest1: Letter character",
"P001", "001", "002", ch, true);
}
public bool PosTest2()
{
//Generate a non character for validate
int index = TestLibrary.Generator.GetInt32(-55) % r_decimalDigits.Length;
char ch = r_decimalDigits[index];
return this.DoTest("PosTest2: Decimal digit character.",
"P002", "003", "004", ch, true);
}
public bool PosTest3()
{
//Generate a non character for validate
char ch = '\n';
return this.DoTest("PosTest3: Not decimal digit nor letter character.",
"P003", "005", "006", ch, false);
}
#endregion
#region Helper method for positive tests
private bool DoTest(string testDesc,
string testId,
string errorNum1,
string errorNum2,
char ch,
bool expectedResult)
{
bool retVal = true;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
bool actualResult = char.IsLetterOrDigit(ch);
if (expectedResult != actualResult)
{
if (expectedResult)
{
errorDesc = string.Format("Character \\u{0:x} should belong to letter or decimal digit characters.", (int)ch);
}
else
{
errorDesc = string.Format("Character \\u{0:x} does not belong to letter or decimal digit characters.", (int)ch);
}
TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nCharacter is \\u{0:x}", ch);
TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentNullException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: String is a null reference (Nothing in Visual Basic).";
string errorDesc;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
index = TestLibrary.Generator.GetInt32(-55);
char.IsLetterOrDigit(null, index);
errorDesc = "ArgumentNullException is not thrown as expected, index is " + index;
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e + "\n Index is " + index;
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//ArgumentOutOfRangeException
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: Index is too great.";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = str.Length + TestLibrary.Generator.GetInt16(-55);
index = str.Length;
char.IsLetterOrDigit(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe character is \\u{0:x}", str[index]);
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: Index is a negative value";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = -1 * (TestLibrary.Generator.GetInt16(-55));
char.IsLetterOrDigit(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe character is \\u{0:x}", str[index]);
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
/*
* Copyright 2007 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 NUnit.Framework;
namespace ZXing.Common.Test
{
/// <summary>
/// <author>Sean Owen</author>
/// </summary>
[TestFixture]
public sealed class BitArrayTestCase
{
[Test]
public void testGetSet()
{
BitArray array = new BitArray(33);
for (int i = 0; i < 33; i++)
{
Assert.IsFalse(array[i]);
array[i] = true;
Assert.IsTrue(array[i]);
}
}
[Test]
public void testGetNextSet1()
{
BitArray array = new BitArray(32);
for (int i = 0; i < array.Size; i++)
{
Assert.AreEqual(32, array.getNextSet(i));
}
array = new BitArray(33);
for (int i = 0; i < array.Size; i++)
{
Assert.AreEqual(33, array.getNextSet(i));
}
}
[Test]
public void testGetNextSet2()
{
BitArray array = new BitArray(33);
array[31] = true;
for (int i = 0; i < array.Size; i++)
{
Assert.AreEqual(i <= 31 ? 31 : 33, array.getNextSet(i));
}
array = new BitArray(33);
array[32] = true;
for (int i = 0; i < array.Size; i++)
{
Assert.AreEqual(32, array.getNextSet(i));
}
}
[Test]
public void testGetNextSet3()
{
BitArray array = new BitArray(63);
array[31] = true;
array[32] = true;
for (int i = 0; i < array.Size; i++)
{
int expected;
if (i <= 31)
{
expected = 31;
}
else if (i == 32)
{
expected = 32;
}
else
{
expected = 63;
}
Assert.AreEqual(expected, array.getNextSet(i));
}
}
[Test]
public void testGetNextSet4()
{
BitArray array = new BitArray(63);
array[33] = true;
array[40] = true;
for (int i = 0; i < array.Size; i++)
{
int expected;
if (i <= 33)
{
expected = 33;
}
else if (i <= 40)
{
expected = 40;
}
else
{
expected = 63;
}
Assert.AreEqual(expected, array.getNextSet(i));
}
}
[Test]
public void testGetNextSet5()
{
Random r = new Random(0x0EADBEEF);
for (int i = 0; i < 10; i++)
{
BitArray array = new BitArray(1 + r.Next(100));
int numSet = r.Next(20);
for (int j = 0; j < numSet; j++)
{
array[r.Next(array.Size)] = true;
}
int numQueries = r.Next(20);
for (int j = 0; j < numQueries; j++)
{
int query = r.Next(array.Size);
int expected = query;
while (expected < array.Size && !array[expected])
{
expected++;
}
int actual = array.getNextSet(query);
Assert.AreEqual(expected, actual);
}
}
}
[Test]
public void testSetBulk()
{
BitArray array = new BitArray(64);
array.setBulk(32, -65536);
for (int i = 0; i < 48; i++)
{
Assert.IsFalse(array[i]);
}
for (int i = 48; i < 64; i++)
{
Assert.IsTrue(array[i]);
}
}
[Test]
public void testSetRange()
{
BitArray array = new BitArray(64);
array.setRange(28, 36);
Assert.IsFalse(array[27]);
for (int i = 28; i < 36; i++)
{
Assert.IsTrue(array[i]);
}
Assert.IsFalse(array[36]);
}
[Test]
public void testClear()
{
BitArray array = new BitArray(32);
for (int i = 0; i < 32; i++)
{
array[i] = true;
}
array.clear();
for (int i = 0; i < 32; i++)
{
Assert.IsFalse(array[i]);
}
}
[Test]
public void testFlip()
{
BitArray array = new BitArray(32);
Assert.IsFalse(array[5]);
array.flip(5);
Assert.IsTrue(array[5]);
array.flip(5);
Assert.IsFalse(array[5]);
}
[Test]
public void testGetArray()
{
BitArray array = new BitArray(64);
array[0] = true;
array[63] = true;
var ints = array.Array;
Assert.AreEqual(1, ints[0]);
Assert.AreEqual(Int32.MinValue, ints[1]);
}
[Test]
public void testIsRange()
{
BitArray array = new BitArray(64);
Assert.IsTrue(array.isRange(0, 64, false));
Assert.IsFalse(array.isRange(0, 64, true));
array[32] = true;
Assert.IsTrue(array.isRange(32, 33, true));
array[31] = true;
Assert.IsTrue(array.isRange(31, 33, true));
array[34] = true;
Assert.IsFalse(array.isRange(31, 35, true));
for (int i = 0; i < 31; i++)
{
array[i] = true;
}
Assert.IsTrue(array.isRange(0, 33, true));
for (int i = 33; i < 64; i++)
{
array[i] = true;
}
Assert.IsTrue(array.isRange(0, 64, true));
Assert.IsFalse(array.isRange(0, 64, false));
}
[Test]
public void testClone()
{
BitArray array = new BitArray(32);
var clone = (BitArray) array.Clone();
clone[0] = true;
Assert.IsFalse(array[0]);
}
[Test]
public void testEquals()
{
BitArray a = new BitArray(32);
BitArray b = new BitArray(32);
Assert.AreEqual(a, b);
Assert.AreEqual(a.GetHashCode(), b.GetHashCode());
Assert.AreNotEqual(a, new BitArray(31));
a[16] = true;
Assert.AreNotEqual(a, new BitArray(31));
Assert.AreNotEqual(a.GetHashCode(), b.GetHashCode());
b[16] = true;
Assert.AreEqual(a, b);
Assert.AreEqual(a.GetHashCode(), b.GetHashCode());
}
#if !SILVERLIGHT
[Test]
public void ReverseAlgorithmTest()
{
var oldBits = new[] { 128, 256, 512, 6453324, 50934953 };
for (var size = 1; size < 160; size++)
{
var newBitsOriginal = reverseOriginal(oldBits, size);
var newBitsNew = reverseNew(oldBits, size);
if (!arrays_are_equal(newBitsOriginal, newBitsNew, size / 32 + 1))
{
System.Diagnostics.Trace.WriteLine(size);
System.Diagnostics.Trace.WriteLine(BitsToString(oldBits, size));
System.Diagnostics.Trace.WriteLine(BitsToString(newBitsOriginal, size));
System.Diagnostics.Trace.WriteLine(BitsToString(newBitsNew, size));
}
Assert.IsTrue(arrays_are_equal(newBitsOriginal, newBitsNew, size / 32 + 1));
}
}
[Test]
public void ReverseSpeedTest()
{
var size = 140;
var oldBits = new[] {128, 256, 512, 6453324, 50934953};
var newBitsOriginal = reverseOriginal(oldBits, size);
var newBitsNew = reverseNew(oldBits, size);
System.Diagnostics.Trace.WriteLine(BitsToString(oldBits, size));
System.Diagnostics.Trace.WriteLine(BitsToString(newBitsOriginal, size));
System.Diagnostics.Trace.WriteLine(BitsToString(newBitsNew, size));
Assert.IsTrue(arrays_are_equal(newBitsOriginal, newBitsNew, newBitsNew.Length));
var startOld = DateTime.Now;
for (int runs = 0; runs < 1000000; runs++)
{
reverseOriginal(oldBits, 140);
}
var endOld = DateTime.Now;
var startNew = DateTime.Now;
for (int runs = 0; runs < 1000000; runs++)
{
reverseNew(oldBits, 140);
}
var endNew = DateTime.Now;
System.Diagnostics.Trace.WriteLine(endOld - startOld);
System.Diagnostics.Trace.WriteLine(endNew - startNew);
}
/// <summary> Reverses all bits in the array.</summary>
private int[] reverseOriginal(int[] oldBits, int oldSize)
{
int[] newBits = new int[oldBits.Length];
int size = oldSize;
for (int i = 0; i < size; i++)
{
if (bits_index(oldBits, size - i - 1))
{
newBits[i >> 5] |= 1 << (i & 0x1F);
}
}
return newBits;
}
private bool bits_index(int[] bits, int i)
{
return (bits[i >> 5] & (1 << (i & 0x1F))) != 0;
}
/// <summary> Reverses all bits in the array.</summary>
private int[] reverseNew(int[] oldBits, int oldSize)
{
// doesn't work if more ints are used as necessary
int[] newBits = new int[oldBits.Length];
var oldBitsLen = (int)Math.Ceiling(oldSize / 32f);
var len = oldBitsLen - 1;
for (var i = 0; i < oldBitsLen; i++)
{
var x = (long)oldBits[i];
x = ((x >> 1) & 0x55555555u) | ((x & 0x55555555u) << 1);
x = ((x >> 2) & 0x33333333u) | ((x & 0x33333333u) << 2);
x = ((x >> 4) & 0x0f0f0f0fu) | ((x & 0x0f0f0f0fu) << 4);
x = ((x >> 8) & 0x00ff00ffu) | ((x & 0x00ff00ffu) << 8);
x = ((x >> 16) & 0xffffu) | ((x & 0xffffu) << 16);
newBits[len - i] = (int)x;
}
if (oldSize != oldBitsLen * 32)
{
var leftOffset = oldBitsLen * 32 - oldSize;
var mask = 1;
for (var i = 0; i < 31 - leftOffset; i++ )
mask = (mask << 1) | 1;
var currentInt = (newBits[0] >> leftOffset) & mask;
for (var i = 1; i < oldBitsLen; i++)
{
var nextInt = newBits[i];
currentInt |= nextInt << (32 - leftOffset);
newBits[i - 1] = currentInt;
currentInt = (nextInt >> leftOffset) & mask;
}
newBits[oldBitsLen - 1] = currentInt;
}
return newBits;
}
private bool arrays_are_equal(int[] left, int[] right, int size)
{
for (var i = 0; i < size; i++)
{
if (left[i] != right[i])
return false;
}
return true;
}
private string BitsToString(int[] bits, int size)
{
var result = new System.Text.StringBuilder(size);
for (int i = 0; i < size; i++)
{
if ((i & 0x07) == 0)
{
result.Append(' ');
}
result.Append(bits_index(bits, i) ? 'X' : '.');
}
return result.ToString();
}
[Test]
public void testBitArrayNet()
{
var netArray = new System.Collections.BitArray(140, false);
var zxingArray = new BitArray(140);
var netVal = netArray[100];
var zxingVal = zxingArray[100];
Assert.AreEqual(netVal, zxingVal);
var startOld = DateTime.Now;
for (int runs = 0; runs < 1000000; runs++)
{
netVal = netArray[100];
netArray[100] = netVal;
}
var endOld = DateTime.Now;
var startNew = DateTime.Now;
for (int runs = 0; runs < 1000000; runs++)
{
zxingVal = zxingArray[100];
zxingArray[100] = zxingVal;
}
var endNew = DateTime.Now;
System.Diagnostics.Trace.WriteLine(endOld - startOld);
System.Diagnostics.Trace.WriteLine(endNew - startNew);
}
#endif
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Dictionary.cs
//
// 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.Linq;
using Dot42;
namespace System.Collections.Generic
{
internal interface IDictionaryImpl<TKey, TValue> : IDictionary<TKey, TValue>
{
bool ContainsValue(TValue value);
bool IsSynchronized { get; }
object SyncRoot { get; }
void CopyTo(Array array, int index);
}
// since we want both support the lightweight java-forwarding
// and the full c# IComparer<T> functionality, this is a thin
// wrapper around two different implementations.
//
// Note that this redirection could also be handled at the compiler
// to remove one level of indirection at runtime.
// in that case the comparer-wrapper dictionary should derive from
// the plain dictionary. Only the specific constructor call would
// be redirected to a factory function, deciding which class to instantiate.
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, ICollection
{
internal readonly IDictionaryImpl<TKey, TValue> dict;
public IEqualityComparer<TKey> Comparer { get; private set; }
/// <summary>
/// Default ctor
/// </summary>
public Dictionary()
{
if(IsKeyIdentityType())
dict = new DictionaryImplOpenIdentityHashMap<TKey, TValue>();
else
dict = new DictionaryImplHashMap<TKey, TValue>();
}
/// <summary>
/// Creates an Dictionary with the given capacity
/// </summary>
public Dictionary(int capacity)
{
if (IsKeyIdentityType())
dict = new DictionaryImplOpenIdentityHashMap<TKey, TValue>(capacity);
else
dict = new DictionaryImplHashMap<TKey, TValue>(capacity);
}
/// <summary>
/// Default ctor
/// </summary>
public Dictionary(Dictionary<TKey, TValue> source)
{
if (source.dict is DictionaryImplHashMap<TKey, TValue>)
{
dict = new DictionaryImplHashMap<TKey, TValue>((DictionaryImplHashMap<TKey, TValue>) source.dict);
return;
}
if (source.dict is DictionaryImplHashMapWithComparerWrapper<TKey, TValue>)
{
dict = new DictionaryImplHashMapWithComparerWrapper<TKey, TValue>((DictionaryImplHashMapWithComparerWrapper<TKey, TValue>) source.dict);
return;
}
if (source.dict is DictionaryImplOpenIdentityHashMap<TKey, TValue>)
{
dict = new DictionaryImplOpenIdentityHashMap<TKey, TValue>((DictionaryImplOpenIdentityHashMap<TKey, TValue>)source.dict);
return;
}
// can this even happen?
if (source.Comparer == null || source.Comparer is EqualityComparer<TKey>.DefaultComparer)
{
if(IsKeyIdentityType())
dict = new DictionaryImplOpenIdentityHashMap<TKey, TValue>();
else
dict = new DictionaryImplHashMap<TKey, TValue>();
}
else
{
dict = new DictionaryImplHashMapWithComparerWrapper<TKey, TValue>(source.Comparer);
}
foreach (var elem in source)
dict.Add(elem);
}
/// <summary>
/// Default ctor
/// </summary>
public Dictionary(IEqualityComparer<TKey> comparer)
{
Comparer = comparer;
if (comparer == null || comparer is EqualityComparer<TKey>.DefaultComparer)
{
dict = new DictionaryImplHashMap<TKey, TValue>();
}
else
{
// have to use the key-wrapping dictionary.
dict = new DictionaryImplHashMapWithComparerWrapper<TKey, TValue>(comparer);
}
}
private bool IsKeyIdentityType()
{
// TODO: we could use reflection to find out if the type or any of
// its ancestors overrides equals or getHashCode.
return typeof(TKey) == typeof(Type);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return dict.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) dict).GetEnumerator();
}
public bool ContainsValue(TValue value)
{
return dict.ContainsValue(value);
}
public int Count
{
get { return dict.Count; } }
public bool IsSynchronized { get { return dict.IsSynchronized; } }
public object SyncRoot { get { return dict.SyncRoot; } }
public void CopyTo(Array array, int index)
{
dict.CopyTo(array, index);
}
public bool IsReadOnly
{
get { return dict.IsReadOnly; }
}
public void Add(KeyValuePair<TKey, TValue> item)
{
ThrowHelper.ThrowIfArgumentNullException(item, "item");
ThrowIfKeyExists(item.Key);
dict.Add(item);
}
public void Clear()
{
dict.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
ThrowHelper.ThrowIfArgumentNullException(item, "item");
ThrowHelper.ThrowIfArgumentNullException(item.Key, "item.Key");
return dict.Contains(item);
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
ThrowHelper.ThrowIfArgumentNullException(item, "item");
ThrowHelper.ThrowIfArgumentNullException(item.Key, "item.Key");
return dict.Remove(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
dict.CopyTo(array, index);
}
public TValue this[TKey key]
{
get
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
return dict[key];
}
set
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
dict[key] = value;
}
}
public bool ContainsKey(TKey key)
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
return dict.ContainsKey(key);
}
public void Add(TKey key, TValue value)
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
ThrowIfKeyExists(key);
dict.Add(key, value);
}
public bool Remove(TKey key)
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
return dict.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
return dict.TryGetValue(key, out value);
}
[Inline]
private void ThrowIfKeyExists(TKey key)
{
if (dict.ContainsKey(key))
ThrowHelper.ThrowArgumentException("duplicate key: " + key, "key");
}
#region IDictionary explicit implementation
public ICollection<TKey> Keys
{
get { return dict.Keys; }
}
public ICollection<TValue> Values
{
get { return dict.Values; }
}
ICollection IDictionary.Values
{
get { return ((IDictionary)dict).Values; }
}
ICollection IDictionary.Keys
{
get { return ((IDictionary)dict).Keys; }
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return ((IDictionary)dict).GetEnumerator();
}
bool IDictionary.Contains(object key)
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
if (!(key is TKey)) return false;
return ContainsKey((TKey)key);
}
void IDictionary.Remove(object key)
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
if (!(key is TKey)) return;
Remove((TKey)key);
}
void IDictionary.Add(object key, object value)
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
ThrowIfWrongKeyType(key);
ThrowIfWrongValueType(value);
Add((TKey)key, (TValue)value);
}
bool IDictionary.IsFixedSize { get { return false; } }
object IDictionary.this[object key]
{
get
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
if (!(key is TKey)) return null;
TValue val;
if (!TryGetValue((TKey) key, out val))
return null;
return val;
}
set
{
ThrowHelper.ThrowIfArgumentNullException(key, "key");
ThrowIfWrongKeyType(key);
ThrowIfWrongValueType(value);
this[(TKey)key] = (TValue)value;
}
}
private void ThrowIfWrongKeyType(object key)
{
if (!(key is TKey))
{
throw new ArgumentException(string.Format("can not store key type {0} in {1}", key.GetType(), TypeName));
}
}
private void ThrowIfWrongValueType(object value)
{
// be lenient: or else we would have to correctly handle boxing automatically and stuff.
//
//var type = typeof(TValue);
//var isValueType = type.IsValueType;
//if(isValueType && value == null)
// ThrowHelper.ThrowArgumentNullException("value");
//if (!isValueType && value == null)
// return;
//var tvalue = typeof (TValue);
//if (tvalue == typeof (object))
// return;
//if (value != null && !(typeof (TValue).IsAssignableFrom(value.GetType())))
//{
// throw new ArgumentException(string.Format("can not store value type {0} in {1}", value.GetType(), TypeName));
//}
}
private string TypeName
{
get
{
string dictType = string.Format("{0}<{1},{2}>", GetType().FullName, typeof (TKey), typeof (TValue));
return dictType;
}
}
#endregion
}
}
| |
// <copyright file="ObservableQueue{T}.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using IX.Observable.Adapters;
using IX.Observable.DebugAide;
using IX.Observable.UndoLevels;
using IX.StandardExtensions.Contracts;
using IX.StandardExtensions.Threading;
using IX.System.Collections.Generic;
using IX.Undoable;
using JetBrains.Annotations;
namespace IX.Observable
{
/// <summary>
/// A queue that broadcasts its changes.
/// </summary>
/// <typeparam name="T">The type of items in the queue.</typeparam>
[DebuggerDisplay("ObservableQueue, Count = {" + nameof(Count) + "}")]
[DebuggerTypeProxy(typeof(QueueDebugView<>))]
[CollectionDataContract(
Namespace = Constants.DataContractNamespace,
Name = "Observable{0}Queue",
ItemName = "Item")]
[PublicAPI]
public class ObservableQueue<T> : ObservableCollectionBase<T>, IQueue<T>
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
public ObservableQueue()
: base(new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>()))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="collection">A collection of items to copy from.</param>
public ObservableQueue(IEnumerable<T> collection)
: base(new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>(collection)))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="capacity">The initial capacity of the queue.</param>
public ObservableQueue(int capacity)
: base(new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>(capacity)))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="context">The synchronization context top use when posting observable messages.</param>
public ObservableQueue(SynchronizationContext context)
: base(
new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>()),
context)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="context">The synchronization context top use when posting observable messages.</param>
/// <param name="collection">A collection of items to copy from.</param>
public ObservableQueue(
SynchronizationContext context,
IEnumerable<T> collection)
: base(
new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>(collection)),
context)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="context">The synchronization context top use when posting observable messages.</param>
/// <param name="capacity">The initial capacity of the queue.</param>
public ObservableQueue(
SynchronizationContext context,
int capacity)
: base(
new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>(capacity)),
context)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
public ObservableQueue(bool suppressUndoable)
: base(
new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>()),
suppressUndoable)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="collection">A collection of items to copy from.</param>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
public ObservableQueue(
IEnumerable<T> collection,
bool suppressUndoable)
: base(
new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>(collection)),
suppressUndoable)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="capacity">The initial capacity of the queue.</param>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
public ObservableQueue(
int capacity,
bool suppressUndoable)
: base(
new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>(capacity)),
suppressUndoable)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="context">The synchronization context top use when posting observable messages.</param>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
public ObservableQueue(
SynchronizationContext context,
bool suppressUndoable)
: base(
new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>()),
context,
suppressUndoable)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="context">The synchronization context top use when posting observable messages.</param>
/// <param name="collection">A collection of items to copy from.</param>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
public ObservableQueue(
SynchronizationContext context,
IEnumerable<T> collection,
bool suppressUndoable)
: base(
new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>(collection)),
context,
suppressUndoable)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableQueue{T}" /> class.
/// </summary>
/// <param name="context">The synchronization context top use when posting observable messages.</param>
/// <param name="capacity">The initial capacity of the queue.</param>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
public ObservableQueue(
SynchronizationContext context,
int capacity,
bool suppressUndoable)
: base(
new QueueCollectionAdapter<T>(new System.Collections.Generic.Queue<T>(capacity)),
context,
suppressUndoable)
{
}
#endregion
/// <summary>
/// Gets a value indicating whether this queue is empty.
/// </summary>
/// <value>
/// <c>true</c> if this queue is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty => this.Count == 0;
#region Queue-specific methods
/// <summary>
/// De-queues and removes an item from the queue.
/// </summary>
/// <returns>The de-queued item.</returns>
public T Dequeue()
{
this.RequiresNotDisposed();
T item;
using (this.WriteLock())
{
item = ((QueueCollectionAdapter<T>)this.InternalContainer).Dequeue();
this.PushUndoLevel(new DequeueUndoLevel<T> { DequeuedItem = item });
}
this.RaisePropertyChanged(nameof(this.Count));
this.RaisePropertyChanged(Constants.ItemsName);
this.RaiseCollectionChangedRemove(
item,
0);
return item;
}
/// <summary>
/// Attempts to de-queue an item and to remove it from queue.
/// </summary>
/// <param name="item">The item that has been de-queued, default if unsuccessful.</param>
/// <returns>
/// <see langword="true" /> if an item is de-queued successfully, <see langword="false" /> otherwise, or if the
/// queue is empty.
/// </returns>
public bool TryDequeue(out T item)
{
this.RequiresNotDisposed();
using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock())
{
var adapter = (QueueCollectionAdapter<T>)this.InternalContainer;
if (adapter.Count == 0)
{
item = default;
return false;
}
locker.Upgrade();
item = adapter.Dequeue();
this.PushUndoLevel(new DequeueUndoLevel<T> { DequeuedItem = item });
}
this.RaisePropertyChanged(nameof(this.Count));
this.RaisePropertyChanged(Constants.ItemsName);
this.RaiseCollectionChangedRemove(
item,
0);
return true;
}
/// <summary>
/// Queues an item into the queue.
/// </summary>
/// <param name="item">The item to queue.</param>
public void Enqueue(T item)
{
this.RequiresNotDisposed();
int newIndex;
using (this.WriteLock())
{
var internalContainer = (QueueCollectionAdapter<T>)this.InternalContainer;
internalContainer.Enqueue(item);
newIndex = internalContainer.Count - 1;
this.PushUndoLevel(new EnqueueUndoLevel<T> { EnqueuedItem = item });
}
this.RaisePropertyChanged(nameof(this.Count));
this.RaisePropertyChanged(Constants.ItemsName);
this.RaiseCollectionChangedAdd(
item,
newIndex);
}
/// <summary>
/// Queues a range of elements, adding them to the queue.
/// </summary>
/// <param name="items">The item range to push.</param>
public void EnqueueRange(T[] items)
{
Requires.NotNull(items, nameof(items));
foreach (var item in items)
{
this.Enqueue(item);
}
}
/// <summary>
/// Queues a range of elements, adding them to the queue.
/// </summary>
/// <param name="items">The item range to enqueue.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="count">The number of items to enqueue.</param>
public void EnqueueRange(
T[] items,
int startIndex,
int count)
{
Requires.NotNull(items, nameof(items));
Requires.ValidArrayRange(in startIndex, in count, items, nameof(count));
ReadOnlySpan<T> itemsSpan = new ReadOnlySpan<T>(items, startIndex, count);
foreach (var item in itemsSpan)
{
this.Enqueue(item);
}
}
/// <summary>
/// Peeks at the topmost item in the queue without de-queuing it.
/// </summary>
/// <returns>The topmost item in the queue.</returns>
public T Peek()
{
this.RequiresNotDisposed();
using (this.ReadLock())
{
return ((QueueCollectionAdapter<T>)this.InternalContainer).Peek();
}
}
/// <summary>
/// Attempts to peek at the current queue and return the item that is next in line to be dequeued.
/// </summary>
/// <param name="item">The item, or default if unsuccessful.</param>
/// <returns><see langword="true" /> if an item is found, <see langword="false" /> otherwise, or if the queue is empty.</returns>
public bool TryPeek(out T item)
{
this.RequiresNotDisposed();
using (this.ReadLock())
{
var ip = (QueueCollectionAdapter<T>)this.InternalContainer;
if (ip.Count == 0)
{
item = default;
return false;
}
item = ip.Peek();
return true;
}
}
/// <summary>
/// Copies the items of the queue into a new array.
/// </summary>
/// <returns>An array of items that are contained in the queue.</returns>
public T[] ToArray()
{
this.RequiresNotDisposed();
using (this.ReadLock())
{
return ((QueueCollectionAdapter<T>)this.InternalContainer).ToArray();
}
}
/// <summary>
/// Sets the capacity to the actual number of elements in the <see cref="ObservableQueue{T}" />, if that number is less
/// than 90 percent of current capacity.
/// </summary>
public void TrimExcess()
{
this.RequiresNotDisposed();
using (this.WriteLock())
{
((QueueCollectionAdapter<T>)this.InternalContainer).TrimExcess();
}
}
#endregion
#region Undo/Redo
/// <summary>
/// Has the last operation undone.
/// </summary>
/// <param name="undoRedoLevel">A level of undo, with contents.</param>
/// <param name="toInvokeOutsideLock">An action to invoke outside of the lock.</param>
/// <param name="state">The state object to pass to the invocation.</param>
/// <returns><see langword="true" /> if the undo was successful, <see langword="false" /> otherwise.</returns>
protected override bool UndoInternally(
StateChange undoRedoLevel,
out Action<object> toInvokeOutsideLock,
out object state)
{
if (base.UndoInternally(
undoRedoLevel,
out toInvokeOutsideLock,
out state))
{
return true;
}
switch (undoRedoLevel)
{
case AddUndoLevel<T> _:
{
var container = (QueueCollectionAdapter<T>)this.InternalContainer;
var array = new T[container.Count];
container.CopyTo(
array,
0);
container.Clear();
for (var i = 0; i < array.Length - 1; i++)
{
container.Enqueue(array[i]);
}
var index = container.Count;
T item = array.Last();
toInvokeOutsideLock = innerState =>
{
var convertedState = (Tuple<ObservableQueue<T>, T, int>)innerState;
convertedState.Item1.RaisePropertyChanged(nameof(convertedState.Item1.Count));
convertedState.Item1.RaisePropertyChanged(Constants.ItemsName);
convertedState.Item1.RaiseCollectionChangedRemove(
convertedState.Item2,
convertedState.Item3);
};
state = new Tuple<ObservableQueue<T>, T, int>(
this,
item,
index);
break;
}
case EnqueueUndoLevel<T> _:
{
var container = (QueueCollectionAdapter<T>)this.InternalContainer;
var array = new T[container.Count];
container.CopyTo(
array,
0);
container.Clear();
for (var i = 0; i < array.Length - 1; i++)
{
container.Enqueue(array[i]);
}
var index = container.Count;
T item = array.Last();
toInvokeOutsideLock = innerState =>
{
var convertedState = (Tuple<ObservableQueue<T>, T, int>)innerState;
convertedState.Item1.RaisePropertyChanged(nameof(convertedState.Item1.Count));
convertedState.Item1.RaisePropertyChanged(Constants.ItemsName);
convertedState.Item1.RaiseCollectionChangedRemove(
convertedState.Item2,
convertedState.Item3);
};
state = new Tuple<ObservableQueue<T>, T, int>(
this,
item,
index);
break;
}
case DequeueUndoLevel<T> dul:
{
var container = (QueueCollectionAdapter<T>)this.InternalContainer;
container.Enqueue(dul.DequeuedItem);
var index = container.Count - 1;
T item = dul.DequeuedItem;
toInvokeOutsideLock = innerState =>
{
var convertedState = (Tuple<ObservableQueue<T>, T, int>)innerState;
convertedState.Item1.RaisePropertyChanged(nameof(convertedState.Item1.Count));
convertedState.Item1.RaisePropertyChanged(Constants.ItemsName);
convertedState.Item1.RaiseCollectionChangedAdd(
convertedState.Item2,
convertedState.Item3);
};
state = new Tuple<ObservableQueue<T>, T, int>(
this,
item,
index);
break;
}
case RemoveUndoLevel<T> _:
{
toInvokeOutsideLock = null;
state = null;
break;
}
case ClearUndoLevel<T> cul:
{
var container = (QueueCollectionAdapter<T>)this.InternalContainer;
for (var i = 0; i < cul.OriginalItems.Length - 1; i++)
{
container.Enqueue(cul.OriginalItems[i]);
}
toInvokeOutsideLock = innerState =>
{
var convertedState = (ObservableQueue<T>)innerState;
convertedState.RaisePropertyChanged(nameof(convertedState.Count));
convertedState.RaisePropertyChanged(Constants.ItemsName);
convertedState.RaiseCollectionReset();
};
state = this;
break;
}
default:
{
toInvokeOutsideLock = null;
state = null;
return false;
}
}
return true;
}
/// <summary>
/// Has the last undone operation redone.
/// </summary>
/// <param name="undoRedoLevel">A level of undo, with contents.</param>
/// <param name="toInvokeOutsideLock">An action to invoke outside of the lock.</param>
/// <param name="state">The state object to pass to the invocation.</param>
/// <returns><see langword="true" /> if the redo was successful, <see langword="false" /> otherwise.</returns>
protected override bool RedoInternally(
StateChange undoRedoLevel,
out Action<object> toInvokeOutsideLock,
out object state)
{
if (base.RedoInternally(
undoRedoLevel,
out toInvokeOutsideLock,
out state))
{
return true;
}
switch (undoRedoLevel)
{
case AddUndoLevel<T> aul:
{
var container = (QueueCollectionAdapter<T>)this.InternalContainer;
container.Enqueue(aul.AddedItem);
var index = container.Count - 1;
T item = aul.AddedItem;
toInvokeOutsideLock = innerState =>
{
var convertedState = (Tuple<ObservableQueue<T>, T, int>)innerState;
convertedState.Item1.RaisePropertyChanged(nameof(convertedState.Item1.Count));
convertedState.Item1.RaisePropertyChanged(Constants.ItemsName);
convertedState.Item1.RaiseCollectionChangedAdd(
convertedState.Item2,
convertedState.Item3);
};
state = new Tuple<ObservableQueue<T>, T, int>(
this,
item,
index);
break;
}
case EnqueueUndoLevel<T> eul:
{
var container = (QueueCollectionAdapter<T>)this.InternalContainer;
container.Enqueue(eul.EnqueuedItem);
var index = container.Count - 1;
T item = eul.EnqueuedItem;
toInvokeOutsideLock = innerState =>
{
var convertedState = (Tuple<ObservableQueue<T>, T, int>)innerState;
convertedState.Item1.RaisePropertyChanged(nameof(convertedState.Item1.Count));
convertedState.Item1.RaisePropertyChanged(Constants.ItemsName);
convertedState.Item1.RaiseCollectionChangedAdd(
convertedState.Item2,
convertedState.Item3);
};
state = new Tuple<ObservableQueue<T>, T, int>(
this,
item,
index);
break;
}
case DequeueUndoLevel<T> dul:
{
var container = (QueueCollectionAdapter<T>)this.InternalContainer;
container.Dequeue();
var index = 0;
T item = dul.DequeuedItem;
toInvokeOutsideLock = innerState =>
{
var convertedState = (Tuple<ObservableQueue<T>, T, int>)innerState;
convertedState.Item1.RaisePropertyChanged(nameof(convertedState.Item1.Count));
convertedState.Item1.RaisePropertyChanged(Constants.ItemsName);
convertedState.Item1.RaiseCollectionChangedRemove(
convertedState.Item2,
convertedState.Item3);
};
state = new Tuple<ObservableQueue<T>, T, int>(
this,
item,
index);
break;
}
case RemoveUndoLevel<T> _:
{
toInvokeOutsideLock = null;
state = null;
break;
}
case ClearUndoLevel<T> _:
{
this.InternalContainer.Clear();
toInvokeOutsideLock = innerState =>
{
var convertedState = (ObservableQueue<T>)innerState;
convertedState.RaisePropertyChanged(nameof(convertedState.Count));
convertedState.RaisePropertyChanged(Constants.ItemsName);
convertedState.RaiseCollectionReset();
};
state = this;
break;
}
default:
{
toInvokeOutsideLock = null;
state = null;
return false;
}
}
return true;
}
/// <summary>
/// Interprets the block state changes outside the write lock.
/// </summary>
/// <param name="actions">The actions to employ.</param>
/// <param name="states">The state objects to send to the corresponding actions.</param>
protected override void InterpretBlockStateChangesOutsideLock(
Action<object>[] actions,
object[] states)
{
this.RaisePropertyChanged(nameof(this.Count));
this.RaisePropertyChanged(Constants.ItemsName);
this.RaiseCollectionReset();
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class KinectGestures
{
public interface GestureListenerInterface
{
// Invoked when a new user is detected and tracking starts
// Here you can start gesture detection with KinectManager.DetectGesture()
void UserDetected(uint userId, int userIndex);
// Invoked when a user is lost
// Gestures for this user are cleared automatically, but you can free the used resources
void UserLost(uint userId, int userIndex);
// Invoked when a gesture is in progress
void GestureInProgress(uint userId, int userIndex, Gestures gesture, float progress,
KinectWrapper.NuiSkeletonPositionIndex joint, Vector3 screenPos);
// Invoked if a gesture is completed.
// Returns true, if the gesture detection must be restarted, false otherwise
bool GestureCompleted(uint userId, int userIndex, Gestures gesture,
KinectWrapper.NuiSkeletonPositionIndex joint, Vector3 screenPos);
// Invoked if a gesture is cancelled.
// Returns true, if the gesture detection must be retarted, false otherwise
bool GestureCancelled(uint userId, int userIndex, Gestures gesture,
KinectWrapper.NuiSkeletonPositionIndex joint);
}
public enum Gestures
{
None = 0,
RaiseRightHand,
RaiseLeftHand,
Psi,
Tpose,
Stop,
Wave,
Click,
SwipeLeft,
SwipeRight,
SwipeUp,
SwipeDown,
RightHandCursor,
LeftHandCursor,
ZoomOut,
ZoomIn,
Wheel,
Jump,
Squat,
Push,
Pull,
LeftPush,
RightPush,
LeftPull,
RightPull
}
public struct GestureData
{
public uint userId;
public Gestures gesture;
public int state;
public float timestamp;
public int joint;
public Vector3 jointPos;
public Vector3 screenPos;
public float tagFloat;
public Vector3 tagVector;
public Vector3 tagVector2;
public float progress;
public bool complete;
public bool cancelled;
public List<Gestures> checkForGestures;
public float startTrackingAtTime;
}
// Gesture related constants, variables and functions
private const int leftHandIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.HandLeft;
private const int rightHandIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.HandRight;
private const int leftElbowIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.ElbowLeft;
private const int rightElbowIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.ElbowRight;
private const int leftShoulderIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderLeft;
private const int rightShoulderIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderRight;
private const int hipCenterIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter;
private const int shoulderCenterIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderCenter;
private const int leftHipIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.HipLeft;
private const int rightHipIndex = (int)KinectWrapper.NuiSkeletonPositionIndex.HipRight;
private static void SetGestureJoint(ref GestureData gestureData, float timestamp, int joint, Vector3 jointPos)
{
gestureData.joint = joint;
gestureData.jointPos = jointPos;
gestureData.timestamp = timestamp;
gestureData.state++;
}
private static void SetGestureCancelled(ref GestureData gestureData)
{
gestureData.state = 0;
gestureData.progress = 0f;
gestureData.cancelled = true;
}
private static void CheckPoseComplete(ref GestureData gestureData, float timestamp, Vector3 jointPos, bool isInPose, float durationToComplete)
{
if(isInPose)
{
float timeLeft = timestamp - gestureData.timestamp;
gestureData.progress = durationToComplete > 0f ? Mathf.Clamp01(timeLeft / durationToComplete) : 1.0f;
if(timeLeft >= durationToComplete)
{
gestureData.timestamp = timestamp;
gestureData.jointPos = jointPos;
gestureData.state++;
gestureData.complete = true;
}
}
else
{
SetGestureCancelled(ref gestureData);
}
}
private static void SetScreenPos(uint userId, ref GestureData gestureData, ref Vector3[] jointsPos, ref bool[] jointsTracked)
{
Vector3 handPos = jointsPos[rightHandIndex];
// Vector3 elbowPos = jointsPos[rightElbowIndex];
// Vector3 shoulderPos = jointsPos[rightShoulderIndex];
bool calculateCoords = false;
if(gestureData.joint == rightHandIndex)
{
if(jointsTracked[rightHandIndex] /**&& jointsTracked[rightElbowIndex] && jointsTracked[rightShoulderIndex]*/)
{
calculateCoords = true;
}
}
else if(gestureData.joint == leftHandIndex)
{
if(jointsTracked[leftHandIndex] /**&& jointsTracked[leftElbowIndex] && jointsTracked[leftShoulderIndex]*/)
{
handPos = jointsPos[leftHandIndex];
// elbowPos = jointsPos[leftElbowIndex];
// shoulderPos = jointsPos[leftShoulderIndex];
calculateCoords = true;
}
}
if(calculateCoords)
{
// if(gestureData.tagFloat == 0f || gestureData.userId != userId)
// {
// // get length from shoulder to hand (screen range)
// Vector3 shoulderToElbow = elbowPos - shoulderPos;
// Vector3 elbowToHand = handPos - elbowPos;
// gestureData.tagFloat = (shoulderToElbow.magnitude + elbowToHand.magnitude);
// }
if(jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] &&
jointsTracked[leftShoulderIndex] && jointsTracked[rightShoulderIndex])
{
Vector3 neckToHips = jointsPos[shoulderCenterIndex] - jointsPos[hipCenterIndex];
Vector3 rightToLeft = jointsPos[rightShoulderIndex] - jointsPos[leftShoulderIndex];
gestureData.tagVector2.x = rightToLeft.x; // * 1.2f;
gestureData.tagVector2.y = neckToHips.y; // * 1.2f;
if(gestureData.joint == rightHandIndex)
{
gestureData.tagVector.x = jointsPos[rightShoulderIndex].x - gestureData.tagVector2.x / 2;
gestureData.tagVector.y = jointsPos[hipCenterIndex].y;
}
else
{
gestureData.tagVector.x = jointsPos[leftShoulderIndex].x - gestureData.tagVector2.x / 2;
gestureData.tagVector.y = jointsPos[hipCenterIndex].y;
}
}
// Vector3 shoulderToHand = handPos - shoulderPos;
// gestureData.screenPos.x = Mathf.Clamp01((gestureData.tagFloat / 2 + shoulderToHand.x) / gestureData.tagFloat);
// gestureData.screenPos.y = Mathf.Clamp01((gestureData.tagFloat / 2 + shoulderToHand.y) / gestureData.tagFloat);
if(gestureData.tagVector2.x != 0 && gestureData.tagVector2.y != 0)
{
Vector3 relHandPos = handPos - gestureData.tagVector;
gestureData.screenPos.x = Mathf.Clamp01(relHandPos.x / gestureData.tagVector2.x);
gestureData.screenPos.y = Mathf.Clamp01(relHandPos.y / gestureData.tagVector2.y);
}
//Debug.Log(string.Format("{0} - S: {1}, H: {2}, SH: {3}, L : {4}", gestureData.gesture, shoulderPos, handPos, shoulderToHand, gestureData.tagFloat));
}
}
private static void SetZoomFactor(uint userId, ref GestureData gestureData, float initialZoom, ref Vector3[] jointsPos, ref bool[] jointsTracked)
{
Vector3 vectorZooming = jointsPos[rightHandIndex] - jointsPos[leftHandIndex];
if(gestureData.tagFloat == 0f || gestureData.userId != userId)
{
gestureData.tagFloat = 0.5f; // this is 100%
}
float distZooming = vectorZooming.magnitude;
gestureData.screenPos.z = initialZoom + (distZooming / gestureData.tagFloat);
}
// private static void SetWheelRotation(uint userId, ref GestureData gestureData, Vector3 initialPos, Vector3 currentPos)
// {
// float angle = Vector3.Angle(initialPos, currentPos) * Mathf.Sign(currentPos.y - initialPos.y);
// gestureData.screenPos.z = angle;
// }
// estimate the next state and completeness of the gesture
public static void CheckForGesture(uint userId, ref GestureData gestureData, float timestamp, ref Vector3[] jointsPos, ref bool[] jointsTracked)
{
if(gestureData.complete)
return;
float bandSize = (jointsPos[shoulderCenterIndex].y - jointsPos[hipCenterIndex].y);
float gestureTop = jointsPos[shoulderCenterIndex].y + bandSize / 2;
float gestureBottom = jointsPos[shoulderCenterIndex].y - bandSize;
float gestureRight = jointsPos[rightHipIndex].x;
float gestureLeft = jointsPos[leftHipIndex].x;
switch(gestureData.gesture)
{
// check for RaiseRightHand
case Gestures.RaiseRightHand:
switch(gestureData.state)
{
case 0: // gesture detection
if(jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
}
break;
case 1: // gesture complete
bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f;
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectWrapper.Constants.PoseCompleteDuration);
break;
}
break;
// check for RaiseLeftHand
case Gestures.RaiseLeftHand:
switch(gestureData.state)
{
case 0: // gesture detection
if(jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
}
break;
case 1: // gesture complete
bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f;
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectWrapper.Constants.PoseCompleteDuration);
break;
}
break;
// check for Psi
case Gestures.Psi:
switch(gestureData.state)
{
case 0: // gesture detection
if(jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f &&
jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
}
break;
case 1: // gesture complete
bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.1f &&
jointsTracked[leftHandIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.1f;
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectWrapper.Constants.PoseCompleteDuration);
break;
}
break;
// check for Tpose
case Gestures.Tpose:
switch(gestureData.state)
{
case 0: // gesture detection
if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[rightShoulderIndex] &&
Mathf.Abs(jointsPos[rightElbowIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.07f
Mathf.Abs(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.7f
jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[leftShoulderIndex] &&
Mathf.Abs(jointsPos[leftElbowIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
}
break;
case 1: // gesture complete
bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[rightShoulderIndex] &&
Mathf.Abs(jointsPos[rightElbowIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.7f
Mathf.Abs(jointsPos[rightHandIndex].y - jointsPos[rightShoulderIndex].y) < 0.1f && // 0.7f
jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[leftShoulderIndex] &&
Mathf.Abs(jointsPos[leftElbowIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].y - jointsPos[leftShoulderIndex].y) < 0.1f;
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectWrapper.Constants.PoseCompleteDuration);
break;
}
break;
// check for Stop
case Gestures.Stop:
switch(gestureData.state)
{
case 0: // gesture detection
if(jointsTracked[rightHandIndex] && jointsTracked[rightHipIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightHipIndex].y) < 0.1f &&
(jointsPos[rightHandIndex].x - jointsPos[rightHipIndex].x) >= 0.4f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
}
else if(jointsTracked[leftHandIndex] && jointsTracked[leftHipIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftHipIndex].y) < 0.1f &&
(jointsPos[leftHandIndex].x - jointsPos[leftHipIndex].x) <= -0.4f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
}
break;
case 1: // gesture complete
bool isInPose = (gestureData.joint == rightHandIndex) ?
(jointsTracked[rightHandIndex] && jointsTracked[rightHipIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightHipIndex].y) < 0.1f &&
(jointsPos[rightHandIndex].x - jointsPos[rightHipIndex].x) >= 0.4f) :
(jointsTracked[leftHandIndex] && jointsTracked[leftHipIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftHipIndex].y) < 0.1f &&
(jointsPos[leftHandIndex].x - jointsPos[leftHipIndex].x) <= -0.4f);
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectWrapper.Constants.PoseCompleteDuration);
break;
}
break;
// check for Wave
case Gestures.Wave:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > 0.1f &&
(jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) > 0.05f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.progress = 0.3f;
}
else if(jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > 0.1f &&
(jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) < -0.05f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
gestureData.progress = 0.3f;
}
break;
case 1: // gesture - phase 2
if((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > 0.1f &&
(jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) < -0.05f :
jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > 0.1f &&
(jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) > 0.05f;
if(isInPose)
{
gestureData.timestamp = timestamp;
gestureData.state++;
gestureData.progress = 0.7f;
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
case 2: // gesture phase 3 = complete
if((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > 0.1f &&
(jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) > 0.05f :
jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > 0.1f &&
(jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) < -0.05f;
if(isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for Click
case Gestures.Click:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.progress = 0.3f;
// set screen position at the start, because this is the most accurate click position
SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked);
}
else if(jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
gestureData.progress = 0.3f;
// set screen position at the start, because this is the most accurate click position
SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked);
}
break;
case 1: // gesture - phase 2
// if((timestamp - gestureData.timestamp) < 1.0f)
// {
// bool isInPose = gestureData.joint == rightHandIndex ?
// jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] &&
// //(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
// Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.08f &&
// (jointsPos[rightHandIndex].z - gestureData.jointPos.z) < -0.05f :
// jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] &&
// //(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
// Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.08f &&
// (jointsPos[leftHandIndex].z - gestureData.jointPos.z) < -0.05f;
//
// if(isInPose)
// {
// gestureData.timestamp = timestamp;
// gestureData.jointPos = jointsPos[gestureData.joint];
// gestureData.state++;
// gestureData.progress = 0.7f;
// }
// else
// {
// // check for stay-in-place
// Vector3 distVector = jointsPos[gestureData.joint] - gestureData.jointPos;
// isInPose = distVector.magnitude < 0.05f;
//
// Vector3 jointPos = jointsPos[gestureData.joint];
// CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, Constants.ClickStayDuration);
// }
// }
// else
{
// check for stay-in-place
Vector3 distVector = jointsPos[gestureData.joint] - gestureData.jointPos;
bool isInPose = distVector.magnitude < 0.05f;
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, KinectWrapper.Constants.ClickStayDuration);
// SetGestureCancelled(gestureData);
}
break;
// case 2: // gesture phase 3 = complete
// if((timestamp - gestureData.timestamp) < 1.0f)
// {
// bool isInPose = gestureData.joint == rightHandIndex ?
// jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] &&
// //(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
// Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.08f &&
// (jointsPos[rightHandIndex].z - gestureData.jointPos.z) > 0.05f :
// jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] &&
// //(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
// Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.08f &&
// (jointsPos[leftHandIndex].z - gestureData.jointPos.z) > 0.05f;
//
// if(isInPose)
// {
// Vector3 jointPos = jointsPos[gestureData.joint];
// CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
// }
// }
// else
// {
// // cancel the gesture
// SetGestureCancelled(ref gestureData);
// }
// break;
}
break;
// check for SwipeLeft
case Gestures.SwipeLeft:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
// if(jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] &&
// (jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) > -0.05f &&
// (jointsPos[rightHandIndex].x - jointsPos[rightElbowIndex].x) > 0f)
// {
// SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
// gestureData.progress = 0.5f;
// }
if(jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop &&
jointsPos[rightHandIndex].x <= gestureRight && jointsPos[rightHandIndex].x > gestureLeft)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.progress = 0.1f;
}
break;
case 1: // gesture phase 2 = complete
if((timestamp - gestureData.timestamp) < 1.5f)
{
// bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[rightElbowIndex] &&
// Mathf.Abs(jointsPos[rightHandIndex].y - jointsPos[rightElbowIndex].y) < 0.1f &&
// Mathf.Abs(jointsPos[rightHandIndex].y - gestureData.jointPos.y) < 0.08f &&
// (jointsPos[rightHandIndex].x - gestureData.jointPos.x) < -0.15f;
bool isInPose = jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop &&
jointsPos[rightHandIndex].x < gestureLeft;
if(isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
else if(jointsPos[rightHandIndex].x <= gestureRight)
{
float gestureSize = gestureRight - gestureLeft;
gestureData.progress = gestureSize > 0.01f ? (gestureRight - jointsPos[rightHandIndex].x) / gestureSize : 0f;
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for SwipeRight
case Gestures.SwipeRight:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
// if(jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] &&
// (jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) > -0.05f &&
// (jointsPos[leftHandIndex].x - jointsPos[leftElbowIndex].x) < 0f)
// {
// SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
// gestureData.progress = 0.5f;
// }
if(jointsTracked[leftHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop &&
jointsPos[leftHandIndex].x >= gestureLeft && jointsPos[leftHandIndex].x < gestureRight)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
gestureData.progress = 0.1f;
}
break;
case 1: // gesture phase 2 = complete
if((timestamp - gestureData.timestamp) < 1.5f)
{
// bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[leftElbowIndex] &&
// Mathf.Abs(jointsPos[leftHandIndex].y - jointsPos[leftElbowIndex].y) < 0.1f &&
// Mathf.Abs(jointsPos[leftHandIndex].y - gestureData.jointPos.y) < 0.08f &&
// (jointsPos[leftHandIndex].x - gestureData.jointPos.x) > 0.15f;
bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop &&
jointsPos[leftHandIndex].x > gestureRight;
if(isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
else if(jointsPos[leftHandIndex].x >= gestureLeft)
{
float gestureSize = gestureRight - gestureLeft;
gestureData.progress = gestureSize > 0.01f ? (jointsPos[leftHandIndex].x - gestureLeft) / gestureSize : 0f;
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for SwipeUp
case Gestures.SwipeUp:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) < 0.0f &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.15f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.progress = 0.5f;
}
else if(jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) < 0.0f &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.15f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.05f &&
Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) <= 0.1f :
jointsTracked[leftHandIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.05f &&
Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) <= 0.1f;
if(isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for SwipeDown
case Gestures.SwipeDown:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[rightHandIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftShoulderIndex].y) > 0.05f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.progress = 0.5f;
}
else if(jointsTracked[leftHandIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightShoulderIndex].y) > 0.05f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) < -0.15f &&
Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) <= 0.1f :
jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) < -0.15f &&
Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) <= 0.1f;
if(isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for RightHandCursor
case Gestures.RightHandCursor:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1 (perpetual)
if(jointsTracked[rightHandIndex] && jointsTracked[rightHipIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[rightHipIndex].y) > -0.1f)
{
gestureData.joint = rightHandIndex;
gestureData.timestamp = timestamp;
//gestureData.jointPos = jointsPos[rightHandIndex];
SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked);
gestureData.progress = 0.7f;
}
else
{
// cancel the gesture
//SetGestureCancelled(ref gestureData);
gestureData.progress = 0f;
}
break;
}
break;
// check for LeftHandCursor
case Gestures.LeftHandCursor:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1 (perpetual)
if(jointsTracked[leftHandIndex] && jointsTracked[leftHipIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[leftHipIndex].y) > -0.1f)
{
gestureData.joint = leftHandIndex;
gestureData.timestamp = timestamp;
//gestureData.jointPos = jointsPos[leftHandIndex];
SetScreenPos(userId, ref gestureData, ref jointsPos, ref jointsTracked);
gestureData.progress = 0.7f;
}
else
{
// cancel the gesture
//SetGestureCancelled(ref gestureData);
gestureData.progress = 0f;
}
break;
}
break;
// check for ZoomOut
case Gestures.ZoomOut:
Vector3 vectorZoomOut = (Vector3)jointsPos[rightHandIndex] - jointsPos[leftHandIndex];
float distZoomOut = vectorZoomOut.magnitude;
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop &&
jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop &&
distZoomOut < 0.3f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.tagVector = Vector3.right;
gestureData.tagFloat = 0f;
gestureData.progress = 0.3f;
}
break;
case 1: // gesture phase 2 = zooming
if((timestamp - gestureData.timestamp) < 1.5f)
{
float angleZoomOut = Vector3.Angle(gestureData.tagVector, vectorZoomOut) * Mathf.Sign(vectorZoomOut.y - gestureData.tagVector.y);
bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop &&
jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop &&
distZoomOut < 1.5f && Mathf.Abs(angleZoomOut) < 20f;
if(isInPose)
{
SetZoomFactor(userId, ref gestureData, 1.0f, ref jointsPos, ref jointsTracked);
gestureData.timestamp = timestamp;
gestureData.progress = 0.7f;
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for ZoomIn
case Gestures.ZoomIn:
Vector3 vectorZoomIn = (Vector3)jointsPos[rightHandIndex] - jointsPos[leftHandIndex];
float distZoomIn = vectorZoomIn.magnitude;
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop &&
jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop &&
distZoomIn >= 0.7f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.tagVector = Vector3.right;
gestureData.tagFloat = distZoomIn;
gestureData.progress = 0.3f;
}
break;
case 1: // gesture phase 2 = zooming
if((timestamp - gestureData.timestamp) < 1.5f)
{
float angleZoomIn = Vector3.Angle(gestureData.tagVector, vectorZoomIn) * Mathf.Sign(vectorZoomIn.y - gestureData.tagVector.y);
bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop &&
jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop &&
distZoomIn >= 0.2f && Mathf.Abs(angleZoomIn) < 20f;
if(isInPose)
{
SetZoomFactor(userId, ref gestureData, 0.0f, ref jointsPos, ref jointsTracked);
gestureData.timestamp = timestamp;
gestureData.progress = 0.7f;
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for Wheel
case Gestures.Wheel:
Vector3 vectorWheel = (Vector3)jointsPos[rightHandIndex] - jointsPos[leftHandIndex];
float distWheel = vectorWheel.magnitude;
// Debug.Log(string.Format("{0}. Dist: {1:F1}, Tag: {2:F1}, Diff: {3:F1}", gestureData.state,
// distWheel, gestureData.tagFloat, Mathf.Abs(distWheel - gestureData.tagFloat)));
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop &&
jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop &&
distWheel >= 0.3f && distWheel < 0.7f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.tagVector = Vector3.right;
gestureData.tagFloat = distWheel;
gestureData.progress = 0.3f;
}
break;
case 1: // gesture phase 2 = turning wheel
if((timestamp - gestureData.timestamp) < 1.5f)
{
float angle = Vector3.Angle(gestureData.tagVector, vectorWheel) * Mathf.Sign(vectorWheel.y - gestureData.tagVector.y);
bool isInPose = jointsTracked[leftHandIndex] && jointsTracked[rightHandIndex] && jointsTracked[hipCenterIndex] && jointsTracked[shoulderCenterIndex] && jointsTracked[leftHipIndex] && jointsTracked[rightHipIndex] &&
jointsPos[leftHandIndex].y >= gestureBottom && jointsPos[leftHandIndex].y <= gestureTop &&
jointsPos[rightHandIndex].y >= gestureBottom && jointsPos[rightHandIndex].y <= gestureTop &&
distWheel >= 0.3f && distWheel < 0.7f &&
Mathf.Abs(distWheel - gestureData.tagFloat) < 0.1f;
if(isInPose)
{
//SetWheelRotation(userId, ref gestureData, gestureData.tagVector, vectorWheel);
gestureData.screenPos.z = angle; // wheel angle
gestureData.timestamp = timestamp;
gestureData.tagFloat = distWheel;
gestureData.progress = 0.7f;
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for Jump
case Gestures.Jump:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[hipCenterIndex] &&
(jointsPos[hipCenterIndex].y > 0.9f) && (jointsPos[hipCenterIndex].y < 1.3f))
{
SetGestureJoint(ref gestureData, timestamp, hipCenterIndex, jointsPos[hipCenterIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = jointsTracked[hipCenterIndex] &&
(jointsPos[hipCenterIndex].y - gestureData.jointPos.y) > 0.15f &&
Mathf.Abs(jointsPos[hipCenterIndex].x - gestureData.jointPos.x) < 0.2f;
if(isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for Squat
case Gestures.Squat:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[hipCenterIndex] &&
(jointsPos[hipCenterIndex].y <= 0.9f))
{
SetGestureJoint(ref gestureData, timestamp, hipCenterIndex, jointsPos[hipCenterIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = jointsTracked[hipCenterIndex] &&
(jointsPos[hipCenterIndex].y - gestureData.jointPos.y) < -0.15f &&
Mathf.Abs(jointsPos[hipCenterIndex].x - gestureData.jointPos.x) < 0.2f;
if(isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for Push
case Gestures.Push:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - jointsPos[rightShoulderIndex].x) < 0.2f &&
(jointsPos[rightHandIndex].z - jointsPos[leftElbowIndex].z) < -0.2f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.progress = 0.5f;
}
else if(jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - jointsPos[leftShoulderIndex].x) < 0.2f &&
(jointsPos[leftHandIndex].z - jointsPos[rightElbowIndex].z) < -0.2f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[rightHandIndex].z - gestureData.jointPos.z) < -0.1f :
jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[leftHandIndex].z - gestureData.jointPos.z) < -0.1f;
if(isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for Push
case Gestures.LeftPush:
switch (gestureData.state)
{
case 0: // gesture detection - phase 1
if (jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - jointsPos[leftShoulderIndex].x) < 0.2f &&
(jointsPos[leftHandIndex].z - jointsPos[rightElbowIndex].z) < -0.2f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if ((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[rightHandIndex].z - gestureData.jointPos.z) < -0.1f :
jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[leftHandIndex].z - gestureData.jointPos.z) < -0.1f;
if (isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for Push
case Gestures.RightPush:
switch (gestureData.state)
{
case 0: // gesture detection - phase 1
if (jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - jointsPos[rightShoulderIndex].x) < 0.2f &&
(jointsPos[rightHandIndex].z - jointsPos[leftElbowIndex].z) < -0.2f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if ((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[rightHandIndex].z - gestureData.jointPos.z) < -0.1f :
jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[leftHandIndex].z - gestureData.jointPos.z) < -0.1f;
if (isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for Pull
case Gestures.Pull:
switch(gestureData.state)
{
case 0: // gesture detection - phase 1
if(jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - jointsPos[rightShoulderIndex].x) < 0.2f &&
(jointsPos[rightHandIndex].z - jointsPos[leftElbowIndex].z) < -0.3f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.progress = 0.5f;
}
else if(jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - jointsPos[leftShoulderIndex].x) < 0.2f &&
(jointsPos[leftHandIndex].z - jointsPos[rightElbowIndex].z) < -0.3f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[rightHandIndex].z - gestureData.jointPos.z) > 0.1f :
jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[leftHandIndex].z - gestureData.jointPos.z) > 0.1f;
if(isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for LeftPull
case Gestures.LeftPull:
switch (gestureData.state)
{
case 0: // gesture detection - phase 1
if (jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - jointsPos[leftShoulderIndex].x) < 0.2f &&
(jointsPos[leftHandIndex].z - jointsPos[rightElbowIndex].z) < -0.3f)
{
SetGestureJoint(ref gestureData, timestamp, leftHandIndex, jointsPos[leftHandIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if ((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[rightHandIndex].z - gestureData.jointPos.z) > 0.1f :
jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[leftHandIndex].z - gestureData.jointPos.z) > 0.1f;
if (isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// check for RightPull
case Gestures.RightPull:
switch (gestureData.state)
{
case 0: // gesture detection - phase 1
if (jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - jointsPos[rightShoulderIndex].x) < 0.2f &&
(jointsPos[rightHandIndex].z - jointsPos[leftElbowIndex].z) < -0.3f)
{
SetGestureJoint(ref gestureData, timestamp, rightHandIndex, jointsPos[rightHandIndex]);
gestureData.progress = 0.5f;
}
break;
case 1: // gesture phase 2 = complete
if ((timestamp - gestureData.timestamp) < 1.5f)
{
bool isInPose = gestureData.joint == rightHandIndex ?
jointsTracked[rightHandIndex] && jointsTracked[leftElbowIndex] && jointsTracked[rightShoulderIndex] &&
(jointsPos[rightHandIndex].y - jointsPos[leftElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[rightHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[rightHandIndex].z - gestureData.jointPos.z) > 0.1f :
jointsTracked[leftHandIndex] && jointsTracked[rightElbowIndex] && jointsTracked[leftShoulderIndex] &&
(jointsPos[leftHandIndex].y - jointsPos[rightElbowIndex].y) > -0.1f &&
Mathf.Abs(jointsPos[leftHandIndex].x - gestureData.jointPos.x) < 0.2f &&
(jointsPos[leftHandIndex].z - gestureData.jointPos.z) > 0.1f;
if (isInPose)
{
Vector3 jointPos = jointsPos[gestureData.joint];
CheckPoseComplete(ref gestureData, timestamp, jointPos, isInPose, 0f);
}
}
else
{
// cancel the gesture
SetGestureCancelled(ref gestureData);
}
break;
}
break;
// here come more gesture-cases
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class ArgumentValidation
{
// This type is used to test Socket.Select's argument validation.
private sealed class LargeList : IList
{
private const int MaxSelect = 65536;
public int Count { get { return MaxSelect + 1; } }
public bool IsFixedSize { get { return true; } }
public bool IsReadOnly { get { return true; } }
public bool IsSynchronized { get { return false; } }
public object SyncRoot { get { return null; } }
public object this[int index]
{
get { return null; }
set { }
}
public int Add(object value) { return -1; }
public void Clear() { }
public bool Contains(object value) { return false; }
public void CopyTo(Array array, int index) { }
public IEnumerator GetEnumerator() { return null; }
public int IndexOf(object value) { return -1; }
public void Insert(int index, object value) { }
public void Remove(object value) { }
public void RemoveAt(int index) { }
}
private static readonly byte[] s_buffer = new byte[1];
private static readonly IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) };
private static readonly SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs();
private static readonly Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static readonly Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
private static void TheAsyncCallback(IAsyncResult ar)
{
}
private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork)
{
Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6);
return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket;
}
[Fact]
public void SetExclusiveAddressUse_BoundSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() =>
{
socket.ExclusiveAddressUse = true;
});
}
}
[Fact]
public void SetReceiveBufferSize_Negative_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().ReceiveBufferSize = -1;
});
}
[Fact]
public void SetSendBufferSize_Negative_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().SendBufferSize = -1;
});
}
[Fact]
public void SetReceiveTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().ReceiveTimeout = int.MinValue;
});
}
[Fact]
public void SetSendTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().SendTimeout = int.MinValue;
});
}
[Fact]
public void SetTtl_OutOfRange_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().Ttl = -1;
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().Ttl = 256;
});
}
[Fact]
public void DontFragment_IPv6_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).DontFragment);
}
[Fact]
public void SetDontFragment_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() =>
{
GetSocket(AddressFamily.InterNetworkV6).DontFragment = true;
});
}
[Fact]
public void Bind_Throws_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Bind(null));
}
[Fact]
public void Connect_EndPoint_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect(null));
}
[Fact]
public void Connect_EndPoint_ListeningSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.Connect(new IPEndPoint(IPAddress.Loopback, 1)));
}
}
[Fact]
public void Connect_IPAddress_NullIPAddress_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress)null, 1));
}
[Fact]
public void Connect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, 65536));
}
[Fact]
public void Connect_IPAddress_InvalidAddressFamily_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).Connect(IPAddress.IPv6Loopback, 1));
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).Connect(IPAddress.Loopback, 1));
}
[Fact]
public void Connect_Host_NullHost_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((string)null, 1));
}
[Fact]
public void Connect_Host_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", 65536));
}
[Fact]
public void Connect_IPAddresses_NullArray_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress[])null, 1));
}
[Fact]
public void Connect_IPAddresses_EmptyArray_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().Connect(new IPAddress[0], 1));
}
[Fact]
public void Connect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, 65536));
}
[Fact]
public void Accept_NotBound_Throws_InvalidOperation()
{
Assert.Throws<InvalidOperationException>(() => GetSocket().Accept());
}
[Fact]
public void Accept_NotListening_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() => socket.Accept());
}
}
[Fact]
public void Send_Buffer_NullBuffer_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, 0, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, -1, 0, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, -1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffers_NullBuffers_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffers_EmptyBuffers_Throws_Argument()
{
SocketError errorCode;
AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
}
[Fact]
public void SendTo_NullBuffer_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)));
}
[Fact]
public void SendTo_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(s_buffer, 0, 0, SocketFlags.None, null));
}
[Fact]
public void SendTo_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint));
}
[Fact]
public void SendTo_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, -1, SocketFlags.None, endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint));
}
[Fact]
public void Receive_Buffer_NullBuffer_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, 0, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, -1, 0, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, -1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffers_NullBuffers_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffers_EmptyBuffers_Throws_Argument()
{
SocketError errorCode;
AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
}
[Fact]
public void ReceiveFrom_NullBuffer_Throws_ArgumentNull()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_NullEndPoint_Throws_ArgumentNull()
{
EndPoint endpoint = null;
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_AddressFamily_Throws_Argument()
{
EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_NotBound_Throws_InvalidOperation()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveMessageFrom_NullBuffer_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(null, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = null;
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_AddressFamily_Throws_Argument()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
IPPacketInformation packetInfo;
AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, -1, s_buffer.Length, ref flags, ref remote, out packetInfo));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, -1, ref flags, ref remote, out packetInfo));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, ref flags, ref remote, out packetInfo));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length, 1, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_NotBound_Throws_InvalidOperation()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void SetSocketOption_Object_ObjectNull_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, (object)null));
}
[Fact]
public void SetSocketOption_Linger_NotLingerOption_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object()));
}
[Fact]
public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1)));
AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1)));
}
[Fact]
public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object()));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object()));
}
[Fact]
public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object()));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object()));
}
[Fact]
public void SetSocketOption_Object_InvalidOptionName_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object()));
}
[Fact]
public void Select_NullOrEmptyLists_Throws_ArgumentNull()
{
var emptyList = new List<Socket>();
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, emptyList, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, emptyList, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, emptyList, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, emptyList, -1));
}
[Fact]
public void Select_LargeList_Throws_ArgumentOutOfRange()
{
var largeList = new LargeList();
Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(largeList, null, null, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, largeList, null, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, null, largeList, -1));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in AcceptAsync that dereferences null SAEA argument")]
[Fact]
public void AcceptAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().AcceptAsync(null));
}
[Fact]
public void AcceptAsync_BufferList_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
BufferList = s_buffers
};
AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().AcceptAsync(eventArgs));
}
[Fact]
public void AcceptAsync_NotBound_Throws_InvalidOperation()
{
Assert.Throws<InvalidOperationException>(() => GetSocket().AcceptAsync(s_eventArgs));
}
[Fact]
public void AcceptAsync_NotListening_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs));
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveAsync that dereferences null SAEA argument")]
[Fact]
public void ConnectAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(null));
}
[Fact]
public void ConnectAsync_BufferList_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
BufferList = s_buffers
};
AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().ConnectAsync(eventArgs));
}
[Fact]
public void ConnectAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(s_eventArgs));
}
[Fact]
public void ConnectAsync_ListeningSocket_Throws_InvalidOperation()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 1)
};
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.ConnectAsync(eventArgs));
}
}
[Fact]
public void ConnectAsync_AddressFamily_Throws_NotSupported()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6)
};
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs));
eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ConnectAsync that dereferences null SAEA argument")]
[Fact]
public void ConnectAsync_Static_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, null));
}
[Fact]
public void ConnectAsync_Static_BufferList_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
BufferList = s_buffers
};
AssertExtensions.Throws<ArgumentException>("BufferList", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs));
}
[Fact]
public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveAsync that dereferences null SAEA argument")]
[Fact]
public void ReceiveAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveAsync(null));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveFromAsync that dereferences null SAEA argument")]
[Fact]
public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(null));
}
[Fact]
public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs));
}
[Fact]
public void ReceiveFromAsync_AddressFamily_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveMessageFromAsync that dereferences null SAEA argument")]
[Fact]
public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(null));
}
[Fact]
public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs));
}
[Fact]
public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendAsync that dereferences null SAEA argument")]
[Fact]
public void SendAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendAsync(null));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")]
[Fact]
public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(null));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA.SendPacketsElements")]
[Fact]
public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs));
}
[Fact]
public void SendPacketsAsync_NotConnected_Throws_NotSupported()
{
var eventArgs = new SocketAsyncEventArgs {
SendPacketsElements = new SendPacketsElement[0]
};
Assert.Throws<NotSupportedException>(() => GetSocket().SendPacketsAsync(eventArgs));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendToAsync that dereferences null SAEA argument")]
[Fact]
public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(null));
}
[Fact]
public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix
public void Socket_Connect_DnsEndPoint_ExposedHandle_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IntPtr ignored = s.Handle;
Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new DnsEndPoint("localhost", 12345)));
}
}
[Fact]
public async Task Socket_Connect_DnsEndPointWithIPAddressString_Supported()
{
using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
host.Bind(new IPEndPoint(IPAddress.Loopback, 0));
host.Listen(1);
Task accept = host.AcceptAsync();
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
s.Connect(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port));
}
await accept;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix
public void Socket_Connect_StringHost_ExposedHandle_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IntPtr ignored = s.Handle;
Assert.Throws<PlatformNotSupportedException>(() => s.Connect("localhost", 12345));
}
}
[Fact]
public async Task Socket_Connect_IPv4AddressAsStringHost_Supported()
{
using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
host.Bind(new IPEndPoint(IPAddress.Loopback, 0));
host.Listen(1);
Task accept = host.AcceptAsync();
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
s.Connect(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port);
}
await accept;
}
}
[Fact]
public async Task Socket_Connect_IPv6AddressAsStringHost_Supported()
{
using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
host.Listen(1);
Task accept = host.AcceptAsync();
using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
s.Connect(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port);
}
await accept;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix
public void Socket_Connect_MultipleAddresses_ExposedHandle_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IntPtr ignored = s.Handle;
Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new[] { IPAddress.Loopback }, 12345));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix
public void Socket_ConnectAsync_DnsEndPoint_ExposedHandle_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IntPtr ignored = s.Handle;
Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new DnsEndPoint("localhost", 12345)); });
}
}
[Fact]
public async Task Socket_ConnectAsync_DnsEndPointWithIPAddressString_Supported()
{
using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
host.Bind(new IPEndPoint(IPAddress.Loopback, 0));
host.Listen(1);
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
await Task.WhenAll(
host.AcceptAsync(),
s.ConnectAsync(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)));
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix
public void Socket_ConnectAsync_StringHost_ExposedHandle_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IntPtr ignored = s.Handle;
Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync("localhost", 12345); });
}
}
[Fact]
public async Task Socket_ConnectAsync_IPv4AddressAsStringHost_Supported()
{
using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
host.Bind(new IPEndPoint(IPAddress.Loopback, 0));
host.Listen(1);
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
await Task.WhenAll(
host.AcceptAsync(),
s.ConnectAsync(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port));
}
}
}
[Fact]
public async Task Socket_ConnectAsync_IPv6AddressAsStringHost_Supported()
{
using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
host.Listen(1);
using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
await Task.WhenAll(
host.AcceptAsync(),
s.ConnectAsync(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port));
}
}
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix
[InlineData(0)]
[InlineData(1)]
public void Connect_ConnectTwice_NotSupported(int invalidatingAction)
{
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
switch (invalidatingAction)
{
case 0:
IntPtr handle = client.Handle; // exposing the underlying handle
break;
case 1:
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option
break;
}
//
// Connect once, to an invalid address, expecting failure
//
EndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1234);
Assert.ThrowsAny<SocketException>(() => client.Connect(ep));
//
// Connect again, expecting PlatformNotSupportedException
//
Assert.Throws<PlatformNotSupportedException>(() => client.Connect(ep));
}
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix
[InlineData(0)]
[InlineData(1)]
public void ConnectAsync_ConnectTwice_NotSupported(int invalidatingAction)
{
AutoResetEvent completed = new AutoResetEvent(false);
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
switch (invalidatingAction)
{
case 0:
IntPtr handle = client.Handle; // exposing the underlying handle
break;
case 1:
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option
break;
}
//
// Connect once, to an invalid address, expecting failure
//
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 1234);
args.Completed += delegate
{
completed.Set();
};
if (client.ConnectAsync(args))
{
Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection");
}
Assert.NotEqual(SocketError.Success, args.SocketError);
//
// Connect again, expecting PlatformNotSupportedException
//
Assert.Throws<PlatformNotSupportedException>(() => client.ConnectAsync(args));
}
}
[Fact]
public void BeginAccept_NotBound_Throws_InvalidOperation()
{
Assert.Throws<InvalidOperationException>(() => GetSocket().BeginAccept(TheAsyncCallback, null));
Assert.Throws<InvalidOperationException>(() => { GetSocket().AcceptAsync(); });
}
[Fact]
public void BeginAccept_NotListening_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null));
Assert.Throws<InvalidOperationException>(() => { socket.AcceptAsync(); });
}
}
[Fact]
public void EndAccept_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndAccept(null));
}
[Fact]
public void BeginConnect_EndPoint_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((EndPoint)null, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((EndPoint)null); });
}
[Fact]
public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null));
Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 1)); });
}
}
[Fact]
public void BeginConnect_EndPoint_AddressFamily_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(
new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6), TheAsyncCallback, null));
Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync(
new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6)); });
}
[Fact]
public void BeginConnect_Host_NullHost_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((string)null, 1, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((string)null, 1); });
}
[Theory]
[InlineData(-1)]
[InlineData(65536)]
public void BeginConnect_Host_InvalidPort_Throws_ArgumentOutOfRange(int port)
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", port, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync("localhost", port); });
}
[Fact]
public void BeginConnect_Host_ListeningSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.BeginConnect("localhost", 1, TheAsyncCallback, null));
Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync("localhost", 1); });
}
}
[Fact]
public void BeginConnect_IPAddress_NullIPAddress_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress)null, 1, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress)null, 1); });
}
[Theory]
[InlineData(-1)]
[InlineData(65536)]
public void BeginConnect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange(int port)
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, port, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(IPAddress.Loopback, 65536); });
}
[Fact]
public void BeginConnect_IPAddress_AddressFamily_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(IPAddress.IPv6Loopback, 1, TheAsyncCallback, null));
Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync(IPAddress.IPv6Loopback, 1); });
}
[Fact]
public void BeginConnect_IPAddresses_NullIPAddresses_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress[])null, 1, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress[])null, 1); });
}
[Fact]
public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("addresses", () => { GetSocket().ConnectAsync(new IPAddress[0], 1); });
}
[Theory]
[InlineData(-1)]
[InlineData(65536)]
public void BeginConnect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange(int port)
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, port, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(new[] { IPAddress.Loopback }, port); });
}
[Fact]
public void BeginConnect_IPAddresses_ListeningSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null));
}
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new[] { IPAddress.Loopback }, 1); });
}
}
[Fact]
public void EndConnect_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndConnect(null));
}
[Fact]
public void EndConnect_UnrelatedAsyncResult_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndConnect(Task.CompletedTask));
}
[Fact]
public void BeginSend_Buffer_NullBuffer_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, 0, 0, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); });
}
[Fact]
public void BeginSend_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); });
}
[Fact]
public void BeginSend_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); });
}
[Fact]
public void BeginSend_Buffers_NullBuffers_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); });
}
[Fact]
public void BeginSend_Buffers_EmptyBuffers_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().SendAsync(new List<ArraySegment<byte>>(), SocketFlags.None); });
}
[Fact]
public void EndSend_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndSend(null));
}
[Fact]
public void EndSend_UnrelatedAsyncResult_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSend(Task.CompletedTask));
}
[Fact]
public void BeginSendTo_NullBuffer_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)); });
}
[Fact]
public void BeginSendTo_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(s_buffer, 0, 0, SocketFlags.None, null, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, null); });
}
[Fact]
public void BeginSendTo_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); });
}
[Fact]
public void BeginSendTo_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, -1, SocketFlags.None, endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); });
}
[Fact]
public void EndSendTo_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndSendTo(null));
}
[Fact]
public void EndSendto_UnrelatedAsyncResult_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSendTo(Task.CompletedTask));
}
[Fact]
public void BeginReceive_Buffer_NullBuffer_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, 0, 0, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); });
}
[Fact]
public void BeginReceive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); });
}
[Fact]
public void BeginReceive_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); });
}
[Fact]
public void BeginReceive_Buffers_NullBuffers_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); });
}
[Fact]
public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().ReceiveAsync(new List<ArraySegment<byte>>(), SocketFlags.None); });
}
[Fact]
public void EndReceive_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceive(null));
}
[Fact]
public void BeginReceiveFrom_NullBuffer_Throws_ArgumentNull()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, endpoint); });
}
[Fact]
public void BeginReceiveFrom_NullEndPoint_Throws_ArgumentNull()
{
EndPoint endpoint = null;
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); });
}
[Fact]
public void BeginReceiveFrom_AddressFamily_Throws_Argument()
{
EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); });
}
[Fact]
public void BeginReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); });
}
[Fact]
public void BeginReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); });
}
[Fact]
public void BeginReceiveFrom_NotBound_Throws_InvalidOperation()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); });
}
[Fact]
public void EndReceiveFrom_NullAsyncResult_Throws_ArgumentNull()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveFrom(null, ref endpoint));
}
[Fact]
public void BeginReceiveMessageFrom_NullBuffer_Throws_ArgumentNull()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(null, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, remote); });
}
[Fact]
public void BeginReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull()
{
EndPoint remote = null;
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); });
}
[Fact]
public void BeginReceiveMessageFrom_AddressFamily_Throws_Argument()
{
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); });
}
[Fact]
public void BeginReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, remote); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, remote); });
}
[Fact]
public void BeginReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, -1, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, remote); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, remote); });
Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, remote); });
}
[Fact]
public void BeginReceiveMessageFrom_NotBound_Throws_InvalidOperation()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); });
}
[Fact]
public void EndReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = null;
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo));
}
[Fact]
public void EndReceiveMessageFrom_AddressFamily_Throws_Argument()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
IPPacketInformation packetInfo;
AssertExtensions.Throws<ArgumentException>("endPoint", () => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo));
}
[Fact]
public void EndReceiveMessageFrom_NullAsyncResult_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo));
}
[Fact]
public void CancelConnectAsync_NullEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => Socket.CancelConnectAsync(null));
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Studio.Controls.ControlsPublic
File: StrategySecuritiesPanel.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Studio.Controls
{
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Configuration;
using Ecng.Serialization;
using Ecng.Xaml;
using Ecng.ComponentModel;
using MoreLinq;
using StockSharp.Algo;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Studio.Core;
using StockSharp.Studio.Core.Commands;
using StockSharp.Localization;
[DisplayNameLoc(LocalizedStrings.SecuritiesKey)]
[DescriptionLoc(LocalizedStrings.Str3274Key)]
[Icon("images/security_32x32.png")]
public partial class StrategySecuritiesPanel
{
public static readonly RoutedCommand OpenMarketDepthCommand = new RoutedCommand();
private readonly SynchronizedSet<string> _securityIds = new SynchronizedSet<string>(StringComparer.InvariantCultureIgnoreCase);
private readonly string _defaultToolTipText;
private readonly ToolTip _newSecuritiesTooltip;
private readonly Brush _defaultStorageBrush;
private bool _isTooltipVisible;
private Security[] Securities
{
get
{
var entityRegistry = ConfigManager.GetService<IStudioEntityRegistry>();
return _securityIds
.Select(id => entityRegistry.Securities.ReadById(id))
.Where(s => s != null)
.ToArray();
}
}
public StrategySecuritiesPanel()
{
InitializeComponent();
SecurityPicker.GridChanged += RaiseChangedCommand;
AlertBtn.SchemaChanged += RaiseChangedCommand;
GotFocus += (s, e) => RaiseSelectedCommand();
_newSecuritiesTooltip = (ToolTip)AddSecurity.ToolTip;
_defaultStorageBrush = ((TextBlock)_newSecuritiesTooltip.Content).Foreground;
_defaultToolTipText = ((TextBlock)_newSecuritiesTooltip.Content).Text;
var cmdSvc = ConfigManager.GetService<IStudioCommandService>();
cmdSvc.Register<ResetedCommand>(this, false, cmd =>
{
var selectedSecurities = Securities;
selectedSecurities.ForEach(RaiseRefuseMarketData);
selectedSecurities.ForEach(RaiseRequestMarketData);
});
cmdSvc.Register<NewSecuritiesCommand>(this, false, cmd =>
{
if (_isTooltipVisible)
return;
_isTooltipVisible = true;
GuiDispatcher.GlobalDispatcher.AddAction(() =>
{
((TextBlock)_newSecuritiesTooltip.Content).Text = LocalizedStrings.Str3276;
((TextBlock)_newSecuritiesTooltip.Content).Foreground = Brushes.Red;
_newSecuritiesTooltip.Placement = PlacementMode.Bottom;
_newSecuritiesTooltip.PlacementTarget = AddSecurity;
_newSecuritiesTooltip.IsOpen = true;
});
});
cmdSvc.Register<BindStrategyCommand>(this, false, cmd =>
{
if (!cmd.CheckControl(this))
return;
if (_securityIds.Count == 0)
{
_securityIds.Add(cmd.Source.Security.Id);
AddDefaultSecurities("RI");
AddDefaultSecurities("Si");
AddDefaultSecurities("GZ");
}
var selectedSecurities = Securities;
SecurityPicker.Securities.AddRange(selectedSecurities);
selectedSecurities.ForEach(RaiseRequestMarketData);
GuiDispatcher.GlobalDispatcher.AddAction(() =>
{
SecurityPicker.AddContextMenuItem(new Separator());
SecurityPicker.AddContextMenuItem(new MenuItem { Header = LocalizedStrings.Str3277, Command = OpenMarketDepthCommand, CommandTarget = this });
});
});
WhenLoaded(() => new RequestBindSource(this).SyncProcess(this));
}
private void AddDefaultSecurities(string baseCode)
{
baseCode
.GetFortsJumps(DateTime.Today.AddMonths(-3), DateTime.Today.AddMonths(6), code => new Security
{
Id = code + "@" + ExchangeBoard.Forts.Code,
Code = code,
Board = ExchangeBoard.Forts,
})
.Take(3)
.ForEach(s => _securityIds.Add(s.Id));
}
private void RaiseChangedCommand()
{
new ControlChangedCommand(this).Process(this);
}
private void RaiseSelectedCommand()
{
new SelectCommand<Security>(SecurityPicker.SelectedSecurity, false).Process(this);
}
private void RaiseRequestMarketData(Security security)
{
new RequestMarketDataCommand(security, MarketDataTypes.Level1).Process(this);
}
private void RaiseRefuseMarketData(Security security)
{
new RefuseMarketDataCommand(security, MarketDataTypes.Level1).Process(this);
}
public override void Dispose()
{
var cmdSvc = ConfigManager.GetService<IStudioCommandService>();
cmdSvc.UnRegister<ResetedCommand>(this);
cmdSvc.UnRegister<NewSecuritiesCommand>(this);
cmdSvc.UnRegister<BindStrategyCommand>(this);
AlertBtn.Dispose();
}
public override void Save(SettingsStorage storage)
{
storage.SetValue("SecurityPicker", SecurityPicker.Save());
storage.SetValue("AlertSettings", AlertBtn.Save());
storage.SetValue("Securities", _securityIds.ToArray());
}
public override void Load(SettingsStorage storage)
{
var gridSettings = storage.GetValue<SettingsStorage>("SecurityPicker");
if (gridSettings != null)
SecurityPicker.Load(gridSettings);
var alertSettings = storage.GetValue<SettingsStorage>("AlertSettings");
if (alertSettings != null)
AlertBtn.Load(alertSettings);
_securityIds.SyncDo(list =>
{
list.Clear();
list.AddRange(storage.GetValue("Securities", ArrayHelper.Empty<string>()));
});
SecurityPicker.SecurityProvider = ConfigManager.GetService<ISecurityProvider>();
}
private void SecurityPicker_SecuritySelected(Security security)
{
RemoveSecurity.IsEnabled = security != null;
RaiseSelectedCommand();
}
private void SecurityPicker_SecurityDoubleClick(Security security)
{
new EditSecurityCommand(security).Process(this);
}
private void RemoveSecurity_Click(object sender, RoutedEventArgs e)
{
SecurityPicker
.SelectedSecurities
.ForEach(ProcessRemoveSecurity);
}
private void AddSecurity_Click(object sender, RoutedEventArgs e)
{
_isTooltipVisible = false;
((TextBlock)_newSecuritiesTooltip.Content).Foreground = _defaultStorageBrush;
((TextBlock)_newSecuritiesTooltip.Content).Text = _defaultToolTipText;
_newSecuritiesTooltip.IsOpen = false;
var window = new SecuritiesWindowEx
{
SecurityProvider = ConfigManager.GetService<ISecurityProvider>()
};
var selectedSecurities = Securities;
window.SelectSecurities(selectedSecurities);
if (!window.ShowModal(this))
return;
var toRemove = selectedSecurities.Except(window.SelectedSecurities).ToArray();
var toAdd = window.SelectedSecurities.Except(selectedSecurities).ToArray();
toRemove.ForEach(ProcessRemoveSecurity);
toAdd.ForEach(ProcessAddSecurity);
new ControlChangedCommand(this).Process(this);
}
private void ProcessAddSecurity(Security security)
{
_securityIds.Add(security.Id);
SecurityPicker.Securities.Add(security);
RaiseRequestMarketData(security);
}
private void ProcessRemoveSecurity(Security security)
{
_securityIds.Remove(security.Id);
SecurityPicker.Securities.Remove(security);
RaiseRefuseMarketData(security);
}
private void ExecutedOpenMarketDepthCommand(object sender, ExecutedRoutedEventArgs e)
{
new OpenMarketDepthCommand(SecurityPicker.SelectedSecurity).SyncProcess(this);
}
private void CanExecuteOpenMarketDepthCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = SecurityPicker != null && SecurityPicker.SelectedSecurity != null;
}
}
}
| |
/*
* 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.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using CookComputing.XmlRpc;
namespace XenAPI
{
public partial class Session : XenObject<Session>
{
public const int STANDARD_TIMEOUT = 24 * 60 * 60 * 1000;
/// <summary>
/// This string is used as the HTTP UserAgent for each XML-RPC request.
/// </summary>
public static string UserAgent = string.Format("XenAPI/{0}", Helper.APIVersionString(API_Version.LATEST));
/// <summary>
/// If null, no proxy is used, otherwise this proxy is used for each XML-RPC request.
/// </summary>
public static IWebProxy Proxy = null;
public API_Version APIVersion = API_Version.API_1_1;
private Proxy _proxy;
private string _uuid;
public object Tag;
// Filled in after successful session_login_with_password for version 1.6 or newer connections
private bool _isLocalSuperuser = true;
private XenRef<Subject> _subject = null;
private string _userSid = null;
private string[] permissions = null;
private List<Role> roles = new List<Role>();
public Session(int timeout, string url)
{
_proxy = XmlRpcProxyGen.Create<Proxy>();
_proxy.Url = url;
_proxy.NonStandard = XmlRpcNonStandard.All;
_proxy.Timeout = timeout;
_proxy.UseIndentation = false;
_proxy.UserAgent = UserAgent;
_proxy.KeepAlive = true;
// Commenting these out as hooking these events cause problems in XmlRpcClientProtocol.cs#148
//_proxy.RequestEvent += LogRequest;
//_proxy.ResponseEvent += LogResponse;
_proxy.Proxy = Proxy;
}
public Session(string url)
: this(STANDARD_TIMEOUT, url)
{
}
public Session(int timeout, string host, int port)
: this(timeout, GetUrl(host, port))
{
}
public Session(string host, int port)
: this(STANDARD_TIMEOUT, host, port)
{
}
public Session(string url, string opaque_ref)
: this(STANDARD_TIMEOUT, url)
{
this._uuid = opaque_ref;
SetAPIVersion();
if (APIVersion >= API_Version.API_1_6)
SetADDetails();
}
/// <summary>
/// Create a new Session instance, using the given instance and timeout. The connection details and Xen-API session handle will be
/// copied from the given instance, but a new connection will be created. Use this if you want a duplicate connection to a host,
/// for example when you need to cancel an operation that is blocking the primary connection.
/// </summary>
/// <param name="session"></param>
/// <param name="timeout"></param>
public Session(Session session, int timeout)
: this(timeout, session.Url)
{
_uuid = session.uuid;
APIVersion = session.APIVersion;
_isLocalSuperuser = session._isLocalSuperuser;
_subject = session._subject;
_userSid = session._userSid;
}
// Used after VDI.open_database
public static Session get_record(Session session, string _session)
{
Session newSession = new Session(STANDARD_TIMEOUT, session.proxy.Url);
newSession._uuid = _session;
newSession.SetAPIVersion();
return newSession;
}
private void SetADDetails()
{
_isLocalSuperuser = get_is_local_superuser();
if (IsLocalSuperuser)
return;
_subject = get_subject();
_userSid = get_auth_user_sid();
// Cache the details of this user to avoid making server calls later
// For example, some users get access to the pool through a group subject and will not be in the main cache
UserDetails.UpdateDetails(_userSid, this);
if (APIVersion <= API_Version.API_1_6) // Older versions have no RBAC, only AD
return;
// allRoles will contain every role on the server, permissions contains the subset of those that are available to this session.
permissions = Session.get_rbac_permissions(this, uuid);
Dictionary<XenRef<Role>,Role> allRoles = Role.get_all_records(this);
// every Role object is either a single api call (a permission) or has subroles and contains permissions through its descendants.
// We take out the parent Roles (VM-Admin etc.) into the Session.Roles field
foreach (string s in permissions)
{
foreach (XenRef<Role> xr in allRoles.Keys)
{
Role r = allRoles[xr];
if (r.subroles.Count > 0 && r.name_label == s)
{
r.opaque_ref = xr.opaque_ref;
roles.Add(r);
break;
}
}
}
}
/// <summary>
/// Retrieves the current users details from the UserDetails map. These values are only updated when a new session is created.
/// </summary>
public virtual UserDetails CurrentUserDetails
{
get
{
return _userSid == null ? null : UserDetails.Sid_To_UserDetails[_userSid];
}
}
public override void UpdateFrom(Session update)
{
throw new Exception("The method or operation is not implemented.");
}
public override string SaveChanges(Session session, string _serverOpaqueRef, Session serverObject)
{
throw new Exception("The method or operation is not implemented.");
}
public Proxy proxy
{
get { return _proxy; }
}
public string uuid
{
get { return _uuid; }
}
public string Url
{
get { return _proxy.Url; }
}
/// <summary>
/// Always true before API version 1.6.
/// </summary>
public virtual bool IsLocalSuperuser
{
get { return _isLocalSuperuser; }
}
/// <summary>
/// The OpaqueRef for the Subject under whose authority the current user is logged in;
/// may correspond to either a group or a user.
/// Null if IsLocalSuperuser is true.
/// </summary>
public XenRef<Subject> Subject
{
get { return _subject; }
}
/// <summary>
/// The Active Directory SID of the currently logged-in user.
/// Null if IsLocalSuperuser is true.
/// </summary>
public string UserSid
{
get { return _userSid; }
}
/// <summary>
/// All permissions associated with the session at the time of log in. This is the list xapi uses until the session is logged out;
/// even if the permitted roles change on the server side, they don't apply until the next session.
/// </summary>
public string[] Permissions
{
get { return permissions; }
}
/// <summary>
/// All roles associated with the session at the time of log in. Do not rely on roles for determining what a user can do,
/// instead use Permissions. This list should only be used for UI purposes.
/// </summary>
public List<Role> Roles
{
get { return roles; }
}
public void login_with_password(string username, string password)
{
_uuid = proxy.session_login_with_password(username, password).parse();
SetAPIVersion();
}
public void login_with_password(string username, string password, string version)
{
try
{
_uuid = proxy.session_login_with_password(username, password, version).parse();
SetAPIVersion();
if (APIVersion >= API_Version.API_1_6)
SetADDetails();
}
catch (Failure exn)
{
if (exn.ErrorDescription[0] == Failure.MESSAGE_PARAMETER_COUNT_MISMATCH)
{
// Call the 1.1 version instead.
login_with_password(username, password);
}
else
{
throw;
}
}
}
public void login_with_password(string username, string password, string version, string originator)
{
try
{
_uuid = proxy.session_login_with_password(username, password, version, originator).parse();
SetAPIVersion();
if (APIVersion >= API_Version.API_1_6)
SetADDetails();
}
catch (Failure exn)
{
if (exn.ErrorDescription[0] == Failure.MESSAGE_PARAMETER_COUNT_MISMATCH)
{
// Call the pre-2.0 version instead.
login_with_password(username, password, version);
}
else
{
throw;
}
}
}
public void login_with_password(string username, string password, API_Version version)
{
login_with_password(username, password, Helper.APIVersionString(version));
}
private void SetAPIVersion()
{
Dictionary<XenRef<Pool>, Pool> pools = Pool.get_all_records(this);
foreach (Pool pool in pools.Values)
{
Host host = Host.get_record(this, pool.master);
APIVersion = Helper.GetAPIVersion(host.API_version_major, host.API_version_minor);
break;
}
}
public void slave_local_login_with_password(string username, string password)
{
_uuid = proxy.session_slave_local_login_with_password(username, password).parse();
//assume the latest API
APIVersion = API_Version.LATEST;
}
public void logout()
{
logout(this);
}
/// <summary>
/// Log out of the given session2, using this session for the connection.
/// </summary>
/// <param name="session2">The session to log out</param>
public void logout(Session session2)
{
logout(session2._uuid);
session2._uuid = null;
}
/// <summary>
/// Log out of the session with the given reference, using this session for the connection.
/// </summary>
/// <param name="_self">The session to log out</param>
public void logout(string _self)
{
if (_self != null)
proxy.session_logout(_self).parse();
}
public void local_logout()
{
local_logout(this);
}
public void local_logout(Session session2)
{
local_logout(session2._uuid);
session2._uuid = null;
}
public void local_logout(string session_uuid)
{
if (session_uuid != null)
proxy.session_local_logout(session_uuid).parse();
}
public void change_password(string oldPassword, string newPassword)
{
change_password(this, oldPassword, newPassword);
}
/// <summary>
/// Change the password on the given session2, using this session for the connection.
/// </summary>
/// <param name="session2">The session to change</param>
public void change_password(Session session2, string oldPassword, string newPassword)
{
proxy.session_change_password(session2.uuid, oldPassword, newPassword).parse();
}
public string get_this_host()
{
return get_this_host(this, uuid);
}
public static string get_this_host(Session session, string _self)
{
return (string)session.proxy.session_get_this_host(session.uuid, (_self != null) ? _self : "").parse();
}
public string get_this_user()
{
return get_this_user(this, uuid);
}
public static string get_this_user(Session session, string _self)
{
return (string)session.proxy.session_get_this_user(session.uuid, (_self != null) ? _self : "").parse();
}
public bool get_is_local_superuser()
{
return get_is_local_superuser(this, uuid);
}
public static bool get_is_local_superuser(Session session, string _self)
{
return session.proxy.session_get_is_local_superuser(session.uuid, (_self != null) ? _self : "").parse();
}
public static string[] get_rbac_permissions(Session session, string _self)
{
return session.proxy.session_get_rbac_permissions(session.uuid, (_self != null) ? _self : "").parse();
}
public DateTime get_last_active()
{
return get_last_active(this, uuid);
}
public static DateTime get_last_active(Session session, string _self)
{
return session.proxy.session_get_last_active(session.uuid, (_self != null) ? _self : "").parse();
}
public bool get_pool()
{
return get_pool(this, uuid);
}
public static bool get_pool(Session session, string _self)
{
return (bool)session.proxy.session_get_pool(session.uuid, (_self != null) ? _self : "").parse();
}
public XenRef<Subject> get_subject()
{
return get_subject(this, uuid);
}
public static XenRef<Subject> get_subject(Session session, string _self)
{
return new XenRef<Subject>(session.proxy.session_get_subject(session.uuid, (_self != null) ? _self : "").parse());
}
public string get_auth_user_sid()
{
return get_auth_user_sid(this, uuid);
}
public static string get_auth_user_sid(Session session, string _self)
{
return (string)session.proxy.session_get_auth_user_sid(session.uuid, (_self != null) ? _self : "").parse();
}
#region AD SID enumeration and bootout
public string[] get_all_subject_identifiers()
{
return get_all_subject_identifiers(this);
}
public static string[] get_all_subject_identifiers(Session session)
{
return session.proxy.session_get_all_subject_identifiers(session.uuid).parse();
}
public XenRef<Task> async_get_all_subject_identifiers()
{
return async_get_all_subject_identifiers(this);
}
public static XenRef<Task> async_get_all_subject_identifiers(Session session)
{
return XenRef<Task>.Create(session.proxy.async_session_get_all_subject_identifiers(session.uuid).parse());
}
public string logout_subject_identifier(string subject_identifier)
{
return logout_subject_identifier(this, subject_identifier);
}
public static string logout_subject_identifier(Session session, string subject_identifier)
{
return session.proxy.session_logout_subject_identifier(session.uuid, subject_identifier).parse();
}
public XenRef<Task> async_logout_subject_identifier(string subject_identifier)
{
return async_logout_subject_identifier(this, subject_identifier);
}
public static XenRef<Task> async_logout_subject_identifier(Session session, string subject_identifier)
{
return XenRef<Task>.Create(session.proxy.async_session_logout_subject_identifier(session.uuid, subject_identifier).parse());
}
#endregion
#region other_config stuff
public Dictionary<string, string> get_other_config()
{
return get_other_config(this, uuid);
}
public static Dictionary<string, string> get_other_config(Session session, string _self)
{
return Maps.convert_from_proxy_string_string(session.proxy.session_get_other_config(session.uuid, (_self != null) ? _self : "").parse());
}
public void set_other_config(Dictionary<string, string> _other_config)
{
set_other_config(this, uuid, _other_config);
}
public static void set_other_config(Session session, string _self, Dictionary<string, string> _other_config)
{
session.proxy.session_set_other_config(session.uuid, (_self != null) ? _self : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
public void add_to_other_config(string _key, string _value)
{
add_to_other_config(this, uuid, _key, _value);
}
public static void add_to_other_config(Session session, string _self, string _key, string _value)
{
session.proxy.session_add_to_other_config(session.uuid, (_self != null) ? _self : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
public void remove_from_other_config(string _key)
{
remove_from_other_config(this, uuid, _key);
}
public static void remove_from_other_config(Session session, string _self, string _key)
{
session.proxy.session_remove_from_other_config(session.uuid, (_self != null) ? _self : "", (_key != null) ? _key : "").parse();
}
#endregion
static Session()
{
//ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
}
private static string GetUrl(string hostname, int port)
{
return string.Format("{0}://{1}:{2}", port==8080||port == 80 ? "http" : "https", hostname, port); // https, unless port=80
}
private static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Pixie.Options
{
/// <summary>
/// Describes a value option: an option takes exactly one argument.
/// </summary>
public sealed class ValueOption<T> : Option
{
/// <summary>
/// Creates a value option from an option form,
/// a function that parses an argument and a
/// default value.
/// </summary>
/// <param name="form">
/// The option's form.
/// </param>
/// <param name="parseArgument">
/// A function that parses a string argument.
/// </param>
/// <param name="defaultValue">
/// A default value for the value option.
/// </param>
public ValueOption(
OptionForm form,
Func<OptionForm, string, ILog, T> parseArgument,
T defaultValue)
: this(
new OptionForm[] { form },
parseArgument,
defaultValue)
{ }
/// <summary>
/// Creates a value option from a list of forms,
/// a function that parses an argument and a
/// default value.
/// </summary>
/// <param name="forms">
/// The list of forms that the value option accepts.
/// </param>
/// <param name="parseArgument">
/// A function that parses a string argument.
/// </param>
/// <param name="defaultValue">
/// A default value for the value option.
/// </param>
public ValueOption(
IReadOnlyList<OptionForm> forms,
Func<OptionForm, string, ILog, T> parseArgument,
T defaultValue)
: this(
forms,
parseArgument,
defaultValue,
OptionDocs.DefaultCategory,
"",
new SymbolicOptionParameter("arg", false))
{ }
private ValueOption(
IReadOnlyList<OptionForm> forms,
Func<OptionForm, string, ILog, T> parseArgument,
T defaultValue,
string category,
MarkupNode description,
OptionParameter parameter)
{
this.forms = forms;
this.parseArgument = parseArgument;
this.defaultValue = defaultValue;
this.category = category;
this.description = description;
this.parameter = parameter;
}
private ValueOption(ValueOption<T> other)
: this(
other.forms,
other.parseArgument,
other.defaultValue,
other.category,
other.description,
other.parameter)
{ }
private IReadOnlyList<OptionForm> forms;
private Func<OptionForm, string, ILog, T> parseArgument;
private T defaultValue;
private string category;
private MarkupNode description;
private OptionParameter parameter;
/// <summary>
/// Creates a copy of this option that is classified under a
/// particular category.
/// </summary>
/// <param name="category">The new option's category.</param>
/// <returns>An option.</returns>
public ValueOption<T> WithCategory(string category)
{
var result = new ValueOption<T>(this);
result.category = category;
return result;
}
/// <summary>
/// Creates a copy of this option that has a particular description.
/// </summary>
/// <param name="description">The new option's description.</param>
/// <returns>An option.</returns>
public ValueOption<T> WithDescription(MarkupNode description)
{
var result = new ValueOption<T>(this);
result.description = description;
return result;
}
/// <summary>
/// Creates a copy of this option that has a particular parameter.
/// </summary>
/// <param name="parameter">The new option's sole parameter.</param>
/// <returns>An option.</returns>
public ValueOption<T> WithParameter(OptionParameter parameter)
{
var result = new ValueOption<T>(this);
result.parameter = parameter;
return result;
}
/// <inheritdoc/>
public override IReadOnlyList<OptionForm> Forms => forms;
/// <inheritdoc/>
public override object DefaultValue => defaultValue;
/// <inheritdoc/>
public override OptionDocs Documentation =>
new OptionDocs(
category,
description,
forms,
new OptionParameter[] { parameter });
/// <inheritdoc/>
public override OptionParser CreateParser(OptionForm form)
{
return new ValueOptionParser<T>(form, parseArgument);
}
/// <inheritdoc/>
public override ParsedOption MergeValues(ParsedOption first, ParsedOption second)
{
return second;
}
}
/// <summary>
/// Helps build value options.
/// </summary>
public static class ValueOption
{
/// <summary>
/// Creates a string option that takes a single form.
/// </summary>
/// <param name="form">The string option's form.</param>
/// <param name="defaultValue">The default value for the option.</param>
/// <returns>A string option.</returns>
public static ValueOption<string> CreateStringOption(
OptionForm form,
string defaultValue)
{
return new ValueOption<string>(
form,
SequenceOption.parseStringArgument,
defaultValue);
}
/// <summary>
/// Creates a string option that takes a list of forms.
/// </summary>
/// <param name="forms">The string option's forms.</param>
/// <param name="defaultValue">The default value for the option.</param>
/// <returns>A string option.</returns>
public static ValueOption<string> CreateStringOption(
IReadOnlyList<OptionForm> forms,
string defaultValue)
{
return new ValueOption<string>(
forms,
SequenceOption.parseStringArgument,
defaultValue);
}
/// <summary>
/// Creates a 32-bit signed integer option that takes a single form.
/// </summary>
/// <param name="form">The 32-bit signed integer option's form.</param>
/// <param name="defaultValue">The default value for the option.</param>
/// <returns>A 32-bit signed integer option.</returns>
public static ValueOption<int> CreateInt32Option(
OptionForm form,
int defaultValue)
{
return new ValueOption<int>(
form,
SequenceOption.parseInt32Argument,
defaultValue);
}
/// <summary>
/// Creates a 32-bit signed integer option that takes a list of forms.
/// </summary>
/// <param name="forms">The 32-bit signed integer option's forms.</param>
/// <param name="defaultValue">The default value for the option.</param>
/// <returns>A 32-bit signed integer option.</returns>
public static ValueOption<int> CreateInt32Option(
IReadOnlyList<OptionForm> forms,
int defaultValue)
{
return new ValueOption<int>(
forms,
SequenceOption.parseInt32Argument,
defaultValue);
}
}
internal sealed class ValueOptionParser<T> : OptionParser
{
public ValueOptionParser(
OptionForm form,
Func<OptionForm, string, ILog, T> parseArgument)
{
this.form = form;
this.parseArgument = parseArgument;
this.argument = null;
}
private OptionForm form;
private Func<OptionForm, string, ILog, T> parseArgument;
private string argument;
public override object GetValue(ILog log)
{
return parseArgument(form, argument, log);
}
public override bool Parse(string argument)
{
// Accept exactly one argument.
if (this.argument == null)
{
this.argument = argument;
return true;
}
else
{
return false;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Microsoft.NodejsTools.Repl
{
internal class History
{
private readonly int _maxLength;
private int _pos;
private bool _live;
private readonly List<HistoryEntry> _history;
private string _uncommitedInput;
internal History()
: this(50)
{
}
internal History(int maxLength)
{
_maxLength = maxLength;
_pos = -1;
_history = new List<HistoryEntry>();
}
internal void Clear()
{
_pos = -1;
_live = false;
_history.Clear();
}
internal int MaxLength
{
get { return _maxLength; }
}
internal int Length
{
get { return _history.Count; }
}
internal string UncommittedInput
{
get { return _uncommitedInput; }
set { _uncommitedInput = value; }
}
internal IEnumerable<HistoryEntry> Items
{
get { return _history; }
}
internal HistoryEntry Last
{
get
{
if (_history.Count > 0)
{
return _history[_history.Count - 1];
}
else
{
return null;
}
}
}
internal void Add(string text)
{
var entry = new HistoryEntry { Text = text };
_live = false;
if (Length == 0 || Last.Text != text)
{
_history.Add(entry);
}
if (_history[InternalPosition].Text != text)
{
_pos = -1;
}
if (Length > MaxLength)
{
_history.RemoveAt(0);
if (_pos > 0)
{
_pos--;
}
}
}
private int InternalPosition
{
get
{
if (_pos == -1)
{
return Length - 1;
}
else
{
return _pos;
}
}
}
private string GetHistoryText(int pos)
{
if (pos < 0)
{
pos += Length;
}
return _history[pos].Text;
}
private string MoveToNext(string search)
{
do
{
_live = true;
if (_pos < 0 || _pos == Length - 1)
{
return null;
}
_pos++;
} while (SearchDoesntMatch(search));
return GetHistoryMatch(search);
}
private string MoveToPrevious(string search)
{
bool wasLive = _live;
_live = true;
do
{
if (Length == 0 || (Length > 1 && _pos == 0))
{
// we have no history or we have history but have scrolled to the very beginning
return null;
}
if (_pos == -1)
{
// no search in progress, start our search at the end
_pos = Length - 1;
}
else if (!wasLive && string.IsNullOrWhiteSpace(search))
{
// Handles up up up enter up
// Do nothing
}
else
{
// go to the previous item
_pos--;
}
} while (SearchDoesntMatch(search));
return GetHistoryMatch(search);
}
private bool SearchDoesntMatch(string search)
{
return !string.IsNullOrWhiteSpace(search) && GetHistoryText(_pos).IndexOf(search) == -1;
}
private string GetHistoryMatch(string search)
{
if (SearchDoesntMatch(search))
{
return null;
}
return GetHistoryText(_pos);
}
private string Get(Func<string, string> moveFn, string search)
{
var startPos = _pos;
string next = moveFn(search);
if (next == null)
{
_pos = startPos;
return null;
}
return next;
}
internal string GetNext(string search = null)
{
return Get(MoveToNext, search);
}
internal string GetPrevious(string search = null)
{
return Get(MoveToPrevious, search);
}
internal class HistoryEntry
{
internal string Text;
internal bool Command;
internal int Duration;
internal bool Failed;
}
}
}
| |
using System;
using System.Windows;
using System.Security;
using System.Security.Permissions;
using MS.Win32;
using MS.Internal;
namespace System.Windows.Input
{
/// <summary>
/// The Mouse class represents the mouse device to the
/// members of a context.
/// </summary>
/// <remarks>
/// The static members of this class simply delegate to the primary
/// mouse device of the calling thread's input manager.
/// </remarks>
public static class Mouse
{
/// <summary>
/// PreviewMouseMove
/// </summary>
public static readonly RoutedEvent PreviewMouseMoveEvent = EventManager.RegisterRoutedEvent("PreviewMouseMove", RoutingStrategy.Tunnel, typeof(MouseEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the PreviewMouseMove attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddPreviewMouseMoveHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.AddHandler(element, PreviewMouseMoveEvent, handler);
}
/// <summary>
/// Removes a handler for the PreviewMouseMove attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemovePreviewMouseMoveHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.RemoveHandler(element, PreviewMouseMoveEvent, handler);
}
/// <summary>
/// MouseMove
/// </summary>
public static readonly RoutedEvent MouseMoveEvent = EventManager.RegisterRoutedEvent("MouseMove", RoutingStrategy.Bubble, typeof(MouseEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the MouseMove attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddMouseMoveHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.AddHandler(element, MouseMoveEvent, handler);
}
/// <summary>
/// Removes a handler for the MouseMove attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that removedto this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveMouseMoveHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.RemoveHandler(element, MouseMoveEvent, handler);
}
/// <summary>
/// MouseDownOutsideCapturedElement
/// </summary>
public static readonly RoutedEvent PreviewMouseDownOutsideCapturedElementEvent = EventManager.RegisterRoutedEvent("PreviewMouseDownOutsideCapturedElement", RoutingStrategy.Tunnel, typeof(MouseButtonEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the PreviewMouseDownOutsideCapturedElement attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddPreviewMouseDownOutsideCapturedElementHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.AddHandler(element, PreviewMouseDownOutsideCapturedElementEvent, handler);
}
/// <summary>
/// Removes a handler for the MouseDownOutsideCapturedElement attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemovePreviewMouseDownOutsideCapturedElementHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.RemoveHandler(element, PreviewMouseDownOutsideCapturedElementEvent, handler);
}
/// <summary>
/// MouseUpOutsideCapturedElement
/// </summary>
public static readonly RoutedEvent PreviewMouseUpOutsideCapturedElementEvent = EventManager.RegisterRoutedEvent("PreviewMouseUpOutsideCapturedElement", RoutingStrategy.Tunnel, typeof(MouseButtonEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the MouseUpOutsideCapturedElement attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddPreviewMouseUpOutsideCapturedElementHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.AddHandler(element, PreviewMouseUpOutsideCapturedElementEvent, handler);
}
/// <summary>
/// Removes a handler for the MouseUpOutsideCapturedElement attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemovePreviewMouseUpOutsideCapturedElementHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.RemoveHandler(element, PreviewMouseUpOutsideCapturedElementEvent, handler);
}
/// <summary>
/// PreviewMouseDown
/// </summary>
public static readonly RoutedEvent PreviewMouseDownEvent = EventManager.RegisterRoutedEvent("PreviewMouseDown", RoutingStrategy.Tunnel, typeof(MouseButtonEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the PreviewMouseDown attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddPreviewMouseDownHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.AddHandler(element, PreviewMouseDownEvent, handler);
}
/// <summary>
/// Removes a handler for the PreviewMouseDown attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemovePreviewMouseDownHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.RemoveHandler(element, PreviewMouseDownEvent, handler);
}
/// <summary>
/// MouseDown
/// </summary>
public static readonly RoutedEvent MouseDownEvent = EventManager.RegisterRoutedEvent("MouseDown", RoutingStrategy.Bubble, typeof(MouseButtonEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the MouseDown attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddMouseDownHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.AddHandler(element, MouseDownEvent, handler);
}
/// <summary>
/// Removes a handler for the MouseDown attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveMouseDownHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.RemoveHandler(element, MouseDownEvent, handler);
}
/// <summary>
/// PreviewMouseUp
/// </summary>
public static readonly RoutedEvent PreviewMouseUpEvent = EventManager.RegisterRoutedEvent("PreviewMouseUp", RoutingStrategy.Tunnel, typeof(MouseButtonEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the PreviewMouseUp attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddPreviewMouseUpHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.AddHandler(element, PreviewMouseUpEvent, handler);
}
/// <summary>
/// Removes a handler for the PreviewMouseUp attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemovePreviewMouseUpHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.RemoveHandler(element, PreviewMouseUpEvent, handler);
}
/// <summary>
/// MouseUp
/// </summary>
public static readonly RoutedEvent MouseUpEvent = EventManager.RegisterRoutedEvent("MouseUp", RoutingStrategy.Bubble, typeof(MouseButtonEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the MouseUp attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddMouseUpHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.AddHandler(element, MouseUpEvent, handler);
}
/// <summary>
/// Removes a handler for the MouseUp attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveMouseUpHandler(DependencyObject element, MouseButtonEventHandler handler)
{
UIElement.RemoveHandler(element, MouseUpEvent, handler);
}
/// <summary>
/// PreviewMouseWheel
/// </summary>
public static readonly RoutedEvent PreviewMouseWheelEvent = EventManager.RegisterRoutedEvent("PreviewMouseWheel", RoutingStrategy.Tunnel, typeof(MouseWheelEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the PreviewMouseWheel attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddPreviewMouseWheelHandler(DependencyObject element, MouseWheelEventHandler handler)
{
UIElement.AddHandler(element, PreviewMouseWheelEvent, handler);
}
/// <summary>
/// Removes a handler for the PreviewMouseWheel attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemovePreviewMouseWheelHandler(DependencyObject element, MouseWheelEventHandler handler)
{
UIElement.RemoveHandler(element, PreviewMouseWheelEvent, handler);
}
/// <summary>
/// MouseWheel
/// </summary>
public static readonly RoutedEvent MouseWheelEvent = EventManager.RegisterRoutedEvent("MouseWheel", RoutingStrategy.Bubble, typeof(MouseWheelEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the MouseWheel attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddMouseWheelHandler(DependencyObject element, MouseWheelEventHandler handler)
{
UIElement.AddHandler(element, MouseWheelEvent, handler);
}
/// <summary>
/// Removes a handler for the MouseWheel attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveMouseWheelHandler(DependencyObject element, MouseWheelEventHandler handler)
{
UIElement.RemoveHandler(element, MouseWheelEvent, handler);
}
/// <summary>
/// MouseEnter
/// </summary>
public static readonly RoutedEvent MouseEnterEvent = EventManager.RegisterRoutedEvent("MouseEnter", RoutingStrategy.Direct, typeof(MouseEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the MouseEnter attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddMouseEnterHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.AddHandler(element, MouseEnterEvent, handler);
}
/// <summary>
/// Removes a handler for the MouseEnter attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveMouseEnterHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.RemoveHandler(element, MouseEnterEvent, handler);
}
/// <summary>
/// MouseLeave
/// </summary>
public static readonly RoutedEvent MouseLeaveEvent = EventManager.RegisterRoutedEvent("MouseLeave", RoutingStrategy.Direct, typeof(MouseEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the MouseLeave attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddMouseLeaveHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.AddHandler(element, MouseLeaveEvent, handler);
}
/// <summary>
/// Removes a handler for the MouseLeave attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveMouseLeaveHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.RemoveHandler(element, MouseLeaveEvent, handler);
}
/// <summary>
/// GotMouseCapture
/// </summary>
public static readonly RoutedEvent GotMouseCaptureEvent = EventManager.RegisterRoutedEvent("GotMouseCapture", RoutingStrategy.Bubble, typeof(MouseEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the GotMouseCapture attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddGotMouseCaptureHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.AddHandler(element, GotMouseCaptureEvent, handler);
}
/// <summary>
/// Removes a handler for the GotMouseCapture attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveGotMouseCaptureHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.RemoveHandler(element, GotMouseCaptureEvent, handler);
}
/// <summary>
/// LostMouseCapture
/// </summary>
public static readonly RoutedEvent LostMouseCaptureEvent = EventManager.RegisterRoutedEvent("LostMouseCapture", RoutingStrategy.Bubble, typeof(MouseEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the LostMouseCapture attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddLostMouseCaptureHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.AddHandler(element, LostMouseCaptureEvent, handler);
}
/// <summary>
/// Removes a handler for the LostMouseCapture attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveLostMouseCaptureHandler(DependencyObject element, MouseEventHandler handler)
{
UIElement.RemoveHandler(element, LostMouseCaptureEvent, handler);
}
/// <summary>
/// QueryCursor
/// </summary>
public static readonly RoutedEvent QueryCursorEvent = EventManager.RegisterRoutedEvent("QueryCursor", RoutingStrategy.Bubble, typeof(QueryCursorEventHandler), typeof(Mouse));
/// <summary>
/// Adds a handler for the QueryCursor attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddQueryCursorHandler(DependencyObject element, QueryCursorEventHandler handler)
{
UIElement.AddHandler(element, QueryCursorEvent, handler);
}
/// <summary>
/// Removes a handler for the QueryCursor attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveQueryCursorHandler(DependencyObject element, QueryCursorEventHandler handler)
{
UIElement.RemoveHandler(element, QueryCursorEvent, handler);
}
/// <summary>
/// Returns the element that the mouse is over.
/// </summary>
/// <remarks>
/// This will be true if the element has captured the mouse.
/// </remarks>
public static IInputElement DirectlyOver
{
get
{
return Mouse.PrimaryDevice.DirectlyOver;
}
}
/// <summary>
/// Returns the element that has captured the mouse.
/// </summary>
public static IInputElement Captured
{
get
{
return Mouse.PrimaryDevice.Captured;
}
}
/// <summary>
/// Returns the element that has captured the mouse.
/// </summary>
internal static CaptureMode CapturedMode
{
get
{
return Mouse.PrimaryDevice.CapturedMode;
}
}
/// <summary>
/// Captures the mouse to a particular element.
/// </summary>
/// <param name="element">
/// The element to capture the mouse to.
/// </param>
public static bool Capture(IInputElement element)
{
return Mouse.PrimaryDevice.Capture(element);
}
/// <summary>
/// Captures the mouse to a particular element.
/// </summary>
/// <param name="element">
/// The element to capture the mouse to.
/// </param>
/// <param name="captureMode">
/// The kind of capture to acquire.
/// </param>
public static bool Capture(IInputElement element, CaptureMode captureMode)
{
return Mouse.PrimaryDevice.Capture(element, captureMode);
}
/// <summary>
/// Retrieves the history of intermediate Points up to 64 previous coordinates of the mouse or pen.
/// </summary>
/// <param name="relativeTo">
/// The element relative which the points need to be returned.
/// </param>
/// <param name="points">
/// Points relative to the first parameter are returned.
/// </param>
/// <SecurityNote>
/// Critical: calls critical method (GetInputProvider) and gets PresentationSource.
/// PublicOK: The PresentationSource and input provider aren't
/// returned or stored.
/// </SecurityNote>
[SecurityCritical]
public static int GetIntermediatePoints(IInputElement relativeTo, Point[] points)
{
// Security Mitigation: do not give out input state if the device is not active.
if(Mouse.PrimaryDevice.IsActive)
{
if (relativeTo != null)
{
PresentationSource inputSource = PresentationSource.FromDependencyObject(InputElement.GetContainingVisual(relativeTo as DependencyObject));
if (inputSource != null)
{
IMouseInputProvider mouseInputProvider = inputSource.GetInputProvider(typeof(MouseDevice)) as IMouseInputProvider;
if (null != mouseInputProvider)
{
return mouseInputProvider.GetIntermediatePoints(relativeTo, points);
}
}
}
}
return -1;
}
/// <summary>
/// The override cursor
/// </summary>
public static Cursor OverrideCursor
{
get
{
return Mouse.PrimaryDevice.OverrideCursor;
}
set
{
// forwarding to the MouseDevice, will be validated there.
Mouse.PrimaryDevice.OverrideCursor = value;
}
}
/// <summary>
/// Sets the mouse cursor
/// </summary>
/// <param name="cursor">The cursor to be set</param>
/// <returns>True on success (always the case for Win32)</returns>
public static bool SetCursor(Cursor cursor)
{
return Mouse.PrimaryDevice.SetCursor(cursor);
}
/// <summary>
/// The state of the left button.
/// </summary>
public static MouseButtonState LeftButton
{
get
{
return Mouse.PrimaryDevice.LeftButton;
}
}
/// <summary>
/// The state of the right button.
/// </summary>
public static MouseButtonState RightButton
{
get
{
return Mouse.PrimaryDevice.RightButton;
}
}
/// <summary>
/// The state of the middle button.
/// </summary>
public static MouseButtonState MiddleButton
{
get
{
return Mouse.PrimaryDevice.MiddleButton;
}
}
/// <summary>
/// The state of the first extended button.
/// </summary>
public static MouseButtonState XButton1
{
get
{
return Mouse.PrimaryDevice.XButton1;
}
}
/// <summary>
/// The state of the second extended button.
/// </summary>
public static MouseButtonState XButton2
{
get
{
return Mouse.PrimaryDevice.XButton2;
}
}
/// <summary>
/// Calculates the position of the mouse relative to
/// a particular element.
/// </summary>
public static Point GetPosition(IInputElement relativeTo)
{
return Mouse.PrimaryDevice.GetPosition(relativeTo);
}
/// <summary>
/// Forces the mouse to resynchronize.
/// </summary>
public static void Synchronize()
{
Mouse.PrimaryDevice.Synchronize();
}
/// <summary>
/// Forces the mouse cursor to be updated.
/// </summary>
public static void UpdateCursor()
{
Mouse.PrimaryDevice.UpdateCursor();
}
/// <summary>
/// The number of units the mouse wheel should be rotated to scroll one line.
/// </summary>
/// <remarks>
/// The delta was set to 120 to allow Microsoft or other vendors to
/// build finer-resolution wheels in the future, including perhaps
/// a freely-rotating wheel with no notches. The expectation is
/// that such a device would send more messages per rotation, but
/// with a smaller value in each message. To support this
/// possibility, you should either add the incoming delta values
/// until MouseWheelDeltaForOneLine amount is reached (so for a
/// delta-rotation you get the same response), or scroll partial
/// lines in response to the more frequent messages. You could also
/// choose your scroll granularity and accumulate deltas until it
/// is reached.
/// </remarks>
public const int MouseWheelDeltaForOneLine = 120;
/// <summary>
/// The primary mouse device.
/// </summary>
/// <SecurityNote>
/// Critical: This code acceses InputManager which is critical
/// PublicOK: This data is ok to expose
/// </SecurityNote>
public static MouseDevice PrimaryDevice
{
[SecurityCritical]
get
{
MouseDevice mouseDevice;
//there is a link demand on the Current property
mouseDevice = InputManager.UnsecureCurrent.PrimaryMouseDevice;
return mouseDevice;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
// http://bungee-view.googlecode.com/svn-history/r120/trunk/lbfgs/edu/cmu/cs/bungee/lbfgs/LBFGS.java
//package edu.cmu.cs.bungee.lbfgs;
///* LBFGS.java
// * Copyright (C) 1999, Robert Dodier (robert_dodier@yahoo.com)
// *
// * This program is free software; you can redistribute it and/or modify
// * it under the terms of version 2.1 of the GNU Lesser General Public License
// * as published by the Free Software Foundation.
// *
// * 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 Lesser General Public License for more details.
// *
// * You should have received a copy of the GNU Lesser 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,
// * or visit the GNU web site, www.gnu.org.
// *
///**
// * <p>
// * This class contains code for the limited-memory
// * Broyden-Fletcher-Goldfarb-Shanno (LBFGS) algorithm for large-scale
// * multidimensional unconstrained minimization problems. This file is a
// * translation of Fortran code written by Jorge Nocedal. The only modification
// * to the algorithm is the addition of a cache to store the result of the most
// * recent line search. See <tt>solution_cache</tt> below.
// *
// * Following is a message from Jorge Nocedal:
// *
// * <pre>
// * From: Jorge Nocedal [mailto:nocedal@dario.ece.nwu.edu]
// * Sent: Friday, August 17, 2001 9:09 AM
// * To: Robert Dodier
// * Subject: Re: Commercial licensing terms for LBFGS?
// *
// * Robert:
// * The code L-BFGS (for unconstrained problems) is in the public domain.
// * It can be used in any commercial application.
// *
// * The code L-BFGS-B (for bound constrained problems) belongs to
// * ACM. You need to contact them for a commercial license. It is
// * algorithm 778.
// *
// * Jorge
// * </pre>
// *
// * <p>
// * This code is derived from the Fortran program <code>lbfgs.f</code>. The Java
// * translation was effected mostly mechanically, with some manual clean-up; in
// * particular, array indices start at 0 instead of 1. Most of the comments from
// * the Fortran code have been pasted in here as well.
// * </p>
// *
// * <p>
// * Here's some information on the original LBFGS Fortran source code, available
// * at <a href="http://www.netlib.org/opt/lbfgs_um.shar">
// * http://www.netlib.org/opt/lbfgs_um.shar</a>. This info is taken verbatim from
// * the Netlib blurb on the Fortran source.
// * </p>
// *
// * <pre>
// * file opt/lbfgs_um.shar
// * for unconstrained optimization problems
// * alg limited memory BFGS method
// * by J. Nocedal
// * contact nocedal@eecs.nwu.edu
// * ref D. C. Liu and J. Nocedal, ``On the limited memory BFGS method for
// * , large scale optimization methods'' Mathematical Programming 45
// * , (1989), pp. 503-528.
// * , (Postscript file of this paper is available via anonymous ftp
// * , to eecs.nwu.edu in the directory pub/lbfgs/lbfgs_um.)
// * http://www.ece.northwestern.edu/~nocedal/PDFfiles/limited-memory.pdf
// * </pre>
// *
// * @author Jorge Nocedal: original Fortran version, including comments (July
// * 1990). Robert Dodier: Java translation, August 1997.
// *
namespace HTLib2
{
public class LBFGS
{
///**
// * Specialized exception class for LBFGS; contains the <code>iflag</code>
// * value returned by <code>lbfgs</code>.
// *
public class ExceptionWithIflag : Exception {
///**
// *
// *
private const long serialVersionUID = 1L;
public int iflag;
public ExceptionWithIflag(int i, String s)
: base(s)
{
iflag = i;
}
public override String ToString()
{
return base.ToString() + " (iflag == " + iflag + ")";
//return getMessage() + " (iflag == " + iflag + ")";
}
}
///**
// * Controls the accuracy of the line search <code>mcsrch</code>. If the
// * function and gradient evaluations are inexpensive with respect to the
// * cost of the iteration (which is sometimes the case when solving very
// * large problems) it may be advantageous to set <code>gtol</code> to a
// * small value. A typical small value is 0.1. Restriction: <code>gtol</code>
// * should be greater than 1e-4.
// *
public static double gtol = 0.9;
///**
// * Specify lower bound for the step in the line search. The default value is
// * 1e-20. This value need not be modified unless the exponent is too large
// * for the machine being used, or unless the problem is extremely badly
// * scaled (in which case the exponent should be increased).
// *
public static double stpmin = 1e-20;
///**
// * Specify upper bound for the step in the line search. The default value is
// * 1e20. This value need not be modified unless the exponent is too large
// * for the machine being used, or unless the problem is extremely badly
// * scaled (in which case the exponent should be increased).
// *
public static double stpmax = 1e20;
public static int maxfev = 200;
///**
// * The solution vector as it was at the end of the most recently completed
// * line search. This will usually be different from the return value of the
// * parameter <tt>x</tt> of <tt>lbfgs</tt>, which is modified by line-search
// * steps. A caller which wants to stop the optimization iterations before
// * <tt>LBFGS.lbfgs</tt> automatically stops (by reaching a very small
// * gradient) should copy this vector instead of using <tt>x</tt>. When
// * <tt>LBFGS.lbfgs</tt> automatically stops, then <tt>x</tt> and
// * <tt>solution_cache</tt> are the same.
// *
public static double[] solution_cache = null;
private static double gnorm = 0, stp1 = 0, ftol = 0;
private static double[] stp = new double[1];
private static double ys = 0, yy = 0, sq = 0, yr = 0, beta = 0, xnorm = 0;
private static int iter = 0, nfun = 0, point = 0, ispt = 0, iypt = 0;
private static int[] info = new int[1];
private static int bound = 0, npt = 0, cp = 0, i = 0;
private static int[] nfev = new int[1];
private static int inmc = 0, iycn = 0, iscn = 0;
private static bool finish = false;
private static double[] w = null;
///**
// * This method returns the total number of evaluations of the objective
// * function since the last time LBFGS was restarted. The total number of
// * function evaluations increases by the number of evaluations required for
// * the line search; the total is only increased after a successful line
// * search.
// *
public static int nfevaluations() {
return nfun;
}
///**
// * This subroutine solves the unconstrained minimization problem
// *
// * <pre>
// * min f(x), x = (x1,x2,...,x_n),
// * </pre>
// *
// * using the limited-memory BFGS method. The routine is especially effective
// * on problems involving a large number of variables. In a typical iteration
// * of this method an approximation <code>Hk</code> to the inverse of the
// * Hessian is obtained by applying <code>m</code> BFGS updates to a diagonal
// * matrix <code>Hk0</code>, using information from the previous M steps. The
// * user specifies the number <code>m</code>, which determines the amount of
// * storage required by the routine. The user may also provide the diagonal
// * matrices <code>Hk0</code> if not satisfied with the default choice. The
// * algorithm is described in "On the limited memory BFGS method for large
// * scale optimization", by D. Liu and J. Nocedal, Mathematical Programming B
// * 45 (1989) 503-528.
// *
// * The user is required to calculate the function value <code>f</code> and
// * its gradient <code>g</code>. In order to allow the user complete control
// * over these computations, reverse communication is used. The routine must
// * be called repeatedly under the control of the parameter
// * <code>iflag</code>.
// *
// * The steplength is determined at each iteration by means of the line
// * search routine <code>mcsrch</code>, which is a slight modification of the
// * routine <code>CSRCH</code> written by More' and Thuente.
// *
// * The only variables that are machine-dependent are <code>xtol</code>,
// * <code>stpmin</code> and <code>stpmax</code>.
// *
// * Progress messages and non-fatal error messages are printed to
// * <code>System.err</code>. Fatal errors cause exception to be thrown, as
// * listed below.
// *
// * @param n
// * The number of variables in the minimization problem.
// * Restriction: <code>n > 0</code>.
// *
// * @param m
// * The number of corrections used in the BFGS update. Values of
// * <code>m</code> less than 3 are not recommended; large values
// * of <code>m</code> will result in excessive computing time.
// * <code>3 <= m <= 7</code> is recommended. Restriction:
// * <code>m > 0</code>.
// *
// * @param x
// * On initial entry this must be set by the user to the values of
// * the initial estimate of the solution vector. On exit with
// * <code>iflag = 0</code>, it contains the values of the
// * variables at the best point found (usually a solution).
// *
// * @param f
// * Before initial entry and on a re-entry with
// * <code>iflag = 1</code>, it must be set by the user to contain
// * the value of the function <code>f</code> at the point
// * <code>x</code>.
// *
// * @param g
// * Before initial entry and on a re-entry with
// * <code>iflag = 1</code>, it must be set by the user to contain
// * the components of the gradient <code>g</code> at the point
// * <code>x</code>.
// *
// * @param diagco
// * Set this to <code>true</code> if the user wishes to provide
// * the diagonal matrix <code>Hk0</code> at each iteration.
// * Otherwise it should be set to <code>false</code> in which case
// * <code>lbfgs</code> will use a default value described below.
// * If <code>diagco</code> is set to <code>true</code> the routine
// * will return at each iteration of the algorithm with
// * <code>iflag = 2</code>, and the diagonal matrix
// * <code>Hk0</code> must be provided in the array
// * <code>diag</code>.
// *
// * @param diag
// * If <code>diagco = true</code>, then on initial entry or on
// * re-entry with <code>iflag = 2</code>, <code>diag</code> must
// * be set by the user to contain the values of the diagonal
// * matrix <code>Hk0</code>. Restriction: all elements of
// * <code>diag</code> must be positive.
// *
// * @param iprint
// * Specifies output generated by <code>lbfgs</code>.
// * <code>iprint[0]</code> specifies the frequency of the output:
// * <ul>
// * <li> <code>iprint[0] < 0</code>: no output is generated,
// * <li> <code>iprint[0] = 0</code>: output only at first and last
// * iteration,
// * <li> <code>iprint[0] > 0</code>: output every
// * <code>iprint[0]</code> iterations.
// * </ul>
// *
// * <code>iprint[1]</code> specifies the type of output generated:
// * <ul>
// * <li> <code>iprint[1] = 0</code>: iteration count, number of
// * function evaluations, function value, norm of the gradient,
// * and steplength,
// * <li> <code>iprint[1] = 1</code>: same as
// * <code>iprint[1]=0</code>, plus vector of variables and
// * gradient vector at the initial point,
// * <li> <code>iprint[1] = 2</code>: same as
// * <code>iprint[1]=1</code>, plus vector of variables,
// * <li> <code>iprint[1] = 3</code>: same as
// * <code>iprint[1]=2</code>, plus gradient vector.
// * </ul>
// *
// * @param eps
// * Determines the accuracy with which the solution is to be
// * found. The subroutine terminates when
// *
// * <pre>
// * ||G|| < EPS max(1,||X||),
// * </pre>
// *
// * where <code>||.||</code> denotes the Euclidean norm.
// *
// * @param xtol
// * An estimate of the machine precision (e.g. 10e-16 on a SUN
// * station 3/60). The line search routine will terminate if the
// * relative width of the interval of uncertainty is less than
// * <code>xtol</code>.
// *
// * @param iflag
// * This must be set to 0 on initial entry to <code>lbfgs</code>.
// * A return with <code>iflag < 0</code> indicates an error,
// * and <code>iflag = 0</code> indicates that the routine has
// * terminated without detecting errors. On a return with
// * <code>iflag = 1</code>, the user must evaluate the function
// * <code>f</code> and gradient <code>g</code>. On a return with
// * <code>iflag = 2</code>, the user must provide the diagonal
// * matrix <code>Hk0</code>.
// *
// * The following negative values of <code>iflag</code>, detecting
// * an error, are possible:
// * <ul>
// * <li> <code>iflag = -1</code> The line search routine
// * <code>mcsrch</code> failed. One of the following messages is
// * printed:
// * <ul>
// * <li>Improper input parameters.
// * <li>Relative width of the interval of uncertainty is at most
// * <code>xtol</code>.
// * <li>More than 20 function evaluations were required at the
// * present iteration.
// * <li>The step is too small.
// * <li>The step is too large.
// * <li>Rounding errors prevent further progress. There may not be
// * a step which satisfies the sufficient decrease and curvature
// * conditions. Tolerances may be too small.
// * </ul>
// * <li><code>iflag = -2</code> The i-th diagonal element of the
// * diagonal inverse Hessian approximation, given in DIAG, is not
// * positive.
// * <li><code>iflag = -3</code> Improper input parameters for
// * LBFGS (<code>n</code> or <code>m</code> are not positive).
// * </ul>
// *
// * @throws LBFGS.ExceptionWithIflag
// *
public static void lbfgs(int n, int m, double[] x, double f, double[] g,
bool diagco, double[] diag, int[] iprint, double eps,
double xtol, int[] iflag) // throws ExceptionWithIflag
{
bool execute_entire_while_loop = false;
if (w == null || w.Length != n * (2 * m + 1) + 2 * m) {
w = new double[n * (2 * m + 1) + 2 * m];
}
if (iflag[0] == 0) {
// Initialize.
solution_cache = new double[n];
//System.arraycopy(x, 0, solution_cache, 0, n);
for(int i=0; i<n; i++) solution_cache[i] = x[i];
iter = 0;
if (n <= 0 || m <= 0) {
iflag[0] = -3;
throw new ExceptionWithIflag(iflag[0],
"Improper input parameters (n or m are not positive.)");
}
if (gtol <= 0.0001) {
System_err_println("LBFGS.lbfgs: gtol is less than or equal to 0.0001. It has been reset to 0.9.");
gtol = 0.9;
}
nfun = 1;
point = 0;
finish = false;
if (diagco) {
for (i = 1; i <= n; i += 1) {
if (diag[i - 1] <= 0) {
iflag[0] = -2;
throw new ExceptionWithIflag(
iflag[0],
"The "
+ i
+ "-th diagonal element of the inverse hessian approximation is not positive.");
}
}
} else {
for (i = 1; i <= n; i += 1) {
diag[i - 1] = 1;
}
}
ispt = n + 2 * m;
iypt = ispt + n * m;
for (i = 1; i <= n; i += 1) {
w[ispt + i - 1] = -g[i - 1] * diag[i - 1];
if (badNum(w[ispt + i - 1]))
System_err_println("w1 " + g[i - 1] + " " + diag[i - 1]);
}
gnorm = Math.Sqrt(ddot(n, g, 0, 1, g, 0, 1));
stp1 = 1 / gnorm;
ftol = 0.0001;
if (iprint[1 - 1] >= 0)
lb1(iprint, iter, nfun, gnorm, n, m, x, f, g, stp, finish);
execute_entire_while_loop = true;
}
while (true) {
if (execute_entire_while_loop) {
iter = iter + 1;
info[0] = 0;
bound = iter - 1;
if (iter != 1) {
if (iter > m)
bound = m;
ys = ddot(n, w, iypt + npt, 1, w, ispt + npt, 1);
if (!diagco) {
yy = ddot(n, w, iypt + npt, 1, w, iypt + npt, 1);
for (i = 1; i <= n; i += 1) {
diag[i - 1] = safeDiv(ys , yy);
}
} else {
iflag[0] = 2;
return;
}
}
}
if (execute_entire_while_loop || iflag[0] == 2) {
if (iter != 1) {
if (diagco) {
for (i = 1; i <= n; i += 1) {
if (diag[i - 1] <= 0) {
iflag[0] = -2;
throw new ExceptionWithIflag(
iflag[0],
"The "
+ i
+ "-th diagonal element of the inverse hessian approximation is not positive.");
}
}
}
cp = point;
if (point == 0)
cp = m;
w[n + cp - 1] = 1 / ys;
if (badNum(w[n + cp - 1]))
System_err_println("w2 " + ys);
for (i = 1; i <= n; i += 1) {
w[i - 1] = -g[i - 1];
if (badNum(w[i - 1]))
throw new ArgumentException(i + " "
+ g[i - 1]);
}
cp = point;
for (i = 1; i <= bound; i += 1) {
cp = cp - 1;
if (cp == -1)
cp = m - 1;
sq = ddot(n, w, ispt + cp * n, 1, w, 0, 1);
inmc = n + m + cp + 1;
iycn = iypt + cp * n;
w[inmc - 1] = w[n + cp] * sq;
if (badNum(w[inmc - 1])) {
System_err_println("w3 " + w[n + cp] + " " + sq);
lb1(iprint, iter, nfun, gnorm, n, m, x, f, g, stp,
finish);
}
daxpy(n, -w[inmc - 1], w, iycn, 1, w, 0, 1);
}
for (i = 1; i <= n; i += 1) {
w[i - 1] *= diag[i - 1];
if (badNum(w[i - 1]))
System_err_println("w4 " + diag[i - 1]);
}
for (i = 1; i <= bound; i += 1) {
yr = ddot(n, w, iypt + cp * n, 1, w, 0, 1);
beta = safeMult(w[n + cp] , yr);
inmc = n + m + cp + 1;
beta = w[inmc - 1] - beta;
if (badNum(beta)) {
throw new ArgumentException(w[inmc - 1]+" "+safeMult(w[n + cp] , yr));
}
iscn = ispt + cp * n;
daxpy(n, beta, w, iscn, 1, w, 0, 1);
cp = cp + 1;
if (cp == m)
cp = 0;
}
for (i = 1; i <= n; i += 1) {
w[ispt + point * n + i - 1] = w[i - 1];
if (badNum(w[ispt + point * n + i - 1]))
System_err_println("w5 " + w[i - 1]);
}
}
nfev[0] = 0;
Mcsrch.setSTP(stp, iter == 1 && stp1 < 1 ? stp1 : 1);
for (i = 1; i <= n; i += 1) {
w[i - 1] = g[i - 1];
if (badNum(w[i - 1]))
System_err_println("w6 " + g[i - 1]);
}
}
double MY_MAX_STEP = 1;
double directionMag = ddot(n, w, ispt + point * n, 1, w, ispt
+ point * n, 1);
double effectiveStep = stp[0] * directionMag;
if (effectiveStep > MY_MAX_STEP) {
if (iprint[0] > 0)
System_err_println("reducing step: " + stp[0] + " => "
+ (MY_MAX_STEP / directionMag));
// stpmax = MY_MAX_STEP / directionMag;
} else
stpmax = 1e20;
// if (iprint[1 - 1] >= 0)
// lb1(iprint, iter, nfun, gnorm, n, m, x, f, g, stp, finish);
Mcsrch.mcsrch(n, x, f, g, w, ispt + point * n, stp, ftol, xtol,
maxfev, info, nfev, diag, iprint);
if (info[0] == -1) {
iflag[0] = 1;
return;
}
if (iprint[0] > 0)
System_err_println("msrch return = nfev=" + nfev[0] + " nfun="
+ nfun + " info=" + info[0] + " bestx=" + Mcsrch.stx[0]
+ " farx=" + Mcsrch.sty[0] + " brackt="
+ Mcsrch.brackt[0] + " stp=" + stp[0] + " gnorm="
+ Math.Sqrt(ddot(n, g, 0, 1, g, 0, 1)) + " xnorm="
+ Math.Sqrt(ddot(n, x, 0, 1, x, 0, 1)));
if (info[0] != 1) {
iflag[0] = -1;
throw new ExceptionWithIflag(
iflag[0],
"Line search failed. See documentation of routine mcsrch. Error return of line search: info = "
+ info[0]
+ " Possible causes: function or gradient are incorrect, or incorrect tolerances.");
}
nfun += nfev[0];
npt = point * n;
for (i = 1; i <= n; i += 1) {
w[ispt + npt + i - 1] *= stp[0];
if (badNum(w[ispt + npt + i - 1]))
System_err_println("w6 " + stp[0]);
w[iypt + npt + i - 1] = g[i - 1] - w[i - 1];
if (badNum(w[iypt + npt + i - 1]))
System_err_println("w7 " + g[i - 1] + " " + w[i - 1]);
}
point++;
if (point == m)
point = 0;
gnorm = Math.Sqrt(ddot(n, g, 0, 1, g, 0, 1));
xnorm = Math.Sqrt(ddot(n, x, 0, 1, x, 0, 1));
xnorm = Math.Max(1.0, xnorm);
if (gnorm / xnorm <= eps)
finish = true;
if (iprint[1 - 1] >= 0)
lb1(iprint, iter, nfun, gnorm, n, m, x, f, g, stp, finish);
// Cache the current solution vector. Due to the spaghetti-like
// nature of this code, it's not possible to quit here and return;
// we need to go back to the top of the loop, and eventually call
// mcsrch one more time -- but that will modify the solution vector.
// So we need to keep a copy of the solution vector as it was at
// the completion (info[0]==1) of the most recent line search.
//System.arraycopy(x, 0, solution_cache, 0, n);
for(int i=0; i<n; i++) solution_cache[i] = x[i];
if (finish) {
iflag[0] = 0;
return;
}
execute_entire_while_loop = true; // from now on, execute whole loop
}
}
///**
// * Print debugging and status messages for <code>lbfgs</code>. Depending on
// * the parameter <code>iprint</code>, this can include number of function
// * evaluations, current function value, etc. The messages are output to
// * <code>System.err</code>.
// *
// * @param iprint
// * Specifies output generated by <code>lbfgs</code>.
// * <p>
// * <code>iprint[0]</code> specifies the frequency of the output:
// * <ul>
// * <li> <code>iprint[0] < 0</code>: no output is generated,
// * <li> <code>iprint[0] = 0</code>: output only at first and last
// * iteration,
// * <li> <code>iprint[0] > 0</code>: output every
// * <code>iprint[0]</code> iterations.
// * </ul>
// * <p>
// *
// * <code>iprint[1]</code> specifies the type of output generated:
// * <ul>
// * <li> <code>iprint[1] = 0</code>: iteration count, number of
// * function evaluations, function value, norm of the gradient,
// * and steplength,
// * <li> <code>iprint[1] = 1</code>: same as
// * <code>iprint[1]=0</code>, plus vector of variables and
// * gradient vector at the initial point,
// * <li> <code>iprint[1] = 2</code>: same as
// * <code>iprint[1]=1</code>, plus vector of variables,
// * <li> <code>iprint[1] = 3</code>: same as
// * <code>iprint[1]=2</code>, plus gradient vector.
// * </ul>
// * @param iter1
// * Number of iterations so far.
// * @param nfun1
// * Number of function evaluations so far.
// * @param gnorm1
// * Norm of gradient at current solution <code>x</code>.
// * @param n
// * Number of free parameters.
// * @param m
// * Number of corrections kept.
// * @param x
// * Current solution.
// * @param f
// * Function value at current solution.
// * @param g
// * Gradient at current solution <code>x</code>.
// * @param stp11
// * Current stepsize.
// * @param finish1
// * Whether this method should print the ``we're done'' message.
// *
public static void lb1(int[] iprint, int iter1, int nfun1, double gnorm1,
int n, int m, double[] x, double f, double[] g, double[] stp11,
bool finish1) {
String heading = "\ti\tnfn\tfunc\t\t\tgnorm\t\t\tsteplength";
int i1;
if (iter1 == 0) {
System_err_println("*************************************************");
System_err_println(" n = " + n + " number of corrections = " + m
+ "\n initial values");
System_err_println(" f = " + f + " gnorm = " + gnorm1);
if (iprint[2 - 1] >= 1) {
System_err_print(" vector x =");
for (i1 = 1; i1 <= n; i1++)
System_err_print(" " + x[i1 - 1]);
System_err_println("");
System_err_print(" gradient vector g =");
for (i1 = 1; i1 <= n; i1++)
System_err_print(" " + g[i1 - 1]);
System_err_println("");
}
System_err_println("*************************************************");
System_err_println(heading);
} else {
if ((iprint[1 - 1] == 0) && (iter1 != 1 && !finish1))
return;
if (iprint[1 - 1] != 0) {
if ((iter1 - 1) % iprint[1 - 1] == 0 || finish1) {
if (iprint[2 - 1] > 1 && iter1 > 1)
System_err_println(heading);
System_err_println("\t" + iter1 + "\t" + nfun1 + "\t" + f
+ "\t" + gnorm1 + "\t" + stp11[0]);
} else {
return;
}
} else {
if (iprint[2 - 1] > 1 && finish1)
System_err_println(heading);
System_err_println("\t" + iter1 + "\t" + nfun1 + "\t" + f
+ "\t" + gnorm1 + "\t" + stp11[0]);
}
if (iprint[2 - 1] == 2 || iprint[2 - 1] == 3) {
if (finish1) {
System_err_print(" final point x =");
} else {
System_err_print(" vector x = ");
}
for (i1 = 1; i1 <= n; i1++)
System_err_print(" " + x[i1 - 1]);
System_err_println("");
if (iprint[2 - 1] == 3) {
System_err_print(" gradient vector g =");
for (i1 = 1; i1 <= n; i1++)
System_err_print(" " + g[i1 - 1]);
System_err_println("");
}
}
if (finish1)
System_err_println(" The minimization terminated without detecting errors. iflag = 0");
}
return;
}
///**
// * Compute the sum of a vector times a scalara plus another vector. Adapted
// * from the subroutine <code>daxpy</code> in <code>lbfgs.f</code>. There
// * could well be faster ways to carry out this operation; this code is a
// * straight translation from the Fortran.
// *
public static void daxpy(int n, double da, double[] dx, int ix0, int incx,
double[] dy, int iy0, int incy) {
int i1, ix, iy;// , m, mp1;
if (n <= 0)
return;
if (da == 0)
return;
// if (!(incx == 1 && incy == 1)) {
ix = 1;
iy = 1;
if (incx < 0)
ix = (-n + 1) * incx + 1;
if (incy < 0)
iy = (-n + 1) * incy + 1;
for (i1 = 1; i1 <= n; i1 += 1) {
dy[iy0 + iy - 1] += safeMult(da , dx[ix0 + ix - 1]);
ix = ix + incx;
iy = iy + incy;
}
return;
// }
// m = n % 4;
// if (m != 0) {
// for (i1 = 1; i1 <= m; i1 += 1) {
// dy[iy0 + i1 - 1] += da * dx[ix0 + i1 - 1];
// if (badNum(dy[iy0 + i1 - 1]))
// throw new IllegalArgumentException(da + " " + dx[ix0 + i1 - 1]);
// }
//
// if (n < 4)
// return;
// }
//
// mp1 = m + 1;
// for (i1 = mp1; i1 <= n; i1 += 4) {
// dy[iy0 + i1 - 1] = dy[iy0 + i1 - 1] + da * dx[ix0 + i1 - 1];
// dy[iy0 + i1 ] = dy[iy0 + i1 ] + da
// * dx[ix0 + i1 ];
// dy[iy0 + i1 + 1] = dy[iy0 + i1 + 1] + da
// * dx[ix0 + i1 + 1];
// dy[iy0 + i1 + 3 - 1] = dy[iy0 + i1 + 3 - 1] + da
// * dx[ix0 + i1 + 3 - 1];
// }
// return;
}
///**
// * Compute the dot product of two vectors. Adapted from the subroutine
// * <code>ddot</code> in <code>lbfgs.f</code>. There could well be faster
// * ways to carry out this operation; this code is a straight translation
// * from the Fortran.
// *
static double ddot(int n, double[] dx, int ix0, int incx, double[] dy,
int iy0, int incy) {
double result = 0;
for (int in_ = 0, ix = ix0, iy = iy0; in_ < n; in_++, ix += incx, iy += incy) {
result += safeMult(dx[ix], dy[iy]);
}
return result;
}
static bool badNum(double n) {
return Double.IsNaN(n) || Double.IsInfinity(n);
}
static double safeMult(double n1, double n2) {
double result = n1 * n2;
if (badNum(result)) {
if (n1 == 0 || n2 == 0) {
result = 0;
} else {
throw new ArgumentException(n1 + " " + n2);
}
}
return result;
}
static double safeDiv(double n1, double n2) {
double result = n1 / n2;
if (badNum(result)) {
if (n1 == 0 && n2 == 0) {
result = 1;
} else {
throw new ArgumentException(n1 + " " + n2);
}
}
return result;
}
// public static double[] subArray(double[] a, int start, int end) {
// assert start <= end;
// assert end <= a.length;
// double[] result = new double[end - start];
// System.arraycopy(a, start, result, 0, end - start);
// return result;
// }
static void System_err_print (string msg) { System.Console.Error.Write (msg); }
static void System_err_println(string msg) { System.Console.Error.WriteLine(msg); }
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2016, Institute for Software & Systems Engineering
//
// 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 SafetySharp.Compiler.Normalization
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Modeling;
using Roslyn.Symbols;
using Roslyn.Syntax;
using Utilities;
/// <summary>
/// Normalizes classes marked with <see cref="FaultEffectAttribute" />.
/// </summary>
public sealed class FaultEffectNormalizer : Normalizer
{
private readonly Dictionary<Tuple<IMethodSymbol, int>, string> _faultChoiceFields = new Dictionary<Tuple<IMethodSymbol, int>, string>();
private readonly Dictionary<INamedTypeSymbol, INamedTypeSymbol[]> _faults = new Dictionary<INamedTypeSymbol, INamedTypeSymbol[]>();
private readonly Dictionary<string, IMethodSymbol> _methodLookup = new Dictionary<string, IMethodSymbol>();
private readonly string _tryActivate = $"global::{typeof(FaultHelper).FullName}.{nameof(FaultHelper.Activate)}";
private readonly Dictionary<string, INamedTypeSymbol> _typeLookup = new Dictionary<string, INamedTypeSymbol>();
private readonly string _undoActivation = $"global::{typeof(FaultHelper).FullName}.{nameof(FaultHelper.UndoActivation)}";
/// <summary>
/// Normalizes the syntax trees of the <see cref="Compilation" />.
/// </summary>
protected override Compilation Normalize()
{
var types = Compilation.GetSymbolsWithName(_ => true, SymbolFilter.Type).OfType<INamedTypeSymbol>().ToArray();
var components = types.Where(type => type.IsComponent(Compilation)).ToArray();
var faultEffects = types.Where(type => type.IsFaultEffect(Compilation)).ToArray();
foreach (var type in components.Concat(faultEffects))
{
var t = type;
while (t != null && !_typeLookup.ContainsKey(t.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)))
{
_typeLookup.Add(t.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), t);
t = t.BaseType;
}
}
foreach (var component in components)
{
var faults = faultEffects.Where(faultEffect => faultEffect.BaseType.Equals(component)).ToArray();
var faultTypes = faults.OrderBy(type => type.GetPriority(Compilation)).ThenBy(type => type.Name).ToArray();
var nondeterministicFaults = faults.GroupBy(fault => fault.GetPriority(Compilation)).Where(group => group.Count() > 1).ToArray();
_faults.Add(component, faultTypes);
foreach (var method in component.GetFaultAffectableMethods(Compilation))
{
var methodKey = method.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
if (!_methodLookup.ContainsKey(methodKey))
_methodLookup.Add(methodKey, method);
foreach (var group in nondeterministicFaults)
{
var isNondeterministic = group.Count(f => f.GetMembers().OfType<IMethodSymbol>().Any(m => m.Overrides(method))) > 1;
if (!isNondeterministic)
continue;
var key = Tuple.Create(method, group.Key);
var fieldName = Guid.NewGuid().ToString().Replace("-", "_").ToSynthesized();
_faultChoiceFields.Add(key, fieldName);
AddFaultChoiceField(component, fieldName);
}
}
AddRuntimeTypeField(component);
}
return base.Normalize();
}
/// <summary>
/// Normalizes the <paramref name="declaration" />.
/// </summary>
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax declaration)
{
var classSymbol = declaration.GetTypeSymbol(SemanticModel);
if (!classSymbol.IsFaultEffect(SemanticModel))
{
declaration = (ClassDeclarationSyntax)base.VisitClassDeclaration(declaration);
if (classSymbol.IsComponent(SemanticModel))
declaration = ChangeComponentBaseType(classSymbol, declaration);
return declaration;
}
AddFaultField(classSymbol);
declaration = (ClassDeclarationSyntax)base.VisitClassDeclaration(declaration);
return ChangeFaultEffectBaseType(classSymbol, declaration);
}
/// <summary>
/// Normalizes the <paramref name="declaration" />.
/// </summary>
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax declaration)
{
var originalDeclaration = declaration;
var methodSymbol = declaration.GetMethodSymbol(SemanticModel);
if (!methodSymbol.ContainingType.IsFaultEffect(SemanticModel) || !methodSymbol.IsOverride)
return declaration;
var memberAccess = Syntax.MemberAccessExpression(Syntax.BaseExpression(), methodSymbol.Name);
var invocation = Syntax.InvocationExpression(memberAccess, CreateInvocationArguments(methodSymbol.Parameters));
declaration = declaration.WithBody(CreateBody(methodSymbol, declaration.Body, invocation));
return declaration.EnsureLineCount(originalDeclaration);
}
/// <summary>
/// Normalizes the <paramref name="accessor" />.
/// </summary>
public override SyntaxNode VisitAccessorDeclaration(AccessorDeclarationSyntax accessor)
{
var originalAccessor = accessor;
var methodSymbol = accessor.GetMethodSymbol(SemanticModel);
if (!methodSymbol.ContainingType.IsFaultEffect(SemanticModel) || !methodSymbol.IsOverride)
return accessor;
SyntaxNode baseExpression;
if (((IPropertySymbol)methodSymbol.AssociatedSymbol).IsIndexer)
{
var parameterCount = methodSymbol.Parameters.Length - (accessor.Kind() != SyntaxKind.GetAccessorDeclaration ? 1 : 0);
var parameters = methodSymbol.Parameters.Take(parameterCount);
baseExpression = Syntax.ElementAccessExpression(Syntax.BaseExpression(), CreateInvocationArguments(parameters));
}
else
baseExpression = Syntax.MemberAccessExpression(Syntax.BaseExpression(), methodSymbol.GetPropertySymbol().Name);
if (accessor.Kind() != SyntaxKind.GetAccessorDeclaration)
baseExpression = Syntax.AssignmentStatement(baseExpression, Syntax.IdentifierName("value"));
accessor = accessor.WithBody(CreateBody(methodSymbol, accessor.Body, baseExpression));
return accessor.EnsureLineCount(originalAccessor);
}
/// <summary>
/// Creates the arguments for a delegate invocation.
/// </summary>
private static IEnumerable<ArgumentSyntax> CreateInvocationArguments(IEnumerable<IParameterSymbol> parameters)
{
return parameters.Select(parameter =>
{
var argument = SyntaxFactory.Argument(SyntaxFactory.IdentifierName(parameter.Name));
switch (parameter.RefKind)
{
case RefKind.Ref:
return argument.WithRefOrOutKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword));
case RefKind.Out:
return argument.WithRefOrOutKeyword(SyntaxFactory.Token(SyntaxKind.OutKeyword));
case RefKind.None:
return argument;
default:
Assert.NotReached("Unsupported ref kind.");
return null;
}
});
}
/// <summary>
/// Creates a deterministic or nondeterministic fault effect body.
/// </summary>
private BlockSyntax CreateBody(IMethodSymbol method, BlockSyntax originalBody, SyntaxNode baseEffect)
{
var lineAdjustedOriginalBody = originalBody.AppendLineDirective(-1).PrependLineDirective(originalBody.GetLineNumber());
var componentType = _typeLookup[method.ContainingType.BaseType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)];
var faultEffectType = _typeLookup[method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)];
var faults = _faults[componentType];
var baseStatements = !method.ReturnsVoid
? new[] { Syntax.ReturnStatement(baseEffect) }
: new[] { Syntax.ExpressionStatement(baseEffect), Syntax.ReturnStatement() };
IMethodSymbol methodSymbol;
BlockSyntax body = null;
if (_methodLookup.TryGetValue(method.OverriddenMethod.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), out methodSymbol))
{
var priorityFaults = faults.Where(fault => fault.GetPriority(Compilation) == method.ContainingType.GetPriority(Compilation)).ToArray();
var overridingEffects = priorityFaults.Where(f => f.GetMembers().OfType<IMethodSymbol>().Any(m => m.Overrides(methodSymbol))).ToArray();
var overrideCount = overridingEffects.Length;
if (overrideCount > 1)
{
var fieldName = _faultChoiceFields[Tuple.Create(methodSymbol, priorityFaults[0].GetPriority(Compilation))];
var effectIndex = Array.IndexOf(priorityFaults, faultEffectType);
var choiceField = Syntax.MemberAccessExpression(Syntax.ThisExpression(), fieldName);
var levelCondition = Syntax.ValueNotEqualsExpression(choiceField, Syntax.LiteralExpression(effectIndex));
var ifStatement = Syntax.IfStatement(levelCondition, baseStatements).NormalizeWhitespace().WithTrailingNewLines(1);
if (overridingEffects.Last().Equals(faultEffectType))
{
var levelChoiceVariable = "levelChoice".ToSynthesized();
var levelCountVariable = "levelCount".ToSynthesized();
var writer = new CodeWriter();
writer.AppendLine("unsafe");
writer.AppendBlockStatement(() =>
{
writer.AppendLine($"var {levelChoiceVariable} = stackalloc int[{overrideCount}];");
writer.AppendLine($"var {levelCountVariable} = 0;");
for (var i = 0; i < overrideCount; ++i)
{
var effectType = overridingEffects[i].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var index = Array.IndexOf(priorityFaults, overridingEffects[i]);
writer.AppendLine($"if ({_tryActivate}((({effectType})this).{"fault".ToSynthesized()}))");
writer.IncreaseIndent();
writer.AppendLine($"{levelChoiceVariable}[{levelCountVariable}++] = {index};");
writer.DecreaseIndent();
writer.NewLine();
}
writer.AppendLine($"{fieldName} = {levelCountVariable} == 0 ? - 1 : {levelChoiceVariable}[ChooseIndex({levelCountVariable})];");
});
var selectionStatement = SyntaxFactory.ParseStatement(writer.ToString());
body = SyntaxFactory.Block(selectionStatement, (StatementSyntax)ifStatement, lineAdjustedOriginalBody);
}
else
body = SyntaxFactory.Block((StatementSyntax)ifStatement, lineAdjustedOriginalBody);
}
}
if (body == null)
{
var writer = new CodeWriter();
writer.AppendLine($"if (!{_tryActivate}(this.{"fault".ToSynthesized()}))");
writer.AppendBlockStatement(() =>
{
// Optimization: If we're normalizing a non-void returning method without ref/out parameters and
// the fault effect simply returns a constant value of primitive type, we generate code to check whether the non-fault
// value for the case that the fault is not activated (which is always the first case) actually differs
// from the constant value returned by the fault effect when the fault is activated. If both values are
// the same, the activation of the fault will have no effect, so we can undo it, reducing the number
// of transitions that have to be checked
var signatureAllowsOptimization =
!method.ReturnsVoid && CanBeCompared(method.ReturnType) && method.Parameters.All(parameter => parameter.RefKind == RefKind.None);
var faultEffectReturn = originalBody.Statements.Count == 1 ? originalBody.Statements[0] as ReturnStatementSyntax : null;
var isConstantValue = faultEffectReturn != null && SemanticModel.GetConstantValue(faultEffectReturn.Expression).HasValue;
if (signatureAllowsOptimization && isConstantValue)
{
writer.AppendLine($"var {"tmp".ToSynthesized()} = {baseEffect.ToFullString()};");
writer.AppendLine($"if ({"tmp".ToSynthesized()} == {faultEffectReturn.Expression.ToFullString()})");
writer.AppendBlockStatement(() => { writer.AppendLine($"{_undoActivation}(this.{"fault".ToSynthesized()});"); });
writer.AppendLine($"return {"tmp".ToSynthesized()};");
}
else
{
foreach (var statement in baseStatements)
writer.AppendLine(statement.NormalizeWhitespace().ToFullString());
}
});
writer.NewLine();
body = SyntaxFactory.Block(SyntaxFactory.ParseStatement(writer.ToString()), lineAdjustedOriginalBody);
}
return body.PrependLineDirective(-1);
}
/// <summary>
/// Gets the value indicating whether <paramref name="typeSymbol" /> can be compared using the <c>==</c> operator.
/// </summary>
public static bool CanBeCompared(ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.Enum)
return true;
switch (typeSymbol.SpecialType)
{
case SpecialType.System_Enum:
case SpecialType.System_Void:
case SpecialType.System_Boolean:
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_String:
case SpecialType.System_IntPtr:
case SpecialType.System_UIntPtr:
case SpecialType.System_Nullable_T:
case SpecialType.System_DateTime:
return true;
default:
return false;
}
}
/// <summary>
/// Changes the base type of the fault effect declaration based on its location in the fault effect list.
/// </summary>
private ClassDeclarationSyntax ChangeFaultEffectBaseType(INamedTypeSymbol classSymbol, ClassDeclarationSyntax classDeclaration)
{
var baseTypeName = classSymbol.BaseType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var faultEffectSymbol = _typeLookup[classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)];
var faultIndex = Array.IndexOf(_faults[_typeLookup[baseTypeName]], faultEffectSymbol);
if (faultIndex == 0)
return classDeclaration;
var baseType = Syntax.TypeExpression(_faults[_typeLookup[baseTypeName]][faultIndex - 1]).WithTrivia(classDeclaration.BaseList.Types[0]);
var baseTypes = SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)baseType));
var baseList = SyntaxFactory.BaseList(classDeclaration.BaseList.ColonToken, baseTypes).WithTrivia(classDeclaration.BaseList);
return classDeclaration.WithBaseList(baseList);
}
/// <summary>
/// Changes the base type of the derived component declaration.
/// </summary>
private ClassDeclarationSyntax ChangeComponentBaseType(INamedTypeSymbol classSymbol, ClassDeclarationSyntax classDeclaration)
{
if (classSymbol.BaseType.Equals(SemanticModel.GetTypeSymbol<Component>()))
return classDeclaration;
var baseTypeName = classSymbol.BaseType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
INamedTypeSymbol[] faults;
if (!_faults.TryGetValue(_typeLookup[baseTypeName], out faults) || faults.Length == 0)
return classDeclaration;
var baseType = Syntax.TypeExpression(faults[faults.Length - 1]).WithTrivia(classDeclaration.BaseList.Types[0]);
var baseTypes = SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)baseType));
var baseList = SyntaxFactory.BaseList(classDeclaration.BaseList.ColonToken, baseTypes).WithTrivia(classDeclaration.BaseList);
return classDeclaration.WithBaseList(baseList);
}
/// <summary>
/// Adds the runtime type field to the component symbol.
/// </summary>
private void AddRuntimeTypeField(INamedTypeSymbol classSymbol)
{
var className = classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var faults = _faults[_typeLookup[className]];
var runtimeType = faults.Length > 0 ? faults[faults.Length - 1] : classSymbol;
var typeofExpression = SyntaxFactory.TypeOfExpression((TypeSyntax)Syntax.TypeExpression((runtimeType)));
var field = Syntax.FieldDeclaration(
name: "runtimeType".ToSynthesized(),
type: SyntaxFactory.ParseTypeName(typeof(Type).GetGlobalName()),
accessibility: Accessibility.Private,
modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly,
initializer: typeofExpression);
field = Syntax.MarkAsNonDebuggerBrowsable(field);
field = Syntax.AddAttribute<CompilerGeneratedAttribute>(field);
field = field.NormalizeWhitespace();
AddMembers(classSymbol, (MemberDeclarationSyntax)field);
}
/// <summary>
/// Adds the fault choice field to the component symbol.
/// </summary>
private void AddFaultChoiceField(INamedTypeSymbol classSymbol, string fieldName)
{
var field = Syntax.FieldDeclaration(
name: fieldName,
type: Syntax.TypeExpression(SpecialType.System_Int32),
accessibility: Accessibility.Internal);
field = Syntax.MarkAsNonDebuggerBrowsable(field);
field = Syntax.AddAttribute<NonSerializableAttribute>(field);
field = Syntax.AddAttribute<CompilerGeneratedAttribute>(field);
field = field.NormalizeWhitespace();
AddMembers(classSymbol, (MemberDeclarationSyntax)field);
}
/// <summary>
/// Adds the fault field to the fault effect symbol.
/// </summary>
private void AddFaultField(INamedTypeSymbol classSymbol)
{
var faultField = Syntax.FieldDeclaration(
name: "fault".ToSynthesized(),
type: Syntax.TypeExpression<Fault>(SemanticModel),
accessibility: Accessibility.Internal);
faultField = Syntax.MarkAsNonDebuggerBrowsable(faultField);
faultField = Syntax.AddAttribute<HiddenAttribute>(faultField);
faultField = Syntax.AddAttribute<NonDiscoverableAttribute>(faultField);
faultField = Syntax.AddAttribute<CompilerGeneratedAttribute>(faultField);
faultField = faultField.NormalizeWhitespace();
AddMembers(classSymbol, (MemberDeclarationSyntax)faultField);
}
}
}
| |
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 CloudConfVarnaEdition4._0_RestAPI.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;
}
}
}
| |
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* 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
#region Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
using Sanford.Multimedia;
namespace Sanford.Multimedia.Midi
{
/// <summary>
/// Builds key signature MetaMessages.
/// </summary>
public class KeySignatureBuilder : IMessageBuilder
{
private Key key = Key.CMajor;
private MetaMessage result = null;
/// <summary>
/// Initializes a new instance of the KeySignatureBuilder class.
/// </summary>
public KeySignatureBuilder()
{
}
/// <summary>
/// Initializes a new instance of the KeySignatureBuilder class with
/// the specified key signature MetaMessage.
/// </summary>
/// <param name="message">
/// The key signature MetaMessage to use for initializing the
/// KeySignatureBuilder class.
/// </param>
public KeySignatureBuilder(MetaMessage message)
{
Initialize(message);
}
/// <summary>
/// Initializes the KeySignatureBuilder with the specified MetaMessage.
/// </summary>
/// <param name="message">
/// The key signature MetaMessage to use for initializing the
/// KeySignatureBuilder.
/// </param>
public void Initialize(MetaMessage message)
{
#region Require
if(message == null)
{
throw new ArgumentNullException("message");
}
else if(message.MetaType != MetaType.KeySignature)
{
throw new ArgumentException("Wrong meta event type.", "messaege");
}
#endregion
sbyte b = (sbyte)message[0];
// If the key is major.
if(message[1] == 0)
{
switch(b)
{
case -7:
key = Key.CFlatMajor;
break;
case -6:
key = Key.GFlatMajor;
break;
case -5:
key = Key.DFlatMajor;
break;
case -4:
key = Key.AFlatMajor;
break;
case -3:
key = Key.EFlatMajor;
break;
case -2:
key = Key.BFlatMajor;
break;
case -1:
key = Key.FMajor;
break;
case 0:
key = Key.CMajor;
break;
case 1:
key = Key.GMajor;
break;
case 2:
key = Key.DMajor;
break;
case 3:
key = Key.AMajor;
break;
case 4:
key = Key.EMajor;
break;
case 5:
key = Key.BMajor;
break;
case 6:
key = Key.FSharpMajor;
break;
case 7:
key = Key.CSharpMajor;
break;
}
}
// Else the key is minor.
else
{
switch(b)
{
case -7:
key = Key.AFlatMinor;
break;
case -6:
key = Key.EFlatMinor;
break;
case -5:
key = Key.BFlatMinor;
break;
case -4:
key = Key.FMinor;
break;
case -3:
key = Key.CMinor;
break;
case -2:
key = Key.GMinor;
break;
case -1:
key = Key.DMinor;
break;
case 0:
key = Key.AMinor;
break;
case 1:
key = Key.EMinor;
break;
case 2:
key = Key.BMinor;
break;
case 3:
key = Key.FSharpMinor;
break;
case 4:
key = Key.CSharpMinor;
break;
case 5:
key = Key.GSharpMinor;
break;
case 6:
key = Key.DSharpMinor;
break;
case 7:
key = Key.ASharpMinor;
break;
}
}
}
/// <summary>
/// Gets or sets the key.
/// </summary>
public Key Key
{
get
{
return key;
}
set
{
key = value;
}
}
/// <summary>
/// The build key signature MetaMessage.
/// </summary>
public MetaMessage Result
{
get
{
return result;
}
}
#region IMessageBuilder Members
/// <summary>
/// Builds the key signature MetaMessage.
/// </summary>
public void Build()
{
byte[] data = new byte[MetaMessage.KeySigLength];
unchecked
{
switch(Key)
{
case Key.CFlatMajor:
data[0] = (byte)-7;
data[1] = 0;
break;
case Key.GFlatMajor:
data[0] = (byte)-6;
data[1] = 0;
break;
case Key.DFlatMajor:
data[0] = (byte)-5;
data[1] = 0;
break;
case Key.AFlatMajor:
data[0] = (byte)-4;
data[1] = 0;
break;
case Key.EFlatMajor:
data[0] = (byte)-3;
data[1] = 0;
break;
case Key.BFlatMajor:
data[0] = (byte)-2;
data[1] = 0;
break;
case Key.FMajor:
data[0] = (byte)-1;
data[1] = 0;
break;
case Key.CMajor:
data[0] = 0;
data[1] = 0;
break;
case Key.GMajor:
data[0] = 1;
data[1] = 0;
break;
case Key.DMajor:
data[0] = 2;
data[1] = 0;
break;
case Key.AMajor:
data[0] = 3;
data[1] = 0;
break;
case Key.EMajor:
data[0] = 4;
data[1] = 0;
break;
case Key.BMajor:
data[0] = 5;
data[1] = 0;
break;
case Key.FSharpMajor:
data[0] = 6;
data[1] = 0;
break;
case Key.CSharpMajor:
data[0] = 7;
data[1] = 0;
break;
case Key.AFlatMinor:
data[0] = (byte)-7;
data[1] = 1;
break;
case Key.EFlatMinor:
data[0] = (byte)-6;
data[1] = 1;
break;
case Key.BFlatMinor:
data[0] = (byte)-5;
data[1] = 1;
break;
case Key.FMinor:
data[0] = (byte)-4;
data[1] = 1;
break;
case Key.CMinor:
data[0] = (byte)-3;
data[1] = 1;
break;
case Key.GMinor:
data[0] = (byte)-2;
data[1] = 1;
break;
case Key.DMinor:
data[0] = (byte)-1;
data[1] = 1;
break;
case Key.AMinor:
data[0] = 1;
data[1] = 0;
break;
case Key.EMinor:
data[0] = 1;
data[1] = 1;
break;
case Key.BMinor:
data[0] = 2;
data[1] = 1;
break;
case Key.FSharpMinor:
data[0] = 3;
data[1] = 1;
break;
case Key.CSharpMinor:
data[0] = 4;
data[1] = 1;
break;
case Key.GSharpMinor:
data[0] = 5;
data[1] = 1;
break;
case Key.DSharpMinor:
data[0] = 6;
data[1] = 1;
break;
case Key.ASharpMinor:
data[0] = 7;
data[1] = 1;
break;
}
}
result = new MetaMessage(MetaType.KeySignature, data);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace DotNet
{
public class FiddleRunner
{
private static readonly Regex LitreralPattern = new Regex( "^\\/[^\\/]+\\/\\w*", RegexOptions.Multiline );
private static readonly Regex CorpusTestPattern = new Regex( "^#(\\+|\\-)", RegexOptions.Multiline );
public static bool IsCorpusTest( string corpus )
{
return CorpusTestPattern.IsMatch( corpus );
}
public static bool IsLiteralPattern( string pattern )
{
return LitreralPattern.IsMatch( pattern );
}
public object Match( string pattern, string corpus )
{
var parsedPattern = this.ParsePattern( pattern );
if( parsedPattern == null || corpus == null )
{
return null;
}
if( IsCorpusTest( corpus ) )
{
return this.MatchCorpusTests( parsedPattern, corpus );
}
return this.MatchWholeCorpus( parsedPattern, corpus );
}
public object Replace( string pattern, string corpus, string replace )
{
var dictionary = new Dictionary<string, string> {
{
"replace",
corpus
}
};
var parsedPattern = this.ParsePattern( pattern );
if( parsedPattern == null || corpus == null || replace == null )
{
return dictionary;
}
if( IsCorpusTest( corpus ) )
{
var stringBuilder = new StringBuilder( corpus.Length );
var array = corpus.Split( new[] { '\n' } );
for( var i = 0; i < array.Length; i++ )
{
var input = array[ i ];
stringBuilder.AppendLine( parsedPattern.Pattern.Replace( input, replace,
( ( parsedPattern.Options & SudoRegexOptions.Global ) ==
SudoRegexOptions.None )
? 1
: 2147483647 ) );
dictionary[ "replace" ] = stringBuilder.ToString();
}
}
else
{
var value = parsedPattern.Pattern.Replace( corpus, replace,
( ( parsedPattern.Options & SudoRegexOptions.Global ) ==
SudoRegexOptions.None )
? 1
: 2147483647 );
dictionary[ "replace" ] = value;
}
return dictionary;
}
private Dictionary<string, object> MatchWholeCorpus( ParsedPattern parsedPattern, string corpus )
{
var dictionary = new Dictionary<string, object>();
var matchCollection = parsedPattern.Pattern.Matches( corpus );
if( ( parsedPattern.Options & SudoRegexOptions.Global ) == SudoRegexOptions.None )
{
if( matchCollection.Count >= 1 )
{
dictionary[ "0" ] = this.HashMatch( matchCollection[ 0 ] );
}
}
else
{
foreach( Match match in parsedPattern.Pattern.Matches( corpus ) )
{
dictionary[ match.Index.ToString() ] = this.HashMatch( match );
}
}
dictionary[ "matchSummary" ] = new {
total = dictionary.Count
};
return dictionary;
}
private Dictionary<string, object> MatchCorpusTests( ParsedPattern parsedPattern, string corpus )
{
var summary = new Dictionary<string, object> {
{ "total", 0 },
{ "tests", true },
{ "passed", 0 },
{ "failed", 0 }
};
var results = new Dictionary<string, object> {
{ "matchSummary", summary }
};
Action<string, int, bool> addMatch = delegate( string line, int offset, bool passed ) {
summary[ "total" ] = (int) summary[ "total" ] + 1;
var key = passed ? "passed" : "failed";
summary[ key ] = (int) summary[ key ] + 1;
results[ offset.ToString() ] = new object[] {
offset,
line.Length,
passed ? "match" : "nomatch"
};
};
Action<string, int> nothingMatcher = delegate { };
Action<string, int> positiveMatcher =
delegate( string line, int offset ) { addMatch( line, offset, parsedPattern.Pattern.IsMatch( line ) ); };
Action<string, int> negativeMatcher =
delegate( string line, int offset ) { addMatch( line, offset, !parsedPattern.Pattern.IsMatch( line ) ); };
Func<string, Action<string, int>> func = delegate( string line ) {
if( line.Length <= 1 )
{
return nothingMatcher;
}
if( line[ 1 ] == '+' )
{
return positiveMatcher;
}
if( line[ 1 ] == '-' )
{
return negativeMatcher;
}
return nothingMatcher;
};
var action = nothingMatcher;
var num = 0;
var array = corpus.Split( new[] {
'\n'
} );
for( var i = 0; i < array.Length; i++ )
{
var text = array[ i ];
if( text.Length > 1 && text[ 0 ] == '#' )
{
action = func( text );
}
else if( text.Length > 0 )
{
action( text, num );
}
num += text.Length + 1;
}
return results;
}
private object HashMatch( Match match )
{
return new[] {
match.Index,
match.Length
};
}
private ParsedPattern ParsePattern( string pattern )
{
var regexOptions = RegexOptions.None;
var sudoRegexOptions = SudoRegexOptions.None;
if( pattern == null )
{
return null;
}
if( !IsLiteralPattern( pattern ) )
{
return new ParsedPattern {
Pattern = new Regex( pattern, regexOptions ),
Options = sudoRegexOptions
};
}
sudoRegexOptions |= SudoRegexOptions.Literal;
var num = pattern.LastIndexOf( "/" );
var text = pattern.Substring( num + 1 );
pattern = pattern.Substring( 1, num - 1 );
var text2 = text;
var i = 0;
while( i < text2.Length )
{
var c = text2[ i ];
var c2 = c;
if( c2 <= 'i' )
{
switch( c2 )
{
case 'a':
regexOptions |= RegexOptions.ECMAScript;
break;
case 'b':
goto IL_115;
case 'c':
sudoRegexOptions |= SudoRegexOptions.Compiled;
break;
default:
switch( c2 )
{
case 'g':
sudoRegexOptions |= SudoRegexOptions.Global;
break;
case 'h':
goto IL_115;
case 'i':
regexOptions |= RegexOptions.IgnoreCase;
break;
default:
goto IL_115;
}
break;
}
}
else
{
switch( c2 )
{
case 'm':
regexOptions |= RegexOptions.Multiline;
break;
case 'n':
regexOptions |= RegexOptions.ExplicitCapture;
break;
default:
switch( c2 )
{
case 's':
regexOptions |= RegexOptions.Singleline;
break;
case 't':
goto IL_115;
case 'u':
regexOptions |= RegexOptions.CultureInvariant;
break;
default:
if( c2 != 'x' )
{
goto IL_115;
}
regexOptions |= RegexOptions.IgnorePatternWhitespace;
break;
}
break;
}
}
i++;
continue;
IL_115:
return null;
}
return new ParsedPattern {
Pattern = new Regex( pattern, regexOptions ),
Options = sudoRegexOptions
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace Hydra.Framework.XmlSerialization.Common.XPath
{
//
//**********************************************************************
/// <summary>
/// Provides the evaluation context for fast execution and custom
/// variables resolution.
/// </summary>
//**********************************************************************
//
public class DynamicContext : XsltContext
{
#region Private vars
IDictionary<string, IXsltContextVariable> _variables =
new Dictionary<string, IXsltContextVariable>();
#endregion Private
#region Constructors & Initialization
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="DynamicContext"/> class.
/// </summary>
//**********************************************************************
//
public DynamicContext()
: base(new NameTable())
{
}
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="DynamicContext"/>
/// class with the specified <see cref="NameTable"/>.
/// </summary>
/// <param name="table">The NameTable to use.</param>
//**********************************************************************
//
public DynamicContext(NameTable table)
: base(table)
{
}
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="DynamicContext"/> class.
/// </summary>
/// <param name="context">A previously filled context with the namespaces to use.</param>
//**********************************************************************
//
public DynamicContext(XmlNamespaceManager context)
: this(context, new NameTable())
{
}
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="DynamicContext"/> class.
/// </summary>
/// <param name="context">A previously filled context with the namespaces to use.</param>
/// <param name="table">The NameTable to use.</param>
//**********************************************************************
//
public DynamicContext(XmlNamespaceManager context, NameTable table)
: base(table)
{
object xml = table.Add(XmlNamespaces.Xml);
object xmlns = table.Add(XmlNamespaces.XmlNs);
if (context != null)
{
foreach (string prefix in context)
{
string uri = context.LookupNamespace(prefix);
//
// Use fast object reference comparison to omit forbidden namespace declarations.
//
if (Object.Equals(uri, xml) || Object.Equals(uri, xmlns))
continue;
base.AddNamespace(prefix, uri);
}
}
}
#endregion Constructors & Initialization
#region Common Overrides
//
//**********************************************************************
/// <summary>
/// Implementation equal to <see cref="XsltContext"/>.
/// </summary>
//**********************************************************************
//
public override int CompareDocument(string baseUri, string nextbaseUri)
{
return String.Compare(baseUri, nextbaseUri, false, System.Globalization.CultureInfo.InvariantCulture);
}
//
//**********************************************************************
/// <summary>
/// Same as <see cref="XmlNamespaceManager"/>.
/// </summary>
//**********************************************************************
//
public override string LookupNamespace(string prefix)
{
string key = NameTable.Get(prefix);
if (key == null)
return null;
else
return base.LookupNamespace(key);
}
//
//**********************************************************************
/// <summary>
/// Same as <see cref="XmlNamespaceManager"/>.
/// </summary>
//**********************************************************************
//
public override string LookupPrefix(string uri)
{
string key = NameTable.Get(uri);
if (key == null)
return null;
else
return base.LookupPrefix(key);
}
//
//**********************************************************************
/// <summary>
/// Same as <see cref="XsltContext"/>.
/// </summary>
//**********************************************************************
//
public override bool PreserveWhitespace(XPathNavigator node)
{
return true;
}
//
//**********************************************************************
/// <summary>
/// Same as <see cref="XsltContext"/>.
/// </summary>
//**********************************************************************
//
public override bool Whitespace
{
get { return true; }
}
#endregion Common Overrides
#region Public Members
//
//**********************************************************************
/// <summary>
/// Shortcut method that compiles an expression using an empty navigator.
/// </summary>
/// <param name="xpath">The expression to compile</param>
/// <returns>A compiled <see cref="XPathExpression"/>.</returns>
//**********************************************************************
//
public static XPathExpression Compile(string xpath)
{
return new XmlDocument().CreateNavigator().Compile(xpath);
}
#endregion Public Members
#region Variable Handling Code
//
//**********************************************************************
/// <summary>
/// Adds the variable to the dynamic evaluation context.
/// </summary>
/// <param name="name">The name of the variable to add to the context.</param>
/// <param name="value">The value of the variable to add to the context.</param>
/// <remarks>
/// Value type conversion for XPath evaluation is as follows:
/// <list type="table">
/// <listheader>
/// <term>CLR Type</term>
/// <description>XPath type</description>
/// </listheader>
/// <item>
/// <term>System.String</term>
/// <description>XPathResultType.String</description>
/// </item>
/// <item>
/// <term>System.Double (or types that can be converted to)</term>
/// <description>XPathResultType.Number</description>
/// </item>
/// <item>
/// <term>System.Boolean</term>
/// <description>XPathResultType.Boolean</description>
/// </item>
/// <item>
/// <term>System.Xml.XPath.XPathNavigator</term>
/// <description>XPathResultType.Navigator</description>
/// </item>
/// <item>
/// <term>System.Xml.XPath.XPathNodeIterator</term>
/// <description>XPathResultType.NodeSet</description>
/// </item>
/// <item>
/// <term>Others</term>
/// <description>XPathResultType.Any</description>
/// </item>
/// </list>
/// <note type="note">See the topic "Compile, Select, Evaluate, and Matches with
/// XPath and XPathExpressions" in MSDN documentation for additional information.</note>
/// </remarks>
/// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception>
//**********************************************************************
//
public void AddVariable(string name, object value)
{
if (value == null) throw new ArgumentNullException("value");
_variables[name] = new DynamicVariable(name, value);
}
//
//**********************************************************************
/// <summary>
/// See <see cref="XsltContext"/>. Not used in our implementation.
/// </summary>
//**********************************************************************
//
public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] ArgTypes)
{
return null;
}
//
//**********************************************************************
/// <summary>
/// Resolves the dynamic variables added to the context. See <see cref="XsltContext"/>.
/// </summary>
//**********************************************************************
//
public override IXsltContextVariable ResolveVariable(string prefix, string name)
{
IXsltContextVariable var;
_variables.TryGetValue(name, out var);
return var;
}
#endregion Variable Handling Code
#region Internal DynamicVariable class
//
//**********************************************************************
/// <summary>
/// Represents a variable during dynamic expression execution.
/// </summary>
//**********************************************************************
//
internal class DynamicVariable : IXsltContextVariable
{
string _name;
object _value;
#region Public Members
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="name">The name of the variable.</param>
/// <param name="value">The value of the variable.</param>
//**********************************************************************
//
public DynamicVariable(string name, object value)
{
_name = name;
_value = value;
if (value is String)
_type = XPathResultType.String;
else if (value is bool)
_type = XPathResultType.Boolean;
else if (value is XPathNavigator)
_type = XPathResultType.Navigator;
else if (value is XPathNodeIterator)
_type = XPathResultType.NodeSet;
else
{
//
// Try to convert to double (native XPath numeric type)
//
if (value is double)
{
_type = XPathResultType.Number;
}
else
{
if (value is IConvertible)
{
try
{
_value = Convert.ToDouble(value);
//
// We suceeded, so it's a number.
//
_type = XPathResultType.Number;
}
catch (FormatException)
{
_type = XPathResultType.Any;
}
catch (OverflowException)
{
_type = XPathResultType.Any;
}
}
else
{
_type = XPathResultType.Any;
}
}
}
}
#endregion Public Members
#region IXsltContextVariable Implementation
XPathResultType IXsltContextVariable.VariableType
{
get { return _type; }
} XPathResultType _type;
object IXsltContextVariable.Evaluate(XsltContext context)
{
return _value;
}
bool IXsltContextVariable.IsLocal
{
get { return false; }
}
bool IXsltContextVariable.IsParam
{
get { return false; }
}
#endregion IXsltContextVariable Implementation
}
#endregion Internal DynamicVariable class
}
}
| |
using Newtonsoft.Json.Linq;
using DotVVM.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotVVM.Framework.ResourceManagement.ClientGlobalize
{
public static class JQueryGlobalizeScriptCreator
{
private static readonly string[] numberPatternStrings =
{ "(n)", "-n", "- n", "n-", "n -" };
private static readonly string[] percentPositivePatternStrings =
{ "n %", "n%", "%n", "% n" };
private static readonly string[] percentNegativePatternStrings =
{ "-n %", "-n%", "-%n", "%-n", "%n", "n-%", "n%-", "-% n", "n %-", "% n-", "% -n", "n- %"};
private static readonly string[] currencyNegativePatternStrings =
{ "($n)", "-$n", "$-n", "$n-", "(n$)", "-n$", "n-$", "n$-", "-n $", "-$ n", "n $-", "$ n-", "$ -n", "n- $", "($ n)", "(n $)" };
private static readonly string[] currencyPositivePatternStrings =
{ "$n", "n$", "$ n", "n $" };
private static readonly JObject defaultJson = JObject.Parse(@"{
name: 'en',
englishName: 'English',
nativeName: 'English',
isRTL: false,
language: 'en',
numberFormat: {
pattern: ['-n'],
decimals: 2,
',': ',',
'.': '.',
groupSizes: [3],
'+': '+',
'-': '-',
NaN: 'NaN',
negativeInfinity: '-Infinity',
positiveInfinity: 'Infinity',
percent: {
pattern: ['-n %', 'n %'],
decimals: 2,
groupSizes: [3],
',': ',',
'.': '.',
symbol: '%'
},
currency: {
pattern: [ '($n)', '$n' ],
decimals: 2,
groupSizes: [ 3 ],
',': ',',
'.': '.',
symbol: '$'
}
},
calendars: {
standard: {
name: 'Gregorian_USEnglish',
'/': '/',
':': ':',
firstDay: 0,
days: {
names: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ],
namesAbbr: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
namesShort: [ 'Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa' ]
},
months: {
names: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', '' ],
namesAbbr: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', '' ]
},
AM: [ 'AM', 'am', 'AM' ],
PM: [ 'PM', 'pm', 'PM' ],
eras: [
{
'name': 'A.D.',
'start': null,
'offset': 0
}
],
twoDigitYearMax: 2029,
'patterns': {
'd': 'M/d/yyyy',
'D': 'dddd, MMMM dd, yyyy',
't': 'h:mm tt',
'T': 'h:mm:ss tt',
'f': 'dddd, MMMM dd, yyyy h:mm tt',
'F': 'dddd, MMMM dd, yyyy h:mm:ss tt',
'M': 'MMMM dd',
'Y': 'yyyy MMMM',
'S': 'yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss'
}
}
},
'messages': {}
}
");
private static JObject CreateNumberInfoJson(NumberFormatInfo ni)
{
var numberFormat = new
{
pattern = new[] { numberPatternStrings[ni.NumberNegativePattern] },
decimals = ni.NumberDecimalDigits,
groupSizes = ni.NumberGroupSizes,
NaN = ni.NaNSymbol,
negativeInfinity = ni.NegativeInfinitySymbol,
positiveInfinity = ni.PositiveInfinitySymbol,
percent = new
{
pattern = new[] {
percentNegativePatternStrings[ni.PercentNegativePattern],
percentPositivePatternStrings[ni.PercentPositivePattern]
},
decimals = ni.PercentDecimalDigits,
groupSizes = ni.PercentGroupSizes,
symbol = ni.PercentSymbol
},
currency = new
{
pattern = new[]
{
currencyNegativePatternStrings[ni.CurrencyNegativePattern],
currencyPositivePatternStrings[ni.CurrencyPositivePattern]
},
decimals = ni.CurrencyDecimalDigits,
groupSizes = ni.CurrencyGroupSizes,
symbol = ni.CurrencySymbol
}
};
var jobj = JObject.FromObject(numberFormat);
jobj[","] = ni.NumberGroupSeparator;
jobj["."] = ni.NumberDecimalSeparator;
jobj["percent"][","] = ni.PercentGroupSeparator;
jobj["percent"]["."] = ni.PercentDecimalSeparator;
jobj["currency"][","] = ni.CurrencyGroupSeparator;
jobj["currency"]["."] = ni.CurrencyDecimalSeparator;
return jobj;
}
private static JObject CreateDateInfoJson(DateTimeFormatInfo di)
{
var obj = new
{
firstDay = di.FirstDayOfWeek,
days = new
{
names = di.DayNames,
namesAbbr = di.AbbreviatedDayNames,
namesShort = di.ShortestDayNames
},
months = new
{
names = di.MonthNames,
namesAbbr = di.AbbreviatedMonthNames
},
AM = new[] { di.AMDesignator, di.AMDesignator.ToLower(), di.AMDesignator.ToUpper() },
PM = new[] { di.PMDesignator, di.PMDesignator.ToLower(), di.PMDesignator.ToUpper() },
eras = di.Calendar.Eras.Select(era => new { offset = 0, start = (string)null, name = di.GetEraName(era) }).ToArray(),
twoDigitYearMax = di.Calendar.TwoDigitYearMax,
patterns = new
{
d = di.ShortDatePattern,
D = di.LongDatePattern,
t = di.ShortTimePattern,
T = di.LongTimePattern,
f = di.LongDatePattern + " " + di.ShortTimePattern,
F = di.LongDatePattern + " " + di.LongTimePattern,
M = di.MonthDayPattern,
Y = di.YearMonthPattern,
g = di.ShortDatePattern + " " + di.ShortTimePattern,
G = di.ShortDatePattern + " " + di.LongTimePattern
}
};
var jobj = JObject.FromObject(obj);
if (!di.MonthNames.SequenceEqual(di.MonthGenitiveNames))
{
var monthsGenitive = jobj["monthsGenitive"] = new JObject();
monthsGenitive["names"] = JArray.FromObject(di.MonthGenitiveNames);
monthsGenitive["namesAbbr"] = JArray.FromObject(di.AbbreviatedMonthGenitiveNames);
}
return new JObject()
{
{"standard", jobj }
};
}
public static JObject BuildCultureInfoJson(CultureInfo ci)
{
var cultureInfoClientObj = new
{
name = ci.Name,
nativeName = ci.NativeName,
englishName = ci.EnglishName,
isRTL = ci.TextInfo.IsRightToLeft,
language = ci.TwoLetterISOLanguageName
};
var jobj = JObject.FromObject(cultureInfoClientObj);
jobj["numberFormat"] = CreateNumberInfoJson(ci.NumberFormat);
jobj["calendars"] = CreateDateInfoJson(ci.DateTimeFormat);
return JsonUtils.Diff(defaultJson, jobj);
}
public static string BuildCultureInfoScript(CultureInfo ci)
{
var template = new JQueryGlobalizeRegisterTemplate();
template.Name = ci.Name;
template.CultureInfoJson = BuildCultureInfoJson(ci);
return template.TransformText();
}
}
}
| |
// ReSharper disable InconsistentNaming
// ReSharper disable IdentifierTypo
// ReSharper disable UnusedMember.Global
#pragma warning disable SA1307 // Accessible fields must begin with upper-case letter
#pragma warning disable GU0060 // Enum member value conflict. According to Roman this is ok.
#pragma warning disable CA1707 // Identifiers should not contain underscores
namespace Gu.Wpf.UiAutomation
{
#pragma warning disable CA1008 // Enums should have zero value
#pragma warning disable CA1028 // Enum Storage should be Int32
public enum Key : ushort
#pragma warning restore CA1028 // Enum Storage should be Int32
#pragma warning restore CA1008 // Enums should have zero value
{
/// <summary>
/// Left mouse button
/// </summary>
LBUTTON = 0x01,
/// <summary>
/// Right mouse button
/// </summary>
RBUTTON = 0x02,
/// <summary>
/// Control-break processing
/// </summary>
CANCEL = 0x03,
/// <summary>
/// Middle mouse button (three-button mouse)
/// </summary>
MBUTTON = 0x04,
/// <summary>
/// Windows 2000/XP: X1 mouse button
/// </summary>
XBUTTON1 = 0x05,
/// <summary>
/// Windows 2000/XP: X2 mouse button
/// </summary>
XBUTTON2 = 0x06,
/// <summary>
/// BACKSPACE key
/// </summary>
BACK = 0x08,
/// <summary>
/// TAB key
/// </summary>
TAB = 0x09,
/// <summary>
/// CLEAR key
/// </summary>
CLEAR = 0x0C,
/// <summary>
/// ENTER key
/// </summary>
RETURN = 0x0D,
ENTER = RETURN,
/// <summary>
/// SHIFT key
/// </summary>
SHIFT = 0x10,
/// <summary>
/// CTRL key
/// </summary>
CONTROL = 0x11,
/// <summary>
/// ALT key
/// </summary>
ALT = 0x12,
/// <summary>
/// PAUSE key
/// </summary>
PAUSE = 0x13,
/// <summary>
/// CAPS LOCK key
/// </summary>
CAPITAL = 0x14,
/// <summary>
/// Input Method Editor (IME) Kana mode
/// </summary>
KANA = 0x15,
/// <summary>
/// IME Hangul mode
/// </summary>
#pragma warning disable CA1069 // Enums values should not be duplicated
HANGUL = 0x15,
#pragma warning restore CA1069 // Enums values should not be duplicated
/// <summary>
/// IME Junja mode
/// </summary>
JUNJA = 0x17,
/// <summary>
/// IME final mode
/// </summary>
FINAL = 0x18,
/// <summary>
/// IME Hanja mode
/// </summary>
HANJA = 0x19,
/// <summary>
/// IME Kanji mode
/// </summary>
#pragma warning disable CA1069 // Enums values should not be duplicated
KANJI = 0x19,
#pragma warning restore CA1069 // Enums values should not be duplicated
/// <summary>
/// ESC key
/// </summary>
ESCAPE = 0x1B,
ESC = ESCAPE,
/// <summary>
/// IME convert
/// </summary>
CONVERT = 0x1C,
/// <summary>
/// IME nonconvert
/// </summary>
NONCONVERT = 0x1D,
/// <summary>
/// IME accept
/// </summary>
ACCEPT = 0x1E,
/// <summary>
/// IME mode change request
/// </summary>
MODECHANGE = 0x1F,
/// <summary>
/// SPACEBAR
/// </summary>
SPACE = 0x20,
/// <summary>
/// PAGE UP key
/// </summary>
PRIOR = 0x21,
/// <summary>
/// PAGE DOWN key
/// </summary>
NEXT = 0x22,
/// <summary>
/// END key
/// </summary>
END = 0x23,
/// <summary>
/// HOME key
/// </summary>
HOME = 0x24,
/// <summary>
/// LEFT ARROW key
/// </summary>
LEFT = 0x25,
/// <summary>
/// UP ARROW key
/// </summary>
UP = 0x26,
/// <summary>
/// RIGHT ARROW key
/// </summary>
RIGHT = 0x27,
/// <summary>
/// DOWN ARROW key
/// </summary>
DOWN = 0x28,
/// <summary>
/// SELECT key
/// </summary>
SELECT = 0x29,
/// <summary>
/// PRINT key
/// </summary>
PRINT = 0x2A,
/// <summary>
/// EXECUTE key
/// </summary>
EXECUTE = 0x2B,
/// <summary>
/// PRINT SCREEN key
/// </summary>
SNAPSHOT = 0x2C,
/// <summary>
/// INS key
/// </summary>
INSERT = 0x2D,
/// <summary>
/// DEL key
/// </summary>
DELETE = 0x2E,
/// <summary>
/// HELP key
/// </summary>
HELP = 0x2F,
/// <summary>
/// 0 key
/// </summary>
KEY_0 = 0x30,
/// <summary>
/// 1 key
/// </summary>
KEY_1 = 0x31,
/// <summary>
/// 2 key
/// </summary>
KEY_2 = 0x32,
/// <summary>
/// 3 key
/// </summary>
KEY_3 = 0x33,
/// <summary>
/// 4 key
/// </summary>
KEY_4 = 0x34,
/// <summary>
/// 5 key
/// </summary>
KEY_5 = 0x35,
/// <summary>
/// 6 key
/// </summary>
KEY_6 = 0x36,
/// <summary>
/// 7 key
/// </summary>
KEY_7 = 0x37,
/// <summary>
/// 8 key
/// </summary>
KEY_8 = 0x38,
/// <summary>
/// 9 key
/// </summary>
KEY_9 = 0x39,
/// <summary>
/// A key
/// </summary>
KEY_A = 0x41,
/// <summary>
/// B key
/// </summary>
KEY_B = 0x42,
/// <summary>
/// C key
/// </summary>
KEY_C = 0x43,
/// <summary>
/// D key
/// </summary>
KEY_D = 0x44,
/// <summary>
/// E key
/// </summary>
KEY_E = 0x45,
/// <summary>
/// F key
/// </summary>
KEY_F = 0x46,
/// <summary>
/// G key
/// </summary>
KEY_G = 0x47,
/// <summary>
/// H key
/// </summary>
KEY_H = 0x48,
/// <summary>
/// I key
/// </summary>
KEY_I = 0x49,
/// <summary>
/// J key
/// </summary>
KEY_J = 0x4A,
/// <summary>
/// K key
/// </summary>
KEY_K = 0x4B,
/// <summary>
/// L key
/// </summary>
KEY_L = 0x4C,
/// <summary>
/// M key
/// </summary>
KEY_M = 0x4D,
/// <summary>
/// N key
/// </summary>
KEY_N = 0x4E,
/// <summary>
/// O key
/// </summary>
KEY_O = 0x4F,
/// <summary>
/// P key
/// </summary>
KEY_P = 0x50,
/// <summary>
/// Q key
/// </summary>
KEY_Q = 0x51,
/// <summary>
/// R key
/// </summary>
KEY_R = 0x52,
/// <summary>
/// S key
/// </summary>
KEY_S = 0x53,
/// <summary>
/// T key
/// </summary>
KEY_T = 0x54,
/// <summary>
/// U key
/// </summary>
KEY_U = 0x55,
/// <summary>
/// V key
/// </summary>
KEY_V = 0x56,
/// <summary>
/// W key
/// </summary>
KEY_W = 0x57,
/// <summary>
/// X key
/// </summary>
KEY_X = 0x58,
/// <summary>
/// Y key
/// </summary>
KEY_Y = 0x59,
/// <summary>
/// Z key
/// </summary>
KEY_Z = 0x5A,
/// <summary>
/// Left Windows key (Microsoft Natural keyboard)
/// </summary>
LWIN = 0x5B,
/// <summary>
/// Right Windows key (Natural keyboard)
/// </summary>
RWIN = 0x5C,
/// <summary>
/// Applications key (Natural keyboard)
/// </summary>
APPS = 0x5D,
/// <summary>
/// Computer Sleep key
/// </summary>
SLEEP = 0x5F,
/// <summary>
/// Numeric keypad 0 key
/// </summary>
NUMPAD0 = 0x60,
/// <summary>
/// Numeric keypad 1 key
/// </summary>
NUMPAD1 = 0x61,
/// <summary>
/// Numeric keypad 2 key
/// </summary>
NUMPAD2 = 0x62,
/// <summary>
/// Numeric keypad 3 key
/// </summary>
NUMPAD3 = 0x63,
/// <summary>
/// Numeric keypad 4 key
/// </summary>
NUMPAD4 = 0x64,
/// <summary>
/// Numeric keypad 5 key
/// </summary>
NUMPAD5 = 0x65,
/// <summary>
/// Numeric keypad 6 key
/// </summary>
NUMPAD6 = 0x66,
/// <summary>
/// Numeric keypad 7 key
/// </summary>
NUMPAD7 = 0x67,
/// <summary>
/// Numeric keypad 8 key
/// </summary>
NUMPAD8 = 0x68,
/// <summary>
/// Numeric keypad 9 key
/// </summary>
NUMPAD9 = 0x69,
/// <summary>
/// Multiply key
/// </summary>
MULTIPLY = 0x6A,
/// <summary>
/// Add key
/// </summary>
ADD = 0x6B,
/// <summary>
/// Separator key
/// </summary>
SEPARATOR = 0x6C,
/// <summary>
/// Subtract key
/// </summary>
SUBTRACT = 0x6D,
#pragma warning disable CA1720 // Identifier contains type name
/// <summary>
/// Decimal key
/// </summary>
DECIMAL = 0x6E,
#pragma warning restore CA1720 // Identifier contains type name
/// <summary>
/// Divide key
/// </summary>
DIVIDE = 0x6F,
/// <summary>
/// F1 key
/// </summary>
F1 = 0x70,
/// <summary>
/// F2 key
/// </summary>
F2 = 0x71,
/// <summary>
/// F3 key
/// </summary>
F3 = 0x72,
/// <summary>
/// F4 key
/// </summary>
F4 = 0x73,
/// <summary>
/// F5 key
/// </summary>
F5 = 0x74,
/// <summary>
/// F6 key
/// </summary>
F6 = 0x75,
/// <summary>
/// F7 key
/// </summary>
F7 = 0x76,
/// <summary>
/// F8 key
/// </summary>
F8 = 0x77,
/// <summary>
/// F9 key
/// </summary>
F9 = 0x78,
/// <summary>
/// F10 key
/// </summary>
F10 = 0x79,
/// <summary>
/// F11 key
/// </summary>
F11 = 0x7A,
/// <summary>
/// F12 key
/// </summary>
F12 = 0x7B,
/// <summary>
/// F13 key
/// </summary>
F13 = 0x7C,
/// <summary>
/// F14 key
/// </summary>
F14 = 0x7D,
/// <summary>
/// F15 key
/// </summary>
F15 = 0x7E,
/// <summary>
/// F16 key
/// </summary>
F16 = 0x7F,
/// <summary>
/// F17 key
/// </summary>
F17 = 0x80,
/// <summary>
/// F18 key
/// </summary>
F18 = 0x81,
/// <summary>
/// F19 key
/// </summary>
F19 = 0x82,
/// <summary>
/// F20 key
/// </summary>
F20 = 0x83,
/// <summary>
/// F21 key
/// </summary>
F21 = 0x84,
/// <summary>
/// F22 key, (PPC only) Key used to lock device.
/// </summary>
F22 = 0x85,
/// <summary>
/// F23 key
/// </summary>
F23 = 0x86,
/// <summary>
/// F24 key
/// </summary>
F24 = 0x87,
/// <summary>
/// NUM LOCK key
/// </summary>
NUMLOCK = 0x90,
/// <summary>
/// SCROLL LOCK key
/// </summary>
SCROLL = 0x91,
/// <summary>
/// Left SHIFT key
/// </summary>
LSHIFT = 0xA0,
/// <summary>
/// Right SHIFT key
/// </summary>
RSHIFT = 0xA1,
/// <summary>
/// Left CONTROL key
/// </summary>
LCONTROL = 0xA2,
/// <summary>
/// Right CONTROL key
/// </summary>
RCONTROL = 0xA3,
/// <summary>
/// Left MENU key
/// </summary>
LMENU = 0xA4,
/// <summary>
/// Right MENU key
/// </summary>
RMENU = 0xA5,
/// <summary>
/// Windows 2000/XP: Browser Back key
/// </summary>
BROWSER_BACK = 0xA6,
/// <summary>
/// Windows 2000/XP: Browser Forward key
/// </summary>
BROWSER_FORWARD = 0xA7,
/// <summary>
/// Windows 2000/XP: Browser Refresh key
/// </summary>
BROWSER_REFRESH = 0xA8,
/// <summary>
/// Windows 2000/XP: Browser Stop key
/// </summary>
BROWSER_STOP = 0xA9,
/// <summary>
/// Windows 2000/XP: Browser Search key
/// </summary>
BROWSER_SEARCH = 0xAA,
/// <summary>
/// Windows 2000/XP: Browser Favorites key
/// </summary>
BROWSER_FAVORITES = 0xAB,
/// <summary>
/// Windows 2000/XP: Browser Start and Home key
/// </summary>
BROWSER_HOME = 0xAC,
/// <summary>
/// Windows 2000/XP: Volume Mute key
/// </summary>
VOLUME_MUTE = 0xAD,
/// <summary>
/// Windows 2000/XP: Volume Down key
/// </summary>
VOLUME_DOWN = 0xAE,
/// <summary>
/// Windows 2000/XP: Volume Up key
/// </summary>
VOLUME_UP = 0xAF,
/// <summary>
/// Windows 2000/XP: Next Track key
/// </summary>
MEDIA_NEXT_TRACK = 0xB0,
/// <summary>
/// Windows 2000/XP: Previous Track key
/// </summary>
MEDIA_PREV_TRACK = 0xB1,
/// <summary>
/// Windows 2000/XP: Stop Media key
/// </summary>
MEDIA_STOP = 0xB2,
/// <summary>
/// Windows 2000/XP: Play/Pause Media key
/// </summary>
MEDIA_PLAY_PAUSE = 0xB3,
/// <summary>
/// Windows 2000/XP: Start Mail key
/// </summary>
LAUNCH_MAIL = 0xB4,
/// <summary>
/// Windows 2000/XP: Select Media key
/// </summary>
LAUNCH_MEDIA_SELECT = 0xB5,
/// <summary>
/// Windows 2000/XP: Start Application 1 key
/// </summary>
LAUNCH_APP1 = 0xB6,
/// <summary>
/// Windows 2000/XP: Start Application 2 key
/// </summary>
LAUNCH_APP2 = 0xB7,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard.
/// </summary>
OEM_1 = 0xBA,
/// <summary>
/// Windows 2000/XP: For any country/region, the '+' key
/// </summary>
OEM_PLUS = 0xBB,
/// <summary>
/// Windows 2000/XP: For any country/region, the ',' key
/// </summary>
OEM_COMMA = 0xBC,
/// <summary>
/// Windows 2000/XP: For any country/region, the '-' key
/// </summary>
OEM_MINUS = 0xBD,
/// <summary>
/// Windows 2000/XP: For any country/region, the '.' key
/// </summary>
OEM_PERIOD = 0xBE,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard.
/// </summary>
OEM_2 = 0xBF,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard.
/// </summary>
OEM_3 = 0xC0,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard.
/// </summary>
OEM_4 = 0xDB,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard.
/// </summary>
OEM_5 = 0xDC,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard.
/// </summary>
OEM_6 = 0xDD,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard.
/// </summary>
OEM_7 = 0xDE,
/// <summary>
/// Used for miscellaneous characters; it can vary by keyboard.
/// </summary>
OEM_8 = 0xDF,
/// <summary>
/// Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
/// </summary>
OEM_102 = 0xE2,
/// <summary>
/// Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
/// </summary>
PROCESSKEY = 0xE5,
/// <summary>
/// Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes.
/// The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more
/// information,
/// see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP
/// </summary>
PACKET = 0xE7,
/// <summary>
/// Attn key
/// </summary>
ATTN = 0xF6,
/// <summary>
/// CrSel key
/// </summary>
CRSEL = 0xF7,
/// <summary>
/// ExSel key
/// </summary>
EXSEL = 0xF8,
/// <summary>
/// Erase EOF key
/// </summary>
EREOF = 0xF9,
/// <summary>
/// Play key
/// </summary>
PLAY = 0xFA,
/// <summary>
/// Zoom key
/// </summary>
ZOOM = 0xFB,
/// <summary>
/// Reserved
/// </summary>
NONAME = 0xFC,
/// <summary>
/// PA1 key
/// </summary>
PA1 = 0xFD,
/// <summary>
/// Clear key
/// </summary>
OEM_CLEAR = 0xFE,
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.Facilities.WcfIntegration.Async
{
using System;
using System.Threading;
using Castle.DynamicProxy;
public abstract class AsyncWcfCallBase<TProxy> : IWcfAsyncBindings
{
private readonly TProxy proxy;
private readonly Action<TProxy> onBegin;
private readonly WcfRemotingAsyncInterceptor wcfAsyncInterceptor;
private AsyncWcfCallContext context;
protected object[] outArguments;
protected object[] unboundOutArguments;
public AsyncWcfCallBase(TProxy proxy, Action<TProxy> onBegin)
{
if (proxy == null)
{
throw new ArgumentNullException("proxy");
}
if (onBegin == null)
{
throw new ArgumentNullException("onBegin");
}
if ((proxy is IProxyTargetAccessor) == false)
{
throw new ArgumentException(
"The given object is not a proxy created using Castle Dynamic Proxy library and is not supported.",
"proxy");
}
this.proxy = proxy;
this.onBegin = onBegin;
wcfAsyncInterceptor = GetAsyncInterceptor(proxy);
}
public object[] OutArgs
{
get { return outArguments; }
}
public object[] UnboundOutArgs
{
get { return unboundOutArguments; }
}
public TOut GetOutArg<TOut>(int index)
{
return (TOut)ExtractOutOfType(typeof(TOut), index);
}
public TOut GetUnboundOutArg<TOut>(int index)
{
return (TOut)ExtractUnboundOutOfType(typeof(TOut), index);
}
public bool UseSynchronizationContext { get; set; }
#region IAsyncResult Members
public object AsyncState
{
get { return context.AsyncResult.AsyncState; }
}
public WaitHandle AsyncWaitHandle
{
get { return context.AsyncResult.AsyncWaitHandle; }
}
public bool CompletedSynchronously
{
get { return context.AsyncResult.CompletedSynchronously; }
}
public bool IsCompleted
{
get { return context.AsyncResult.IsCompleted; }
}
#endregion
private WcfRemotingAsyncInterceptor GetAsyncInterceptor(TProxy proxy)
{
var interceptors = Array.FindAll(((IProxyTargetAccessor)proxy).GetInterceptors(),
i => i is WcfRemotingAsyncInterceptor);
if (interceptors.Length <= 0)
{
throw new ArgumentException("This proxy does not support async calls.", "proxy");
}
if (interceptors.Length != 1)
{
throw new ArgumentException("This proxy has more than one WcfRemotingAsyncInterceptor.", "proxy");
}
return interceptors[0] as WcfRemotingAsyncInterceptor;
}
internal IAsyncResult Begin(AsyncCallback callback, object state)
{
context = wcfAsyncInterceptor.PrepareCall(WrapCallback(callback), state, proxy, GetDefaultReturnValue());
onBegin(proxy);
return context.AsyncResult;
}
private AsyncCallback WrapCallback(AsyncCallback callback)
{
var cb = callback;
callback = ar =>
{
if (context != null)
context.AsyncResult = ar;
cb(ar);
};
var useSynchronizationContext = UseSynchronizationContext;
var currentSynchronizationContext = SynchronizationContext.Current;
if (callback == null || useSynchronizationContext == false || currentSynchronizationContext == null)
{
return callback;
}
return ar => currentSynchronizationContext.Post(o => callback(ar), null);
}
protected abstract object GetDefaultReturnValue();
protected void End(Action<WcfRemotingAsyncInterceptor, AsyncWcfCallContext> action)
{
if (context == null)
{
throw new InvalidOperationException(
"Something is wrong. Either Begin threw an exception, or we have a bug here. Please report it.");
}
if (context.AsyncResult == null)
{
throw new InvalidOperationException(
"Something is wrong. No AsyncResult is available. This may be a bug so please report it.");
}
action(wcfAsyncInterceptor, context);
}
protected object ExtractOutOfType(Type type, int index)
{
return ExtractOutOfType(type, index, outArguments);
}
protected object ExtractUnboundOutOfType(Type type, int index)
{
return ExtractOutOfType(type, index, unboundOutArguments);
}
private object ExtractOutOfType(Type type, int index, object[] outArgs)
{
if (outArgs == null)
{
throw new InvalidOperationException("Out arguments are not available. Did you forget to call End?");
}
if (index >= outArgs.Length)
{
throw new IndexOutOfRangeException(string.Format(
"There is no out argument at index {0}. Please check the method signature.", index));
}
object outArg = outArgs[index];
if (outArg == null && type.IsValueType)
{
throw new InvalidOperationException(string.Format(
"The out argument at index {0} is a value type and cannot be null. Please check the method signature.", index));
}
if (!type.IsInstanceOfType(outArg))
{
throw new InvalidOperationException(string.Format(
"There is a type mismatch for the out argument at index {0}. Expected {1}, but found {2}. Please check the method signature.",
index, type.FullName, outArg.GetType().FullName));
}
return outArg;
}
protected void CreateUnusedOutArgs(int fromIndex)
{
unboundOutArguments = new object[Math.Max(0, outArguments.Length - fromIndex)];
if (unboundOutArguments.Length > 0)
{
Array.Copy(outArguments, fromIndex, unboundOutArguments, 0, unboundOutArguments.Length);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Layout.Layered;
using Microsoft.Msagl.Routing;
using Microsoft.Msagl.Routing.Visibility;
namespace Microsoft.Msagl.Prototype.LayoutEditing {
/// <summary>
/// the router between nodes
/// </summary>
public class RouterBetweenTwoNodes {
readonly Dictionary<Point, Polyline> pointsToObstacles = new Dictionary<Point, Polyline>();
VisibilityGraph _visGraph;
ObstacleCalculator obstacleCalculator;
/// <summary>
/// the port of the edge start
/// </summary>
public Port SourcePort { get; private set; }
/// <summary>
/// the port of the edge end
/// </summary>
public Port TargetPort { get; private set; }
const double enteringAngleBound = 10;
/// <summary>
/// the minimum angle between a node boundary curve and and an edge
/// curve at the place where the edge curve intersects the node boundary
/// </summary>
public double EnteringAngleBound {
get { return enteringAngleBound; }
}
double minimalPadding = 1;
/// <summary>
/// the curve should not come to the nodes closer than MinimalPaddin
/// </summary>
public double Padding {
get { return minimalPadding; }
private set { minimalPadding = value; }
}
/// <summary>
/// we pad each node but not more than MaximalPadding
/// </summary>
public double LoosePadding { get; set; }
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
readonly GeometryGraph graph;
internal Node Target { get; private set; }
VisibilityVertex sourceVisibilityVertex;
VisibilityVertex targetVisibilityVertex;
VisibilityVertex TargetVisibilityVertex {
get { return targetVisibilityVertex; }
// set { targetVisibilityVertex = value; }
}
internal Node Source { get; private set; }
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal GeometryGraph Graph {
get { return graph; }
}
Polyline Polyline { get; set; }
internal static double DistanceFromPointToPolyline(Point p, Polyline poly) {
double d = double.PositiveInfinity;
double u;
for (PolylinePoint pp = poly.StartPoint; pp.Next != null; pp = pp.Next)
d = Math.Min(d, Point.DistToLineSegment(p, pp.Point, pp.Next.Point, out u));
return d;
}
/// <summary>
///
/// </summary>
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Polyline")]
double OffsetForPolylineRelaxing { get; set; }
/// <summary>
/// constructor
/// </summary>
/// <param name="graph"></param>
/// <param name="minimalPadding"></param>
/// <param name="maximalPadding"></param>
/// <param name="offsetForRelaxing"></param>
public RouterBetweenTwoNodes(GeometryGraph graph, double minimalPadding, double maximalPadding,
double offsetForRelaxing) {
this.graph = graph;
LoosePadding = maximalPadding;
Padding = minimalPadding;
OffsetForPolylineRelaxing = offsetForRelaxing;
}
/// <summary>
/// Routes a spline between two graph nodes. sourcePort and targetPort define the start and end point of the resulting curve:
/// startPoint=source.BoundaryCurve[sourcePort] and endPoint=target.BoundaryCurve[target].
/// </summary>
/// <param name="edge"></param>
/// <param name="takeYourTime">if set to true then the method will try to improve the spline</param>
public void RouteEdge(Edge edge, bool takeYourTime) {
Source = edge.Source;
Target = edge.Target;
SourcePort = edge.SourcePort;
TargetPort = edge.TargetPort;
CalculateObstacles();
LineSegment lineSeg = TryRouteStraightLine();
if (lineSeg != null) {
Polyline = new Polyline(lineSeg.Start, lineSeg.End);
edge.UnderlyingPolyline = SmoothedPolyline.FromPoints(Polyline);
} else {
CalculateTangentVisibilityGraph();
Polyline = GetShortestPolyline();
// ShowPolylineAndObstacles();
RelaxPolyline();
//ShowPolylineAndObstacles();
//ReducePolyline();
//ShowPolylineAndObstacles();
edge.UnderlyingPolyline = SmoothedPolyline.FromPoints(Polyline);
if (takeYourTime) {
TryToRemoveInflectionsAndCollinearSegs(edge.UnderlyingPolyline);
SmoothCorners(edge.UnderlyingPolyline);
}
}
edge.Curve = edge.UnderlyingPolyline.CreateCurve();
}
//void ReducePolyline() {
// for (PolylinePoint pp = this.Polyline.StartPoint.Next; pp.Next != null && pp.Next.Next != null;pp=pp.Next )
// pp = TryToRemoveOrDiminishSegment(pp, pp.Next);
//}
//PolylinePoint TryToRemoveOrDiminishSegment(PolylinePoint pp, PolylinePoint polylinePoint) {
// TriangleOrientation orientation = Point.GetTriangleOrientation(pp.Prev.Point, pp.Point, pp.Next.Point);
// if (orientation == Point.GetTriangleOrientation(pp.Point, pp.Next.Point, pp.Next.Next.Point)) {
// Point x;
// if (Point.LineLineIntersection(pp.Prev.Point, pp.Point, pp.Next.Point, pp.Next.Next.Point, out x)) {
// if (orientation == Point.GetTriangleOrientation(pp.Point, x, pp.Next.Point)) {
// if (!LineIntersectsTightObstacles(pp.Prev.Point, x) && !LineIntersectsTightObstacles(x, pp.Next.Next.Point)) {
// PolylinePoint px = new PolylinePoint(x);
// //inserting px instead of pp and pp.Next
// px.Prev = pp.Prev;
// pp.Prev.Next = px;
// px.Next = pp.Next.Next;
// pp.Next.Next.Prev = px;
// return px.Prev;
// } else {
// for (double k = 0.5; k > 0.01; k /= 2) {
// Point a = pp.Point * (1 - k) + x * k;
// Point b = pp.Next.Point * (1 - k) + x * k;
// if (!LineIntersectsTightObstacles(pp.Point, a) &&
// !LineIntersectsTightObstacles(a, b) &&
// !LineIntersectsTightObstacles(b, pp.Next.Point)) {
// pp.Point = a;
// pp.Next.Point = b;
// break;
// }
// }
// }
// }
// }
// }
// return pp;
//}
//bool LineIntersectsTightObstacles(Point point, Point x) {
// return LineIntersectsTightObstacles(new LineSegment(point, x));
//}
#if TEST_MSAGL
//private void ShowPolylineAndObstaclesWithGraph() {
// List<ICurve> ls = new List<ICurve>();
// foreach (Polyline poly in this.obstacleCalculator.TightObstacles)
// ls.Add(poly);
// foreach (Polyline poly in this.obstacleCalculator.LooseObstacles)
// ls.Add(poly);
// AddVisibilityGraph(ls);
// ls.Add(Polyline);
// SugiyamaLayoutSettings.Show(ls.ToArray());
//}
#endif
//pull the polyline out from the corners
void RelaxPolyline() {
RelaxedPolylinePoint relaxedPolylinePoint = CreateRelaxedPolylinePoints(Polyline);
//ShowPolylineAndObstacles();
for (relaxedPolylinePoint = relaxedPolylinePoint.Next;
relaxedPolylinePoint.Next != null;
relaxedPolylinePoint = relaxedPolylinePoint.Next)
RelaxPolylinePoint(relaxedPolylinePoint);
}
static RelaxedPolylinePoint CreateRelaxedPolylinePoints(Polyline polyline) {
PolylinePoint p = polyline.StartPoint;
var ret = new RelaxedPolylinePoint(p, p.Point);
RelaxedPolylinePoint currentRelaxed = ret;
while (p.Next != null) {
p = p.Next;
var r = new RelaxedPolylinePoint(p, p.Point) { Prev = currentRelaxed };
currentRelaxed.Next = r;
currentRelaxed = r;
}
return ret;
}
void RelaxPolylinePoint(RelaxedPolylinePoint relaxedPoint) {
for (double d = OffsetForPolylineRelaxing; !RelaxWithGivenOffset(d, relaxedPoint); d /= 2) {
}
}
bool RelaxWithGivenOffset(double offset, RelaxedPolylinePoint relaxedPoint) {
SetRelaxedPointLocation(offset, relaxedPoint);
#if TEST_MSAGL
//ShowPolylineAndObstacles();
#endif
if (StickingSegmentDoesNotIntersectTightObstacles(relaxedPoint))
return true;
PullCloserRelaxedPoint(relaxedPoint.Prev);
return false;
}
static void PullCloserRelaxedPoint(RelaxedPolylinePoint relaxedPolylinePoint) {
relaxedPolylinePoint.PolylinePoint.Point = 0.2 * relaxedPolylinePoint.OriginalPosition +
0.8 * relaxedPolylinePoint.PolylinePoint.Point;
}
bool StickingSegmentDoesNotIntersectTightObstacles(RelaxedPolylinePoint relaxedPoint) {
return
!LineIntersectsTightObstacles(new LineSegment(relaxedPoint.PolylinePoint.Point,
relaxedPoint.Prev.PolylinePoint.Point)) && (
(relaxedPoint
.Next ==
null ||
!LineIntersectsTightObstacles
(new LineSegment
(relaxedPoint
.
PolylinePoint
.
Point,
relaxedPoint
.
Next
.
PolylinePoint
.
Point))));
}
bool LineIntersectsTightObstacles(LineSegment ls) {
return LineIntersectsRectangleNode(ls, obstacleCalculator.RootOfTightHierararchy);
}
static bool LineIntersectsRectangleNode(LineSegment ls, RectangleNode<Polyline> rectNode) {
if (!ls.BoundingBox.Intersects(rectNode.Rectangle))
return false;
if (rectNode.UserData != null) {
// SugiyamaLayoutSettings.Show(ls, rectNode.UserData);
return Curve.GetAllIntersections(rectNode.UserData, ls, false).Count > 0;
}
return LineIntersectsRectangleNode(ls, rectNode.Left) || LineIntersectsRectangleNode(ls, rectNode.Right);
}
static void SetRelaxedPointLocation(double offset, RelaxedPolylinePoint relaxedPoint) {
bool leftTurn = Point.GetTriangleOrientation(relaxedPoint.Next.OriginalPosition,
relaxedPoint.OriginalPosition,
relaxedPoint.Prev.OriginalPosition) ==
TriangleOrientation.Counterclockwise;
Point v =
((relaxedPoint.Next.OriginalPosition - relaxedPoint.Prev.OriginalPosition).Normalize() * offset).Rotate(
Math.PI / 2);
if (!leftTurn)
v = -v;
relaxedPoint.PolylinePoint.Point = relaxedPoint.OriginalPosition + v;
}
#if TEST_MSAGL
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
void ShowPolylineAndObstacles(){
List<ICurve> ls = CreateListWithObstaclesAndPolyline();
SugiyamaLayoutSettings.Show(ls.ToArray());
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
List<ICurve> CreateListWithObstaclesAndPolyline(){
var ls = new List<ICurve>();
foreach (Polyline poly in obstacleCalculator.TightObstacles)
ls.Add(poly);
foreach (Polyline poly in obstacleCalculator.LooseObstacles)
ls.Add(poly);
ls.Add(Polyline);
return ls;
}
#endif
void SmoothCorners(SmoothedPolyline edgePolyline) {
Site a = edgePolyline.HeadSite; //the corner start
Site b; //the corner origin
Site c; //the corner other end
const double mult = 1.5;
while (Curve.FindCorner(a, out b, out c)) {
double k = 0.5;
CubicBezierSegment seg;
double u, v;
if (a.Previous == null) {
//this will allow to the segment to start from site "a"
u = 2;
v = 1;
} else if (c.Next == null) {
u = 1;
v = 2; //this will allow to the segment to end at site "c"
} else {
u = v = 1;
}
do {
seg = Curve.CreateBezierSeg(k * u, k * v, a, b, c);
b.PreviousBezierSegmentFitCoefficient = k * u;
b.NextBezierSegmentFitCoefficient = k * v;
k /= mult;
} while (obstacleCalculator.ObstaclesIntersectICurve(seg));
k *= mult; //that was the last k
if (k < 0.5) {
//one time try a smoother seg
k = 0.5 * (k + k * mult);
seg = Curve.CreateBezierSeg(k * u, k * v, a, b, c);
if (!obstacleCalculator.ObstaclesIntersectICurve(seg)) {
b.PreviousBezierSegmentFitCoefficient = k * u;
b.NextBezierSegmentFitCoefficient = k * v;
}
}
a = b;
}
}
void TryToRemoveInflectionsAndCollinearSegs(SmoothedPolyline underlyingPolyline) {
bool progress = true;
while (progress) {
progress = false;
for (Site s = underlyingPolyline.HeadSite; s != null && s.Next != null; s = s.Next) {
if (s.Turn * s.Next.Turn < 0)
progress = TryToRemoveInflectionEdge(ref s) || progress;
}
}
}
bool TryToRemoveInflectionEdge(ref Site s) {
if (!obstacleCalculator.ObstaclesIntersectLine(s.Previous.Point, s.Next.Point)) {
Site a = s.Previous; //forget s
Site b = s.Next;
a.Next = b;
b.Previous = a;
s = a;
return true;
}
if (!obstacleCalculator.ObstaclesIntersectLine(s.Previous.Point, s.Next.Next.Point)) {
//forget about s and s.Next
Site a = s.Previous;
Site b = s.Next.Next;
a.Next = b;
b.Previous = a;
s = a;
return true;
}
if (!obstacleCalculator.ObstaclesIntersectLine(s.Point, s.Next.Next.Point)) {
//forget about s.Next
Site b = s.Next.Next;
s.Next = b;
b.Previous = s;
return true;
}
return false;
}
LineSegment TryRouteStraightLine() {
var ls = new LineSegment(SourcePoint, TargetPoint);
if (obstacleCalculator.ObstaclesIntersectICurve(ls))
return null;
return ls;
}
internal Point TargetPoint {
get {
var tp = TargetPort as CurvePort;
if (tp != null)
return Target.BoundaryCurve[tp.Parameter];
return TargetPort.Location;
}
}
internal Point SourcePoint {
get {
var sp = SourcePort as CurvePort;
if (sp != null)
return Source.BoundaryCurve[sp.Parameter];
return SourcePort.Location;
}
}
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
Polyline GetShortestPolyline() {
var pathCalc = new SingleSourceSingleTargetShortestPathOnVisibilityGraph(_visGraph, this.sourceVisibilityVertex,
TargetVisibilityVertex);
var path = pathCalc.GetPath(false);
var ret = new Polyline();
foreach (var v in path)
ret.AddPoint(v.Point);
return RemoveCollinearPoint(ret);
}
static Polyline RemoveCollinearPoint(Polyline ret) {
for (PolylinePoint pp = ret.StartPoint.Next; pp.Next != null; pp = pp.Next)
if (Point.GetTriangleOrientation(pp.Prev.Point, pp.Point, pp.Next.Point) == TriangleOrientation.Collinear) {
pp.Prev.Next = pp.Next;
pp.Next.Prev = pp.Prev;
}
return ret;
}
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
void CalculateTangentVisibilityGraph() {
_visGraph = VisibilityGraph.GetVisibilityGraphForShortestPath(
SourcePoint, TargetPoint, obstacleCalculator.LooseObstacles, out sourceVisibilityVertex,
out targetVisibilityVertex);
}
void CalculateObstacles() {
obstacleCalculator = new ObstacleCalculator(this);
obstacleCalculator.Calculate();
foreach (Polyline poly in obstacleCalculator.TightObstacles)
foreach (Point p in poly)
pointsToObstacles[p] = poly;
}
}
}
| |
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
using System.Diagnostics;
/// <summary>
/// This improved version of the System.Collections.Generic.List that doesn't release the buffer on Clear(),
/// resulting in better performance and less garbage collection.
/// PRO: BetterList performs faster than List when you Add and Remove items (although slower if you remove from the beginning).
/// CON: BetterList performs worse when sorting the list. If your operations involve sorting, use the standard List instead.
/// </summary>
namespace Nebule.DevEditor.BMFontMaker
{
public class BetterList<T>
{
/// <summary>
/// Direct access to the buffer. Note that you should not use its 'Length' parameter, but instead use BetterList.size.
/// </summary>
public T[] buffer;
/// <summary>
/// Direct access to the buffer's size. Note that it's only public for speed and efficiency. You shouldn't modify it.
/// </summary>
public int size = 0;
/// <summary>
/// For 'foreach' functionality.
/// </summary>
[DebuggerHidden]
[DebuggerStepThrough]
public IEnumerator<T> GetEnumerator()
{
if (buffer != null)
{
for (int i = 0; i < size; ++i)
{
yield return buffer[i];
}
}
}
/// <summary>
/// Convenience function. I recommend using .buffer instead.
/// </summary>
[DebuggerHidden]
public T this[int i]
{
get { return buffer[i]; }
set { buffer[i] = value; }
}
/// <summary>
/// Helper function that expands the size of the array, maintaining the content.
/// </summary>
void AllocateMore()
{
T[] newList = (buffer != null) ? new T[Mathf.Max(buffer.Length << 1, 32)] : new T[32];
if (buffer != null && size > 0) buffer.CopyTo(newList, 0);
buffer = newList;
}
/// <summary>
/// Trim the unnecessary memory, resizing the buffer to be of 'Length' size.
/// Call this function only if you are sure that the buffer won't need to resize anytime soon.
/// </summary>
void Trim()
{
if (size > 0)
{
if (size < buffer.Length)
{
T[] newList = new T[size];
for (int i = 0; i < size; ++i) newList[i] = buffer[i];
buffer = newList;
}
}
else buffer = null;
}
/// <summary>
/// Clear the array by resetting its size to zero. Note that the memory is not actually released.
/// </summary>
public void Clear() { size = 0; }
/// <summary>
/// Clear the array and release the used memory.
/// </summary>
public void Release() { size = 0; buffer = null; }
/// <summary>
/// Add the specified item to the end of the list.
/// </summary>
public void Add(T item)
{
if (buffer == null || size == buffer.Length) AllocateMore();
buffer[size++] = item;
}
/// <summary>
/// Insert an item at the specified index, pushing the entries back.
/// </summary>
public void Insert(int index, T item)
{
if (buffer == null || size == buffer.Length) AllocateMore();
if (index > -1 && index < size)
{
for (int i = size; i > index; --i) buffer[i] = buffer[i - 1];
buffer[index] = item;
++size;
}
else Add(item);
}
/// <summary>
/// Returns 'true' if the specified item is within the list.
/// </summary>
public bool Contains(T item)
{
if (buffer == null) return false;
for (int i = 0; i < size; ++i) if (buffer[i].Equals(item)) return true;
return false;
}
/// <summary>
/// Return the index of the specified item.
/// </summary>
public int IndexOf(T item)
{
if (buffer == null) return -1;
for (int i = 0; i < size; ++i) if (buffer[i].Equals(item)) return i;
return -1;
}
/// <summary>
/// Remove the specified item from the list. Note that RemoveAt() is faster and is advisable if you already know the index.
/// </summary>
public bool Remove(T item)
{
if (buffer != null)
{
EqualityComparer<T> comp = EqualityComparer<T>.Default;
for (int i = 0; i < size; ++i)
{
if (comp.Equals(buffer[i], item))
{
--size;
buffer[i] = default(T);
for (int b = i; b < size; ++b) buffer[b] = buffer[b + 1];
buffer[size] = default(T);
return true;
}
}
}
return false;
}
/// <summary>
/// Remove an item at the specified index.
/// </summary>
public void RemoveAt(int index)
{
if (buffer != null && index > -1 && index < size)
{
--size;
buffer[index] = default(T);
for (int b = index; b < size; ++b) buffer[b] = buffer[b + 1];
buffer[size] = default(T);
}
}
/// <summary>
/// Remove an item from the end.
/// </summary>
public T Pop()
{
if (buffer != null && size != 0)
{
T val = buffer[--size];
buffer[size] = default(T);
return val;
}
return default(T);
}
/// <summary>
/// Mimic List's ToArray() functionality, except that in this case the list is resized to match the current size.
/// </summary>
public T[] ToArray() { Trim(); return buffer; }
//class Comparer : System.Collections.IComparer
//{
// public System.Comparison<T> func;
// public int Compare (object x, object y) { return func((T)x, (T)y); }
//}
//Comparer mComp = new Comparer();
/// <summary>
/// List.Sort equivalent. Doing Array.Sort causes GC allocations.
/// </summary>
//public void Sort (System.Comparison<T> comparer)
//{
// if (size > 0)
// {
// mComp.func = comparer;
// System.Array.Sort(buffer, 0, size, mComp);
// }
//}
/// <summary>
/// List.Sort equivalent. Manual sorting causes no GC allocations.
/// </summary>
[DebuggerHidden]
[DebuggerStepThrough]
public void Sort(CompareFunc comparer)
{
int start = 0;
int max = size - 1;
bool changed = true;
while (changed)
{
changed = false;
for (int i = start; i < max; ++i)
{
// Compare the two values
if (comparer(buffer[i], buffer[i + 1]) > 0)
{
// Swap the values
T temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
changed = true;
}
else if (!changed)
{
// Nothing has changed -- we can start here next time
start = (i == 0) ? 0 : i - 1;
}
}
}
}
/// <summary>
/// Comparison function should return -1 if left is less than right, 1 if left is greater than right, and 0 if they match.
/// </summary>
public delegate int CompareFunc(T left, T right);
}
}
| |
//
// HttpClient.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.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.Threading;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.IO;
namespace System.Net.Http
{
public class HttpClient : HttpMessageInvoker
{
static readonly TimeSpan TimeoutDefault = TimeSpan.FromSeconds (100);
Uri base_address;
CancellationTokenSource cts;
bool disposed;
HttpRequestHeaders headers;
long buffer_size;
TimeSpan timeout;
public HttpClient ()
: this (new HttpClientHandler (), true)
{
}
public HttpClient (HttpMessageHandler handler)
: this (handler, true)
{
}
public HttpClient (HttpMessageHandler handler, bool disposeHandler)
: base (handler, disposeHandler)
{
buffer_size = int.MaxValue;
timeout = TimeoutDefault;
cts = new CancellationTokenSource ();
}
public Uri BaseAddress {
get {
return base_address;
}
set {
base_address = value;
}
}
public HttpRequestHeaders DefaultRequestHeaders {
get {
return headers ?? (headers = new HttpRequestHeaders ());
}
}
public long MaxResponseContentBufferSize {
get {
return buffer_size;
}
set {
if (value <= 0)
throw new ArgumentOutOfRangeException ();
buffer_size = value;
}
}
static readonly TimeSpan INFINITE = new TimeSpan(0, 0, 0, 0, -1);
public TimeSpan Timeout {
get {
return timeout;
}
set {
if (value != INFINITE && value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException ();
timeout = value;
}
}
public void CancelPendingRequests ()
{
// Cancel only any already running requests not any new request after this cancellation
using (var c = Interlocked.Exchange (ref cts, new CancellationTokenSource ()))
c.Cancel ();
}
protected override void Dispose (bool disposing)
{
if (disposing && !disposed) {
disposed = true;
cts.Dispose ();
}
base.Dispose (disposing);
}
public Task<HttpResponseMessage> DeleteAsync (string requestUri)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Delete, requestUri));
}
public Task<HttpResponseMessage> DeleteAsync (string requestUri, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Delete, requestUri), cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync (Uri requestUri)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Delete, requestUri));
}
public Task<HttpResponseMessage> DeleteAsync (Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Delete, requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync (string requestUri)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Get, requestUri));
}
public Task<HttpResponseMessage> GetAsync (string requestUri, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Get, requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync (string requestUri, HttpCompletionOption completionOption)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Get, requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync (string requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync (Uri requestUri)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Get, requestUri));
}
public Task<HttpResponseMessage> GetAsync (Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Get, requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync (Uri requestUri, HttpCompletionOption completionOption)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Get, requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync (Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync (string requestUri, HttpContent content)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Post, requestUri) { Content = content });
}
public Task<HttpResponseMessage> PostAsync (string requestUri, HttpContent content, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Post, requestUri) { Content = content }, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync (Uri requestUri, HttpContent content)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Post, requestUri) { Content = content });
}
public Task<HttpResponseMessage> PostAsync (Uri requestUri, HttpContent content, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Post, requestUri) { Content = content }, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync (Uri requestUri, HttpContent content)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Put, requestUri) { Content = content });
}
public Task<HttpResponseMessage> PutAsync (Uri requestUri, HttpContent content, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Put, requestUri) { Content = content }, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync (string requestUri, HttpContent content)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Put, requestUri) { Content = content });
}
public Task<HttpResponseMessage> PutAsync (string requestUri, HttpContent content, CancellationToken cancellationToken)
{
return SendAsync (new HttpRequestMessage (HttpMethod.Put, requestUri) { Content = content }, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync (HttpRequestMessage request)
{
return SendAsync (request, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
}
public Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, HttpCompletionOption completionOption)
{
return SendAsync (request, completionOption, CancellationToken.None);
}
public override Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
{
return SendAsync (request, HttpCompletionOption.ResponseContentRead, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
if (request == null)
throw new ArgumentNullException ("request");
if (request.SetIsUsed ())
throw new InvalidOperationException ("Cannot send the same request message multiple times");
var uri = request.RequestUri;
if (uri == null) {
if (base_address == null)
throw new InvalidOperationException ("The request URI must either be an absolute URI or BaseAddress must be set");
request.RequestUri = base_address;
} else if (!uri.IsAbsoluteUri || uri.Scheme == Uri.UriSchemeFile && uri.OriginalString.StartsWith ("/", StringComparison.Ordinal)) {
if (base_address == null)
throw new InvalidOperationException ("The request URI must either be an absolute URI or BaseAddress must be set");
request.RequestUri = new Uri (base_address, uri);
}
if (headers != null) {
request.Headers.AddHeaders (headers);
}
return SendAsyncWorker (request, completionOption, cancellationToken);
}
#if UNITY
Task<HttpResponseMessage> SendAsyncWorker (HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
var lcts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
lcts.CancelAfter(timeout);
var task = base.SendAsync(request, lcts.Token);
if (task == null)
throw new InvalidOperationException("Handler failed to return a value");
return task.ContinueWith(t =>
{
var response = task.Result;
if (response == null)
throw new InvalidOperationException("Handler failed to return a response");
//
// Read the content when default HttpCompletionOption.ResponseContentRead is set
//
if (response.Content != null && (completionOption & HttpCompletionOption.ResponseHeadersRead) == 0) {
response.Content.LoadIntoBufferAsync(MaxResponseContentBufferSize).Await();
}
lcts.Dispose();
return response;
});
}
public Task<byte[]> GetByteArrayAsync (string requestUri)
{
return GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ContinueWith(t =>
{
using(var resp = t.Result) {
resp.EnsureSuccessStatusCode ();
return resp.Content.ReadAsByteArrayAsync ().Await();
}
});
}
public Task<byte[]> GetByteArrayAsync (Uri requestUri)
{
return GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ContinueWith(t =>
{
using(var resp = t.Result) {
resp.EnsureSuccessStatusCode ();
return resp.Content.ReadAsByteArrayAsync ().Await();
}
});
}
public Task<Stream> GetStreamAsync (string requestUri)
{
return GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ContinueWith(t =>
{
using(var resp = t.Result) {
resp.EnsureSuccessStatusCode ();
return resp.Content.ReadAsStreamAsync ().Await();
}
});
}
public Task<Stream> GetStreamAsync (Uri requestUri)
{
return GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ContinueWith(t =>
{
using(var resp = t.Result) {
resp.EnsureSuccessStatusCode ();
return resp.Content.ReadAsStreamAsync ().Await();
}
});
}
public Task<string> GetStringAsync (string requestUri)
{
return GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ContinueWith(t =>
{
using(var resp = t.Result) {
resp.EnsureSuccessStatusCode ();
return resp.Content.ReadAsStringAsync ().Await();
}
});
}
public Task<string> GetStringAsync (Uri requestUri)
{
return GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ContinueWith(t =>
{
using(var resp = t.Result) {
resp.EnsureSuccessStatusCode ();
return resp.Content.ReadAsStringAsync ().Await();
}
});
}
#else
public async Task<Stream> GetStreamAsync (string requestUri)
{
var resp = await GetAsync (requestUri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait (false);
resp.EnsureSuccessStatusCode ();
return await resp.Content.ReadAsStreamAsync ().ConfigureAwait (false);
}
public async Task<Stream> GetStreamAsync (Uri requestUri)
{
var resp = await GetAsync (requestUri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait (false);
resp.EnsureSuccessStatusCode ();
return await resp.Content.ReadAsStreamAsync ().ConfigureAwait (false);
}
public async Task<string> GetStringAsync (string requestUri)
{
using (var resp = await GetAsync (requestUri, HttpCompletionOption.ResponseContentRead).ConfigureAwait (false)) {
resp.EnsureSuccessStatusCode ();
return await resp.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
}
public async Task<string> GetStringAsync (Uri requestUri)
{
using (var resp = await GetAsync (requestUri, HttpCompletionOption.ResponseContentRead).ConfigureAwait (false)) {
resp.EnsureSuccessStatusCode ();
return await resp.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
}
public async Task<byte[]> GetByteArrayAsync (string requestUri)
{
using (var resp = await GetAsync (requestUri, HttpCompletionOption.ResponseContentRead).ConfigureAwait (false)) {
resp.EnsureSuccessStatusCode ();
return await resp.Content.ReadAsByteArrayAsync ().ConfigureAwait (false);
}
}
public async Task<byte[]> GetByteArrayAsync (Uri requestUri)
{
using (var resp = await GetAsync (requestUri, HttpCompletionOption.ResponseContentRead).ConfigureAwait (false)) {
resp.EnsureSuccessStatusCode ();
return await resp.Content.ReadAsByteArrayAsync ().ConfigureAwait (false);
}
}
async Task<HttpResponseMessage> SendAsyncWorker (HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
using (var lcts = CancellationTokenSource.CreateLinkedTokenSource (cts.Token, cancellationToken)) {
lcts.CancelAfter (timeout);
var task = base.SendAsync (request, lcts.Token);
if (task == null)
throw new InvalidOperationException ("Handler failed to return a value");
var response = await task.ConfigureAwait(false);
if (response == null)
throw new InvalidOperationException ("Handler failed to return a response");
//
// Read the content when default HttpCompletionOption.ResponseContentRead is set
//
if (response.Content != null && (completionOption & HttpCompletionOption.ResponseHeadersRead) == 0) {
await response.Content.LoadIntoBufferAsync (MaxResponseContentBufferSize).ConfigureAwait(false);
}
return response;
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace Tyrrrz.Extensions.Tests
{
[TestFixture]
public class StringExtensionsTests
{
[Test]
[TestCase(null, true)]
[TestCase("", true)]
[TestCase(" ", false)]
[TestCase("test", false)]
[TestCase(" test", false)]
public void IsNullOrEmpty_Test(string input, bool expectedOutput)
{
Assert.That(input.IsNullOrEmpty(), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase(null, true)]
[TestCase("", true)]
[TestCase(" ", true)]
[TestCase("test", false)]
[TestCase(" test", false)]
public void IsNullOrWhiteSpace_Test(string input, bool expectedOutput)
{
Assert.That(input.IsNullOrWhiteSpace(), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase(null, "")]
[TestCase("test", "test")]
[TestCase(" ", " ")]
public void EmptyIfNull_Test(string input, string expectedOutput)
{
Assert.That(input.EmptyIfNull(), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("123", true)]
[TestCase("test", false)]
[TestCase("123.5", false)]
public void IsNumeric_Test(string input, bool expectedOutput)
{
Assert.That(input.IsNumeric(), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("test", true)]
[TestCase("123", false)]
[TestCase("test123", false)]
public void IsAlphabetic_Test(string input, bool expectedOutput)
{
Assert.That(input.IsAlphabetic(), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("123", true)]
[TestCase("test", true)]
[TestCase("test123", true)]
[TestCase("123.5", false)]
public void IsAlphanumeric_Test(string input, bool expectedOutput)
{
Assert.That(input.IsAlphanumeric(), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("test", "te", "st")]
[TestCase("test", "st", "test")]
[TestCase("tetetetest", "te", "st")]
[TestCase("tESt", "te", "St", StringComparison.OrdinalIgnoreCase)]
public void TrimStart_Test(string input, string sub, string expectedOutput,
StringComparison comparison = StringComparison.Ordinal)
{
Assert.That(input.TrimStart(sub, comparison), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("test", "st", "te")]
[TestCase("test", "te", "test")]
[TestCase("testststst", "st", "te")]
[TestCase("tESt", "st", "tE", StringComparison.OrdinalIgnoreCase)]
public void TrimEnd_Test(string input, string sub, string expectedOutput,
StringComparison comparison = StringComparison.Ordinal)
{
Assert.That(input.TrimEnd(sub, comparison), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("test", "t", "es")]
[TestCase("test", "es", "test")]
[TestCase("tetesttete", "te", "st")]
[TestCase("teTestTete", "te", "st", StringComparison.OrdinalIgnoreCase)]
public void Trim_Test(string input, string sub, string expectedOutput,
StringComparison comparison = StringComparison.Ordinal)
{
Assert.That(input.Trim(sub, comparison), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("test", "tset")]
[TestCase("", "")]
[TestCase("t", "t")]
public void Reverse_Test(string input, string expectedOutput)
{
Assert.That(input.Reverse(), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("test", 3, "testtesttest")]
[TestCase("test", 1, "test")]
[TestCase("test", 0, "")]
public void Repeat_Test(string input, int count, string expectedOutput)
{
Assert.That(input.Repeat(count), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase('a', 3, "aaa")]
[TestCase('a', 1, "a")]
[TestCase('a', 0, "")]
public void Repeat_Test(char input, int count, string expectedOutput)
{
Assert.That(input.Repeat(count), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("aaatestbbtest", "test", "xyz", "aaaxyzbbxyz")]
[TestCase("aaatestbb", "test", "xyz", "aaaxyzbb")]
[TestCase("aaabbc", "test", "xyz", "aaabbc")]
[TestCase("aaaTESTbbTeStc", "test", "xyz", "aaaxyzbbxyzc", StringComparison.OrdinalIgnoreCase)]
public void Replace_Test(string input, string oldValue, string newValue, string expectedOutput,
StringComparison comparison = StringComparison.Ordinal)
{
Assert.That(input.Replace(oldValue, newValue, comparison), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("aaatestbbb", "test", "aaa")]
[TestCase("aaatestbbbtestccc", "test", "aaa")]
[TestCase("aaatestbbbtestccc", "xyz", "aaatestbbbtestccc")]
[TestCase("testaaa", "test", "")]
[TestCase("aaatEStbbb", "test", "aaa", StringComparison.OrdinalIgnoreCase)]
public void SubstringUntil_Test(string input, string sub, string expectedOutput,
StringComparison comparison = StringComparison.Ordinal)
{
Assert.That(input.SubstringUntil(sub, comparison), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("aaatestbbb", "test", "bbb")]
[TestCase("aaatestbbbtestccc", "test", "bbbtestccc")]
[TestCase("aaatestbbbtestccc", "xyz", "")]
[TestCase("aaatest", "test", "")]
[TestCase("aaatEStbbb", "test", "bbb", StringComparison.OrdinalIgnoreCase)]
public void SubstringAfter_Test(string input, string sub, string expectedOutput,
StringComparison comparison = StringComparison.Ordinal)
{
Assert.That(input.SubstringAfter(sub, comparison), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("aaatestbbb", "test", "aaa")]
[TestCase("aaatestbbbtestccc", "test", "aaatestbbb")]
[TestCase("aaatestbbbtestccc", "xyz", "aaatestbbbtestccc")]
[TestCase("testaaa", "test", "")]
[TestCase("aaatEStbbb", "test", "aaa", StringComparison.OrdinalIgnoreCase)]
public void SubstringUntilLast_Test(string input, string sub, string expectedOutput,
StringComparison comparison = StringComparison.Ordinal)
{
Assert.That(input.SubstringUntilLast(sub, comparison), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("aaatestbbb", "test", "bbb")]
[TestCase("aaatestbbbtestccc", "test", "ccc")]
[TestCase("aaatestbbbtestccc", "xyz", "")]
[TestCase("aaatest", "test", "")]
[TestCase("aaatEStbbb", "test", "bbb", StringComparison.OrdinalIgnoreCase)]
public void SubstringAfterLast_Test(string input, string sub, string expectedOutput,
StringComparison comparison = StringComparison.Ordinal)
{
Assert.That(input.SubstringAfterLast(sub, comparison), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase(new[] {"aaa", "", " ", "bbb"}, new[] {"aaa", "bbb"})]
public void ExceptNullOrWhiteSpace_Test(IEnumerable<string> input, IEnumerable<string> expectedOutput)
{
Assert.That(input.ExceptNullOrWhiteSpace(), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("testaaatestaaatestaaa", new[] {"aaa"}, new[] {"test", "test", "test"})]
public void Split_Test(string input, string[] separators, string[] expectedOutput)
{
Assert.That(input.Split(separators), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase("testaatestbbbtesta", new[] {'a', 'b'}, new[] {"test", "test", "test"})]
public void Split_Test(string input, char[] separators, string[] expectedOutput)
{
// Using fully qualified name because it defaults to member method
Assert.That(StringExtensions.Split(input, separators), Is.EqualTo(expectedOutput));
}
[Test]
[TestCase(new[] {"test", "test"}, ", ", "test, test")]
public void JoinToString_Test(IEnumerable<string> input, string separator, string expectedOutput)
{
Assert.That(input.JoinToString(separator), Is.EqualTo(expectedOutput));
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using MessageStream2;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayer
{
public class ScreenshotWorker
{
//Height setting
public int screenshotHeight = 720;
//GUI stuff
private bool initialized;
private bool isWindowLocked = false;
public bool workerEnabled;
private GUIStyle windowStyle;
private GUILayoutOption[] windowLayoutOption;
private GUIStyle buttonStyle;
private GUIStyle highlightStyle;
private GUILayoutOption[] fixedButtonSizeOption;
private GUIStyle scrollStyle;
public bool display;
private bool safeDisplay;
private Rect windowRect;
private Rect moveRect;
private Vector2 scrollPos;
//State tracking
public bool screenshotButtonHighlighted;
List<string> highlightedPlayers = new List<string>();
private string selectedPlayer = "";
private string safeSelectedPlayer = "";
private Dictionary<string, Texture2D> screenshots = new Dictionary<string, Texture2D>();
private bool uploadEventHandled = true;
public bool uploadScreenshot = false;
private float lastScreenshotSend;
private Queue<ScreenshotEntry> newScreenshotQueue = new Queue<ScreenshotEntry>();
private Queue<ScreenshotWatchEntry> newScreenshotWatchQueue = new Queue<ScreenshotWatchEntry>();
private Queue<string> newScreenshotNotifiyQueue = new Queue<string>();
private Dictionary<string, string> watchPlayers = new Dictionary<string, string>();
//Screenshot uploading message
private bool displayScreenshotUploadingMessage = false;
public bool finishedUploadingScreenshot = false;
public string downloadingScreenshotFromPlayer;
private float lastScreenshotMessageCheck;
ScreenMessage screenshotUploadMessage;
ScreenMessage screenshotDownloadMessage;
//delay the screenshot message until we've taken a screenshot
public bool screenshotTaken;
//const
private const float MIN_WINDOW_HEIGHT = 200;
private const float MIN_WINDOW_WIDTH = 150;
private const float BUTTON_WIDTH = 150;
private const float SCREENSHOT_MESSAGE_CHECK_INTERVAL = .2f;
private const float MIN_SCREENSHOT_SEND_INTERVAL = 3f;
//Services
private DMPGame dmpGame;
private Settings dmpSettings;
private ChatWorker chatWorker;
private NetworkWorker networkWorker;
private PlayerStatusWorker playerStatusWorker;
private NamedAction updateAction;
private NamedAction drawAction;
public ScreenshotWorker(DMPGame dmpGame, Settings dmpSettings, ChatWorker chatWorker, NetworkWorker networkWorker, PlayerStatusWorker playerStatusWorker)
{
this.dmpGame = dmpGame;
this.dmpSettings = dmpSettings;
this.chatWorker = chatWorker;
this.networkWorker = networkWorker;
this.playerStatusWorker = playerStatusWorker;
updateAction = new NamedAction(Update);
drawAction = new NamedAction(Draw);
dmpGame.updateEvent.Add(updateAction);
dmpGame.drawEvent.Add(drawAction);
}
private void InitGUI()
{
windowRect = new Rect(50, (Screen.height / 2f) - (MIN_WINDOW_HEIGHT / 2f), MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT);
moveRect = new Rect(0, 0, 10000, 20);
windowLayoutOption = new GUILayoutOption[4];
windowLayoutOption[0] = GUILayout.MinWidth(MIN_WINDOW_WIDTH);
windowLayoutOption[1] = GUILayout.MinHeight(MIN_WINDOW_HEIGHT);
windowLayoutOption[2] = GUILayout.ExpandWidth(true);
windowLayoutOption[3] = GUILayout.ExpandHeight(true);
windowStyle = new GUIStyle(GUI.skin.window);
buttonStyle = new GUIStyle(GUI.skin.button);
highlightStyle = new GUIStyle(GUI.skin.button);
highlightStyle.normal.textColor = Color.red;
highlightStyle.active.textColor = Color.red;
highlightStyle.hover.textColor = Color.red;
fixedButtonSizeOption = new GUILayoutOption[2];
fixedButtonSizeOption[0] = GUILayout.Width(BUTTON_WIDTH);
fixedButtonSizeOption[1] = GUILayout.ExpandWidth(true);
scrollStyle = new GUIStyle(GUI.skin.scrollView);
scrollPos = new Vector2(0, 0);
}
private void Update()
{
safeDisplay = display;
if (workerEnabled)
{
while (newScreenshotNotifiyQueue.Count > 0)
{
string notifyPlayer = newScreenshotNotifiyQueue.Dequeue();
if (!display)
{
screenshotButtonHighlighted = true;
}
if (selectedPlayer != notifyPlayer)
{
if (!highlightedPlayers.Contains(notifyPlayer))
{
highlightedPlayers.Add(notifyPlayer);
}
}
chatWorker.QueueChannelMessage("Server", "", notifyPlayer + " shared screenshot");
}
//Update highlights
if (screenshotButtonHighlighted && display)
{
screenshotButtonHighlighted = false;
}
if (highlightedPlayers.Contains(selectedPlayer))
{
highlightedPlayers.Remove(selectedPlayer);
}
while (newScreenshotQueue.Count > 0)
{
ScreenshotEntry se = newScreenshotQueue.Dequeue();
Texture2D screenshotTexture = new Texture2D(4, 4, TextureFormat.RGB24, false, true);
if (screenshotTexture.LoadImage(se.screenshotData))
{
screenshotTexture.Apply();
//Make sure screenshots aren't bigger than 2/3rds of the screen.
ResizeTextureIfNeeded(ref screenshotTexture);
//Save the texture in memory
screenshots[se.fromPlayer] = screenshotTexture;
DarkLog.Debug("Loaded screenshot from " + se.fromPlayer);
}
else
{
DarkLog.Debug("Error loading screenshot from " + se.fromPlayer);
}
}
while (newScreenshotWatchQueue.Count > 0)
{
ScreenshotWatchEntry swe = newScreenshotWatchQueue.Dequeue();
if (swe.watchPlayer != "")
{
watchPlayers[swe.fromPlayer] = swe.watchPlayer;
}
else
{
if (watchPlayers.ContainsKey(swe.fromPlayer))
{
watchPlayers.Remove(swe.fromPlayer);
}
}
}
if (safeSelectedPlayer != selectedPlayer)
{
windowRect.height = 0;
windowRect.width = 0;
safeSelectedPlayer = selectedPlayer;
WatchPlayer(selectedPlayer);
}
if (Input.GetKey(dmpSettings.screenshotKey))
{
uploadEventHandled = false;
}
if (!uploadEventHandled)
{
uploadEventHandled = true;
if ((Client.realtimeSinceStartup - lastScreenshotSend) > MIN_SCREENSHOT_SEND_INTERVAL)
{
lastScreenshotSend = Client.realtimeSinceStartup;
screenshotTaken = false;
finishedUploadingScreenshot = false;
uploadScreenshot = true;
displayScreenshotUploadingMessage = true;
}
}
if ((Client.realtimeSinceStartup - lastScreenshotMessageCheck) > SCREENSHOT_MESSAGE_CHECK_INTERVAL)
{
if (screenshotTaken && displayScreenshotUploadingMessage)
{
lastScreenshotMessageCheck = Client.realtimeSinceStartup;
if (screenshotUploadMessage != null)
{
screenshotUploadMessage.duration = 0f;
}
if (finishedUploadingScreenshot)
{
displayScreenshotUploadingMessage = false;
screenshotUploadMessage = ScreenMessages.PostScreenMessage("Screenshot uploaded!", 2f, ScreenMessageStyle.UPPER_CENTER);
}
else
{
screenshotUploadMessage = ScreenMessages.PostScreenMessage("Uploading screenshot...", 1f, ScreenMessageStyle.UPPER_CENTER);
}
}
if (downloadingScreenshotFromPlayer != null)
{
if (screenshotDownloadMessage != null)
{
screenshotDownloadMessage.duration = 0f;
}
screenshotDownloadMessage = ScreenMessages.PostScreenMessage("Downloading screenshot...", 1f, ScreenMessageStyle.UPPER_CENTER);
}
}
if (downloadingScreenshotFromPlayer == null && screenshotDownloadMessage != null)
{
screenshotDownloadMessage.duration = 0f;
screenshotDownloadMessage = null;
}
}
}
private void ResizeTextureIfNeeded(ref Texture2D screenshotTexture)
{
//Make sure screenshots aren't bigger than 2/3rds of the screen.
int resizeWidth = (int)(Screen.width * .66);
int resizeHeight = (int)(Screen.height * .66);
if (screenshotTexture.width > resizeWidth || screenshotTexture.height > resizeHeight)
{
RenderTexture renderTexture = new RenderTexture(resizeWidth, resizeHeight, 24);
renderTexture.useMipMap = false;
Graphics.Blit(screenshotTexture, renderTexture);
RenderTexture.active = renderTexture;
Texture2D resizeTexture = new Texture2D(resizeWidth, resizeHeight, TextureFormat.RGB24, false);
resizeTexture.ReadPixels(new Rect(0, 0, resizeWidth, resizeHeight), 0, 0);
resizeTexture.Apply();
screenshotTexture = resizeTexture;
RenderTexture.active = null;
}
}
private void Draw()
{
if (safeDisplay)
{
if (!initialized)
{
initialized = true;
InitGUI();
}
windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6710 + Client.WINDOW_OFFSET, windowRect, DrawContent, "Screenshots", windowStyle, windowLayoutOption));
}
CheckWindowLock();
}
private void DrawContent(int windowID)
{
GUI.DragWindow(moveRect);
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
scrollPos = GUILayout.BeginScrollView(scrollPos, scrollStyle, fixedButtonSizeOption);
DrawPlayerButton(dmpSettings.playerName);
foreach (PlayerStatus player in playerStatusWorker.playerStatusList)
{
DrawPlayerButton(player.playerName);
}
GUILayout.EndScrollView();
GUILayout.FlexibleSpace();
GUI.enabled = ((Client.realtimeSinceStartup - lastScreenshotSend) > MIN_SCREENSHOT_SEND_INTERVAL);
if (GUILayout.Button("Upload (" + dmpSettings.screenshotKey.ToString() + ")", buttonStyle))
{
uploadEventHandled = false;
}
GUI.enabled = true;
GUILayout.EndVertical();
if (safeSelectedPlayer != "")
{
if (screenshots.ContainsKey(safeSelectedPlayer))
{
GUILayout.Box(screenshots[safeSelectedPlayer]);
}
}
GUILayout.EndHorizontal();
}
private void CheckWindowLock()
{
if (!dmpGame.running)
{
RemoveWindowLock();
return;
}
if (HighLogic.LoadedSceneIsFlight)
{
RemoveWindowLock();
return;
}
if (safeDisplay)
{
Vector2 mousePos = Input.mousePosition;
mousePos.y = Screen.height - mousePos.y;
bool shouldLock = windowRect.Contains(mousePos);
if (shouldLock && !isWindowLocked)
{
InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, "DMP_ScreenshotLock");
isWindowLocked = true;
}
if (!shouldLock && isWindowLocked)
{
RemoveWindowLock();
}
}
if (!safeDisplay && isWindowLocked)
{
RemoveWindowLock();
}
}
private void RemoveWindowLock()
{
if (isWindowLocked)
{
isWindowLocked = false;
InputLockManager.RemoveControlLock("DMP_ScreenshotLock");
}
}
private void DrawPlayerButton(string playerName)
{
GUIStyle playerButtonStyle = buttonStyle;
if (highlightedPlayers.Contains(playerName))
{
playerButtonStyle = highlightStyle;
}
bool newValue = GUILayout.Toggle(safeSelectedPlayer == playerName, playerName, playerButtonStyle);
if (newValue && (safeSelectedPlayer != playerName))
{
selectedPlayer = playerName;
}
if (!newValue && (safeSelectedPlayer == playerName))
{
selectedPlayer = "";
}
}
private void WatchPlayer(string playerName)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ScreenshotMessageType.WATCH);
mw.Write<string>(dmpSettings.playerName);
mw.Write<string>(playerName);
networkWorker.SendScreenshotMessage(mw.GetMessageBytes());
}
}
//Called from main due to WaitForEndOfFrame timing.
public void SendScreenshot()
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ScreenshotMessageType.SCREENSHOT);
mw.Write<string>(dmpSettings.playerName);
mw.Write<byte[]>(GetScreenshotBytes());
networkWorker.SendScreenshotMessage(mw.GetMessageBytes());
}
}
//Adapted from KMP.
private byte[] GetScreenshotBytes()
{
int screenshotWidth = (int)(Screen.width * (screenshotHeight / (float)Screen.height));
//Read the screen pixels into a texture
Texture2D fullScreenTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
fullScreenTexture.filterMode = FilterMode.Bilinear;
fullScreenTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
fullScreenTexture.Apply();
RenderTexture renderTexture = new RenderTexture(screenshotWidth, screenshotHeight, 24);
renderTexture.useMipMap = false;
Graphics.Blit(fullScreenTexture, renderTexture); //Blit the screen texture to a render texture
RenderTexture.active = renderTexture;
//Read the pixels from the render texture into a Texture2D
Texture2D resizedTexture = new Texture2D(screenshotWidth, screenshotHeight, TextureFormat.RGB24, false);
Texture2D ourTexture = new Texture2D(screenshotWidth, screenshotHeight, TextureFormat.RGB24, false);
resizedTexture.ReadPixels(new Rect(0, 0, screenshotWidth, screenshotHeight), 0, 0);
resizedTexture.Apply();
//Save a copy locally in case we need to resize it.
ourTexture.ReadPixels(new Rect(0, 0, screenshotWidth, screenshotHeight), 0, 0);
ourTexture.Apply();
ResizeTextureIfNeeded(ref ourTexture);
//Save our texture in memory.
screenshots[dmpSettings.playerName] = ourTexture;
RenderTexture.active = null;
return resizedTexture.EncodeToPNG();
}
public void QueueNewScreenshot(string fromPlayer, byte[] screenshotData)
{
downloadingScreenshotFromPlayer = null;
ScreenshotEntry se = new ScreenshotEntry();
se.fromPlayer = fromPlayer;
se.screenshotData = screenshotData;
newScreenshotQueue.Enqueue(se);
}
public void QueueNewScreenshotWatch(string fromPlayer, string watchPlayer)
{
ScreenshotWatchEntry swe = new ScreenshotWatchEntry();
swe.fromPlayer = fromPlayer;
swe.watchPlayer = watchPlayer;
newScreenshotWatchQueue.Enqueue(swe);
}
public void QueueNewNotify(string fromPlayer)
{
newScreenshotNotifiyQueue.Enqueue(fromPlayer);
}
public void Stop()
{
workerEnabled = false;
RemoveWindowLock();
dmpGame.updateEvent.Remove(updateAction);
dmpGame.drawEvent.Remove(drawAction);
}
}
}
class ScreenshotEntry
{
public string fromPlayer;
public byte[] screenshotData;
}
class ScreenshotWatchEntry
{
public string fromPlayer;
public string watchPlayer;
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The base class for the */content commands
/// </summary>
public class ContentCommandBase : CoreCommandWithCredentialsBase, IDisposable
{
#region Parameters
/// <summary>
/// Gets or sets the path parameter to the command
/// </summary>
[Parameter(Position = 0, ParameterSetName = "Path",
Mandatory = true, ValueFromPipelineByPropertyName = true)]
public string[] Path { get; set; }
/// <summary>
/// Gets or sets the literal path parameter to the command
/// </summary>
[Parameter(ParameterSetName = "LiteralPath",
Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)]
[Alias("PSPath")]
public string[] LiteralPath
{
get { return Path; }
set
{
base.SuppressWildcardExpansion = true;
Path = value;
}
}
/// <summary>
/// Gets or sets the filter property
/// </summary>
[Parameter]
public override string Filter
{
get { return base.Filter; }
set { base.Filter = value; }
}
/// <summary>
/// Gets or sets the include property
/// </summary>
[Parameter]
public override string[] Include
{
get { return base.Include; }
set { base.Include = value; }
}
/// <summary>
/// Gets or sets the exclude property
/// </summary>
[Parameter]
public override string[] Exclude
{
get { return base.Exclude; }
set { base.Exclude = value; }
}
/// <summary>
/// Gets or sets the force property
/// </summary>
///
/// <remarks>
/// Gives the provider guidance on how vigorous it should be about performing
/// the operation. If true, the provider should do everything possible to perform
/// the operation. If false, the provider should attempt the operation but allow
/// even simple errors to terminate the operation.
/// For example, if the user tries to copy a file to a path that already exists and
/// the destination is read-only, if force is true, the provider should copy over
/// the existing read-only file. If force is false, the provider should write an error.
/// </remarks>
///
[Parameter]
public override SwitchParameter Force
{
get { return base.Force; }
set { base.Force = value; }
}
#endregion Parameters
#region parameter data
#endregion parameter data
#region protected members
/// <summary>
/// An array of content holder objects that contain the path information
/// and content readers/writers for the item represented by the path information.
/// </summary>
///
internal List<ContentHolder> contentStreams = new List<ContentHolder>();
/// <summary>
/// Wraps the content into a PSObject and adds context information as notes
/// </summary>
///
/// <param name="content">
/// The content being written out.
/// </param>
///
/// <param name="readCount">
/// The number of blocks that have been read so far.
/// </param>
///
/// <param name="pathInfo">
/// The context the content was retrieved from.
/// </param>
///
/// <param name="context">
/// The context the command is being run under.
/// </param>
///
internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context)
{
Dbg.Diagnostics.Assert(
content != null,
"The caller should verify the content.");
Dbg.Diagnostics.Assert(
pathInfo != null,
"The caller should verify the pathInfo.");
Dbg.Diagnostics.Assert(
context != null,
"The caller should verify the context.");
PSObject result = PSObject.AsPSObject(content);
Dbg.Diagnostics.Assert(
result != null,
"A PSObject should always be constructed.");
// Use the cached notes if the cache exists and the path is still the same
PSNoteProperty note;
if (_currentContentItem != null &&
((_currentContentItem.PathInfo == pathInfo) ||
(
String.Compare(
pathInfo.Path,
_currentContentItem.PathInfo.Path,
StringComparison.OrdinalIgnoreCase) == 0)
)
)
{
result = _currentContentItem.AttachNotes(result);
}
else
{
// Generate a new cache item and cache the notes
_currentContentItem = new ContentPathsCache(pathInfo);
// Construct a provider qualified path as the Path note
string psPath = pathInfo.Path;
note = new PSNoteProperty("PSPath", psPath);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath);
_currentContentItem.PSPath = psPath;
try
{
// Now get the parent path and child name
string parentPath = null;
if (pathInfo.Drive != null)
{
parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context);
}
else
{
parentPath = SessionState.Path.ParseParent(pathInfo.Path, String.Empty, context);
}
note = new PSNoteProperty("PSParentPath", parentPath);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath);
_currentContentItem.ParentPath = parentPath;
// Get the child name
string childName = SessionState.Path.ParseChildName(pathInfo.Path, context);
note = new PSNoteProperty("PSChildName", childName);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName);
_currentContentItem.ChildName = childName;
}
catch (NotSupportedException)
{
// Ignore. The object just won't have ParentPath or ChildName set.
}
// PSDriveInfo
if (pathInfo.Drive != null)
{
PSDriveInfo drive = pathInfo.Drive;
note = new PSNoteProperty("PSDrive", drive);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive);
_currentContentItem.Drive = drive;
}
// ProviderInfo
ProviderInfo provider = pathInfo.Provider;
note = new PSNoteProperty("PSProvider", provider);
result.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider);
_currentContentItem.Provider = provider;
}
// Add the ReadCount note
note = new PSNoteProperty("ReadCount", readCount);
result.Properties.Add(note, true);
WriteObject(result);
} // WriteContentObject
/// <summary>
/// A cache of the notes that get added to the content items as they are written
/// to the pipeline.
/// </summary>
private ContentPathsCache _currentContentItem;
/// <summary>
/// A class that stores a cache of the notes that get attached to content items
/// as they get written to the pipeline. An instance of this cache class is
/// only valid for a single path.
/// </summary>
internal class ContentPathsCache
{
/// <summary>
/// Constructs a content cache item.
/// </summary>
///
/// <param name="pathInfo">
/// The path information for which the cache will be bound.
/// </param>
///
public ContentPathsCache(PathInfo pathInfo)
{
PathInfo = pathInfo;
}
/// <summary>
/// The path information for the cached item.
/// </summary>
///
public PathInfo PathInfo { get; }
/// <summary>
/// The cached PSPath of the item.
/// </summary>
///
public String PSPath { get; set; }
/// <summary>
/// The cached parent path of the item.
/// </summary>
///
public String ParentPath { get; set; }
/// <summary>
/// The cached drive for the item.
/// </summary>
///
public PSDriveInfo Drive { get; set; }
/// <summary>
/// The cached provider of the item.
/// </summary>
///
public ProviderInfo Provider { get; set; }
/// <summary>
/// The cached child name of the item.
/// </summary>
///
public String ChildName { get; set; }
/// <summary>
/// Attaches the cached notes to the specified PSObject.
/// </summary>
///
/// <param name="content">
/// The PSObject to attached the cached notes to.
/// </param>
///
/// <returns>
/// The PSObject that was passed in with the cached notes added.
/// </returns>
///
public PSObject AttachNotes(PSObject content)
{
// Construct a provider qualified path as the Path note
PSNoteProperty note = new PSNoteProperty("PSPath", PSPath);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSPath", PSPath);
// Now attach the parent path and child name
note = new PSNoteProperty("PSParentPath", ParentPath);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", ParentPath);
// Attach the child name
note = new PSNoteProperty("PSChildName", ChildName);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSChildName", ChildName);
// PSDriveInfo
if (PathInfo.Drive != null)
{
note = new PSNoteProperty("PSDrive", Drive);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSDrive", Drive);
}
// ProviderInfo
note = new PSNoteProperty("PSProvider", Provider);
content.Properties.Add(note, true);
tracer.WriteLine("Attaching {0} = {1}", "PSProvider", Provider);
return content;
} // AttachNotes
} // ContentPathsCache
/// <summary>
/// A struct to hold the path information and the content readers/writers
/// for an item.
/// </summary>
///
internal struct ContentHolder
{
internal ContentHolder(
PathInfo pathInfo,
IContentReader reader,
IContentWriter writer)
{
if (pathInfo == null)
{
throw PSTraceSource.NewArgumentNullException("pathInfo");
}
PathInfo = pathInfo;
Reader = reader;
Writer = writer;
} // constructor
internal PathInfo PathInfo { get; }
internal IContentReader Reader { get; }
internal IContentWriter Writer { get; }
} // struct ContentHolder
/// <summary>
/// Closes the content readers and writers in the content holder array
/// </summary>
internal void CloseContent(List<ContentHolder> contentHolders, bool disposing)
{
if (contentHolders == null)
{
throw PSTraceSource.NewArgumentNullException("contentHolders");
}
foreach (ContentHolder holder in contentHolders)
{
try
{
if (holder.Writer != null)
{
holder.Writer.Close();
}
}
catch (Exception e) // Catch-all OK. 3rd party callout
{
CommandsCommon.CheckForSevereException(this, e);
// Catch all the exceptions caused by closing the writer
// and write out an error.
ProviderInvocationException providerException =
new ProviderInvocationException(
"ProviderContentCloseError",
SessionStateStrings.ProviderContentCloseError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
if (!disposing)
{
WriteError(
new ErrorRecord(
providerException.ErrorRecord,
providerException));
}
}
try
{
if (holder.Reader != null)
{
holder.Reader.Close();
}
}
catch (Exception e) // Catch-all OK. 3rd party callout
{
CommandsCommon.CheckForSevereException(this, e);
// Catch all the exceptions caused by closing the writer
// and write out an error.
ProviderInvocationException providerException =
new ProviderInvocationException(
"ProviderContentCloseError",
SessionStateStrings.ProviderContentCloseError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
if (!disposing)
{
WriteError(
new ErrorRecord(
providerException.ErrorRecord,
providerException));
}
}
}
} // CloseContent
/// <summary>
/// Overridden by derived classes to support ShouldProcess with
/// the appropriate information.
/// </summary>
///
/// <param name="path">
/// The path to the item from which the content writer will be
/// retrieved.
/// </param>
///
/// <returns>
/// True if the action should continue or false otherwise.
/// </returns>
///
internal virtual bool CallShouldProcess(string path)
{
return true;
}
/// <summary>
/// Gets the IContentReaders for the current path(s)
/// </summary>
///
/// <returns>
/// An array of IContentReaders for the current path(s)
/// </returns>
///
internal List<ContentHolder> GetContentReaders(
string[] readerPaths,
CmdletProviderContext currentCommandContext)
{
// Resolve all the paths into PathInfo objects
Collection<PathInfo> pathInfos = ResolvePaths(readerPaths, false, true, currentCommandContext);
// Create the results array
List<ContentHolder> results = new List<ContentHolder>();
foreach (PathInfo pathInfo in pathInfos)
{
// For each path, get the content writer
Collection<IContentReader> readers = null;
try
{
string pathToProcess = WildcardPattern.Escape(pathInfo.Path);
if (currentCommandContext.SuppressWildcardExpansion)
{
pathToProcess = pathInfo.Path;
}
readers =
InvokeProvider.Content.GetReader(pathToProcess, currentCommandContext);
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
continue;
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
continue;
}
if (readers != null && readers.Count > 0)
{
if (readers.Count == 1 && readers[0] != null)
{
ContentHolder holder =
new ContentHolder(pathInfo, readers[0], null);
results.Add(holder);
}
}
} // foreach pathInfo in pathInfos
return results;
} // GetContentReaders
/// <summary>
/// Resolves the specified paths to PathInfo objects
/// </summary>
///
/// <param name="pathsToResolve">
/// The paths to be resolved. Each path may contain glob characters.
/// </param>
///
/// <param name="allowNonexistingPaths">
/// If true, resolves the path even if it doesn't exist.
/// </param>
///
/// <param name="allowEmptyResult">
/// If true, allows a wildcard that returns no results.
/// </param>
///
/// <param name="currentCommandContext">
/// The context under which the command is running.
/// </param>
///
/// <returns>
/// An array of PathInfo objects that are the resolved paths for the
/// <paramref name="pathsToResolve"/> parameter.
/// </returns>
///
internal Collection<PathInfo> ResolvePaths(
string[] pathsToResolve,
bool allowNonexistingPaths,
bool allowEmptyResult,
CmdletProviderContext currentCommandContext)
{
Collection<PathInfo> results = new Collection<PathInfo>();
foreach (string path in pathsToResolve)
{
bool pathNotFound = false;
bool filtersHidPath = false;
ErrorRecord pathNotFoundErrorRecord = null;
try
{
// First resolve each of the paths
Collection<PathInfo> pathInfos =
SessionState.Path.GetResolvedPSPathFromPSPath(
path,
currentCommandContext);
if (pathInfos.Count == 0)
{
pathNotFound = true;
// If the item simply did not exist,
// we would have got an ItemNotFoundException.
// If we get here, it's because the filters
// excluded the file.
if (!currentCommandContext.SuppressWildcardExpansion)
{
filtersHidPath = true;
}
}
foreach (PathInfo pathInfo in pathInfos)
{
results.Add(pathInfo);
}
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
}
catch (DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
}
catch (ItemNotFoundException pathNotFoundException)
{
pathNotFound = true;
pathNotFoundErrorRecord = new ErrorRecord(pathNotFoundException.ErrorRecord, pathNotFoundException);
}
if (pathNotFound)
{
if (allowNonexistingPaths &&
(!filtersHidPath) &&
(currentCommandContext.SuppressWildcardExpansion ||
(!WildcardPattern.ContainsWildcardCharacters(path))))
{
ProviderInfo provider = null;
PSDriveInfo drive = null;
string unresolvedPath =
SessionState.Path.GetUnresolvedProviderPathFromPSPath(
path,
currentCommandContext,
out provider,
out drive);
PathInfo pathInfo =
new PathInfo(
drive,
provider,
unresolvedPath,
SessionState);
results.Add(pathInfo);
}
else
{
if (pathNotFoundErrorRecord == null)
{
// Detect if the path resolution failed to resolve to a file.
String error = StringUtil.Format(NavigationResources.ItemNotFound, Path);
Exception e = new Exception(error);
pathNotFoundErrorRecord = new ErrorRecord(
e,
"ItemNotFound",
ErrorCategory.ObjectNotFound,
Path);
}
WriteError(pathNotFoundErrorRecord);
}
}
}
return results;
} // ResolvePaths
#endregion protected members
#region IDisposable
internal void Dispose(bool isDisposing)
{
if (isDisposing)
{
CloseContent(contentStreams, true);
contentStreams = new List<ContentHolder>();
}
}
/// <summary>
/// Dispose method in IDisposeable
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Finalizer
/// </summary>
~ContentCommandBase()
{
Dispose(false);
}
#endregion IDisposable
} // ContentCommandBase
} // namespace Microsoft.PowerShell.Commands
| |
//==============================================================================
// Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott.
// K Weiner 12/00
//==============================================================================
using System;
using System.IO;
namespace GifEncoder
{
public class LZWEncoder
{
private static readonly int EOF = -1;
private int imgW, imgH;
private byte[] pixAry;
private int initCodeSize;
private int remaining;
private int curPixel;
// GIFCOMPR.C - GIF Image compression routines
//
// Lempel-Ziv compression based on 'compress'. GIF modifications by
// David Rowley (mgardi@watdcsu.waterloo.edu)
// General DEFINEs
static readonly int BITS = 12;
static readonly int HSIZE = 5003; // 80% occupancy
// GIF Image compression - modified 'compress'
//
// Based on: compress.c - File compression ala IEEE Computer, June 1984.
//
// By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
// Jim McKie (decvax!mcvax!jim)
// Steve Davies (decvax!vax135!petsd!peora!srd)
// Ken Turkowski (decvax!decwrl!turtlevax!ken)
// James A. Woods (decvax!ihnp4!ames!jaw)
// Joe Orost (decvax!vax135!petsd!joe)
int n_bits; // number of bits/code
int maxbits = BITS; // user settable max # bits/code
int maxcode; // maximum code, given n_bits
int maxmaxcode = 1 << BITS; // should NEVER generate this code
int[] htab = new int[HSIZE];
int[] codetab = new int[HSIZE];
int hsize = HSIZE; // for dynamic table sizing
int free_ent = 0; // first unused entry
// block compression parameters -- after all codes are used up,
// and compression rate changes, start over.
bool clear_flg = false;
// Algorithm: use open addressing double hashing (no chaining) on the
// prefix code / next character combination. We do a variant of Knuth's
// algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
// secondary probe. Here, the modular division first probe is gives way
// to a faster exclusive-or manipulation. Also do block compression with
// an adaptive reset, whereby the code table is cleared when the compression
// ratio decreases, but after the table fills. The variable-length output
// codes are re-sized at this point, and a special CLEAR code is generated
// for the decompressor. Late addition: construct the table according to
// file size for noticeable speed improvement on small files. Please direct
// questions about this implementation to ames!jaw.
int g_init_bits;
int ClearCode;
int EOFCode;
// output
//
// Output the given code.
// Inputs:
// code: A n_bits-bit integer. If == -1, then EOF. This assumes
// that n_bits =< wordsize - 1.
// Outputs:
// Outputs code to the file.
// Assumptions:
// Chars are 8 bits long.
// Algorithm:
// Maintain a BITS character long buffer (so that 8 codes will
// fit in it exactly). Use the VAX insv instruction to insert each
// code in turn. When the buffer fills up empty it and start over.
int cur_accum = 0;
int cur_bits = 0;
int [] masks =
{
0x0000,
0x0001,
0x0003,
0x0007,
0x000F,
0x001F,
0x003F,
0x007F,
0x00FF,
0x01FF,
0x03FF,
0x07FF,
0x0FFF,
0x1FFF,
0x3FFF,
0x7FFF,
0xFFFF };
// Number of characters so far in this 'packet'
int a_count;
// Define the storage for the packet accumulator
byte[] accum = new byte[256];
//----------------------------------------------------------------------------
public LZWEncoder(int width, int height, byte[] pixels, int color_depth)
{
imgW = width;
imgH = height;
pixAry = pixels;
initCodeSize = Math.Max(2, color_depth);
}
// Add a character to the end of the current packet, and if it is 254
// characters, flush the packet to disk.
void Add(byte c, Stream outs)
{
accum[a_count++] = c;
if (a_count >= 254)
Flush(outs);
}
// Clear out the hash table
// table clear for block compress
void ClearTable(Stream outs)
{
ResetCodeTable(hsize);
free_ent = ClearCode + 2;
clear_flg = true;
Output(ClearCode, outs);
}
// reset code table
void ResetCodeTable(int hsize)
{
for (int i = 0; i < hsize; ++i)
htab[i] = -1;
}
void Compress(int init_bits, Stream outs)
{
int fcode;
int i /* = 0 */;
int c;
int ent;
int disp;
int hsize_reg;
int hshift;
// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;
// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MaxCode(n_bits);
ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;
a_count = 0; // clear packet
ent = NextPixel();
hshift = 0;
for (fcode = hsize; fcode < 65536; fcode *= 2)
++hshift;
hshift = 8 - hshift; // set hash code range bound
hsize_reg = hsize;
ResetCodeTable(hsize_reg); // clear hash table
Output(ClearCode, outs);
outer_loop : while ((c = NextPixel()) != EOF)
{
fcode = (c << maxbits) + ent;
i = (c << hshift) ^ ent; // xor hashing
if (htab[i] == fcode)
{
ent = codetab[i];
continue;
}
else if (htab[i] >= 0) // non-empty slot
{
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i == 0)
disp = 1;
do
{
if ((i -= disp) < 0)
i += hsize_reg;
if (htab[i] == fcode)
{
ent = codetab[i];
goto outer_loop;
}
} while (htab[i] >= 0);
}
Output(ent, outs);
ent = c;
if (free_ent < maxmaxcode)
{
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
}
else
ClearTable(outs);
}
// Put out the final code.
Output(ent, outs);
Output(EOFCode, outs);
}
//----------------------------------------------------------------------------
public void Encode( Stream os)
{
os.WriteByte( Convert.ToByte( initCodeSize) ); // write "initial code size" byte
remaining = imgW * imgH; // reset navigation variables
curPixel = 0;
Compress(initCodeSize + 1, os); // compress and write the pixel data
os.WriteByte(0); // write block terminator
}
// Flush the packet to disk, and reset the accumulator
void Flush(Stream outs)
{
if (a_count > 0)
{
outs.WriteByte( Convert.ToByte( a_count ));
outs.Write(accum, 0, a_count);
a_count = 0;
}
}
int MaxCode(int n_bits)
{
return (1 << n_bits) - 1;
}
//----------------------------------------------------------------------------
// Return the next pixel from the image
//----------------------------------------------------------------------------
private int NextPixel()
{
if (remaining == 0)
return EOF;
--remaining;
int temp = curPixel + 1;
if ( temp < pixAry.GetUpperBound( 0 ))
{
byte pix = pixAry[curPixel++];
return pix & 0xff;
}
return 0xff;
}
void Output(int code, Stream outs)
{
cur_accum &= masks[cur_bits];
if (cur_bits > 0)
cur_accum |= (code << cur_bits);
else
cur_accum = code;
cur_bits += n_bits;
while (cur_bits >= 8)
{
Add((byte) (cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if (free_ent > maxcode || clear_flg)
{
if (clear_flg)
{
maxcode = MaxCode(n_bits = g_init_bits);
clear_flg = false;
}
else
{
++n_bits;
if (n_bits == maxbits)
maxcode = maxmaxcode;
else
maxcode = MaxCode(n_bits);
}
}
if (code == EOFCode)
{
// At EOF, write the rest of the buffer.
while (cur_bits > 0)
{
Add((byte) (cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
Flush(outs);
}
}
}
}
| |
using System;
using System.IO;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
namespace LibGit2Sharp.Tests
{
public class StageFixture : BaseFixture
{
[Theory]
[InlineData("1/branch_file.txt", FileStatus.Unaltered, true, FileStatus.Unaltered, true, 0)]
[InlineData("README", FileStatus.Unaltered, true, FileStatus.Unaltered, true, 0)]
[InlineData("deleted_unstaged_file.txt", FileStatus.Missing, true, FileStatus.Removed, false, -1)]
[InlineData("modified_unstaged_file.txt", FileStatus.Modified, true, FileStatus.Staged, true, 0)]
[InlineData("new_untracked_file.txt", FileStatus.Untracked, false, FileStatus.Added, true, 1)]
[InlineData("modified_staged_file.txt", FileStatus.Staged, true, FileStatus.Staged, true, 0)]
[InlineData("new_tracked_file.txt", FileStatus.Added, true, FileStatus.Added, true, 0)]
public void CanStage(string relativePath, FileStatus currentStatus, bool doesCurrentlyExistInTheIndex, FileStatus expectedStatusOnceStaged, bool doesExistInTheIndexOnceStaged, int expectedIndexCountVariation)
{
string path = CloneStandardTestRepo();
using (var repo = new Repository(path))
{
int count = repo.Index.Count;
Assert.Equal(doesCurrentlyExistInTheIndex, (repo.Index[relativePath] != null));
Assert.Equal(currentStatus, repo.Index.RetrieveStatus(relativePath));
repo.Index.Stage(relativePath);
Assert.Equal(count + expectedIndexCountVariation, repo.Index.Count);
Assert.Equal(doesExistInTheIndexOnceStaged, (repo.Index[relativePath] != null));
Assert.Equal(expectedStatusOnceStaged, repo.Index.RetrieveStatus(relativePath));
}
}
[Fact]
public void CanStageTheUpdationOfAStagedFile()
{
string path = CloneStandardTestRepo();
using (var repo = new Repository(path))
{
int count = repo.Index.Count;
const string filename = "new_tracked_file.txt";
IndexEntry blob = repo.Index[filename];
Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(filename));
Touch(repo.Info.WorkingDirectory, filename, "brand new content");
Assert.Equal(FileStatus.Added | FileStatus.Modified, repo.Index.RetrieveStatus(filename));
repo.Index.Stage(filename);
IndexEntry newBlob = repo.Index[filename];
Assert.Equal(count, repo.Index.Count);
Assert.NotEqual(newBlob.Id, blob.Id);
Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(filename));
}
}
[Theory]
[InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)]
[InlineData("deleted_staged_file.txt", FileStatus.Removed)]
public void StagingAnUnknownFileThrowsIfExplicitPath(string relativePath, FileStatus status)
{
using (var repo = new Repository(StandardTestRepoPath))
{
Assert.Null(repo.Index[relativePath]);
Assert.Equal(status, repo.Index.RetrieveStatus(relativePath));
Assert.Throws<UnmatchedPathException>(() => repo.Index.Stage(relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions() }));
}
}
[Theory]
[InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)]
[InlineData("deleted_staged_file.txt", FileStatus.Removed)]
public void CanStageAnUnknownFileWithLaxUnmatchedExplicitPathsValidation(string relativePath, FileStatus status)
{
using (var repo = new Repository(StandardTestRepoPath))
{
Assert.Null(repo.Index[relativePath]);
Assert.Equal(status, repo.Index.RetrieveStatus(relativePath));
Assert.DoesNotThrow(() => repo.Index.Stage(relativePath));
Assert.DoesNotThrow(() => repo.Index.Stage(relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions { ShouldFailOnUnmatchedPath = false } }));
Assert.Equal(status, repo.Index.RetrieveStatus(relativePath));
}
}
[Theory]
[InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)]
[InlineData("deleted_staged_file.txt", FileStatus.Removed)]
public void StagingAnUnknownFileWithLaxExplicitPathsValidationDoesntThrow(string relativePath, FileStatus status)
{
using (var repo = new Repository(StandardTestRepoPath))
{
Assert.Null(repo.Index[relativePath]);
Assert.Equal(status, repo.Index.RetrieveStatus(relativePath));
repo.Index.Stage(relativePath);
repo.Index.Stage(relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions { ShouldFailOnUnmatchedPath = false } });
}
}
[Fact]
public void CanStageTheRemovalOfAStagedFile()
{
string path = CloneStandardTestRepo();
using (var repo = new Repository(path))
{
int count = repo.Index.Count;
const string filename = "new_tracked_file.txt";
Assert.NotNull(repo.Index[filename]);
Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(filename));
File.Delete(Path.Combine(repo.Info.WorkingDirectory, filename));
Assert.Equal(FileStatus.Added | FileStatus.Missing, repo.Index.RetrieveStatus(filename));
repo.Index.Stage(filename);
Assert.Null(repo.Index[filename]);
Assert.Equal(count - 1, repo.Index.Count);
Assert.Equal(FileStatus.Nonexistent, repo.Index.RetrieveStatus(filename));
}
}
[Theory]
[InlineData("unit_test.txt")]
[InlineData("!unit_test.txt")]
[InlineData("!bang/unit_test.txt")]
public void CanStageANewFileInAPersistentManner(string filename)
{
string path = CloneStandardTestRepo();
using (var repo = new Repository(path))
{
Assert.Equal(FileStatus.Nonexistent, repo.Index.RetrieveStatus(filename));
Assert.Null(repo.Index[filename]);
Touch(repo.Info.WorkingDirectory, filename, "some contents");
Assert.Equal(FileStatus.Untracked, repo.Index.RetrieveStatus(filename));
Assert.Null(repo.Index[filename]);
repo.Index.Stage(filename);
Assert.NotNull(repo.Index[filename]);
Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(filename));
}
using (var repo = new Repository(path))
{
Assert.NotNull(repo.Index[filename]);
Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(filename));
}
}
[SkippableTheory]
[InlineData(false)]
[InlineData(true)]
public void CanStageANewFileWithAFullPath(bool ignorecase)
{
// Skipping due to ignorecase issue in libgit2.
// See: https://github.com/libgit2/libgit2/pull/1689.
InconclusiveIf(() => ignorecase,
"Skipping 'ignorecase = true' test due to ignorecase issue in libgit2.");
//InconclusiveIf(() => IsFileSystemCaseSensitive && ignorecase,
// "Skipping 'ignorecase = true' test on case-sensitive file system.");
string path = CloneStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Config.Set("core.ignorecase", ignorecase);
}
using (var repo = new Repository(path))
{
const string filename = "new_untracked_file.txt";
string fullPath = Path.Combine(repo.Info.WorkingDirectory, filename);
Assert.True(File.Exists(fullPath));
AssertStage(null, repo, fullPath);
AssertStage(ignorecase, repo, fullPath.ToUpperInvariant());
AssertStage(ignorecase, repo, fullPath.ToLowerInvariant());
}
}
private static void AssertStage(bool? ignorecase, IRepository repo, string path)
{
try
{
repo.Index.Stage(path);
Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(path));
repo.Reset();
Assert.Equal(FileStatus.Untracked, repo.Index.RetrieveStatus(path));
}
catch (ArgumentException)
{
Assert.False(ignorecase ?? true);
}
}
[Fact]
public void CanStageANewFileWithARelativePathContainingNativeDirectorySeparatorCharacters()
{
string path = CloneStandardTestRepo();
using (var repo = new Repository(path))
{
int count = repo.Index.Count;
string file = Path.Combine("Project", "a_file.txt");
Touch(repo.Info.WorkingDirectory, file, "With backward slash on Windows!");
repo.Index.Stage(file);
Assert.Equal(count + 1, repo.Index.Count);
const string posixifiedPath = "Project/a_file.txt";
Assert.NotNull(repo.Index[posixifiedPath]);
Assert.Equal(file, repo.Index[posixifiedPath].Path);
}
}
[Fact]
public void StagingANewFileWithAFullPathWhichEscapesOutOfTheWorkingDirThrows()
{
SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
string path = CloneStandardTestRepo();
using (var repo = new Repository(path))
{
string fullPath = Touch(scd.RootedDirectoryPath, "unit_test.txt", "some contents");
Assert.Throws<ArgumentException>(() => repo.Index.Stage(fullPath));
}
}
[Fact]
public void StagingFileWithBadParamsThrows()
{
using (var repo = new Repository(StandardTestRepoPath))
{
Assert.Throws<ArgumentException>(() => repo.Index.Stage(string.Empty));
Assert.Throws<ArgumentNullException>(() => repo.Index.Stage((string)null));
Assert.Throws<ArgumentException>(() => repo.Index.Stage(new string[] { }));
Assert.Throws<ArgumentException>(() => repo.Index.Stage(new string[] { null }));
}
}
/*
* $ git status -s
* M 1/branch_file.txt
* M README
* M branch_file.txt
* D deleted_staged_file.txt
* D deleted_unstaged_file.txt
* M modified_staged_file.txt
* M modified_unstaged_file.txt
* M new.txt
* A new_tracked_file.txt
* ?? new_untracked_file.txt
*
* By passing "*" to Stage, the following files will be added/removed/updated from the index:
* - deleted_unstaged_file.txt : removed
* - modified_unstaged_file.txt : updated
* - new_untracked_file.txt : added
*/
[Theory]
[InlineData("*u*", 0)]
[InlineData("*", 0)]
[InlineData("1/*", 0)]
[InlineData("RE*", 0)]
[InlineData("d*", -1)]
[InlineData("*modified_unstaged*", 0)]
[InlineData("new_*file.txt", 1)]
public void CanStageWithPathspec(string relativePath, int expectedIndexCountVariation)
{
using (var repo = new Repository(CloneStandardTestRepo()))
{
int count = repo.Index.Count;
repo.Index.Stage(relativePath);
Assert.Equal(count + expectedIndexCountVariation, repo.Index.Count);
}
}
[Fact]
public void CanStageWithMultiplePathspecs()
{
using (var repo = new Repository(CloneStandardTestRepo()))
{
int count = repo.Index.Count;
repo.Index.Stage(new string[] { "*", "u*" });
Assert.Equal(count, repo.Index.Count); // 1 added file, 1 deleted file, so same count
}
}
[Theory]
[InlineData("ignored_file.txt")]
[InlineData("ignored_folder/file.txt")]
public void CanIgnoreIgnoredPaths(string path)
{
using (var repo = new Repository(CloneStandardTestRepo()))
{
Touch(repo.Info.WorkingDirectory, ".gitignore", "ignored_file.txt\nignored_folder/\n");
Touch(repo.Info.WorkingDirectory, path, "This file is ignored.");
Assert.Equal(FileStatus.Ignored, repo.Index.RetrieveStatus(path));
repo.Index.Stage("*");
Assert.Equal(FileStatus.Ignored, repo.Index.RetrieveStatus(path));
}
}
[Theory]
[InlineData("ignored_file.txt")]
[InlineData("ignored_folder/file.txt")]
public void CanStageIgnoredPaths(string path)
{
using (var repo = new Repository(CloneStandardTestRepo()))
{
Touch(repo.Info.WorkingDirectory, ".gitignore", "ignored_file.txt\nignored_folder/\n");
Touch(repo.Info.WorkingDirectory, path, "This file is ignored.");
Assert.Equal(FileStatus.Ignored, repo.Index.RetrieveStatus(path));
repo.Index.Stage(path, new StageOptions { IncludeIgnored = true });
Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(path));
}
}
}
}
/* This is extra329 */
| |
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections.Generic;
namespace Rewired.Integration.UnityUI {
[AddComponentMenu("Event/Rewired Standalone Input Module")]
public class RewiredStandaloneInputModule : PointerInputModule {
#region Rewired Variables
[SerializeField]
private bool useAllRewiredGamePlayers = false;
[SerializeField]
private bool useRewiredSystemPlayer = false;
[SerializeField]
private int[] rewiredPlayerIds = new int[1] { 0 };
[SerializeField]
private bool moveOneElementPerAxisPress;
private Rewired.Player[] players;
private Rewired.Mouse mouse;
private bool recompiling;
#endregion
private float m_NextAction;
private Vector2 m_LastMousePosition;
private Vector2 m_MousePosition;
protected RewiredStandaloneInputModule() { }
[SerializeField]
private string m_HorizontalAxis = "Horizontal";
/// <summary>
/// Name of the vertical axis for movement (if axis events are used).
/// </summary>
[SerializeField]
private string m_VerticalAxis = "Vertical";
/// <summary>
/// Name of the submit button.
/// </summary>
[SerializeField]
private string m_SubmitButton = "Submit";
/// <summary>
/// Name of the submit button.
/// </summary>
[SerializeField]
private string m_CancelButton = "Cancel";
[SerializeField]
private float m_InputActionsPerSecond = 10;
[SerializeField]
private bool m_AllowActivationOnMobileDevice;
public bool allowActivationOnMobileDevice {
get { return m_AllowActivationOnMobileDevice; }
set { m_AllowActivationOnMobileDevice = value; }
}
public float inputActionsPerSecond {
get { return m_InputActionsPerSecond; }
set { m_InputActionsPerSecond = value; }
}
/// <summary>
/// Name of the horizontal axis for movement (if axis events are used).
/// </summary>
public string horizontalAxis {
get { return m_HorizontalAxis; }
set { m_HorizontalAxis = value; }
}
/// <summary>
/// Name of the vertical axis for movement (if axis events are used).
/// </summary>
public string verticalAxis {
get { return m_VerticalAxis; }
set { m_VerticalAxis = value; }
}
public string submitButton {
get { return m_SubmitButton; }
set { m_SubmitButton = value; }
}
public string cancelButton {
get { return m_CancelButton; }
set { m_CancelButton = value; }
}
// Methods
protected override void Awake() {
base.Awake();
InitializeRewired();
}
public override void UpdateModule() {
CheckEditorRecompile();
if(recompiling) return;
m_LastMousePosition = m_MousePosition;
m_MousePosition = mouse.screenPosition;
}
public override bool IsModuleSupported() {
// Check for mouse presence instead of whether touch is supported,
// as you can connect mouse to a tablet and in that case we'd want
// to use StandaloneInputModule for non-touch input events.
return m_AllowActivationOnMobileDevice || Input.mousePresent;
}
public override bool ShouldActivateModule() {
if(!base.ShouldActivateModule())
return false;
if(recompiling) return false;
bool shouldActivate = false;
// Combine input for all players
for(int i = 0; i < players.Length; i++) {
Rewired.Player player = players[i];
if(player == null) continue;
shouldActivate |= player.GetButtonDown(m_SubmitButton);
shouldActivate |= player.GetButtonDown(m_CancelButton);
if(moveOneElementPerAxisPress) { // axis press moves only to the next UI element with each press
shouldActivate |= player.GetButtonDown(m_HorizontalAxis) || player.GetNegativeButtonDown(m_HorizontalAxis);
shouldActivate |= player.GetButtonDown(m_VerticalAxis) || player.GetNegativeButtonDown(m_VerticalAxis);
} else { // default behavior - axis press scrolls quickly through UI elements
shouldActivate |= !Mathf.Approximately(player.GetAxisRaw(m_HorizontalAxis), 0.0f);
shouldActivate |= !Mathf.Approximately(player.GetAxisRaw(m_VerticalAxis), 0.0f);
}
}
shouldActivate |= (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f;
shouldActivate |= mouse.GetButtonDown(0);
return shouldActivate;
}
public override void ActivateModule() {
base.ActivateModule();
if(recompiling) return;
m_MousePosition = mouse.screenPosition;
m_LastMousePosition = m_MousePosition;
var toSelect = eventSystem.currentSelectedGameObject;
if(toSelect == null)
toSelect = eventSystem.lastSelectedGameObject;
if(toSelect == null)
toSelect = eventSystem.firstSelectedGameObject;
eventSystem.SetSelectedGameObject(null, GetBaseEventData());
eventSystem.SetSelectedGameObject(toSelect, GetBaseEventData());
}
public override void DeactivateModule() {
base.DeactivateModule();
ClearSelection();
}
public override void Process() {
bool usedEvent = SendUpdateEventToSelectedObject();
if(eventSystem.sendNavigationEvents) {
if(!usedEvent)
usedEvent |= SendMoveEventToSelectedObject();
if(!usedEvent)
SendSubmitEventToSelectedObject();
}
ProcessMouseEvent();
}
/// <summary>
/// Process submit keys.
/// </summary>
private bool SendSubmitEventToSelectedObject() {
if(eventSystem.currentSelectedGameObject == null)
return false;
if(recompiling) return false;
var data = GetBaseEventData();
for(int i = 0; i < players.Length; i++) {
if(players[i] == null) continue;
if(players[i].GetButtonDown(m_SubmitButton)) {
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.submitHandler);
break;
}
if(players[i].GetButtonDown(m_CancelButton)) {
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.cancelHandler);
break;
}
}
return data.used;
}
private bool AllowMoveEventProcessing(float time) {
if(recompiling) return false;
bool allow = false;
for(int i = 0; i < players.Length; i++) {
Rewired.Player player = players[i];
if(player == null) continue;
allow |= player.GetButtonDown(m_HorizontalAxis) || player.GetNegativeButtonDown(m_HorizontalAxis);
allow |= player.GetButtonDown(m_VerticalAxis) || player.GetNegativeButtonDown(m_VerticalAxis);
allow |= (time > m_NextAction);
}
return allow;
}
private Vector2 GetRawMoveVector() {
if(recompiling) return Vector2.zero;
Vector2 move = Vector2.zero;
bool horizButton = false;
bool vertButton = false;
// Combine inputs of all Players
for(int i = 0; i < players.Length; i++) {
Rewired.Player player = players[i];
if(player == null) continue;
if(moveOneElementPerAxisPress) { // axis press moves only to the next UI element with each press
float x = 0.0f;
if(player.GetButtonDown(m_HorizontalAxis)) x = 1.0f;
else if(player.GetNegativeButtonDown(m_HorizontalAxis)) x = -1.0f;
float y = 0.0f;
if(player.GetButtonDown(m_VerticalAxis)) y = 1.0f;
else if(player.GetNegativeButtonDown(m_VerticalAxis)) y = -1.0f;
move.x += x;
move.y += y;
} else { // default behavior - axis press scrolls quickly through UI elements
move.x += player.GetAxisRaw(m_HorizontalAxis);
move.y += player.GetAxisRaw(m_VerticalAxis);
}
horizButton |= player.GetButtonDown(m_HorizontalAxis) || player.GetNegativeButtonDown(m_HorizontalAxis);
vertButton |= player.GetButtonDown(m_VerticalAxis) || player.GetNegativeButtonDown(m_VerticalAxis);
}
if(horizButton) {
if(move.x < 0)
move.x = -1f;
if(move.x > 0)
move.x = 1f;
}
if(vertButton) {
if(move.y < 0)
move.y = -1f;
if(move.y > 0)
move.y = 1f;
}
return move;
}
/// <summary>
/// Process keyboard events.
/// </summary>
private bool SendMoveEventToSelectedObject() {
float time = Time.unscaledTime;
if(!AllowMoveEventProcessing(time))
return false;
Vector2 movement = GetRawMoveVector();
// Debug.Log(m_ProcessingEvent.rawType + " axis:" + m_AllowAxisEvents + " value:" + "(" + x + "," + y + ")");
var axisEventData = GetAxisEventData(movement.x, movement.y, 0.6f);
if(!Mathf.Approximately(axisEventData.moveVector.x, 0f)
|| !Mathf.Approximately(axisEventData.moveVector.y, 0f)) {
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, axisEventData, ExecuteEvents.moveHandler);
}
m_NextAction = time + 1f / m_InputActionsPerSecond;
return axisEventData.used;
}
/// <summary>
/// Process all mouse events.
/// </summary>
private void ProcessMouseEvent() {
var mouseData = GetMousePointerEventData();
var pressed = mouseData.AnyPressesThisFrame();
var released = mouseData.AnyReleasesThisFrame();
var leftButtonData = mouseData.GetButtonState(PointerEventData.InputButton.Left).eventData;
if(!UseMouse(pressed, released, leftButtonData.buttonData))
return;
// Process the first mouse button fully
ProcessMousePress(leftButtonData);
ProcessMove(leftButtonData.buttonData);
ProcessDrag(leftButtonData.buttonData);
// Now process right / middle clicks
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData.buttonData);
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData.buttonData);
if(!Mathf.Approximately(leftButtonData.buttonData.scrollDelta.sqrMagnitude, 0.0f)) {
var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(leftButtonData.buttonData.pointerCurrentRaycast.gameObject);
ExecuteEvents.ExecuteHierarchy(scrollHandler, leftButtonData.buttonData, ExecuteEvents.scrollHandler);
}
}
private static bool UseMouse(bool pressed, bool released, PointerEventData pointerData) {
if(pressed || released || pointerData.IsPointerMoving() || pointerData.IsScrolling())
return true;
return false;
}
private bool SendUpdateEventToSelectedObject() {
if(eventSystem.currentSelectedGameObject == null)
return false;
var data = GetBaseEventData();
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.updateSelectedHandler);
return data.used;
}
/// <summary>
/// Process the current mouse press.
/// </summary>
private void ProcessMousePress(MouseButtonEventData data) {
var pointerEvent = data.buttonData;
var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject;
// PointerDown notification
if(data.PressedThisFrame()) {
pointerEvent.eligibleForClick = true;
pointerEvent.delta = Vector2.zero;
pointerEvent.dragging = false;
pointerEvent.useDragThreshold = true;
pointerEvent.pressPosition = pointerEvent.position;
pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast;
DeselectIfSelectionChanged(currentOverGo, pointerEvent);
// search for the control that will receive the press
// if we can't find a press handler set the press
// handler to be what would receive a click.
var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler);
// didnt find a press handler... search for a click handler
if(newPressed == null)
newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// Debug.Log("Pressed: " + newPressed);
float time = Time.unscaledTime;
if(newPressed == pointerEvent.lastPress) {
var diffTime = time - pointerEvent.clickTime;
if(diffTime < 0.3f)
++pointerEvent.clickCount;
else
pointerEvent.clickCount = 1;
pointerEvent.clickTime = time;
} else {
pointerEvent.clickCount = 1;
}
pointerEvent.pointerPress = newPressed;
pointerEvent.rawPointerPress = currentOverGo;
pointerEvent.clickTime = time;
// Save the drag handler as well
pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
if(pointerEvent.pointerDrag != null)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag);
}
// PointerUp notification
if(data.ReleasedThisFrame()) {
// Debug.Log("Executing pressup on: " + pointer.pointerPress);
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
// Debug.Log("KeyCode: " + pointer.eventData.keyCode);
// see if we mouse up on the same element that we clicked on...
var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// PointerClick and Drop events
if(pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick) {
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler);
} else if(pointerEvent.pointerDrag != null) {
ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler);
}
pointerEvent.eligibleForClick = false;
pointerEvent.pointerPress = null;
pointerEvent.rawPointerPress = null;
if(pointerEvent.pointerDrag != null && pointerEvent.dragging)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler);
pointerEvent.dragging = false;
pointerEvent.pointerDrag = null;
// redo pointer enter / exit to refresh state
// so that if we moused over somethign that ignored it before
// due to having pressed on something else
// it now gets it.
if(currentOverGo != pointerEvent.pointerEnter) {
HandlePointerExitAndEnter(pointerEvent, null);
HandlePointerExitAndEnter(pointerEvent, currentOverGo);
}
}
}
#region Rewired Methods
private void InitializeRewired() {
if(!Rewired.ReInput.isReady) return;
Rewired.ReInput.EditorRecompileEvent += OnEditorRecompile;
SetupRewiredVars();
}
private void SetupRewiredVars() {
// Set up Rewired vars
mouse = Rewired.ReInput.controllers.Mouse; // get the mouse
// Set up Rewired Players
if(useAllRewiredGamePlayers) {
IList<Rewired.Player> rwPlayers = useRewiredSystemPlayer ? Rewired.ReInput.players.AllPlayers : Rewired.ReInput.players.Players;
players = new Rewired.Player[rwPlayers.Count];
for(int i = 0; i < rwPlayers.Count; i++) {
players[i] = rwPlayers[i];
}
} else {
int rewiredPlayerCount = rewiredPlayerIds.Length + (useRewiredSystemPlayer ? 1 : 0);
players = new Rewired.Player[rewiredPlayerCount];
for(int i = 0; i < rewiredPlayerIds.Length; i++) {
players[i] = Rewired.ReInput.players.GetPlayer(rewiredPlayerIds[i]);
}
if(useRewiredSystemPlayer) players[rewiredPlayerCount - 1] = Rewired.ReInput.players.GetSystemPlayer();
}
}
private void CheckEditorRecompile() {
if(!recompiling) return;
if(!Rewired.ReInput.isReady) return;
recompiling = false;
InitializeRewired();
}
private void OnEditorRecompile() {
recompiling = true;
ClearRewiredVars();
}
private void ClearRewiredVars() {
players = new Rewired.Player[0];
mouse = null;
}
#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.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Region.CoreModules.Scripting.DynamicTexture;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using log4net;
using System.Reflection;
using Mono.Addins;
//using Cairo;
namespace OpenSim.Region.CoreModules.Scripting.VectorRender
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "VectorRenderModule")]
public class VectorRenderModule : ISharedRegionModule, IDynamicTextureRender
{
// These fields exist for testing purposes, please do not remove.
// private static bool s_flipper;
// private static byte[] s_asset1Data;
// private static byte[] s_asset2Data;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private IDynamicTextureManager m_textureManager;
private Graphics m_graph;
private string m_fontName = "Arial";
public VectorRenderModule()
{
}
#region IDynamicTextureRender Members
public string GetContentType()
{
return "vector";
}
public string GetName()
{
return Name;
}
public bool SupportsAsynchronous()
{
return true;
}
// public bool AlwaysIdenticalConversion(string bodyData, string extraParams)
// {
// string[] lines = GetLines(bodyData);
// return lines.Any((str, r) => str.StartsWith("Image"));
// }
public IDynamicTexture ConvertUrl(string url, string extraParams)
{
return null;
}
public IDynamicTexture ConvertData(string bodyData, string extraParams)
{
return Draw(bodyData, extraParams);
}
public bool AsyncConvertUrl(UUID id, string url, string extraParams)
{
return false;
}
public bool AsyncConvertData(UUID id, string bodyData, string extraParams)
{
if (m_textureManager == null)
{
m_log.Warn("[VECTORRENDERMODULE]: No texture manager. Can't function");
return false;
}
// XXX: This isn't actually being done asynchronously!
m_textureManager.ReturnData(id, ConvertData(bodyData, extraParams));
return true;
}
public void GetDrawStringSize(string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
lock (this)
{
using (Font myFont = new Font(fontName, fontSize))
{
SizeF stringSize = new SizeF();
// XXX: This lock may be unnecessary.
lock (m_graph)
{
stringSize = m_graph.MeasureString(text, myFont);
xSize = stringSize.Width;
ySize = stringSize.Height;
}
}
}
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
IConfig cfg = config.Configs["VectorRender"];
if (null != cfg)
{
m_fontName = cfg.GetString("font_name", m_fontName);
}
m_log.DebugFormat("[VECTORRENDERMODULE]: using font \"{0}\" for text rendering.", m_fontName);
// We won't dispose of these explicitly since this module is only removed when the entire simulator
// is shut down.
Bitmap bitmap = new Bitmap(1024, 1024, PixelFormat.Format32bppArgb);
m_graph = Graphics.FromImage(bitmap);
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
{
m_scene = scene;
}
}
public void RegionLoaded(Scene scene)
{
if (m_textureManager == null && m_scene == scene)
{
m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
if (m_textureManager != null)
{
m_textureManager.RegisterRender(GetContentType(), this);
}
}
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "VectorRenderModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
private IDynamicTexture Draw(string data, string extraParams)
{
// We need to cater for old scripts that didnt use extraParams neatly, they use either an integer size which represents both width and height, or setalpha
// we will now support multiple comma seperated params in the form width:256,height:512,alpha:255
int width = 256;
int height = 256;
int alpha = 255; // 0 is transparent
Color bgColor = Color.White; // Default background color
char altDataDelim = ';';
char[] paramDelimiter = { ',' };
char[] nvpDelimiter = { ':' };
extraParams = extraParams.Trim();
extraParams = extraParams.ToLower();
string[] nvps = extraParams.Split(paramDelimiter);
int temp = -1;
foreach (string pair in nvps)
{
string[] nvp = pair.Split(nvpDelimiter);
string name = "";
string value = "";
if (nvp[0] != null)
{
name = nvp[0].Trim();
}
if (nvp.Length == 2)
{
value = nvp[1].Trim();
}
switch (name)
{
case "width":
temp = parseIntParam(value);
if (temp != -1)
{
if (temp < 1)
{
width = 1;
}
else if (temp > 2048)
{
width = 2048;
}
else
{
width = temp;
}
}
break;
case "height":
temp = parseIntParam(value);
if (temp != -1)
{
if (temp < 1)
{
height = 1;
}
else if (temp > 2048)
{
height = 2048;
}
else
{
height = temp;
}
}
break;
case "alpha":
temp = parseIntParam(value);
if (temp != -1)
{
if (temp < 0)
{
alpha = 0;
}
else if (temp > 255)
{
alpha = 255;
}
else
{
alpha = temp;
}
}
// Allow a bitmap w/o the alpha component to be created
else if (value.ToLower() == "false") {
alpha = 256;
}
break;
case "bgcolor":
case "bgcolour":
int hex = 0;
if (Int32.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex))
{
bgColor = Color.FromArgb(hex);
}
else
{
bgColor = Color.FromName(value);
}
break;
case "altdatadelim":
altDataDelim = value.ToCharArray()[0];
break;
case "":
// blank string has been passed do nothing just use defaults
break;
default: // this is all for backwards compat, all a bit ugly hopfully can be removed in future
// could be either set alpha or just an int
if (name == "setalpha")
{
alpha = 0; // set the texture to have transparent background (maintains backwards compat)
}
else
{
// this function used to accept an int on its own that represented both
// width and height, this is to maintain backwards compat, could be removed
// but would break existing scripts
temp = parseIntParam(name);
if (temp != -1)
{
if (temp > 1024)
temp = 1024;
if (temp < 128)
temp = 128;
width = temp;
height = temp;
}
}
break;
}
}
Bitmap bitmap = null;
Graphics graph = null;
bool reuseable = false;
try
{
// XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously,
// the native malloc heap can become corrupted, possibly due to a double free(). This may be due to
// bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX. These problems were
// seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1. They go away if disposal is perfomed
// under lock.
lock (this)
{
if (alpha == 256)
bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
else
bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
graph = Graphics.FromImage(bitmap);
// this is really just to save people filling the
// background color in their scripts, only do when fully opaque
if (alpha >= 255)
{
using (SolidBrush bgFillBrush = new SolidBrush(bgColor))
{
graph.FillRectangle(bgFillBrush, 0, 0, width, height);
}
}
for (int w = 0; w < bitmap.Width; w++)
{
if (alpha <= 255)
{
for (int h = 0; h < bitmap.Height; h++)
{
bitmap.SetPixel(w, h, Color.FromArgb(alpha, bitmap.GetPixel(w, h)));
}
}
}
GDIDraw(data, graph, altDataDelim, out reuseable);
}
byte[] imageJ2000 = new byte[0];
// This code exists for testing purposes, please do not remove.
// if (s_flipper)
// imageJ2000 = s_asset1Data;
// else
// imageJ2000 = s_asset2Data;
//
// s_flipper = !s_flipper;
try
{
imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[VECTORRENDERMODULE]: OpenJpeg Encode Failed. Exception {0}{1}",
e.Message, e.StackTrace);
}
return new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
data, extraParams, imageJ2000, new Size(width, height), reuseable);
}
finally
{
// XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously,
// the native malloc heap can become corrupted, possibly due to a double free(). This may be due to
// bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX. These problems were
// seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1. They go away if disposal is perfomed
// under lock.
lock (this)
{
if (graph != null)
graph.Dispose();
if (bitmap != null)
bitmap.Dispose();
}
}
}
private int parseIntParam(string strInt)
{
int parsed;
try
{
parsed = Convert.ToInt32(strInt);
}
catch (Exception)
{
//Ckrinke: Add a WriteLine to remove the warning about 'e' defined but not used
// m_log.Debug("Problem with Draw. Please verify parameters." + e.ToString());
parsed = -1;
}
return parsed;
}
/*
private void CairoDraw(string data, System.Drawing.Graphics graph)
{
using (Win32Surface draw = new Win32Surface(graph.GetHdc()))
{
Context contex = new Context(draw);
contex.Antialias = Antialias.None; //fastest method but low quality
contex.LineWidth = 7;
char[] lineDelimiter = { ';' };
char[] partsDelimiter = { ',' };
string[] lines = data.Split(lineDelimiter);
foreach (string line in lines)
{
string nextLine = line.Trim();
if (nextLine.StartsWith("MoveTO"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, ref x, ref y);
contex.MoveTo(x, y);
}
else if (nextLine.StartsWith("LineTo"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, ref x, ref y);
contex.LineTo(x, y);
contex.Stroke();
}
}
}
graph.ReleaseHdc();
}
*/
/// <summary>
/// Split input data into discrete command lines.
/// </summary>
/// <returns></returns>
/// <param name='data'></param>
/// <param name='dataDelim'></param>
private string[] GetLines(string data, char dataDelim)
{
char[] lineDelimiter = { dataDelim };
return data.Split(lineDelimiter);
}
private void GDIDraw(string data, Graphics graph, char dataDelim, out bool reuseable)
{
reuseable = true;
Point startPoint = new Point(0, 0);
Point endPoint = new Point(0, 0);
Pen drawPen = null;
Font myFont = null;
SolidBrush myBrush = null;
try
{
drawPen = new Pen(Color.Black, 7);
string fontName = m_fontName;
float fontSize = 14;
myFont = new Font(fontName, fontSize);
myBrush = new SolidBrush(Color.Black);
char[] partsDelimiter = {','};
foreach (string line in GetLines(data, dataDelim))
{
string nextLine = line.Trim();
//replace with switch, or even better, do some proper parsing
if (nextLine.StartsWith("MoveTo"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y);
startPoint.X = (int) x;
startPoint.Y = (int) y;
}
else if (nextLine.StartsWith("LineTo"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y);
endPoint.X = (int) x;
endPoint.Y = (int) y;
graph.DrawLine(drawPen, startPoint, endPoint);
startPoint.X = endPoint.X;
startPoint.Y = endPoint.Y;
}
else if (nextLine.StartsWith("Text"))
{
nextLine = nextLine.Remove(0, 4);
nextLine = nextLine.Trim();
graph.DrawString(nextLine, myFont, myBrush, startPoint);
}
else if (nextLine.StartsWith("Image"))
{
// We cannot reuse any generated texture involving fetching an image via HTTP since that image
// can change.
reuseable = false;
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 5, ref x, ref y);
endPoint.X = (int) x;
endPoint.Y = (int) y;
using (Image image = ImageHttpRequest(nextLine))
{
if (image != null)
{
graph.DrawImage(image, (float)startPoint.X, (float)startPoint.Y, x, y);
}
else
{
using (Font errorFont = new Font(m_fontName,6))
{
graph.DrawString("URL couldn't be resolved or is", errorFont,
myBrush, startPoint);
graph.DrawString("not an image. Please check URL.", errorFont,
myBrush, new Point(startPoint.X, 12 + startPoint.Y));
}
graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
}
}
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("Rectangle"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 9, ref x, ref y);
endPoint.X = (int) x;
endPoint.Y = (int) y;
graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("FillRectangle"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 13, ref x, ref y);
endPoint.X = (int) x;
endPoint.Y = (int) y;
graph.FillRectangle(myBrush, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("FillPolygon"))
{
PointF[] points = null;
GetParams(partsDelimiter, ref nextLine, 11, ref points);
graph.FillPolygon(myBrush, points);
}
else if (nextLine.StartsWith("Polygon"))
{
PointF[] points = null;
GetParams(partsDelimiter, ref nextLine, 7, ref points);
graph.DrawPolygon(drawPen, points);
}
else if (nextLine.StartsWith("Ellipse"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y);
endPoint.X = (int)x;
endPoint.Y = (int)y;
graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("FontSize"))
{
nextLine = nextLine.Remove(0, 8);
nextLine = nextLine.Trim();
fontSize = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture);
myFont.Dispose();
myFont = new Font(fontName, fontSize);
}
else if (nextLine.StartsWith("FontProp"))
{
nextLine = nextLine.Remove(0, 8);
nextLine = nextLine.Trim();
string[] fprops = nextLine.Split(partsDelimiter);
foreach (string prop in fprops)
{
switch (prop)
{
case "B":
if (!(myFont.Bold))
{
Font newFont = new Font(myFont, myFont.Style | FontStyle.Bold);
myFont.Dispose();
myFont = newFont;
}
break;
case "I":
if (!(myFont.Italic))
{
Font newFont = new Font(myFont, myFont.Style | FontStyle.Italic);
myFont.Dispose();
myFont = newFont;
}
break;
case "U":
if (!(myFont.Underline))
{
Font newFont = new Font(myFont, myFont.Style | FontStyle.Underline);
myFont.Dispose();
myFont = newFont;
}
break;
case "S":
if (!(myFont.Strikeout))
{
Font newFont = new Font(myFont, myFont.Style | FontStyle.Strikeout);
myFont.Dispose();
myFont = newFont;
}
break;
case "R":
// We need to place this newFont inside its own context so that the .NET compiler
// doesn't complain about a redefinition of an existing newFont, even though there is none
// The mono compiler doesn't produce this error.
{
Font newFont = new Font(myFont, FontStyle.Regular);
myFont.Dispose();
myFont = newFont;
}
break;
}
}
}
else if (nextLine.StartsWith("FontName"))
{
nextLine = nextLine.Remove(0, 8);
fontName = nextLine.Trim();
myFont.Dispose();
myFont = new Font(fontName, fontSize);
}
else if (nextLine.StartsWith("PenSize"))
{
nextLine = nextLine.Remove(0, 7);
nextLine = nextLine.Trim();
float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture);
drawPen.Width = size;
}
else if (nextLine.StartsWith("PenCap"))
{
bool start = true, end = true;
nextLine = nextLine.Remove(0, 6);
nextLine = nextLine.Trim();
string[] cap = nextLine.Split(partsDelimiter);
if (cap[0].ToLower() == "start")
end = false;
else if (cap[0].ToLower() == "end")
start = false;
else if (cap[0].ToLower() != "both")
return;
string type = cap[1].ToLower();
if (end)
{
switch (type)
{
case "arrow":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
break;
case "round":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
break;
case "diamond":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor;
break;
case "flat":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.Flat;
break;
}
}
if (start)
{
switch (type)
{
case "arrow":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
break;
case "round":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
break;
case "diamond":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor;
break;
case "flat":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.Flat;
break;
}
}
}
else if (nextLine.StartsWith("PenColour") || nextLine.StartsWith("PenColor"))
{
nextLine = nextLine.Remove(0, 9);
nextLine = nextLine.Trim();
int hex = 0;
Color newColor;
if (Int32.TryParse(nextLine, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex))
{
newColor = Color.FromArgb(hex);
}
else
{
// this doesn't fail, it just returns black if nothing is found
newColor = Color.FromName(nextLine);
}
myBrush.Color = newColor;
drawPen.Color = newColor;
}
}
}
finally
{
if (drawPen != null)
drawPen.Dispose();
if (myFont != null)
myFont.Dispose();
if (myBrush != null)
myBrush.Dispose();
}
}
private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref float x, ref float y)
{
line = line.Remove(0, startLength);
string[] parts = line.Split(partsDelimiter);
if (parts.Length == 2)
{
string xVal = parts[0].Trim();
string yVal = parts[1].Trim();
x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
}
else if (parts.Length > 2)
{
string xVal = parts[0].Trim();
string yVal = parts[1].Trim();
x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
line = "";
for (int i = 2; i < parts.Length; i++)
{
line = line + parts[i].Trim();
line = line + " ";
}
}
}
private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref PointF[] points)
{
line = line.Remove(0, startLength);
string[] parts = line.Split(partsDelimiter);
if (parts.Length > 1 && parts.Length % 2 == 0)
{
points = new PointF[parts.Length / 2];
for (int i = 0; i < parts.Length; i = i + 2)
{
string xVal = parts[i].Trim();
string yVal = parts[i+1].Trim();
float x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
float y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
PointF point = new PointF(x, y);
points[i / 2] = point;
}
}
}
private Bitmap ImageHttpRequest(string url)
{
try
{
WebRequest request = HttpWebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)(request).GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream s = response.GetResponseStream())
{
Bitmap image = new Bitmap(s);
return image;
}
}
}
}
catch { }
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using log4net;
using NetGore.Collections;
namespace NetGore.IO.PropertySync
{
/// <summary>
/// Provides helper methods for the <see cref="IPropertySync"/>.
/// </summary>
public static class PropertySyncHelper
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static readonly SyncValueAttributeInfoFactory _factory = SyncValueAttributeInfoFactory.Instance;
/// <summary>
/// Dictionary cache for PropertySyncHandlers where the key is the Type to be handled and the value is
/// the Type of the PropertySyncHandler itself.
/// </summary>
static readonly Dictionary<Type, Type> _propertySyncTypes = new Dictionary<Type, Type>();
/// <summary>
/// Cache that handles creating the <see cref="IPropertySync"/>s that are not actually hooked
/// to a property with a <see cref="SyncValueAttributeInfo"/>. These can be reused since they are only used
/// for reading/writing the type, not for an actual particular attribute.
/// </summary>
static readonly ThreadSafeHashCache<Type, IPropertySync> _unhookedPropertySyncCache =
new ThreadSafeHashCache<Type, IPropertySync>(
x => (IPropertySync)TypeFactory.GetTypeInstance(_propertySyncTypes[x], (SyncValueAttributeInfo)null));
/// <summary>
/// Initializes the <see cref="PropertySyncHelper"/> class.
/// </summary>
/// <exception cref="TypeLoadException">Multiple <see cref="PropertySyncHandlerAttribute"/>s were found on a single type.</exception>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "PropertySyncHandlerAttributes")]
static PropertySyncHelper()
{
// Create the dictionary cache that maps a PropertySyncHandler's handled type
// to the type of the PropertySyncHandler itself
var typeFilterCreator = new TypeFilterCreator
{ IsClass = true, IsAbstract = false, Attributes = new Type[] { typeof(PropertySyncHandlerAttribute) } };
var typeFilter = typeFilterCreator.GetFilter();
foreach (var type in TypeHelper.AllTypes().Where(typeFilter))
{
// Look for classes that inherit the PropertySyncHandlerAttribute
var attribs = type.GetCustomAttributes(typeof(PropertySyncHandlerAttribute), true);
if (attribs.Length < 1)
continue;
if (attribs.Length > 1)
{
const string errmsg = "Multiple PropertySyncHandlerAttributes found on type `{0}`";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, type);
Debug.Fail(string.Format(errmsg, type));
throw new TypeLoadException(string.Format(errmsg, type));
}
// Grab the attribute so we can find out what type this class handles
var attrib = (PropertySyncHandlerAttribute)attribs[0];
// Make sure the handler doesn't already exist
if (_propertySyncTypes.ContainsKey(attrib.HandledType))
{
const string errmsg =
"Duplicate PropertySync implementations for type `{0}`. Implementations: `{1}` and `{2}`.";
var existingPST = _propertySyncTypes[attrib.HandledType];
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, attrib.HandledType, existingPST, type);
Debug.Fail(string.Format(errmsg, attrib.HandledType, existingPST, type));
continue;
}
// Store the handled type
_propertySyncTypes.Add(attrib.HandledType, type);
// If the type can be made nullable, also store the nullable type
if (attrib.HandledType.IsValueType && !attrib.HandledType.IsGenericType)
{
try
{
var nullableType = typeof(Nullable<>).MakeGenericType(attrib.HandledType);
// Make sure the key doesn't already exist
if (!_propertySyncTypes.ContainsKey(nullableType))
{
var psType = typeof(PropertySyncNullable<>).MakeGenericType(attrib.HandledType);
_propertySyncTypes.Add(nullableType, psType);
}
}
catch (Exception ex)
{
const string errmsg = "Failed to create nullable type from `{0}`. Reason: {1}";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, attrib.HandledType, ex);
Debug.Fail(string.Format(errmsg, attrib.HandledType, ex));
}
}
}
}
/// <summary>
/// Gets the <see cref="IPropertySync"/> for a given <see cref="SyncValueAttributeInfo"/>.
/// </summary>
/// <param name="attribInfo">The <see cref="SyncValueAttributeInfo"/>.</param>
/// <returns>The <see cref="IPropertySync"/> for a given <see cref="SyncValueAttributeInfo"/>.</returns>
/// <exception cref="TypeLoadException">Could not create an <see cref="IPropertySync"/> from the
/// <paramref name="attribInfo"/>.</exception>
/// <exception cref="ArgumentException">The <paramref name="attribInfo"/> is for a type that does not have a
/// <see cref="PropertySyncHandlerAttribute"/> defined for it.</exception>
/// <exception cref="ArgumentNullException"><paramref name="attribInfo"/> is null.</exception>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "IPropertySync")]
internal static IPropertySync GetPropertySync(SyncValueAttributeInfo attribInfo)
{
if (attribInfo == null)
throw new ArgumentNullException("attribInfo");
// Get the Type of the class used to handle the type of property
Type propertySyncType;
try
{
propertySyncType = _propertySyncTypes[attribInfo.PropertyType];
}
catch (KeyNotFoundException ex)
{
const string errmsg =
"No PropertySyncHandler exists for type `{0}`. You must define a class to handle this type (preferably derived from PropertySyncBase) and give it the PropertySyncHandlerAttribute.";
throw new ArgumentException(string.Format(errmsg, attribInfo.PropertyType), ex);
}
// Get the instance of the class used to handle the attribute's type
var instance = (IPropertySync)TypeFactory.GetTypeInstance(propertySyncType, attribInfo);
if (instance == null)
{
const string errmsg = "Failed to create IPropertySync of type `{0}` for `{1}`.";
var err = string.Format(errmsg, _propertySyncTypes[attribInfo.PropertyType], attribInfo);
log.Fatal(err);
throw new TypeLoadException(err);
}
return instance;
}
/// <summary>
/// Gets the <see cref="IPropertySync"/> instances for the given <paramref name="type"/>.
/// </summary>
/// <param name="type">The <see cref="Type"/> to get the <see cref="IPropertySync"/>s for.</param>
/// <returns>The <see cref="IPropertySync"/> instances for the given <paramref name="type"/>.</returns>
public static IEnumerable<IPropertySync> GetPropertySyncs(Type type)
{
var infos = _factory[type];
var ret = new IPropertySync[infos.Length];
// Loop through each of the property sync infos
for (var i = 0; i < ret.Length; i++)
{
var instance = GetPropertySync(infos[i]);
ret[i] = instance;
}
return ret;
}
/// <summary>
/// Gets the <see cref="IPropertySync"/> for a given <paramref name="type"/> that does not pass a
/// valid <see cref="SyncValueAttributeInfo"/>. Attempting to perform state tracking operations on the created
/// object will result in an exception being thrown. This method is intended only as a way to provide access
/// to the code for reading and writing the values for the <see cref="PropertySyncNullable{T}"/>.
/// </summary>
/// <param name="type">The type for the <see cref="IPropertySync"/> to handle.</param>
/// <returns>The <see cref="IPropertySync"/> for a given <paramref name="type"/> that does not pass a
/// valid <see cref="SyncValueAttributeInfo"/>.</returns>
internal static IPropertySync GetUnhookedPropertySync(Type type)
{
return _unhookedPropertySyncCache[type];
}
/// <summary>
/// Compares two PropertyInfoDatas by using the PropertyInfo's Name.
/// </summary>
/// <param name="a">First PropertyInfoData.</param>
/// <param name="b">Second PropertyInfoData.</param>
/// <returns>Comparison of the two PropertyInfoDatas.</returns>
static int PropertyInfoAndAttributeComparer(SyncValueAttributeInfo a, SyncValueAttributeInfo b)
{
return String.Compare(a.Name, b.Name, StringComparison.Ordinal);
}
/// <summary>
/// Contains the <see cref="SyncValueAttributeInfo"/>s for a given <see cref="Type"/>.
/// </summary>
class SyncValueAttributeInfoFactory : ThreadSafeHashCache<Type, SyncValueAttributeInfo[]>
{
static readonly SyncValueAttributeInfoFactory _instance;
/// <summary>
/// Initializes the <see cref="SyncValueAttributeInfoFactory"/> class.
/// </summary>
static SyncValueAttributeInfoFactory()
{
_instance = new SyncValueAttributeInfoFactory();
}
/// <summary>
/// Initializes a new instance of the <see cref="SyncValueAttributeInfoFactory"/> class.
/// </summary>
SyncValueAttributeInfoFactory() : base(CreateValue)
{
}
/// <summary>
/// Gets the <see cref="SyncValueAttributeInfoFactory"/> instance.
/// </summary>
public static SyncValueAttributeInfoFactory Instance
{
get { return _instance; }
}
/// <summary>
/// Creates the <see cref="SyncValueAttributeInfo"/>s for the given <paramref name="key"/>.
/// </summary>
/// <param name="key">The key to create the value for.</param>
/// <exception cref="TypeLoadException">Multiple <see cref="SyncValueAttribute"/> found on a single type.</exception>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "SyncValueAttribute")]
static SyncValueAttributeInfo[] CreateValue(Type key)
{
const BindingFlags flags =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty |
BindingFlags.SetProperty;
var tempPropInfos = new List<SyncValueAttributeInfo>();
// Find all of the properties for this type
foreach (var property in key.GetProperties(flags))
{
// Get the SyncValueAttribute for the property, skipping if none found
var attribs = TypeHelper.GetAllCustomAttributes<SyncValueAttribute>(property, flags).ToArray();
if (attribs.IsEmpty())
continue;
if (attribs.Length > 1)
{
const string errmsg = "Property `{0}` contains more than one SyncValueAttribute!";
var err = string.Format(errmsg, property);
log.FatalFormat(err);
Debug.Fail(err);
throw new TypeLoadException(err);
}
// Get the attribute attached to this Property
var attribute = attribs.First();
// Create the SyncValueAttributeInfo
var targetSVAIType = typeof(SyncValueAttributeInfo<>).MakeGenericType(property.PropertyType);
var svai = (SyncValueAttributeInfo)TypeFactory.GetTypeInstance(targetSVAIType, property, attribute);
// Ensure we don't already have a property with this name
if (tempPropInfos.Any(x => x.Name == svai.Name))
{
const string errmsg = "Class `{0}` contains more than one SyncValueAttribute with the name `{1}`!";
var err = string.Format(errmsg, key, svai.Name);
log.FatalFormat(err);
Debug.Fail(err);
throw new TypeLoadException(err);
}
// Add the property the list
tempPropInfos.Add(svai);
}
// Sort the list so we can ensure that, every time this runs, the order will always be the same
tempPropInfos.Sort(PropertyInfoAndAttributeComparer);
// Convert to an array and return
return tempPropInfos.ToArray();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace VoteApp.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Layouts
{
using System;
using System.Linq;
using System.ComponentModel;
using System.Text;
using NLog.Config;
using NLog.Internal;
using NLog.Common;
using System.Collections.Generic;
/// <summary>
/// Abstract interface that layouts must implement.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces", Justification = "Few people will see this conflict.")]
[NLogConfigurationItem]
public abstract class Layout : ISupportsInitialize, IRenderable
{
/// <summary>
/// Is this layout initialized? See <see cref="Initialize(NLog.Config.LoggingConfiguration)"/>
/// </summary>
private bool _isInitialized;
private bool _scannedForObjects;
/// <summary>
/// Gets a value indicating whether this layout is thread-agnostic (can be rendered on any thread).
/// </summary>
/// <remarks>
/// Layout is thread-agnostic if it has been marked with [ThreadAgnostic] attribute and all its children are
/// like that as well.
///
/// Thread-agnostic layouts only use contents of <see cref="LogEventInfo"/> for its output.
/// </remarks>
internal bool ThreadAgnostic { get; set; }
/// <summary>
/// Gets the level of stack trace information required for rendering.
/// </summary>
internal StackTraceUsage StackTraceUsage { get; private set; }
private const int MaxInitialRenderBufferLength = 16384;
private int _maxRenderedLength;
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Converts a given text to a <see cref="Layout" />.
/// </summary>
/// <param name="text">Text to be converted.</param>
/// <returns><see cref="SimpleLayout"/> object represented by the text.</returns>
public static implicit operator Layout([Localizable(false)] string text)
{
return FromString(text);
}
/// <summary>
/// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
/// </summary>
/// <param name="layoutText">The layout string.</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
public static Layout FromString(string layoutText)
{
return FromString(layoutText, ConfigurationItemFactory.Default);
}
/// <summary>
/// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
/// </summary>
/// <param name="layoutText">The layout string.</param>
/// <param name="configurationItemFactory">The NLog factories to use when resolving layout renderers.</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
public static Layout FromString(string layoutText, ConfigurationItemFactory configurationItemFactory)
{
return new SimpleLayout(layoutText, configurationItemFactory);
}
/// <summary>
/// Precalculates the layout for the specified log event and stores the result
/// in per-log event cache.
///
/// Only if the layout doesn't have [ThreadAgnostic] and doens't contain layouts with [ThreadAgnostic].
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// Calling this method enables you to store the log event in a buffer
/// and/or potentially evaluate it in another thread even though the
/// layout may contain thread-dependent renderer.
/// </remarks>
public virtual void Precalculate(LogEventInfo logEvent)
{
if (!ThreadAgnostic)
{
Render(logEvent);
}
}
/// <summary>
/// Renders the event info in layout.
/// </summary>
/// <param name="logEvent">The event info.</param>
/// <returns>String representing log event.</returns>
public string Render(LogEventInfo logEvent)
{
if (!_isInitialized)
{
Initialize(LoggingConfiguration);
}
return GetFormattedMessage(logEvent);
}
internal void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target)
{
if (!ThreadAgnostic)
{
RenderAppendBuilder(logEvent, target, true);
}
}
/// <summary>
/// Renders the event info in layout to the provided target
/// </summary>
/// <param name="logEvent">The event info.</param>
/// <param name="target">Appends the string representing log event to target</param>
/// <param name="cacheLayoutResult">Should rendering result be cached on LogEventInfo</param>
internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder target, bool cacheLayoutResult = false)
{
if (!_isInitialized)
{
Initialize(LoggingConfiguration);
}
if (!ThreadAgnostic)
{
string cachedValue;
if (logEvent.TryGetCachedLayoutValue(this, out cachedValue))
{
target.Append(cachedValue);
return;
}
}
cacheLayoutResult = cacheLayoutResult && !ThreadAgnostic;
using (var localTarget = new AppendBuilderCreator(target, cacheLayoutResult))
{
RenderFormattedMessage(logEvent, localTarget.Builder);
if (cacheLayoutResult)
{
// when needed as it generates garbage
logEvent.AddCachedLayoutValue(this, localTarget.Builder.ToString());
}
}
}
/// <summary>
/// Valid default implementation of <see cref="GetFormattedMessage" />, when having implemented the optimized <see cref="RenderFormattedMessage"/>
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="reusableBuilder">StringBuilder to help minimize allocations [optional].</param>
/// <param name="cacheLayoutResult">Should rendering result be cached on LogEventInfo</param>
/// <returns>The rendered layout.</returns>
internal string RenderAllocateBuilder(LogEventInfo logEvent, StringBuilder reusableBuilder = null, bool cacheLayoutResult = true)
{
if (!ThreadAgnostic)
{
string cachedValue;
if (logEvent.TryGetCachedLayoutValue(this, out cachedValue))
{
return cachedValue;
}
}
int initialLength = _maxRenderedLength;
if (initialLength > MaxInitialRenderBufferLength)
{
initialLength = MaxInitialRenderBufferLength;
}
var sb = reusableBuilder ?? new StringBuilder(initialLength);
RenderFormattedMessage(logEvent, sb);
if (sb.Length > _maxRenderedLength)
{
_maxRenderedLength = sb.Length;
}
if (cacheLayoutResult && !ThreadAgnostic)
{
return logEvent.AddCachedLayoutValue(this, sb.ToString());
}
else
{
return sb.ToString();
}
}
/// <summary>
/// Renders the layout for the specified logging event by invoking layout renderers.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="target"><see cref="StringBuilder"/> for the result</param>
protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
{
target.Append(GetFormattedMessage(logEvent) ?? string.Empty);
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
Close();
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
if (!_isInitialized)
{
LoggingConfiguration = configuration;
_isInitialized = true;
_scannedForObjects = false;
InitializeLayout();
if (!_scannedForObjects)
{
InternalLogger.Debug("Initialized Layout done but not scanned for objects");
PerformObjectScanning();
}
}
}
internal void PerformObjectScanning()
{
var objectGraphScannerList = ObjectGraphScanner.FindReachableObjects<object>(true, this);
// determine whether the layout is thread-agnostic
// layout is thread agnostic if it is thread-agnostic and
// all its nested objects are thread-agnostic.
ThreadAgnostic = objectGraphScannerList.All(item => item.GetType().IsDefined(typeof(ThreadAgnosticAttribute), true));
// determine the max StackTraceUsage, to decide if Logger needs to capture callsite
StackTraceUsage = StackTraceUsage.None; // Incase this Layout should implement IUsesStackTrace
StackTraceUsage = objectGraphScannerList.OfType<IUsesStackTrace>().DefaultIfEmpty().Max(item => item == null ? StackTraceUsage.None : item.StackTraceUsage);
_scannedForObjects = true;
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
if (_isInitialized)
{
LoggingConfiguration = null;
_isInitialized = false;
CloseLayout();
}
}
/// <summary>
/// Initializes the layout.
/// </summary>
protected virtual void InitializeLayout()
{
PerformObjectScanning();
}
/// <summary>
/// Closes the layout.
/// </summary>
protected virtual void CloseLayout()
{
}
/// <summary>
/// Renders the layout for the specified logging event by invoking layout renderers.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <returns>The rendered layout.</returns>
protected abstract string GetFormattedMessage(LogEventInfo logEvent);
/// <summary>
/// Register a custom Layout.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <typeparam name="T"> Type of the Layout.</typeparam>
/// <param name="name"> Name of the Layout.</param>
public static void Register<T>(string name)
where T : Layout
{
var layoutRendererType = typeof(T);
Register(name, layoutRendererType);
}
/// <summary>
/// Register a custom Layout.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <param name="layoutType"> Type of the Layout.</param>
/// <param name="name"> Name of the Layout.</param>
public static void Register(string name, Type layoutType)
{
ConfigurationItemFactory.Default.Layouts
.RegisterDefinition(name, layoutType);
}
internal string ToStringWithNestedItems<T>(IList<T> nestedItems, Func<T, string> nextItemToString)
{
if (nestedItems?.Count > 0)
{
var nestedNames = nestedItems.Select(c => nextItemToString(c)).ToArray();
return string.Concat(GetType().Name, "=", string.Join("|", nestedNames));
}
return base.ToString();
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using Frapid.Configuration;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.DbPolicy;
using Frapid.Framework.Extensions;
using Npgsql;
using Frapid.NPoco;
using Serilog;
namespace Frapid.Config.DataAccess
{
/// <summary>
/// Provides simplified data access features to perform SCRUD operation on the database table "config.custom_field_setup".
/// </summary>
public class CustomFieldSetup : DbAccess, ICustomFieldSetupRepository
{
/// <summary>
/// The schema of this table. Returns literal "config".
/// </summary>
public override string _ObjectNamespace => "config";
/// <summary>
/// The schema unqualified name of this table. Returns literal "custom_field_setup".
/// </summary>
public override string _ObjectName => "custom_field_setup";
/// <summary>
/// Login id of application user accessing this table.
/// </summary>
public long _LoginId { get; set; }
/// <summary>
/// User id of application user accessing this table.
/// </summary>
public int _UserId { get; set; }
/// <summary>
/// The name of the database on which queries are being executed to.
/// </summary>
public string _Catalog { get; set; }
/// <summary>
/// Performs SQL count on the table "config.custom_field_setup".
/// </summary>
/// <returns>Returns the number of rows of the table "config.custom_field_setup".</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long Count()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT COUNT(*) FROM config.custom_field_setup;";
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "config.custom_field_setup" to return all instances of the "CustomFieldSetup" class.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "CustomFieldSetup" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.CustomFieldSetup> GetAll()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.custom_field_setup ORDER BY custom_field_setup_id;";
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "config.custom_field_setup" to return all instances of the "CustomFieldSetup" class to export.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "CustomFieldSetup" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<dynamic> Export()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.custom_field_setup ORDER BY custom_field_setup_id;";
return Factory.Get<dynamic>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "config.custom_field_setup" with a where filter on the column "custom_field_setup_id" to return a single instance of the "CustomFieldSetup" class.
/// </summary>
/// <param name="customFieldSetupId">The column "custom_field_setup_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped instance of "CustomFieldSetup" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.CustomFieldSetup Get(int customFieldSetupId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get entity \"CustomFieldSetup\" filtered by \"CustomFieldSetupId\" with value {CustomFieldSetupId} was denied to the user with Login ID {_LoginId}", customFieldSetupId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.custom_field_setup WHERE custom_field_setup_id=@0;";
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql, customFieldSetupId).FirstOrDefault();
}
/// <summary>
/// Gets the first record of the table "config.custom_field_setup".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "CustomFieldSetup" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.CustomFieldSetup GetFirst()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the first record of entity \"CustomFieldSetup\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.custom_field_setup ORDER BY custom_field_setup_id LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Gets the previous record of the table "config.custom_field_setup" sorted by customFieldSetupId.
/// </summary>
/// <param name="customFieldSetupId">The column "custom_field_setup_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "CustomFieldSetup" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.CustomFieldSetup GetPrevious(int customFieldSetupId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the previous entity of \"CustomFieldSetup\" by \"CustomFieldSetupId\" with value {CustomFieldSetupId} was denied to the user with Login ID {_LoginId}", customFieldSetupId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.custom_field_setup WHERE custom_field_setup_id < @0 ORDER BY custom_field_setup_id DESC LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql, customFieldSetupId).FirstOrDefault();
}
/// <summary>
/// Gets the next record of the table "config.custom_field_setup" sorted by customFieldSetupId.
/// </summary>
/// <param name="customFieldSetupId">The column "custom_field_setup_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "CustomFieldSetup" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.CustomFieldSetup GetNext(int customFieldSetupId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the next entity of \"CustomFieldSetup\" by \"CustomFieldSetupId\" with value {CustomFieldSetupId} was denied to the user with Login ID {_LoginId}", customFieldSetupId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.custom_field_setup WHERE custom_field_setup_id > @0 ORDER BY custom_field_setup_id LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql, customFieldSetupId).FirstOrDefault();
}
/// <summary>
/// Gets the last record of the table "config.custom_field_setup".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "CustomFieldSetup" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.Config.Entities.CustomFieldSetup GetLast()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the last record of entity \"CustomFieldSetup\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.custom_field_setup ORDER BY custom_field_setup_id DESC LIMIT 1;";
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Executes a select query on the table "config.custom_field_setup" with a where filter on the column "custom_field_setup_id" to return a multiple instances of the "CustomFieldSetup" class.
/// </summary>
/// <param name="customFieldSetupIds">Array of column "custom_field_setup_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped collection of "CustomFieldSetup" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.CustomFieldSetup> Get(int[] customFieldSetupIds)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}. customFieldSetupIds: {customFieldSetupIds}.", this._LoginId, customFieldSetupIds);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.custom_field_setup WHERE custom_field_setup_id IN (@0);";
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql, customFieldSetupIds);
}
/// <summary>
/// Custom fields are user defined form elements for config.custom_field_setup.
/// </summary>
/// <returns>Returns an enumerable custom field collection for the table config.custom_field_setup</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get custom fields for entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
string sql;
if (string.IsNullOrWhiteSpace(resourceId))
{
sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='config.custom_field_setup' ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql);
}
sql = "SELECT * from config.get_custom_field_definition('config.custom_field_setup'::text, @0::text) ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId);
}
/// <summary>
/// Displayfields provide a minimal name/value context for data binding the row collection of config.custom_field_setup.
/// </summary>
/// <returns>Returns an enumerable name and value collection for the table config.custom_field_setup</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>();
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return displayFields;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get display field for entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT custom_field_setup_id AS key, form_name as value FROM config.custom_field_setup;";
using (NpgsqlCommand command = new NpgsqlCommand(sql))
{
using (DataTable table = DbOperation.GetDataTable(this._Catalog, command))
{
if (table?.Rows == null || table.Rows.Count == 0)
{
return displayFields;
}
foreach (DataRow row in table.Rows)
{
if (row != null)
{
DisplayField displayField = new DisplayField
{
Key = row["key"].ToString(),
Value = row["value"].ToString()
};
displayFields.Add(displayField);
}
}
}
}
return displayFields;
}
/// <summary>
/// Inserts or updates the instance of CustomFieldSetup class on the database table "config.custom_field_setup".
/// </summary>
/// <param name="customFieldSetup">The instance of "CustomFieldSetup" class to insert or update.</param>
/// <param name="customFields">The custom field collection.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object AddOrEdit(dynamic customFieldSetup, List<Frapid.DataAccess.Models.CustomField> customFields)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
object primaryKeyValue = customFieldSetup.custom_field_setup_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
this.Update(customFieldSetup, Cast.To<int>(primaryKeyValue));
}
else
{
primaryKeyValue = this.Add(customFieldSetup);
}
string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" +
"SELECT custom_field_setup_id " +
"FROM config.custom_field_setup " +
"WHERE form_name=config.get_custom_field_form_name('config.custom_field_setup')" +
");";
Factory.NonQuery(this._Catalog, sql);
if (customFields == null)
{
return primaryKeyValue;
}
foreach (var field in customFields)
{
sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " +
"SELECT config.get_custom_field_setup_id_by_table_name('config.custom_field_setup', @0::character varying(100)), " +
"@1, @2;";
Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value);
}
return primaryKeyValue;
}
/// <summary>
/// Inserts the instance of CustomFieldSetup class on the database table "config.custom_field_setup".
/// </summary>
/// <param name="customFieldSetup">The instance of "CustomFieldSetup" class to insert.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object Add(dynamic customFieldSetup)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to add entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}. {CustomFieldSetup}", this._LoginId, customFieldSetup);
throw new UnauthorizedException("Access is denied.");
}
}
return Factory.Insert(this._Catalog, customFieldSetup, "config.custom_field_setup", "custom_field_setup_id");
}
/// <summary>
/// Inserts or updates multiple instances of CustomFieldSetup class on the database table "config.custom_field_setup";
/// </summary>
/// <param name="customFieldSetups">List of "CustomFieldSetup" class to import.</param>
/// <returns></returns>
public List<object> BulkImport(List<ExpandoObject> customFieldSetups)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to import entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}. {customFieldSetups}", this._LoginId, customFieldSetups);
throw new UnauthorizedException("Access is denied.");
}
}
var result = new List<object>();
int line = 0;
try
{
using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName))
{
using (ITransaction transaction = db.GetTransaction())
{
foreach (dynamic customFieldSetup in customFieldSetups)
{
line++;
object primaryKeyValue = customFieldSetup.custom_field_setup_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
result.Add(customFieldSetup.custom_field_setup_id);
db.Update("config.custom_field_setup", "custom_field_setup_id", customFieldSetup, customFieldSetup.custom_field_setup_id);
}
else
{
result.Add(db.Insert("config.custom_field_setup", "custom_field_setup_id", customFieldSetup));
}
}
transaction.Complete();
}
return result;
}
}
catch (NpgsqlException ex)
{
string errorMessage = $"Error on line {line} ";
if (ex.Code.StartsWith("P"))
{
errorMessage += Factory.GetDbErrorResource(ex);
throw new DataAccessException(errorMessage, ex);
}
errorMessage += ex.Message;
throw new DataAccessException(errorMessage, ex);
}
catch (System.Exception ex)
{
string errorMessage = $"Error on line {line} ";
throw new DataAccessException(errorMessage, ex);
}
}
/// <summary>
/// Updates the row of the table "config.custom_field_setup" with an instance of "CustomFieldSetup" class against the primary key value.
/// </summary>
/// <param name="customFieldSetup">The instance of "CustomFieldSetup" class to update.</param>
/// <param name="customFieldSetupId">The value of the column "custom_field_setup_id" which will be updated.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Update(dynamic customFieldSetup, int customFieldSetupId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to edit entity \"CustomFieldSetup\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {CustomFieldSetup}", customFieldSetupId, this._LoginId, customFieldSetup);
throw new UnauthorizedException("Access is denied.");
}
}
Factory.Update(this._Catalog, customFieldSetup, customFieldSetupId, "config.custom_field_setup", "custom_field_setup_id");
}
/// <summary>
/// Deletes the row of the table "config.custom_field_setup" against the primary key value.
/// </summary>
/// <param name="customFieldSetupId">The value of the column "custom_field_setup_id" which will be deleted.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Delete(int customFieldSetupId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to delete entity \"CustomFieldSetup\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", customFieldSetupId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "DELETE FROM config.custom_field_setup WHERE custom_field_setup_id=@0;";
Factory.NonQuery(this._Catalog, sql, customFieldSetupId);
}
/// <summary>
/// Performs a select statement on table "config.custom_field_setup" producing a paginated result of 10.
/// </summary>
/// <returns>Returns the first page of collection of "CustomFieldSetup" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.CustomFieldSetup> GetPaginatedResult()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the first page of the entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM config.custom_field_setup ORDER BY custom_field_setup_id LIMIT 10 OFFSET 0;";
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on table "config.custom_field_setup" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of "CustomFieldSetup" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.CustomFieldSetup> GetPaginatedResult(long pageNumber)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
const string sql = "SELECT * FROM config.custom_field_setup ORDER BY custom_field_setup_id LIMIT 10 OFFSET @0;";
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql, offset);
}
public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName)
{
const string sql = "SELECT * FROM config.filters WHERE object_name='config.custom_field_setup' AND lower(filter_name)=lower(@0);";
return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList();
}
/// <summary>
/// Performs a filtered count on table "config.custom_field_setup".
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of "CustomFieldSetup" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.custom_field_setup WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomFieldSetup(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "config.custom_field_setup" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns collection of "CustomFieldSetup" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.CustomFieldSetup> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM config.custom_field_setup WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomFieldSetup(), filters);
sql.OrderBy("custom_field_setup_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered count on table "config.custom_field_setup".
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of rows of "CustomFieldSetup" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountFiltered(string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.custom_field_setup WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomFieldSetup(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "config.custom_field_setup" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns collection of "CustomFieldSetup" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Config.Entities.CustomFieldSetup> GetFiltered(long pageNumber, string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"CustomFieldSetup\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM config.custom_field_setup WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomFieldSetup(), filters);
sql.OrderBy("custom_field_setup_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Config.Entities.CustomFieldSetup>(this._Catalog, sql);
}
}
}
| |
using UnityEngine;
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
using Object = UnityEngine.Object;
namespace UnityStandardAssets.CinematicEffects
{
[Serializable]
public class SMAA : IAntiAliasing
{
[AttributeUsage(AttributeTargets.Field)]
public class SettingsGroup : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class TopLevelSettings : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class ExperimentalGroup : Attribute
{}
public enum DebugPass
{
Off,
Edges,
Weights,
Accumulation
}
public enum QualityPreset
{
Low = 0,
Medium = 1,
High = 2,
Ultra = 3,
Custom
}
public enum EdgeDetectionMethod
{
Luma = 1,
Color = 2,
Depth = 3
}
[Serializable]
public struct GlobalSettings
{
[Tooltip("Use this to fine tune your settings when working in Custom quality mode. \"Accumulation\" only works when \"Temporal Filtering\" is enabled.")]
public DebugPass debugPass;
[Tooltip("Low: 60% of the quality.\nMedium: 80% of the quality.\nHigh: 95% of the quality.\nUltra: 99% of the quality (overkill).")]
public QualityPreset quality;
[Tooltip("You've three edge detection methods to choose from: luma, color or depth.\nThey represent different quality/performance and anti-aliasing/sharpness tradeoffs, so our recommendation is for you to choose the one that best suits your particular scenario:\n\n- Depth edge detection is usually the fastest but it may miss some edges.\n- Luma edge detection is usually more expensive than depth edge detection, but catches visible edges that depth edge detection can miss.\n- Color edge detection is usually the most expensive one but catches chroma-only edges.")]
public EdgeDetectionMethod edgeDetectionMethod;
public static GlobalSettings defaultSettings
{
get
{
return new GlobalSettings
{
debugPass = DebugPass.Off,
quality = QualityPreset.High,
edgeDetectionMethod = EdgeDetectionMethod.Color
};
}
}
}
[Serializable]
public struct QualitySettings
{
[Tooltip("Enables/Disables diagonal processing.")]
public bool diagonalDetection;
[Tooltip("Enables/Disables corner detection. Leave this on to avoid blurry corners.")]
public bool cornerDetection;
[Range(0f, 0.5f)]
[Tooltip("Specifies the threshold or sensitivity to edges. Lowering this value you will be able to detect more edges at the expense of performance.\n0.1 is a reasonable value, and allows to catch most visible edges. 0.05 is a rather overkill value, that allows to catch 'em all.")]
public float threshold;
[Min(0.0001f)]
[Tooltip("Specifies the threshold for depth edge detection. Lowering this value you will be able to detect more edges at the expense of performance.")]
public float depthThreshold;
[Range(0, 112)]
[Tooltip("Specifies the maximum steps performed in the horizontal/vertical pattern searches, at each side of the pixel.\nIn number of pixels, it's actually the double. So the maximum line length perfectly handled by, for example 16, is 64 (by perfectly, we meant that longer lines won't look as good, but still antialiased).")]
public int maxSearchSteps;
[Range(0, 20)]
[Tooltip("Specifies the maximum steps performed in the diagonal pattern searches, at each side of the pixel. In this case we jump one pixel at time, instead of two.\nOn high-end machines it is cheap (between a 0.8x and 0.9x slower for 16 steps), but it can have a significant impact on older machines.")]
public int maxDiagonalSearchSteps;
[Range(0, 100)]
[Tooltip("Specifies how much sharp corners will be rounded.")]
public int cornerRounding;
[Min(0f)]
[Tooltip("If there is an neighbor edge that has a local contrast factor times bigger contrast than current edge, current edge will be discarded.\nThis allows to eliminate spurious crossing edges, and is based on the fact that, if there is too much contrast in a direction, that will hide perceptually contrast in the other neighbors.")]
public float localContrastAdaptationFactor;
public static QualitySettings[] presetQualitySettings =
{
// Low
new QualitySettings
{
diagonalDetection = false,
cornerDetection = false,
threshold = 0.15f,
depthThreshold = 0.01f,
maxSearchSteps = 4,
maxDiagonalSearchSteps = 8,
cornerRounding = 25,
localContrastAdaptationFactor = 2f
},
// Medium
new QualitySettings
{
diagonalDetection = false,
cornerDetection = false,
threshold = 0.1f,
depthThreshold = 0.01f,
maxSearchSteps = 8,
maxDiagonalSearchSteps = 8,
cornerRounding = 25,
localContrastAdaptationFactor = 2f
},
// High
new QualitySettings
{
diagonalDetection = true,
cornerDetection = true,
threshold = 0.1f,
depthThreshold = 0.01f,
maxSearchSteps = 16,
maxDiagonalSearchSteps = 8,
cornerRounding = 25,
localContrastAdaptationFactor = 2f
},
// Ultra
new QualitySettings
{
diagonalDetection = true,
cornerDetection = true,
threshold = 0.05f,
depthThreshold = 0.01f,
maxSearchSteps = 32,
maxDiagonalSearchSteps = 16,
cornerRounding = 25,
localContrastAdaptationFactor = 2f
},
};
}
[Serializable]
public struct TemporalSettings
{
[Tooltip("Temporal filtering makes it possible for the SMAA algorithm to benefit from minute subpixel information available that has been accumulated over many frames.")]
public bool enabled;
public bool UseTemporal()
{
#if UNITY_EDITOR
return enabled && EditorApplication.isPlayingOrWillChangePlaymode;
#else
return enabled;
#endif
}
[Range(0.5f, 10.0f)]
[Tooltip("The size of the fuzz-displacement (jitter) in pixels applied to the camera's perspective projection matrix.\nUsed for 2x temporal anti-aliasing.")]
public float fuzzSize;
public static TemporalSettings defaultSettings
{
get
{
return new TemporalSettings
{
enabled = false,
fuzzSize = 2f
};
}
}
}
[Serializable]
public struct PredicationSettings
{
[Tooltip("Predicated thresholding allows to better preserve texture details and to improve performance, by decreasing the number of detected edges using an additional buffer (the detph buffer).\nIt locally decreases the luma or color threshold if an edge is found in an additional buffer (so the global threshold can be higher).")]
public bool enabled;
[Min(0.0001f)]
[Tooltip("Threshold to be used in the additional predication buffer.")]
public float threshold;
[Range(1f, 5f)]
[Tooltip("How much to scale the global threshold used for luma or color edge detection when using predication.")]
public float scale;
[Range(0f, 1f)]
[Tooltip("How much to locally decrease the threshold.")]
public float strength;
public static PredicationSettings defaultSettings
{
get
{
return new PredicationSettings
{
enabled = false,
threshold = 0.01f,
scale = 2f,
strength = 0.4f
};
}
}
}
[TopLevelSettings]
public GlobalSettings settings = GlobalSettings.defaultSettings;
[SettingsGroup]
public QualitySettings quality = QualitySettings.presetQualitySettings[2];
[SettingsGroup]
public PredicationSettings predication = PredicationSettings.defaultSettings;
[SettingsGroup, ExperimentalGroup]
public TemporalSettings temporal = TemporalSettings.defaultSettings;
private Matrix4x4 m_ProjectionMatrix;
private Matrix4x4 m_PreviousViewProjectionMatrix;
private float m_FlipFlop = 1.0f;
private RenderTexture m_Accumulation;
private Shader m_Shader;
public Shader shader
{
get
{
if (m_Shader == null)
m_Shader = Shader.Find("Hidden/Subpixel Morphological Anti-aliasing");
return m_Shader;
}
}
private Texture2D m_AreaTexture;
private Texture2D areaTexture
{
get
{
if (m_AreaTexture == null)
m_AreaTexture = Resources.Load<Texture2D>("AreaTex");
return m_AreaTexture;
}
}
private Texture2D m_SearchTexture;
private Texture2D searchTexture
{
get
{
if (m_SearchTexture == null)
m_SearchTexture = Resources.Load<Texture2D>("SearchTex");
return m_SearchTexture;
}
}
private Material m_Material;
private Material material
{
get
{
if (m_Material == null)
m_Material = ImageEffectHelper.CheckShaderAndCreateMaterial(shader);
return m_Material;
}
}
private int m_AreaTex;
private int m_SearchTex;
private int m_Metrics;
private int m_Params1;
private int m_Params2;
private int m_Params3;
private int m_ReprojectionMatrix;
private int m_SubsampleIndices;
private int m_BlendTex;
private int m_AccumulationTex;
public void Awake()
{
m_AreaTex = Shader.PropertyToID("_AreaTex");
m_SearchTex = Shader.PropertyToID("_SearchTex");
m_Metrics = Shader.PropertyToID("_Metrics");
m_Params1 = Shader.PropertyToID("_Params1");
m_Params2 = Shader.PropertyToID("_Params2");
m_Params3 = Shader.PropertyToID("_Params3");
m_ReprojectionMatrix = Shader.PropertyToID("_ReprojectionMatrix");
m_SubsampleIndices = Shader.PropertyToID("_SubsampleIndices");
m_BlendTex = Shader.PropertyToID("_BlendTex");
m_AccumulationTex = Shader.PropertyToID("_AccumulationTex");
}
public void OnEnable(AntiAliasing owner)
{
if (!ImageEffectHelper.IsSupported(shader, true, false, owner))
owner.enabled = false;
}
public void OnDisable()
{
// Cleanup
if (m_Material != null)
Object.DestroyImmediate(m_Material);
if (m_Accumulation != null)
Object.DestroyImmediate(m_Accumulation);
m_Material = null;
m_Accumulation = null;
}
public void OnPreCull(Camera camera)
{
if (temporal.UseTemporal())
{
m_ProjectionMatrix = camera.projectionMatrix;
m_FlipFlop -= (2.0f * m_FlipFlop);
Matrix4x4 fuzz = Matrix4x4.identity;
fuzz.m03 = (0.25f * m_FlipFlop) * temporal.fuzzSize / camera.pixelWidth;
fuzz.m13 = (-0.25f * m_FlipFlop) * temporal.fuzzSize / camera.pixelHeight;
camera.projectionMatrix = fuzz * camera.projectionMatrix;
}
}
public void OnPostRender(Camera camera)
{
if (temporal.UseTemporal())
camera.ResetProjectionMatrix();
}
public void OnRenderImage(Camera camera, RenderTexture source, RenderTexture destination)
{
int width = camera.pixelWidth;
int height = camera.pixelHeight;
bool isFirstFrame = false;
QualitySettings preset = quality;
if (settings.quality != QualityPreset.Custom)
preset = QualitySettings.presetQualitySettings[(int)settings.quality];
// Pass IDs
int passEdgeDetection = (int)settings.edgeDetectionMethod;
int passBlendWeights = 4;
int passNeighborhoodBlending = 5;
int passResolve = 6;
// Reprojection setup
var viewProjectionMatrix = GL.GetGPUProjectionMatrix(m_ProjectionMatrix, true) * camera.worldToCameraMatrix;
// Uniforms
material.SetTexture(m_AreaTex, areaTexture);
material.SetTexture(m_SearchTex, searchTexture);
material.SetVector(m_Metrics, new Vector4(1f / width, 1f / height, width, height));
material.SetVector(m_Params1, new Vector4(preset.threshold, preset.depthThreshold, preset.maxSearchSteps, preset.maxDiagonalSearchSteps));
material.SetVector(m_Params2, new Vector2(preset.cornerRounding, preset.localContrastAdaptationFactor));
material.SetMatrix(m_ReprojectionMatrix, m_PreviousViewProjectionMatrix * Matrix4x4.Inverse(viewProjectionMatrix));
float subsampleIndex = (m_FlipFlop < 0.0f) ? 2.0f : 1.0f;
material.SetVector(m_SubsampleIndices, new Vector4(subsampleIndex, subsampleIndex, subsampleIndex, 0.0f));
// Handle predication & depth-based edge detection
Shader.DisableKeyword("USE_PREDICATION");
if (settings.edgeDetectionMethod == EdgeDetectionMethod.Depth)
{
camera.depthTextureMode |= DepthTextureMode.Depth;
}
else if (predication.enabled)
{
camera.depthTextureMode |= DepthTextureMode.Depth;
Shader.EnableKeyword("USE_PREDICATION");
material.SetVector(m_Params3, new Vector3(predication.threshold, predication.scale, predication.strength));
}
// Diag search & corner detection
Shader.DisableKeyword("USE_DIAG_SEARCH");
Shader.DisableKeyword("USE_CORNER_DETECTION");
if (preset.diagonalDetection)
Shader.EnableKeyword("USE_DIAG_SEARCH");
if (preset.cornerDetection)
Shader.EnableKeyword("USE_CORNER_DETECTION");
// UV-based reprojection (up to Unity 5.x)
Shader.DisableKeyword("USE_UV_BASED_REPROJECTION");
if (temporal.UseTemporal())
Shader.EnableKeyword("USE_UV_BASED_REPROJECTION");
// Persistent textures and lazy-initializations
if (m_Accumulation == null || (m_Accumulation.width != width || m_Accumulation.height != height))
{
if (m_Accumulation)
RenderTexture.ReleaseTemporary(m_Accumulation);
m_Accumulation = RenderTexture.GetTemporary(width, height, 0, source.format, RenderTextureReadWrite.Linear);
m_Accumulation.hideFlags = HideFlags.HideAndDontSave;
isFirstFrame = true;
}
RenderTexture rt1 = TempRT(width, height, source.format);
Graphics.Blit(null, rt1, material, 0); // Clear
// Edge Detection
Graphics.Blit(source, rt1, material, passEdgeDetection);
if (settings.debugPass == DebugPass.Edges)
{
Graphics.Blit(rt1, destination);
}
else
{
RenderTexture rt2 = TempRT(width, height, source.format);
Graphics.Blit(null, rt2, material, 0); // Clear
// Blend Weights
Graphics.Blit(rt1, rt2, material, passBlendWeights);
if (settings.debugPass == DebugPass.Weights)
{
Graphics.Blit(rt2, destination);
}
else
{
// Neighborhood Blending
material.SetTexture(m_BlendTex, rt2);
if (temporal.UseTemporal())
{
// Temporal filtering
Graphics.Blit(source, rt1, material, passNeighborhoodBlending);
if (settings.debugPass == DebugPass.Accumulation)
{
Graphics.Blit(m_Accumulation, destination);
}
else if (!isFirstFrame)
{
material.SetTexture(m_AccumulationTex, m_Accumulation);
Graphics.Blit(rt1, destination, material, passResolve);
}
else
{
Graphics.Blit(rt1, destination);
}
//Graphics.Blit(rt1, m_Accumulation);
Graphics.Blit(destination, m_Accumulation);
RenderTexture.active = null;
}
else
{
Graphics.Blit(source, destination, material, passNeighborhoodBlending);
}
}
RenderTexture.ReleaseTemporary(rt2);
}
RenderTexture.ReleaseTemporary(rt1);
// Store the future-previous frame's view-projection matrix
m_PreviousViewProjectionMatrix = viewProjectionMatrix;
}
private RenderTexture TempRT(int width, int height, RenderTextureFormat format)
{
// Skip the depth & stencil buffer creation when DebugPass is set to avoid flickering
// int depthStencilBits = DebugPass == DebugPass.Off ? 24 : 0;
int depthStencilBits = 0;
return RenderTexture.GetTemporary(width, height, depthStencilBits, format, RenderTextureReadWrite.Linear);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using StructureMap.Building;
using StructureMap.Configuration.DSL;
using StructureMap.Graph;
using StructureMap.Pipeline;
using StructureMap.Testing.Configuration.DSL;
using StructureMap.Testing.Pipeline;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
namespace StructureMap.Testing
{
[TestFixture]
public class BuildSessionTester
{
public class WidgetHolder
{
private readonly IWidget[] _widgets;
public WidgetHolder(IWidget[] widgets)
{
_widgets = widgets;
}
public IWidget[] Widgets
{
get { return _widgets; }
}
}
[Test]
public void can_get_all_of_a_type_during_object_creation()
{
var container = new Container(x => {
x.For<IWidget>().AddInstances(o => {
o.Type<AWidget>();
o.ConstructedBy(() => new ColorWidget("red"));
o.ConstructedBy(() => new ColorWidget("blue"));
o.ConstructedBy(() => new ColorWidget("green"));
});
x.ForConcreteType<TopClass>().Configure.OnCreation("test",
(c, top) => { top.Widgets = c.All<IWidget>().ToArray(); });
});
container.GetInstance<TopClass>().Widgets.Count().ShouldEqual(4);
}
[Test]
public void descriptive_exception_when_a_named_instance_cannot_be_found()
{
var container = new Container(x => {
x.For<IWidget>().AddInstances(o =>
{
o.Type<AWidget>();
o.ConstructedBy(() => new ColorWidget("red")).Named("red");
o.ConstructedBy(() => new ColorWidget("blue")).Named("blue");
o.ConstructedBy(() => new ColorWidget("green")).Named("green");
});
});
var ex = Exception<StructureMapException>.ShouldBeThrownBy(() => {
container.GetInstance<IWidget>("purple");
});
Debug.WriteLine(ex.ToString());
ex.Context.ShouldContain("The current configuration for type StructureMap.Testing.Widget.IWidget is:");
ex.Title.ShouldEqual(
"Could not find an Instance named 'purple' for PluginType StructureMap.Testing.Widget.IWidget");
}
[Test]
public void can_get_all_of_a_type_during_object_creation_as_generic_type()
{
var container = new Container(x => {
x.For<IWidget>().AddInstances(o => {
o.Type<AWidget>();
o.ConstructedBy(() => new ColorWidget("red"));
o.ConstructedBy(() => new ColorWidget("blue"));
o.ConstructedBy(() => new ColorWidget("green"));
});
x.ForConcreteType<TopClass>().Configure.OnCreation("set the widgets",
(c, top) => { top.Widgets = c.All<IWidget>().ToArray(); });
});
container.GetInstance<TopClass>().Widgets.Count().ShouldEqual(4);
}
[Test]
public void can_get_all_of_a_type_by_GetAllInstances_during_object_creation_as_generic_type()
{
var container = new Container(x => {
x.For<IWidget>().AddInstances(o => {
o.Type<AWidget>();
o.ConstructedBy(() => new ColorWidget("red"));
o.ConstructedBy(() => new ColorWidget("blue"));
o.ConstructedBy(() => new ColorWidget("green"));
});
x.ForConcreteType<TopClass>().Configure.OnCreation("test",
(c, top) => { top.Widgets = c.GetAllInstances<IWidget>().ToArray(); });
});
container.GetInstance<TopClass>().Widgets.Count().ShouldEqual(4);
}
[Test]
public void Get_a_unique_value_for_each_individual_buildsession()
{
var count = 0;
var session = BuildSession.Empty();
var session2 = BuildSession.Empty();
var instance = new LambdaInstance<ColorRule>("counting",() => {
count++;
return new ColorRule("Red");
});
var result1 = session.FindObject(typeof (ColorRule), instance);
var result2 = session.FindObject(typeof (ColorRule), instance);
var result3 = session2.FindObject(typeof (ColorRule), instance);
var result4 = session2.FindObject(typeof (ColorRule), instance);
Assert.AreEqual(2, count);
Assert.AreSame(result1, result2);
Assert.AreNotSame(result1, result3);
Assert.AreSame(result3, result4);
}
[Test]
public void If_no_child_array_is_explicitly_defined_return_all_instances()
{
IContainer manager = new Container(r => {
r.For<IWidget>().AddInstances(x => {
x.Object(new ColorWidget("Red"));
x.Object(new ColorWidget("Blue"));
x.Object(new ColorWidget("Green"));
});
});
var holder = manager.GetInstance<WidgetHolder>();
Assert.AreEqual(3, holder.Widgets.Length);
}
[Test]
public void Return_the_same_object_everytime_an_object_is_requested()
{
var count = 0;
var session = BuildSession.Empty();
var instance = new LambdaInstance<ColorRule>("counting", () => {
count++;
return new ColorRule("Red");
});
var result1 = session.FindObject(typeof (ColorRule), instance);
var result2 = session.FindObject(typeof (ColorRule), instance);
var result3 = session.FindObject(typeof (ColorRule), instance);
var result4 = session.FindObject(typeof (ColorRule), instance);
Assert.AreEqual(1, count);
Assert.AreSame(result1, result2);
Assert.AreSame(result1, result3);
Assert.AreSame(result1, result4);
}
[Test]
public void Return_the_same_object_within_a_session_for_the_default_of_a_plugin_type()
{
var count = 0;
var instance = new LambdaInstance<ColorRule>("counting", () => {
count++;
return new ColorRule("Red");
});
var registry = new Registry();
registry.For<ColorRule>().UseInstance(instance);
var graph = registry.Build();
var session = BuildSession.ForPluginGraph(graph);
var result1 = session.GetInstance(typeof (ColorRule));
var result2 = session.GetInstance(typeof (ColorRule));
var result3 = session.GetInstance(typeof (ColorRule));
var result4 = session.GetInstance(typeof (ColorRule));
Assert.AreEqual(1, count);
Assert.AreSame(result1, result2);
Assert.AreSame(result1, result3);
Assert.AreSame(result1, result4);
}
[Test]
public void Throw_exception_When_trying_to_build_an_instance_that_cannot_be_found()
{
var graph = PipelineGraph.BuildEmpty();
var ex = Exception<StructureMapConfigurationException>.ShouldBeThrownBy(() => {
var session = new BuildSession(graph);
session.CreateInstance(typeof(IGateway), "Gateway that is not configured");
});
ex.Title.ShouldEqual("Could not find an Instance named 'Gateway that is not configured' for PluginType StructureMap.Testing.Widget3.IGateway");
}
[Test]
public void When_calling_GetInstance_if_no_default_can_be_found_throw_202()
{
var graph = PipelineGraph.BuildEmpty();
var ex = Exception<StructureMapConfigurationException>.ShouldBeThrownBy(() => {
var session = new BuildSession(graph);
session.GetInstance(typeof(IGateway));
});
ex.Context.ShouldContain("There is no configuration specified for StructureMap.Testing.Widget3.IGateway");
ex.Title.ShouldEqual("No default Instance is registered and cannot be automatically determined for type 'StructureMap.Testing.Widget3.IGateway'");
}
[Test]
public void when_retrieving_an_object_by_name()
{
var red = new ColorService("red");
var green = new ColorService("green");
var graph = new PluginGraph();
var family = graph.Families[typeof (IService)];
family.AddInstance(new ObjectInstance(red).Named("red"));
family.AddInstance(new ObjectInstance(green).Named("green"));
var session = BuildSession.ForPluginGraph(graph);
session.GetInstance<IService>("red").ShouldBeTheSameAs(red);
}
[Test]
public void when_retrieving_an_object_by_nongeneric_type_and_name()
{
var red = new ColorService("red");
var green = new ColorService("green");
var registry = new Registry();
registry.For<IService>().Add(red).Named("red");
registry.For<IService>().Add(green).Named("green");
var graph = registry.Build();
var session = BuildSession.ForPluginGraph(graph);
session.GetInstance(typeof (IService), "red").ShouldBeTheSameAs(red);
}
[Test]
public void when_retrieving_by_try_get_instance_for_instance_that_does_exist()
{
var theService = new ColorService("red");
var session = BuildSession.Empty(new ExplicitArguments().Set<IService>(theService));
session.TryGetInstance<IService>().ShouldBeTheSameAs(theService);
}
[Test]
public void when_retrieving_by_try_get_named_instance_that_does_exist()
{
var red = new ColorService("red");
var green = new ColorService("green");
var graph = new PluginGraph();
var family = graph.Families[typeof (IService)];
family.AddInstance(new ObjectInstance(red).Named("red"));
family.AddInstance(new ObjectInstance(green).Named("green"));
var session = BuildSession.ForPluginGraph(graph);
session.TryGetInstance<IService>("red").ShouldBeTheSameAs(red);
session.TryGetInstance<IService>("green").ShouldBeTheSameAs(green);
}
[Test]
public void when_retrieving_by_try_get_named_instance_that_does_not_exist()
{
var session = BuildSession.Empty();
session.TryGetInstance<IService>("red").ShouldBeNull();
}
[Test]
public void when_retrieving_with_try_get_instance_for_instance_that_does_not_exists()
{
var session = BuildSession.Empty();
session.TryGetInstance<IService>().ShouldBeNull();
}
[Test]
public void when_retrieving_with_try_get_instance_with_nongeneric_type_that_does_exist()
{
var theService = new ColorService("red");
var registry = new Registry();
registry.For<IService>().Use(theService);
var session = BuildSession.ForPluginGraph(registry.Build());
session.TryGetInstance(typeof (IService)).ShouldBeTheSameAs(theService);
}
[Test]
public void when_retrieving_with_try_get_instance_with_nongeneric_type_that_does_not_exist()
{
var session = BuildSession.Empty();
session.TryGetInstance(typeof (IService)).ShouldBeNull();
}
[Test]
public void when_retrieving_by_try_get_named_instance_with_nongeneric_type_that_does_exist()
{
var red = new ColorService("red");
var green = new ColorService("green");
var registry = new Registry();
registry.For<IService>().Add(red).Named("red");
registry.For<IService>().Add(green).Named("green");
var graph = registry.Build();
var session = BuildSession.ForPluginGraph(graph);
session.TryGetInstance(typeof (IService), "red").ShouldBeTheSameAs(red);
}
[Test]
public void when_retrieving_by_try_get_named_instance_with_type_that_does_not_exist()
{
var session = BuildSession.Empty();
session.TryGetInstance(typeof (IService), "yo").ShouldBeNull();
}
[Test]
public void Can_get_an_instance_using_the_non_generic_method()
{
var registry = new Registry();
registry.For<IFooService>().Use<Service>();
var graph = registry.Build();
var session = BuildSession.ForPluginGraph(graph);
var instance = session.GetInstance(typeof (IFooService));
instance.ShouldNotBeNull();
instance.ShouldBeOfType<Service>();
}
[Test]
public void parent_type_is_null_in_the_initial_state()
{
var session = BuildSession.ForPluginGraph(new PluginGraph());
session.ParentType.ShouldBeNull();
}
[Test]
public void push_an_instance_onto_a_session()
{
var session = BuildSession.ForPluginGraph(new PluginGraph());
session.Push(new LambdaInstance<StubbedGateway>(c => new StubbedGateway()));
session.ParentType.ShouldBeNull();
session.Push(new SmartInstance<ARule>());
session.ParentType.ShouldEqual(typeof (StubbedGateway));
session.Push(new SmartInstance<AWidget>());
session.ParentType.ShouldEqual(typeof (ARule));
}
[Test]
public void push_and_pop_an_instance_onto_a_session()
{
var session = BuildSession.ForPluginGraph(new PluginGraph());
session.Push(new SmartInstance<AWidget>());
session.Push(new LambdaInstance<StubbedGateway>(c => new StubbedGateway()));
session.Push(new SmartInstance<ARule>());
session.Pop();
session.ParentType.ShouldEqual(typeof(AWidget));
}
[Test]
public void pushing_the_same_instance_will_throw_a_bidirectional_dependency_exception()
{
var session = BuildSession.ForPluginGraph(new PluginGraph());
var instance1 = new SmartInstance<StubbedGateway>();
var instance2 = new SmartInstance<ARule>();
var instance3 = new SmartInstance<AWidget>();
session.Push(instance1);
session.Push(instance2);
session.Push(instance3);
var ex = Exception<StructureMapBuildException>.ShouldBeThrownBy(() => {
session.Push(instance1);
});
ex.Message.ShouldContain("Bi-directional dependency relationship detected!");
}
public interface IFooService
{
}
public class Service : IFooService
{
}
}
public class TopClass
{
public TopClass(ClassWithWidget classWithWidget)
{
}
public IWidget[] Widgets { get; set; }
}
public class ClassWithWidget
{
public ClassWithWidget(IWidget[] widgets)
{
}
}
public interface IClassWithRule
{
}
public class ClassWithRule : IClassWithRule
{
public ClassWithRule(Rule rule)
{
}
}
public class BuildSessionInstance1 : Instance
{
public override string Description
{
get { return string.Empty; }
}
public override IDependencySource ToDependencySource(Type pluginType)
{
return new Constant(pluginType, new ColorRule("Red"));
}
public override Type ReturnedType
{
get { return typeof (ColorRule); }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Concurrent;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.Runtime
{
public struct TimeoutHelper
{
public static readonly TimeSpan MaxWait = TimeSpan.FromMilliseconds(Int32.MaxValue);
private static readonly CancellationToken s_precancelledToken = new CancellationToken(true);
private bool _cancellationTokenInitialized;
private bool _deadlineSet;
private CancellationToken _cancellationToken;
private DateTime _deadline;
private TimeSpan _originalTimeout;
public TimeoutHelper(TimeSpan timeout)
{
Contract.Assert(timeout >= TimeSpan.Zero, "timeout must be non-negative");
_cancellationTokenInitialized = false;
_originalTimeout = timeout;
_deadline = DateTime.MaxValue;
_deadlineSet = (timeout == TimeSpan.MaxValue);
}
public CancellationToken GetCancellationToken()
{
return GetCancellationTokenAsync().Result;
}
public async Task<CancellationToken> GetCancellationTokenAsync()
{
if (!_cancellationTokenInitialized)
{
var timeout = RemainingTime();
if (timeout >= MaxWait || timeout == Timeout.InfiniteTimeSpan)
{
_cancellationToken = CancellationToken.None;
}
else if (timeout > TimeSpan.Zero)
{
_cancellationToken = await TimeoutTokenSource.FromTimeoutAsync((int)timeout.TotalMilliseconds);
}
else
{
_cancellationToken = s_precancelledToken;
}
_cancellationTokenInitialized = true;
}
return _cancellationToken;
}
public TimeSpan OriginalTimeout
{
get { return _originalTimeout; }
}
public static bool IsTooLarge(TimeSpan timeout)
{
return (timeout > TimeoutHelper.MaxWait) && (timeout != TimeSpan.MaxValue);
}
public static TimeSpan FromMilliseconds(int milliseconds)
{
if (milliseconds == Timeout.Infinite)
{
return TimeSpan.MaxValue;
}
else
{
return TimeSpan.FromMilliseconds(milliseconds);
}
}
public static int ToMilliseconds(TimeSpan timeout)
{
if (timeout == TimeSpan.MaxValue)
{
return Timeout.Infinite;
}
else
{
long ticks = Ticks.FromTimeSpan(timeout);
if (ticks / TimeSpan.TicksPerMillisecond > int.MaxValue)
{
return int.MaxValue;
}
return Ticks.ToMilliseconds(ticks);
}
}
public static TimeSpan Min(TimeSpan val1, TimeSpan val2)
{
if (val1 > val2)
{
return val2;
}
else
{
return val1;
}
}
public static TimeSpan Add(TimeSpan timeout1, TimeSpan timeout2)
{
return Ticks.ToTimeSpan(Ticks.Add(Ticks.FromTimeSpan(timeout1), Ticks.FromTimeSpan(timeout2)));
}
public static DateTime Add(DateTime time, TimeSpan timeout)
{
if (timeout >= TimeSpan.Zero && DateTime.MaxValue - time <= timeout)
{
return DateTime.MaxValue;
}
if (timeout <= TimeSpan.Zero && DateTime.MinValue - time >= timeout)
{
return DateTime.MinValue;
}
return time + timeout;
}
public static DateTime Subtract(DateTime time, TimeSpan timeout)
{
return Add(time, TimeSpan.Zero - timeout);
}
public static TimeSpan Divide(TimeSpan timeout, int factor)
{
if (timeout == TimeSpan.MaxValue)
{
return TimeSpan.MaxValue;
}
return Ticks.ToTimeSpan((Ticks.FromTimeSpan(timeout) / factor) + 1);
}
public TimeSpan RemainingTime()
{
if (!_deadlineSet)
{
this.SetDeadline();
return _originalTimeout;
}
else if (_deadline == DateTime.MaxValue)
{
return TimeSpan.MaxValue;
}
else
{
TimeSpan remaining = _deadline - DateTime.UtcNow;
if (remaining <= TimeSpan.Zero)
{
return TimeSpan.Zero;
}
else
{
return remaining;
}
}
}
public TimeSpan ElapsedTime()
{
return _originalTimeout - this.RemainingTime();
}
private void SetDeadline()
{
Contract.Assert(!_deadlineSet, "TimeoutHelper deadline set twice.");
_deadline = DateTime.UtcNow + _originalTimeout;
_deadlineSet = true;
}
public static void ThrowIfNegativeArgument(TimeSpan timeout)
{
ThrowIfNegativeArgument(timeout, "timeout");
}
public static void ThrowIfNegativeArgument(TimeSpan timeout, string argumentName)
{
if (timeout < TimeSpan.Zero)
{
throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, InternalSR.TimeoutMustBeNonNegative(argumentName, timeout));
}
}
public static void ThrowIfNonPositiveArgument(TimeSpan timeout)
{
ThrowIfNonPositiveArgument(timeout, "timeout");
}
public static void ThrowIfNonPositiveArgument(TimeSpan timeout, string argumentName)
{
if (timeout <= TimeSpan.Zero)
{
throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, InternalSR.TimeoutMustBePositive(argumentName, timeout));
}
}
public static bool WaitOne(WaitHandle waitHandle, TimeSpan timeout)
{
ThrowIfNegativeArgument(timeout);
if (timeout == TimeSpan.MaxValue)
{
waitHandle.WaitOne();
return true;
}
else
{
// http://msdn.microsoft.com/en-us/library/85bbbxt9(v=vs.110).aspx
// with exitContext was used in Desktop which is not supported in Net Native or CoreClr
return waitHandle.WaitOne(timeout);
}
}
internal static TimeoutException CreateEnterTimedOutException(TimeSpan timeout)
{
return new TimeoutException(SR.Format(SR.LockTimeoutExceptionMessage, timeout));
}
}
/// <summary>
/// This class coalesces timeout tokens because cancelation tokens with timeouts are more expensive to expose.
/// Disposing too many such tokens will cause thread contentions in high throughput scenario.
///
/// Tokens with target cancelation time 15ms apart would resolve to the same instance.
/// </summary>
internal static class TimeoutTokenSource
{
/// <summary>
/// These are constants use to calculate timeout coalescing, for more description see method FromTimeoutAsync
/// </summary>
private const int CoalescingFactor = 15;
private const int GranularityFactor = 2000;
private const int SegmentationFactor = CoalescingFactor * GranularityFactor;
private static readonly ConcurrentDictionary<long, Task<CancellationToken>> s_tokenCache =
new ConcurrentDictionary<long, Task<CancellationToken>>();
private static readonly Action<object> s_deregisterToken = (object state) =>
{
var args = (Tuple<long, CancellationTokenSource>)state;
Task<CancellationToken> ignored;
try
{
s_tokenCache.TryRemove(args.Item1, out ignored);
}
finally
{
args.Item2.Dispose();
}
};
public static CancellationToken FromTimeout(int millisecondsTimeout)
{
return FromTimeoutAsync(millisecondsTimeout).Result;
}
public static Task<CancellationToken> FromTimeoutAsync(int millisecondsTimeout)
{
// Note that CancellationTokenSource constructor requires input to be >= -1,
// restricting millisecondsTimeout to be >= -1 would enforce that
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException("Invalid millisecondsTimeout value " + millisecondsTimeout);
}
// To prevent s_tokenCache growing too large, we have to adjust the granularity of the our coalesce depending
// on the value of millisecondsTimeout. The coalescing span scales proportionally with millisecondsTimeout which
// would garentee constant s_tokenCache size in the case where similar millisecondsTimeout values are accepted.
// If the method is given a wildly different millisecondsTimeout values all the time, the dictionary would still
// only grow logarithmically with respect to the range of the input values
uint currentTime = (uint)Environment.TickCount;
long targetTime = millisecondsTimeout + currentTime;
// Formula for our coalescing span:
// Divide millisecondsTimeout by SegmentationFactor and take the highest bit and then multiply CoalescingFactor back
var segmentValue = millisecondsTimeout / SegmentationFactor;
var coalescingSpanMs = CoalescingFactor;
while (segmentValue > 0)
{
segmentValue >>= 1;
coalescingSpanMs <<= 1;
}
targetTime = ((targetTime + (coalescingSpanMs - 1)) / coalescingSpanMs) * coalescingSpanMs;
Task<CancellationToken> tokenTask;
if (!s_tokenCache.TryGetValue(targetTime, out tokenTask))
{
var tcs = new TaskCompletionSource<CancellationToken>();
// only a single thread may succeed adding its task into the cache
if (s_tokenCache.TryAdd(targetTime, tcs.Task))
{
// Since this thread was successful reserving a spot in the cache, it would be the only thread
// that construct the CancellationTokenSource
var tokenSource = new CancellationTokenSource((int)(targetTime - currentTime));
var token = tokenSource.Token;
// Clean up cache when Token is canceled
token.Register(s_deregisterToken, Tuple.Create(targetTime, tokenSource));
// set the result so other thread may observe the token, and return
tcs.TrySetResult(token);
tokenTask = tcs.Task;
}
else
{
// for threads that failed when calling TryAdd, there should be one already in the cache
if (!s_tokenCache.TryGetValue(targetTime, out tokenTask))
{
// In unlikely scenario the token was already cancelled and timed out, we would not find it in cache.
// In this case we would simply create a non-coalsed token
tokenTask = Task.FromResult(new CancellationTokenSource(millisecondsTimeout).Token);
}
}
}
return tokenTask;
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using NLog.Internal;
using NLog.Targets;
#if NET4_5
using System.Web.Http;
using Owin;
using Microsoft.Owin.Hosting;
#endif
using Xunit;
namespace NLog.UnitTests.Targets
{
public class WebServiceTargetTests : NLogTestBase
{
[Fact]
public void Stream_CopyWithOffset_test()
{
var text = @"
Lorem ipsum dolor sit amet consectetuer tellus semper dictum urna consectetuer. Eu iaculis enim tincidunt mi pede id ut sociis non vitae. Condimentum augue Nam Vestibulum faucibus tortor et at Sed et molestie. Interdum morbi Nullam pellentesque Vestibulum pede et eget semper Pellentesque quis. Velit cursus nec dolor vitae id et urna quis ante velit. Neque urna et vitae neque Vestibulum tellus convallis dui.
Tellus nibh enim augue senectus ut augue Donec Pellentesque Sed pretium. Volutpat nunc rutrum auctor dolor pharetra malesuada elit sapien ac nec. Adipiscing et id penatibus turpis a odio risus orci Suspendisse eu. Nibh eu facilisi eu consectetuer nibh eu in Nunc Curabitur rutrum. Quisque sit lacus consectetuer eu Duis quis felis hendrerit lobortis mauris. Nam Vivamus enim Aenean rhoncus.
Nulla tellus dui orci montes Vestibulum Aenean condimentum non id vel. Euismod Nam libero odio ut ut Nunc ac dui Nulla volutpat. Quisque facilisis consequat tempus tempus Curabitur tortor id Phasellus Suspendisse In. Lorem et Phasellus wisi Fusce fringilla pretium pede sapien amet ligula. In sed id In eget tristique quam sed interdum wisi commodo. Volutpat neque nibh mauris Quisque lorem nunc porttitor Cras faucibus augue. Sociis tempus et.
Morbi Nulla justo Aenean orci Vestibulum ullamcorper tincidunt mollis et hendrerit. Enim at laoreet elit eros ut at laoreet vel velit quis. Netus sed Suspendisse sed Curabitur vel sed wisi sapien nonummy congue. Semper Sed a malesuada tristique Vivamus et est eu quis ante. Wisi cursus Suspendisse dictum pretium habitant sodales scelerisque dui tempus libero. Venenatis consequat Lorem eu.
";
var textStream = GenerateStreamFromString(text);
var textBytes = StreamToBytes(textStream);
textStream.Position = 0;
textStream.Flush();
var resultStream = new MemoryStream();
textStream.CopyWithOffset(resultStream, 3);
var result = StreamToBytes(resultStream);
var expected = textBytes.Skip(3).ToArray();
Assert.Equal(result.Length, expected.Length);
Assert.Equal(result, expected);
}
[Fact]
public void WebserviceTest_httppost_utf8_default_no_bom()
{
WebserviceTest_httppost_utf8("", false);
}
[Fact]
public void WebserviceTest_httppost_utf8_with_bom()
{
WebserviceTest_httppost_utf8("includeBOM='true'", true);
}
[Fact]
public void WebserviceTest_httppost_utf8_no_boml()
{
WebserviceTest_httppost_utf8("includeBOM='false'", false);
}
private void WebserviceTest_httppost_utf8(string bomAttr, bool includeBom)
{
var configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='WebService'
name='webservice'
url='http://localhost:57953/Home/Foo2'
protocol='HttpPost'
" + bomAttr + @"
encoding='UTF-8'
methodName='Foo'>
<parameter name='empty' type='System.String' layout=''/> <!-- work around so the guid is decoded properly -->
<parameter name='guid' type='System.String' layout='${guid}'/>
<parameter name='m' type='System.String' layout='${message}'/>
<parameter name='date' type='System.String' layout='${longdate}'/>
<parameter name='logger' type='System.String' layout='${logger}'/>
<parameter name='level' type='System.String' layout='${level}'/>
</target>
</targets>
</nlog>");
var target = configuration.FindTargetByName("webservice") as WebServiceTarget;
Assert.NotNull(target);
Assert.Equal(target.Parameters.Count, 6);
Assert.Equal(target.Encoding.WebName, "utf-8");
//async call with mockup stream
WebRequest webRequest = WebRequest.Create("http://www.test.com");
var request = (HttpWebRequest)webRequest;
var streamMock = new StreamMock();
//event for async testing
var counterEvent = new ManualResetEvent(false);
var parameterValues = new object[] { "", "336cec87129942eeabab3d8babceead7", "Debg", "2014-06-26 23:15:14.6348", "TestClient.Program", "Debug" };
target.DoInvoke(parameterValues, c => counterEvent.Set(), request,
callback =>
{
var t = new Task(() => { });
callback(t);
return t;
},
result => streamMock);
counterEvent.WaitOne(10000);
var bytes = streamMock.bytes;
var url = streamMock.stringed;
const string expectedUrl = "empty=&guid=336cec87129942eeabab3d8babceead7&m=Debg&date=2014-06-26+23%3a15%3a14.6348&logger=TestClient.Program&level=Debug";
Assert.Equal(expectedUrl, url);
Assert.True(bytes.Length > 3);
//not bom
var possbleBomBytes = bytes.Take(3).ToArray();
if (includeBom)
{
Assert.Equal(possbleBomBytes, EncodingHelpers.Utf8BOM);
}
else
{
Assert.NotEqual(possbleBomBytes, EncodingHelpers.Utf8BOM);
}
Assert.Equal(bytes.Length, includeBom ? 126 : 123);
}
#region helpers
private Stream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
private static byte[] StreamToBytes(Stream stream)
{
stream.Flush();
stream.Position = 0;
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// Mock the stream
/// </summary>
private class StreamMock : MemoryStream
{
public byte[] bytes;
public string stringed;
#region Overrides of MemoryStream
/// <summary>
/// Releases the unmanaged resources used by the <see cref="T:System.IO.MemoryStream"/> class and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
//save stuff before dispose
this.Flush();
bytes = this.ToArray();
stringed = StreamToString(this);
base.Dispose(disposing);
}
private static string StreamToString(Stream s)
{
s.Position = 0;
var sr = new StreamReader(s);
return sr.ReadToEnd();
}
#endregion
}
#endregion
#if NET4_5
const string WsAddress = "http://localhost:9000/";
/// <summary>
/// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpPost"/> (only checking for no exception)
/// </summary>
[Fact]
public void WebserviceTest_restapi_httppost()
{
var configuration = CreateConfigurationFromString(string.Format(@"
<nlog throwExceptions='true'>
<targets>
<target type='WebService'
name='ws'
url='{0}{1}'
protocol='HttpPost'
encoding='UTF-8'
>
<parameter name='param1' type='System.String' layout='${{message}}'/>
<parameter name='param2' type='System.String' layout='${{level}}'/>
</target>
</targets>
<rules>
<logger name='*' writeTo='ws'>
</logger>
</rules>
</nlog>", WsAddress, "api/logme"));
LogManager.Configuration = configuration;
var logger = LogManager.GetCurrentClassLogger();
LogMeController.ResetState(1);
StartOwinTest(() =>
{
logger.Info("message 1 with a post");
});
}
/// <summary>
/// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpGet"/> (only checking for no exception)
/// </summary>
[Fact]
public void WebserviceTest_restapi_httpget()
{
WebServiceTest_httpget("api/logme");
}
[Fact]
public void WebServiceTest_restapi_httpget_querystring()
{
WebServiceTest_httpget("api/logme?paramFromConfig=valueFromConfig");
}
private void WebServiceTest_httpget(string relativeUrl)
{
var configuration = CreateConfigurationFromString(string.Format(@"
<nlog throwExceptions='true' >
<targets>
<target type='WebService'
name='ws'
url='{0}{1}'
protocol='HttpGet'
encoding='UTF-8'
>
<parameter name='param1' type='System.String' layout='${{message}}'/>
<parameter name='param2' type='System.String' layout='${{level}}'/>
</target>
</targets>
<rules>
<logger name='*' writeTo='ws'>
</logger>
</rules>
</nlog>", WsAddress, relativeUrl));
LogManager.Configuration = configuration;
var logger = LogManager.GetCurrentClassLogger();
LogMeController.ResetState(1);
StartOwinTest(() =>
{
logger.Info("message 1 with a post");
});
}
/// <summary>
/// Timeout for <see cref="WebserviceTest_restapi_httppost_checkingLost"/>.
///
/// in miliseconds. 20000 = 20 sec
/// </summary>
const int webserviceCheckTimeoutMs = 20000;
/// <summary>
/// Test the Webservice with REST api - <see cref="WebServiceProtocol.HttpPost"/> (only checking for no exception)
///
/// repeats for checking 'lost messages'
/// </summary>
[Fact]
public void WebserviceTest_restapi_httppost_checkingLost()
{
var configuration = CreateConfigurationFromString(string.Format(@"
<nlog throwExceptions='true'>
<targets>
<target type='WebService'
name='ws'
url='{0}{1}'
protocol='HttpPost'
encoding='UTF-8'
>
<parameter name='param1' type='System.String' layout='${{message}}'/>
<parameter name='param2' type='System.String' layout='${{level}}'/>
</target>
</targets>
<rules>
<logger name='*' writeTo='ws'>
</logger>
</rules>
</nlog>", WsAddress, "api/logme"));
LogManager.Configuration = configuration;
var logger = LogManager.GetCurrentClassLogger();
const int messageCount = 1000;
var createdMessages = new List<string>(messageCount);
for (int i = 0; i < messageCount; i++)
{
var message = "message " + i;
createdMessages.Add(message);
}
//reset
LogMeController.ResetState(messageCount);
StartOwinTest(() =>
{
foreach (var createdMessage in createdMessages)
{
logger.Info(createdMessage);
}
});
Assert.Equal(LogMeController.CountdownEvent.CurrentCount, 0);
Assert.Equal(createdMessages.Count, LogMeController.RecievedLogsPostParam1.Count);
//Assert.Equal(createdMessages, ValuesController.RecievedLogsPostParam1);
}
/// <summary>
/// Start/config route of WS
/// </summary>
private class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
private const string LogTemplate = "Method: {0}, param1: '{1}', param2: '{2}', body: {3}";
///<remarks>Must be public </remarks>
public class LogMeController : ApiController
{
/// <summary>
/// Reset the state for unit testing
/// </summary>
/// <param name="expectedMessages"></param>
public static void ResetState(int expectedMessages)
{
RecievedLogsPostParam1 = new ConcurrentBag<string>();
RecievedLogsGetParam1 = new ConcurrentBag<string>();
CountdownEvent = new CountdownEvent(expectedMessages);
}
/// <summary>
/// Countdown event for keeping WS alive.
/// </summary>
public static CountdownEvent CountdownEvent = null;
/// <summary>
/// Recieved param1 values (get)
/// </summary>
public static ConcurrentBag<string> RecievedLogsGetParam1 = new ConcurrentBag<string>();
/// <summary>
/// Recieved param1 values(post)
/// </summary>
public static ConcurrentBag<string> RecievedLogsPostParam1 = new ConcurrentBag<string>();
/// <summary>
/// We need a complex type for modelbinding because of content-type: "application/x-www-form-urlencoded" in <see cref="WebServiceTarget"/>
/// </summary>
public class ComplexType
{
public string Param1 { get; set; }
public string Param2 { get; set; }
}
/// <summary>
/// Get
/// </summary>
public string Get(int id)
{
return "value";
}
// GET api/values
public IEnumerable<string> Get(string param1 = "", string param2 = "")
{
RecievedLogsGetParam1.Add(param1);
return new string[] { "value1", "value2" };
}
/// <summary>
/// Post
/// </summary>
public void Post([FromBody] ComplexType complexType)
{
//this is working.
if (complexType == null)
{
throw new ArgumentNullException("complexType");
}
RecievedLogsPostParam1.Add(complexType.Param1);
if (CountdownEvent != null)
{
CountdownEvent.Signal();
}
}
/// <summary>
/// Put
/// </summary>
public void Put(int id, [FromBody]string value)
{
}
/// <summary>
/// Delete
/// </summary>
public void Delete(int id)
{
}
}
internal static void StartOwinTest(Action testsFunc)
{
// HttpSelfHostConfiguration. So info: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
// Start webservice
using (WebApp.Start<Startup>(url: WsAddress))
{
testsFunc();
//wait for all recieved message, or timeout. There is no exception on timeout, so we have to check carefully in the unit test.
if (LogMeController.CountdownEvent != null)
{
LogMeController.CountdownEvent.Wait(webserviceCheckTimeoutMs);
//we need some extra time for completion
Thread.Sleep(1000);
}
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
/// <summary>
/// PartialView-related extensions for <see cref="IHtmlHelper"/>.
/// </summary>
public static class HtmlHelperPartialExtensions
{
/// <summary>
/// Returns HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <returns>
/// A <see cref="Task"/> that on completion returns a new <see cref="IHtmlContent"/> instance containing
/// the created HTML.
/// </returns>
public static Task<IHtmlContent> PartialAsync(
this IHtmlHelper htmlHelper,
string partialViewName)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
return htmlHelper.PartialAsync(partialViewName, htmlHelper.ViewData.Model, viewData: null);
}
/// <summary>
/// Returns HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="viewData">A <see cref="ViewDataDictionary"/> to pass into the partial view.</param>
/// <returns>
/// A <see cref="Task"/> that on completion returns a new <see cref="IHtmlContent"/> instance containing
/// the created HTML.
/// </returns>
public static Task<IHtmlContent> PartialAsync(
this IHtmlHelper htmlHelper,
string partialViewName,
ViewDataDictionary viewData)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
return htmlHelper.PartialAsync(partialViewName, htmlHelper.ViewData.Model, viewData);
}
/// <summary>
/// Returns HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="model">A model to pass into the partial view.</param>
/// <returns>
/// A <see cref="Task"/> that on completion returns a new <see cref="IHtmlContent"/> instance containing
/// the created HTML.
/// </returns>
public static Task<IHtmlContent> PartialAsync(
this IHtmlHelper htmlHelper,
string partialViewName,
object model)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
return htmlHelper.PartialAsync(partialViewName, model, viewData: null);
}
/// <summary>
/// Returns HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <returns>
/// Returns a new <see cref="IHtmlContent"/> instance containing the created HTML.
/// </returns>
/// <remarks>
/// This method synchronously calls and blocks on
/// <see cref="IHtmlHelper.PartialAsync(string, object, ViewDataDictionary)"/>
/// </remarks>
public static IHtmlContent Partial(this IHtmlHelper htmlHelper, string partialViewName)
{
return Partial(htmlHelper, partialViewName, htmlHelper.ViewData.Model, viewData: null);
}
/// <summary>
/// Returns HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="viewData">A <see cref="ViewDataDictionary"/> to pass into the partial view.</param>
/// <returns>
/// Returns a new <see cref="IHtmlContent"/> instance containing the created HTML.
/// </returns>
/// <remarks>
/// This method synchronously calls and blocks on
/// <see cref="IHtmlHelper.PartialAsync(string, object, ViewDataDictionary)"/>
/// </remarks>
public static IHtmlContent Partial(
this IHtmlHelper htmlHelper,
string partialViewName,
ViewDataDictionary viewData)
{
return Partial(htmlHelper, partialViewName, htmlHelper.ViewData.Model, viewData);
}
/// <summary>
/// Returns HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="model">A model to pass into the partial view.</param>
/// <returns>
/// Returns a new <see cref="IHtmlContent"/> instance containing the created HTML.
/// </returns>
/// <remarks>
/// This method synchronously calls and blocks on
/// <see cref="IHtmlHelper.PartialAsync(string, object, ViewDataDictionary)"/>
/// </remarks>
public static IHtmlContent Partial(this IHtmlHelper htmlHelper, string partialViewName, object model)
{
return Partial(htmlHelper, partialViewName, model, viewData: null);
}
/// <summary>
/// Returns HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="model">A model to pass into the partial view.</param>
/// <param name="viewData">A <see cref="ViewDataDictionary"/> to pass into the partial view.</param>
/// <returns>
/// Returns a new <see cref="IHtmlContent"/> instance containing the created HTML.
/// </returns>
/// <remarks>
/// This method synchronously calls and blocks on
/// <see cref="IHtmlHelper.PartialAsync(string, object, ViewDataDictionary)"/>
/// </remarks>
public static IHtmlContent Partial(
this IHtmlHelper htmlHelper,
string partialViewName,
object model,
ViewDataDictionary viewData)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
var result = htmlHelper.PartialAsync(partialViewName, model, viewData);
return result.GetAwaiter().GetResult();
}
/// <summary>
/// Renders HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <remarks>
/// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>.
/// </remarks>
public static void RenderPartial(this IHtmlHelper htmlHelper, string partialViewName)
{
RenderPartial(htmlHelper, partialViewName, htmlHelper.ViewData.Model, viewData: null);
}
/// <summary>
/// Renders HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="viewData">A <see cref="ViewDataDictionary"/> to pass into the partial view.</param>
/// <remarks>
/// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>.
/// </remarks>
public static void RenderPartial(
this IHtmlHelper htmlHelper,
string partialViewName,
ViewDataDictionary viewData)
{
RenderPartial(htmlHelper, partialViewName, htmlHelper.ViewData.Model, viewData);
}
/// <summary>
/// Renders HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="model">A model to pass into the partial view.</param>
/// <remarks>
/// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>.
/// </remarks>
public static void RenderPartial(this IHtmlHelper htmlHelper, string partialViewName, object model)
{
RenderPartial(htmlHelper, partialViewName, model, viewData: null);
}
/// <summary>
/// Renders HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="model">A model to pass into the partial view.</param>
/// <param name="viewData">A <see cref="ViewDataDictionary"/> to pass into the partial view.</param>
/// <remarks>
/// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>.
/// </remarks>
public static void RenderPartial(
this IHtmlHelper htmlHelper,
string partialViewName,
object model,
ViewDataDictionary viewData)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
var result = htmlHelper.RenderPartialAsync(partialViewName, model, viewData);
result.GetAwaiter().GetResult();
}
/// <summary>
/// Renders HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <returns>A <see cref="Task"/> that renders the created HTML when it executes.</returns>
/// <remarks>
/// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>.
/// </remarks>
public static Task RenderPartialAsync(
this IHtmlHelper htmlHelper,
string partialViewName)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
return htmlHelper.RenderPartialAsync(partialViewName, htmlHelper.ViewData.Model, viewData: null);
}
/// <summary>
/// Renders HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="viewData">A <see cref="ViewDataDictionary"/> to pass into the partial view.</param>
/// <returns>A <see cref="Task"/> that renders the created HTML when it executes.</returns>
/// <remarks>
/// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>.
/// </remarks>
public static Task RenderPartialAsync(
this IHtmlHelper htmlHelper,
string partialViewName,
ViewDataDictionary viewData)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
return htmlHelper.RenderPartialAsync(partialViewName, htmlHelper.ViewData.Model, viewData);
}
/// <summary>
/// Renders HTML markup for the specified partial view.
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="partialViewName">
/// The name or path of the partial view used to create the HTML markup. Must not be <c>null</c>.
/// </param>
/// <param name="model">A model to pass into the partial view.</param>
/// <returns>A <see cref="Task"/> that renders the created HTML when it executes.</returns>
/// <remarks>
/// In this context, "renders" means the method writes its output using <see cref="ViewContext.Writer"/>.
/// </remarks>
public static Task RenderPartialAsync(
this IHtmlHelper htmlHelper,
string partialViewName,
object model)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (partialViewName == null)
{
throw new ArgumentNullException(nameof(partialViewName));
}
return htmlHelper.RenderPartialAsync(partialViewName, model, viewData: null);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.